text
stringlengths 184
4.48M
|
---|
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<link href="https://fonts.googleapis.com/css?family=Heebo:400,500,700" rel="stylesheet">
<link rel="stylesheet" type="text/css" href="./resources/style.css">
<title>Colmar Academy</title>
</head>
<body>
<!--MAIN CONTENT AREA-->
<div class="main-site">
<!--HEADER SECTION-->
<header>
<div class="desktop">
<div class="logo">
<div id="logo-image">
<img src="./resources/images/ic-logo.svg" alt="Colmar logo">
</div>
<p>Colmar<span class="logo_callout">Academy</span></p>
</div> <!--Close logo div-->
<nav>
<ul>
<li>On Campus</li>
<li>Online</li>
<li>For Companies</li>
<li>Sign in</li>
</ul>
</nav>
</div> <!--Close desktop div-->
<div id="mobile">
<div class="logo">
<div id="logo-image">
<img src="./resources/images/ic-logo.svg" alt="Colmar logo">
</div>
</div>
<div id="desk">
<img src="./resources/images/ic-on-campus.svg" alt="Desk logo">
</div>
<div id="online">
<img src="./resources/images/ic-online.svg" alt="Computer logo">
</div>
<div id="login">
<img src="./resources/images/ic-login.svg" alt="Login logo">
</div>
</div> <!--Close mobile div-->
</header> <!--Close header div-->
<!--MAIN BANNER SECTION-->
<div class="main-banner">
<div class="lg-image-container">
<img src="./resources/images/banner.jpg" alt="students">
</div>
<div class="main-banner_content">
<h1>Learn something new everyday</h1>
<h3>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</h3>
<div id="button">
<a href="#">Start here</a>
</div>
</div> <!--Close main-banner content div-->
</div> <!--Close main-banner div-->
<!--INFORMATION SECTION-->
<div class="information">
<div class="information-main">
<div class="lg-image-container" id=information-image>
<img src="./resources/images/information-main.jpg" alt="reading">
</div>
<div class="information-main-content">
<h2>It doesn't hurt to keep practicing</h2>
<p>"Curabitur vitae libero in ipsum porttitor consequat. Aliquam et commodo
lectus, nec consequat neque. Sed non accumsan urna. Phasellus sed
consequat ex. Etiam eget magna laoreet efficitur dolor consequat, tristique ligula."</p>
<span id="attribute">Emanuel, Sr Strategist at Hiring.com</span>
</div>
</div>
<!--INFORMATION Sidebar-->
<div class="sidebar">
<!--Orientation sidebar-->
<div class="sidebar-item">
<div class="sidebar-image">
<img src="./resources/images/information-orientation.jpg" alt="Campus overhead">
</div>
<div class="orientation-content">
<h3>Orientation date</h3>
<span class="sidebar-content">Tue 10/11 & Wed 10/12: 8am-3pm</span>
<a href="#" class="sidebar-link">Read more</a>
</div> <!--Close orientation-content div-->
</div> <!--Close orientation div-->
<!--Campus sidebar-->
<div class="sidebar-item">
<div class="sidebar-image">
<img src="./resources/images/information-campus.jpg" alt="Classroom">
</div>
<div class="campus-content">
<h3>Our campus</h3>
<span class="sidebar-content">Find which campus is close by you</span>
<a href="#" class="sidebar-link">Read more</a>
</div> <!--Close campus-content div-->
</div> <!--Close campus div-->
<!--Guest Lecture sidebar-->
<div class="sidebar-item">
<div class="sidebar-image">
<img src="./resources/images/information-guest-lecture.jpg" alt="Classroom">
</div>
<div class="lecture-content">
<h3>Our guest lecture</h3>
<span class="sidebar-content">Join a keynote with Oliver Sack about music in medical treatment</span>
<a href="#" class="sidebar-link">Read more</a>
</div> <!--Close guest-content div-->
</div> <!--Close guest-lecture div-->
</div> <!--Close sidebar div-->
</div> <!--Close information div-->
<!--COURSES SECTION-->
<div class="courses-container">
<div> <!--Separate div needed???-->
<h2>Start learning</h2>
</div>
<!--Courses-->
<div class="courses">
<div class="course">
<div class="course-image-container">
<img src="./resources/images/course-software.jpg" alt="Software engineering">
</div>
<div class="course-content">
<h3>Software engineering</h3>
<span class="category">Courses</span>
<p class="description">Web Development, Mobile Development, iOT, APIs</p>
</div> <!--Close course-content div-->
</div> <!--Close course indiv div-->
<div class="course">
<div class="course-image-container">
<img src="./resources/images/course-computer-art.jpg" alt="Mobile Phone">
</div>
<div class="course-content">
<h3>Computer art</h3>
<span class="category">Courses</span>
<p class="description">Imaging & Design, Web Design, Motion Graphics & Visual Effects, Computer Animation</p>
</div> <!--Close course-content div-->
</div> <!--Close course indiv div-->
<div class="course">
<div class="course-image-container">
<img src="./resources/images/course-design.jpg" alt="Photographer">
</div>
<div class="course-content">
<h3>Design</h3>
<span class="category">Courses</span>
<p class="description">User Experience Design, User Research, Visual Design</p>
</div> <!--Close course-content div-->
</div> <!--Close course indiv div-->
<div class="course">
<div class="course-image-container">
<img src="./resources/images/course-data.jpg" alt="Data charts">
</div>
<div class="course-content">
<h3>Data</h3>
<span class="category">Courses</span>
<p class="description">Data Science, Big Data, SQL, Data Visualization</p>
</div> <!--Close course-content div-->
</div> <!--Close course indiv div-->
<div class="course">
<div class="course-image-container">
<img src="./resources/images/course-business.jpg" alt="Chess pieces">
</div>
<div class="course-content">
<h3>Business</h3>
<span class="category">Courses</span>
<p class="description">Product Development, Business Development, Startup</p>
</div> <!--Close course-content div-->
</div> <!--Close course indiv div-->
<div class="course">
<div class="course-image-container">
<img src="./resources/images/course-marketing.jpg" alt="Smartwatch">
</div>
<div class="course-content">
<h3>Marketing</h3>
<span class="category">Courses</span>
<p class="description">Analytics, Content Marketing, Mobile Marketing</p>
</div> <!--Close course-content div-->
</div> <!--Close course indiv div-->
</div> <!--Close courses group div-->
</div> <!--Close courses-container div-->
<!--THESIS SECTION-->
<div class="Thesis-container">
<div>
<h2>Thesis exhibit</h2>
</div>
<div class="thesis-content">
<div class="thesis-main">
<div class="lg-image-container" id="thesis_video">
<video src="./resources/videos/thesis.mp4" autoplay poster="posterimage.jpg">
</video>
</div>
<div class="thesis-main-content">
<h2>Reimagine urban</h2>
<p>"Curabitur vitae libero in ipsum porttitor consequat. Aliquam et commodo
lectus, nec consequat neque. Sed non accumsan urna. Phasellus sed
consequat ex. Etiam eget magna laoreet efficitur dolor consequat, tristique ligula."</p>
</div> <!--Close thesis-main content div-->
</div> <!--Close thesis-main div-->
<!--THESIS Sidebar-->
<div class="sidebar">
<!--Fisma sidebar-->
<div class="sidebar-item" id="fisma">
<div class="sidebar-image">
<img src="./resources/images/thesis-fisma.jpg" alt="Prototype showcase">
</div>
<div class="sidebar-content">
<h3>Fisma: Design and Prototype</h3>
<span class="sidebar-content">Designer showcase of new prototype product</span>
</div> <!--Close sidebar-content div-->
</div> <!--Close sidebar-item div-->
<!--Now and Then sidebar-->
<div class="sidebar-item">
<div class="sidebar-image">
<img src="./resources/images/thesis-now-and-then.jpg" alt="Empire State Building">
</div>
<div class="sidebar-content">
<h3>Now and then</h3>
<span class="sidebar content">Research study about New York</span>
</div> <!--Close sidebar-content div-->
</div> <!--Close sidebar-item div-->
</div> <!--Close sidebar div-->
</div> <!--Close Thesis-content div-->
</div> <!--Close Thesis container div-->
<footer>
<p>© 2016 Colmar Academy. All rights reserved.</p>
<div class="footer_links">
<a href="#">Terms</a>
<a href="#">Privacy</a>
</div>
</footer>
</div> <!--Close main-site div-->
</body>
</html> |
<script lang="ts">
import { Person } from '@hcengineering/contact'
import { AssigneePopup, EmployeePresenter } from '@hcengineering/contact-resources'
import { Doc, Ref, SortingOrder, generateId } from '@hcengineering/core'
import { MessageBox, createQuery, getClient } from '@hcengineering/presentation'
import { NodeViewContent, NodeViewProps, NodeViewWrapper } from '@hcengineering/text-editor'
import { CheckBox, getEventPositionElement, showPopup } from '@hcengineering/ui'
import time, { ToDo, ToDoPriority } from '@hcengineering/time'
import { makeRank } from '@hcengineering/rank'
import document from '../../plugin'
export let node: NodeViewProps['node']
export let editor: NodeViewProps['editor']
export let updateAttributes: NodeViewProps['updateAttributes']
export let object: Doc | undefined = undefined
const client = getClient()
const query = createQuery()
$: todoId = node.attrs.todoid as Ref<ToDo>
$: userId = node.attrs.userid as Ref<Person>
$: checked = node.attrs.checked ?? false
$: readonly = !editor.isEditable || object === undefined
let todo: ToDo | undefined = undefined
$: query.query(
time.class.ToDo,
{
_id: todoId
},
(res) => {
;[todo] = res
void syncTodo(todo)
}
)
async function syncTodo (todo: ToDo | undefined): Promise<void> {
if (todo !== undefined) {
const todoChecked = todo.doneOn != null
if (todo._id !== todoId || todo.user !== userId || todoChecked !== checked) {
updateAttributes({
todoid: todo._id,
userid: todo.user,
checked: todoChecked
})
}
} else {
if (node.attrs.todoid != null) {
updateAttributes({
todoid: null,
userid: null
})
}
}
}
async function markDone (): Promise<void> {
if (todo !== undefined) {
await client.update(todo, { doneOn: todo.doneOn == null ? Date.now() : null })
} else {
updateAttributes({ checked: node.attrs.checked !== true })
}
}
async function assignTodo (user: Ref<Person>): Promise<void> {
if (todo !== undefined && todo.user === user) return
if (object === undefined) return
const title = node.textBetween(0, node.content.size, undefined, ' ')
const ops = client.apply('todo' + generateId())
if (todo !== undefined) {
await ops.remove(todo)
}
const doneOn = node.attrs.checked === true ? Date.now() : null
const latestTodoItem = await ops.findOne(
time.class.ToDo,
{
user,
doneOn: doneOn === null ? null : { $ne: null }
},
{
sort: { rank: SortingOrder.Ascending }
}
)
const rank = makeRank(undefined, latestTodoItem?.rank)
const id = await ops.addCollection(time.class.ProjectToDo, time.space.ToDos, object._id, object._class, 'todos', {
attachedSpace: object.space,
title,
description: '',
user,
workslots: 0,
priority: ToDoPriority.NoPriority,
visibility: 'public',
doneOn,
rank
})
await ops.commit()
updateAttributes({
todoid: id,
userid: user
})
}
async function unassignTodo (): Promise<void> {
updateAttributes({
todoid: null,
userid: null
})
if (todo !== undefined) {
await client.remove(todo)
}
}
async function assignTodoConfirm (user: Ref<Person>): Promise<void> {
showPopup(
MessageBox,
{
label: document.string.ReassignToDo,
message: document.string.ReassignToDoConfirm
},
'top',
async (result?: boolean) => {
if (result === true) {
await assignTodo(user)
}
}
)
}
async function unassignTodoConfirm (): Promise<void> {
showPopup(
MessageBox,
{
label: document.string.UnassignToDo,
message: document.string.UnassignToDoConfirm
},
'top',
async (result?: boolean) => {
if (result === true) {
await unassignTodo()
}
}
)
}
async function changeAssignee (user: Ref<Person> | undefined): Promise<void> {
const shouldConfirm = todo !== undefined && todo?.workslots > 0
if (user !== undefined) {
shouldConfirm ? await assignTodoConfirm(user) : await assignTodo(user)
} else {
shouldConfirm ? await unassignTodoConfirm() : await unassignTodo()
}
}
let hovered = false
function handleAssigneeEdit (ev: MouseEvent): void {
ev.preventDefault()
ev.stopPropagation()
hovered = true
showPopup(
AssigneePopup,
{
selected: userId
},
getEventPositionElement(ev),
async (result) => {
if (result !== undefined && result?._id !== userId) {
await changeAssignee(result?._id)
}
hovered = false
editor.commands.focus()
}
)
}
</script>
<NodeViewWrapper data-drag-handle="" data-type="todoItem">
<div
class="todo-item flex-row-top flex-gap-3"
class:empty={node.textContent.length === 0}
class:unassigned={userId == null}
class:hovered
>
<div class="flex-center assignee" contenteditable="false">
<EmployeePresenter
value={userId}
disabled={readonly}
avatarSize={'card'}
shouldShowName={false}
shouldShowPlaceholder
onEmployeeEdit={handleAssigneeEdit}
/>
</div>
<div class="flex-center todo-check" contenteditable="false">
<CheckBox {readonly} {checked} on:value={markDone} kind={'positive'} size={'medium'} />
</div>
<NodeViewContent style="outline: none;" class="flex-grow" />
</div>
</NodeViewWrapper>
<style lang="scss">
.todo-item {
.assignee {
width: 1.25rem;
cursor: pointer;
}
.assignee,
.todo-check {
height: 1.5em;
}
&.unassigned {
.assignee {
opacity: 0;
}
}
&.empty {
.assignee {
visibility: hidden;
}
}
&.hovered,
&:hover,
&:focus-within {
.assignee {
opacity: 1;
}
}
}
</style> |
import 'package:geek_chat/models/message.dart';
import 'package:geek_chat/repository/sessions_repository.dart';
import 'package:uuid/uuid.dart';
class SessionModel {
//
String sid;
String name;
String promptContent;
String type;
String modelType;
String model;
int maxContextSize;
int maxContextMsgCount;
double temperature;
int maxTokens;
int updated;
bool synced;
int status; // 1 = show, 0 = delete
late MessageModel prompt;
String get maxContextMsgCountLabel {
if (maxContextMsgCount >= 22) {
return "Unlimited";
}
return maxContextMsgCount.toString();
}
SessionModel({
required this.sid,
required this.name,
required this.promptContent,
required this.type,
required this.modelType,
required this.model,
required this.maxContextSize,
required this.maxContextMsgCount,
required this.temperature,
required this.maxTokens,
required this.updated,
required this.synced,
required this.status,
}) {
prompt = MessageModel(
msgId: const Uuid().v4(), role: 'system', content: promptContent);
}
SessionModel copyWith({int? lastUpdated}) {
return SessionModel(
sid: sid,
name: name,
promptContent: promptContent,
type: type,
modelType: modelType,
model: model,
maxContextSize: maxContextSize,
maxContextMsgCount: maxContextMsgCount,
temperature: temperature,
maxTokens: maxTokens,
updated: lastUpdated ?? updated,
synced: synced,
status: status);
}
factory SessionModel.fromTable(SessionTable session) {
return SessionModel(
sid: session.sid,
name: session.name ?? '',
promptContent: session.promptContent ?? '',
type: session.type,
modelType: session.modelType,
model: session.model,
maxContextSize: session.maxContextSize ?? 0,
maxContextMsgCount: session.maxContextMsgCount ?? 0,
temperature: session.temperature ?? 0.1,
maxTokens: session.maxTokens ?? 1024,
updated: session.updated ?? 0,
synced: session.synced,
status: session.status);
}
SessionTable toSessionTable() {
prompt.content = promptContent;
SessionTable st = SessionTable();
st.sid = sid;
st.name = name;
st.promptContent = prompt.content;
st.type = type;
st.modelType = modelType;
st.model = model;
st.maxContextSize = maxContextSize;
st.maxContextMsgCount = maxContextMsgCount;
st.temperature = temperature;
st.maxTokens = maxTokens;
st.updated = updated;
st.synced = synced;
st.status = status;
return st;
}
} |
class QueueItem < ActiveRecord::Base
validates_numericality_of :position, {only_integer: true}
belongs_to :user
belongs_to :video
delegate :category, to: :video
delegate :title, to: :video, prefix: :video
def rating
review = Review.where(user_id: user.id, video_id: video.id).first
review.rating if review
end
def rating=(new_rating)
if review
review.update_column(:rating, new_rating)
else
review = Review.new(user: user, video: video, rating: new_rating)
review.save(validate: false)
end
end
def category_name
category.name
end
def self.append_video_to_user(user, video)
queue_item = QueueItem.new(user: user, video: video)
queue_item.position = user.queue_items.count + 1
queue_item.save
end
private
def review
@review ||= Review.where(user_id: user.id, video_id: video_id).take
end
end |
<div class="form-container mat-elevation-z5">
<h1>Sign Up</h1>
<form class="text-center" [formGroup]="signupForm" (ngSubmit)="onSubmit()">
<mat-form-field>
<input matInput placeholder="User Name" formControlName="name">
<mat-error *ngIf="name?.getError('required')">User name is required</mat-error>
</mat-form-field>
<mat-form-field>
<input matInput placeholder="Email address" formControlName="email">
<mat-error *ngIf="email?.getError('required')">Email is required!</mat-error>
<mat-error *ngIf="email?.getError('email')">
Please enter a valid email
</mat-error>
</mat-form-field>
<mat-form-field>
<input matInput placeholder="Password" formControlName="password">
<mat-error *ngIf="password?.getError('required')">Password is required!</mat-error>
<mat-error *ngIf="password?.getError('minlength')">
Please enter atleast 6 characters
</mat-error>
</mat-form-field>
<mat-form-field>
<input matInput placeholder="Confirm Password" formControlName="confirmPassword">
</mat-form-field>
<mat-error *ngIf="signupForm.errors?.['passwordsDontMatch']">
Passwords should match
</mat-error>
<div class="text-center mt-3">
<button mat-raised-button color="primary" type="submit" [disabled]="!signupForm.valid">Sign Up!</button>
</div>
</form>
</div> |
#include "iostream"
#include "string"
using namespace std;
int main()
{
//El número de columnas es fijo (sólo título y autor)
int cols = 2;
string titulo ,autor;
//Si inicializa la matriz (punteros de punteros)
string** libros;
//Se inicializa la variable
int tamanio = 0;
string entrada;
// Leer la cantidad de libros
cout << "Cuantos libros desea ingresar?";
//Se asigna el valor ingresado
getline(cin, entrada);
//Se transforma la entrada en número
tamanio = stoi(entrada);
//Se asigna el número de filas según el usuario (un arreglo de punteros)
libros = new string*[tamanio];
//Recorro los punteros.
for (int i = 0; i < tamanio; ++i) {
cout << "Dirección de libros[" << i << "] = " << libros[i] << "\n";
}
cout << "Por favor ingrese la siguiente información de los Libros: \n";
for(int i = 0; i < tamanio; i++) {
//Cada fila contendrá dos columnas
libros[i] = new string[cols];
//Notar que cols pudo haber sido ingresada por el usuario también
cout << "\n******* Libro " << i + 1 << "********:\n";
cout << "Titulo: ";
getline(cin,titulo);
cout << "Autor: ";
getline(cin,autor);
libros[i][0] = titulo;
libros[i][1] = autor;
}
//despliego datos de libros.
for (int i = 0; i < tamanio; ++i) {
for (int j = 0; j < cols; j++) {
cout << "Libro[" << i << "," << j << "] = " << libros[i][j] << "\n";
}
}
//Para liberar la memoria debemos recorrer fila por fila primero.
for (int i = 0; i < tamanio; ++i) {
//Cada fila de libros es otro array de punteros
delete [] libros[i];
//Por eso son punteros a punteros
}
//Luego de limpiar las columnas, quitamos la fila única que quedó
delete [] libros;
system("pause");
return 0;
} |
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using System.Reflection;
using FluentValidation;
using Microsoft.EntityFrameworkCore;
using ARC.Product.Persistence.Entities;
using Arc.Common.Automapper;
namespace ARC.Product.Core.DependencyInjection
{
/// <summary>
/// This is where our services for the core project are consolidated.
/// Needs to be called in the main project to add all dependencies.
/// </summary>
public static class ServiceCollectionExtensions
{
public static IServiceCollection AddCore(this IServiceCollection services, IConfiguration configuration, params Assembly[] assemblies)
{
services.AddValidatorsFromAssemblies(assemblies);
services.AddDbContext<ApplicationDbContext>(opt => opt.UseSqlServer(configuration.GetConnectionString("DefaultConnection")!));
services.AddAutoMapperAndProfile(assemblies);
services.AddScoped<CoreHelper>();
return services;
}
}
} |
//
// UserLocationService.swift
//
//
// Created by Ana Márquez on 20/06/2023.
//
import Foundation
import CoreLocation
import MapKit
class UserLocationService: NSObject, ObservableObject {
static let shared: UserLocationService = .init()
// MARK: - Published
@Published var currentCoordinate: CLLocationCoordinate2D? = nil
@Published var authorizationStatus: CLAuthorizationStatus = .denied
// MARK: - Parameters
private let locationManager = CLLocationManager()
private(set) var isEnabled: Bool = false
// Coordinates debouncer
private let userLocationDebouncer = Debouncer<CLLocationCoordinate2D?>()
// MARK: - Init
override init() {
super.init()
self.locationManager.distanceFilter = 5
self.locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters
self.locationManager.pausesLocationUpdatesAutomatically = false
self.locationManager.delegate = self
self.authorizationStatus = self.locationManager.authorizationStatus
self.addListeners()
}
deinit {
self.userLocationDebouncer.cancel()
}
private func addListeners() {
self.userLocationDebouncer.debounce(for: .seconds(4), scheduler: DispatchQueue.main) { newCoordinates in
self.currentCoordinate = newCoordinates
}
}
// MARK: - Structures
internal enum UserLocationError: Error {
case notEnabled
case needAskUserPermission
case userDidNotAllowed
}
// MARK: - Public access
public func askUserPermissionForWhenInUseAuthorizationIfNeeded() {
self.locationManager.requestWhenInUseAuthorization()
}
// MARK: - Internal
@discardableResult
internal func startUpdatingLocation() -> UserLocationError? {
if !isEnabled {
print("ERROR: location service is not enabled")
return .notEnabled
}
let status = self.locationManager.authorizationStatus
if (status == .denied || status == .restricted) {
// show alert to user telling them they need to allow location data to use some feature of your app
return .userDidNotAllowed
}
// if haven't show location permission dialog before, show it to user
if status == .notDetermined {
self.locationManager.requestAlwaysAuthorization()
// if you want the app to retrieve location data even in background, use requestAlwaysAuthorization
// self.locationManager.requestAlwaysAuthorization()
return .needAskUserPermission
}
self.locationManager.startUpdatingLocation()
return nil
}
internal func locationManagerDidChangeAuthorizationStatus(_ manager: CLLocationManager, status: CLAuthorizationStatus) {
print("location manager authorization status changed")
switch status {
case .authorizedAlways:
print("user allow app to get location data when app is active or in background")
self.startUpdatingLocation()
case .authorizedWhenInUse:
print("user allow app to get location data only when app is active")
self.startUpdatingLocation()
case .denied:
print("user tap 'disallow' on the permission dialog, cant get location data")
// Clear current coordinate if user have denied location
self.currentCoordinate = nil
case .restricted:
print("parental control setting disallow location data")
// Clear current coordinate if user have denied location
self.currentCoordinate = nil
case .notDetermined:
print("the location permission dialog haven't shown before, user haven't tap allow/disallow")
// Clear current coordinate if user have denied location
self.currentCoordinate = nil
@unknown default:
print("ERROR: Unhendeled CLLocationManager Authorization status")
}
// Only update if status changed
if status != self.authorizationStatus {
self.authorizationStatus = status
}
}
}
extension UserLocationService: CLLocationManagerDelegate {
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
if let clLocation = locations.last {
if clLocation.horizontalAccuracy <= manager.desiredAccuracy {
if let oldLocation = self.currentCoordinate {
let distance = oldLocation.distance(to: clLocation.coordinate)
// We will only update the user location if the position change for at least 5 meters
guard distance > 5 else { return }
// Sent to debouncer to handle updates
self.userLocationDebouncer.send(clLocation.coordinate)
return
}
}
if self.currentCoordinate == nil {
// If this is the first fetch we just assign the values directly
self.currentCoordinate = clLocation.coordinate
}
}
}
@available(iOS 14.0, *)
func locationManagerDidChangeAuthorization(_ manager: CLLocationManager) {
self.isEnabled = manager.authorizationStatus != .denied && manager.authorizationStatus != .restricted
self.locationManagerDidChangeAuthorizationStatus(manager, status: manager.authorizationStatus)
}
}
extension CLAuthorizationStatus {
// Check is current status allow any type of location tracking
var permissionForLocationTrackingGranted: Bool {
switch self {
case .authorizedAlways, .authorizedWhenInUse:
return true
default: return false
}
}
} |
package mapStorage
import (
"fmt"
"github.com/Refreezer/dnd-util-bot/api"
"sync"
)
type balanceBucketKey struct {
chatId int64
userId int64
}
type MapStorage struct {
rwMutex *sync.RWMutex
userNameToUserId map[string]int64
chatIdUserIdToBalance map[balanceBucketKey]uint
}
func (m *MapStorage) IsRegistered(chatId int64, userId int64) (bool, error) {
m.rwMutex.RLock()
defer m.rwMutex.RUnlock()
_, ok := m.chatIdUserIdToBalance[balanceBucketKey{chatId, userId}]
return ok, nil
}
func NewMapStorage() *MapStorage {
return &MapStorage{
rwMutex: new(sync.RWMutex),
userNameToUserId: make(map[string]int64),
chatIdUserIdToBalance: make(map[balanceBucketKey]uint),
}
}
func (m *MapStorage) MoveMoneyFromUserToUser(chatId int64, fromId int64, toId int64, amount uint) error {
m.rwMutex.Lock()
defer m.rwMutex.Unlock()
fromKey := balanceBucketKey{chatId, fromId}
fromBalance, ok := m.chatIdUserIdToBalance[fromKey]
if !ok {
return api.ErrorNotRegistered
}
if fromBalance < amount {
return api.ErrorInsufficientMoney
}
toKey := balanceBucketKey{chatId, toId}
toBalance, ok := m.chatIdUserIdToBalance[toKey]
if !ok {
return api.ErrorNotRegistered
}
m.chatIdUserIdToBalance[fromKey] = fromBalance - amount
m.chatIdUserIdToBalance[toKey] = amount + toBalance
return nil
}
func (m *MapStorage) SetUserBalance(chatId int64, userId int64, amount uint) error {
m.rwMutex.Lock()
defer m.rwMutex.Unlock()
m.chatIdUserIdToBalance[balanceBucketKey{chatId, userId}] = amount
return nil
}
func (m *MapStorage) GetUserBalance(chatId int64, userId int64) (uint, error) {
m.rwMutex.RLock()
defer m.rwMutex.RUnlock()
balance, ok := m.chatIdUserIdToBalance[balanceBucketKey{chatId, userId}]
if !ok {
return 0, fmt.Errorf("no wallet for %d", userId)
}
return balance, nil
}
func (m *MapStorage) GetIdByUserName(userName string) (userId int64, ok bool) {
m.rwMutex.RLock()
defer m.rwMutex.RUnlock()
userId, ok = m.userNameToUserId[userName]
return userId, ok
}
func (m *MapStorage) SaveUserNameToUserIdMapping(userName string, userId int64) error {
m.rwMutex.Lock()
defer m.rwMutex.Unlock()
m.userNameToUserId[userName] = userId
return nil
} |
# LFRC19.github.io
Project WebSite
# EL GRANO DE ORO
## Descripción
Este repositorio contiene el código fuente de un sitio web llamado "El Grano de Oro", que se centra en la venta de productos cárnicos, incluyendo carne de res, cerdo, pollo, mariscos, embutidos y quesos. El sitio utiliza HTML y CSS para la estructura y estilo, y se espera que los productos se carguen dinámicamente mediante JavaScript.
## Estructura del Proyecto
- **index.html**: Archivo principal que define la estructura del sitio web.
- **styles.css**: Hoja de estilo que proporciona el diseño visual del sitio.
- **Recursos/nico.ico**: Icono utilizado en la cabecera del sitio.
## Familias de Productos
### 1. Carne de Res
- **Chuletas**
- **Cortes Finos**
- **Costillas**
- **Pulpas**
- **Chamorro**
- **Espinazo**
- **Milanesas**
- **Pata**
- **Pecho**
- **Suadero**
- **Tripas**
- **Cabezas**
- **Carne Molida**
- **Carne Seca**
- **Hueso**
- **Arrachera**
- **Menudo**
- **Otros**
- **Diezmillo**
- **Pescuezo**
- **Platanillo**
### 2. Cerdo
- **Chuletas de Cerdo**
- **Costillas de Cerdo**
- **Chamorro de Cerdo**
- **Buche de Cerdo**
- **Espinazo de Cerdo**
- **Manitas de Cerdo**
- **Pecho de Cerdo**
- **Pic Nic de Cerdo**
- **Pierna de Cerdo**
- **Punta de Cerdo**
- **Tocino de Cerdo**
- **Tripas de Cerdo**
- **Cabezas de Cerdo**
- **Chicharron Prensado de Cerdo**
- **Cuero de Cerdo**
- **Otros de Cerdo**
- **Lomo de Cerdo**
### 3. Pollo
- **Alitas**
- **Pechugas de Pollo**
- **Milanesas de Pollo**
- **Pierna de Pollo**
- **Fajitas de Pollo**
- **Otros de Pollo**
### 4. Mariscos
- **Camarón**
- **Filetes**
- **Almeja**
- **Atún**
- **Marlin**
- **Pulpos**
### 5. Embutidos
- **Jamones**
- **Salchichas**
- **Pepperoni**
### 6. Quesos
- **Chester**
- **Chihuahua**
- **Cotija**
- **Cincho**
- **Fresco**
## Uso
El sitio web utiliza clases y estructuras HTML para organizar los diferentes productos. Los productos dentro de cada categoría se cargan dinámicamente mediante JavaScript.
### Actualizacion 1.0.0
Reporte de Actualización
Cambios Estéticos en Imágenes de Cabecera:
Se realizaron mejoras visuales en las imágenes de cabecera para proporcionar una apariencia más atractiva. Se agregó un efecto de escala y sombra al pasar el ratón sobre las imágenes, mejorando la experiencia visual.
Mejoras al Encabezado:
Se implementaron cambios en el encabezado para mejorar la estética y la interactividad. Se añadió una imagen de fondo con propiedades de ajuste y posición. Se aplicó un efecto de sombra al hacer scroll hacia abajo. Además, se introdujo un nuevo elemento con animaciones al pasar el ratón para agregar dinamismo al encabezado.
Estilos Adicionales para Familias:
Se realizaron modificaciones en los estilos de las secciones de familias. Se añadió un fondo semitransparente para mejorar la legibilidad del texto. Al pasar el ratón sobre las secciones de familias, se aplicó un efecto de superposición de color. Además, se asignaron imágenes de fondo específicas para cada familia, mejorando la representación visual de las secciones.
Estos cambios se implementaron con el objetivo de proporcionar una experiencia más agradable y atractiva para los usuarios.
### Actualizacion 1.0.1
Cambios Realizados:
Se agregaron las siguientes funciones:
Sección Final - Redes Sociales:
Se añadieron íconos y enlaces a las redes sociales (Facebook, Pagina Principal GDO).
Se utilizó la clase .social-buttons para alinear los botones horizontalmente.
Se proporcionó un ejemplo básico de cómo agregar más botones según sea necesario.
Sección Final - Formulario de Suscripción:
Se agregó un formulario de suscripción básico con campos para el correo electrónico y un botón de suscripción.
Sección Final - Enlaces Adicionales:
Se añadieron enlaces adicionales con una estructura de lista para Términos de Servicio y Política de Privacidad.
Se incluyó una sección de recursos con enlaces a un blog y una sección de Preguntas Frecuentes (FAQ).
Sección Final - Ubicación y Mapa:
Se creó una sección para la ubicación con un enlace clickeable y un mapa interactivo (imagen simulada).
El texto "Nuestra ubicación:" ahora redirige al enlace de ubicación en Google Maps.
Se proporcionó un tamaño ajustable para la imagen del mapa.
Estilos CSS Adicionales:
Se aplicaron estilos para mejorar la apariencia y legibilidad de la sección final.
Se introdujo la clase .location-text para personalizar el color del texto de ubicación.
Modificación para Texto Blanco en la Ubicación:
Se modificó el código para asegurar que el texto "Nuestra ubicación:" tenga color blanco.
Se agregó un selector más específico .map p a para aplicar el color blanco solo al texto de ubicación.
Observaciones:
Las ultimas modificaciones solo han sido esteticas dado que el esqueleto funcional quedo finalizado desde la version beta, la funcionalidad queda definida desde arriba por lo que en caso de requerir realizar algun cambio las lineas de codigo tanto en HTML, CSS y Javascript son intuitivas y cuentan con sus respectivas narraciones para facilitar la comprension.
Proximas versiones:
-Se trabajara en lo estetico en toda la actualizacion 1.#.#, será hasta la version 2.#.# que se trabajara en un sistema de busqueda y calculo del precio de los articulos seleccionados por un "checkBox" para faciliar el uso para el cliente, la opcion de actualizaciones no guarda los correos hasta que se encuentre una funcionalidad para ellos, y la actualizacion mayor sera el migrar el sistema de productos para que en lugar de actualizarse a mano se puedan insertar por medio de una aplicacion o pagina externa la cual se conectara a una base de datos al igual que esta aplicacion que recibira dichos precios por medio de una API.
## Licencia
Este proyecto se distribuye bajo la licencia del Grupo industrial Corral. |
"use client";
import React from "react";
import Link from "next/link";
import {
Table,
TableBody,
TableCaption,
TableCell,
TableHead,
TableHeader,
TableRow
} from "@/components/ui/table";
import { HoverCard, HoverCardContent, HoverCardTrigger } from "@/components/ui/hover-card";
import { Badge } from "@/components/ui/badge";
import { motion } from "framer-motion";
import { projects } from "@/data";
import Description from "@/components/description";
const Project = () => {
return (
<motion.section
initial={{ opacity: 0, translateY: 20 }}
animate={{ opacity: 1, translateY: 0 }}
className="mb-5 mt-10"
>
<Description label="What have I done" desc="Some of my hobby projects" />
<Table className="table-auto">
<TableCaption>A list of your recent projects.</TableCaption>
<TableHeader>
<TableRow className="text-left">
<TableHead>Project</TableHead>
<TableHead className="hidden sm:table-cell">Description</TableHead>
<TableHead className="text-center">Open Source</TableHead>
<TableHead>GitHub</TableHead>
<TableHead className="px-2 text-right">Live</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{projects.map(project => (
<TableRow key={project.title}>
<TableCell className="pr-0 text-left font-medium ">{project.title}</TableCell>
<TableCell className="hidden max-w-prose cursor-pointer truncate pb-0 font-medium sm:block md:max-w-prose-xl">
<HoverCard>
<HoverCardTrigger>{project.desc}</HoverCardTrigger>
<HoverCardContent className="hidden w-full lg:block">
{project.desc}
</HoverCardContent>
</HoverCard>
</TableCell>
<TableCell className="hidden flex-1 gap-1 md:flex">
{project.tech.map(tech => (
<Badge className="mr-1 shrink-0 last:mr-0" variant={"outline"} key={tech}>
{tech}
</Badge>
))}
</TableCell>
<TableCell className="px-3 text-center">
{project.isOpenSource === "true" ? "🟢" : ""}
</TableCell>
<TableCell>
<Link target={"_blank"} className="hover:underline" href={project.github}>
Repo
</Link>
</TableCell>
<TableCell className="px-2 text-right">
<Link target={"_blank"} className="hover:underline" href={project.link}>
Link
</Link>
</TableCell>
</TableRow>
))}
</TableBody>
</Table>
</motion.section>
);
};
export default Project; |
import React from "react";
import {
Carousel,
CarouselContent,
CarouselItem,
CarouselNext,
CarouselPrevious,
} from "@/components/ui/carousel";
import { Card, CardContent, CardTitle } from "@/components/ui/card";
const travels = [
{
image: "/ampera.jpg",
title: "Ampera Bridge",
},
{
image: "/bkb.png",
title: "BKB",
},
{
image: "/ki.jpg",
title: "JSC",
},
{
image: "/amanzi.png",
title: "Amanzi Waterpark",
},
{
image: "/kemaro.jpg",
title: "Kemaro Island",
},
{
image: "/monpera.jpg",
title: "Monpera",
},
];
function Travel({ title }) {
return (
<div className="w-4/5 mx-auto mt-32 flex flex-col">
<div className="flex justify-between">
<div>
<h1 className="font-bold text-3xl">
{title ? title : "Explore Palembang"}
</h1>
</div>
<div className="max-w-[40rem]">
<p
style={{
fontFamily: "Avenir",
}}
className="text-md"
>
You need inspiration for tourist destinations in Palembang. Check
out some captivating spots to explore during your visit.
</p>
</div>
</div>
<div className="relative my-32">
<Carousel>
<CarouselContent>
{travels.map((travel, index) => (
<CarouselItem key={index + 1} className="basis-1/3">
<Card>
<div className="relative w-full h-96">
<img
src={travel.image}
alt=""
className="w-full z-0 h-96 object-cover rounded-lg"
/>
<p className="text-white z-10 text-2xl absolute bottom-1 right-2">
{travel.title}
</p>
</div>
</Card>
</CarouselItem>
))}
</CarouselContent>
<div className="absolute top-[-2rem] right-10">
<CarouselPrevious />
<CarouselNext />
</div>
</Carousel>
</div>
</div>
);
}
export default Travel; |
import { render } from "@testing-library/react";
import { fireBlurEvent, fireChangeEvent, fireClickEvent, fireFocusEvent, withIntlProvider } from "tests/utils";
import Input, { Props } from "..";
describe("common", () => {
describe("components", () => {
describe("Input", () => {
const testId = "input";
const renderComponent = (props: Partial<Props> = {}) => {
const {
containerClassName,
label = "",
value,
max,
error,
helperMessage,
required,
type,
withPasswordLookup,
onChange = jest.fn(),
onBlur,
} = props;
return render(
withIntlProvider(
<Input
data-testid={testId}
containerClassName={containerClassName}
label={label}
value={value}
max={max}
error={error}
helperMessage={helperMessage}
required={required}
type={type}
withPasswordLookup={withPasswordLookup}
onChange={onChange}
onBlur={onBlur}
/>
)
);
};
it("Should use container class name when provided.", () => {
// given
const containerClassName = "container";
// when
const { getByTestId } = renderComponent({ containerClassName });
// then
expect(getByTestId(`${testId}__container`)).toHaveClass(containerClassName);
});
it("Should add 'focused' class modifier to the container when input is focused.", () => {
// given
const { getByTestId } = renderComponent();
// when
fireFocusEvent(getByTestId(testId));
// then
expect(getByTestId(`${testId}__container`)).toHaveClass("input__container--focused");
});
it("Should add 'error' modifier to container class when error is defined.", () => {
// given & when
const { getByTestId } = renderComponent({ error: "error" });
// then
expect(getByTestId(`${testId}__container`)).toHaveClass("input__container--error");
});
it("Should render label.", () => {
// given
const label = "label";
// when
const { getByTestId } = renderComponent({ label });
// then
expect(getByTestId(`${testId}__label`)).toHaveTextContent(label);
});
it("Should add 'floating' class to the label when input is focused.", () => {
// given
const { getByTestId } = renderComponent({ label: "label" });
// when
fireFocusEvent(getByTestId(testId));
// then
expect(getByTestId(`${testId}__label`)).toHaveClass("input__label--floating");
});
it("Should add 'floating' class to the label when input's value is defined.", () => {
// given & when
const { getByTestId } = renderComponent({ value: "value" });
// then
expect(getByTestId(`${testId}__label`)).toHaveClass("input__label--floating");
});
it("Should add 'focused' class to the label when input is focused.", () => {
// given
const { getByTestId } = renderComponent({ label: "label" });
// when
fireFocusEvent(getByTestId(testId));
// then
expect(getByTestId(`${testId}__label`)).toHaveClass("input__label--focused");
});
it("Should add '*' to the label if required flag is set.", () => {
// given
const label = "label";
const required = true;
// when
const { getByTestId } = renderComponent({ label, required });
// then
expect(getByTestId(`${testId}__label`)).toHaveTextContent(`${label}*`);
});
it("Should render value in input.", () => {
// given
const value = "value";
// when
const { getByTestId } = renderComponent({ value });
// then
expect(getByTestId(testId)).toHaveValue(value);
});
it("Should have 'password' when provided type is 'password' and password lookup is not active.", () => {
// given
const type = "password";
// when
const { getByTestId } = renderComponent({ type });
// then
expect(getByTestId(testId)).toHaveAttribute("type", type);
});
it("Should render password lookup button when provided type is 'password' and withPasswordLookup flag is set.", () => {
// given
const type = "password";
const withPasswordLookup = true;
// when
const { getByTestId } = renderComponent({ type, withPasswordLookup });
// then
expect(getByTestId(`${testId}__password-lookup`)).toBeInTheDocument();
});
it("Should have 'text' type when provided type is 'password' and password lookup button gets clicked.", () => {
// given
const type = "password";
const withPasswordLookup = true;
const { getByTestId } = renderComponent({ type, withPasswordLookup });
// when
fireClickEvent(getByTestId(`${testId}__password-lookup`));
// then
expect(getByTestId(testId)).toHaveAttribute("type", "text");
});
it("Should render error message.", () => {
// given
const error = "error";
// when
const { getByTestId } = renderComponent({ error });
// then
expect(getByTestId(`${testId}__error-message`)).toHaveTextContent(error);
});
it("Should render helper message.", () => {
// given
const helperMessage = "helper";
// when
const { getByTestId } = renderComponent({ helperMessage });
// then
expect(getByTestId(`${testId}__helper-message`)).toHaveTextContent(helperMessage);
});
it("Should render required message when required flag is set.", () => {
// given
const required = true;
// when
const { getByTestId } = renderComponent({ required });
// then
expect(getByTestId(`${testId}__required-message`)).toBeInTheDocument();
});
it("Should render message placeholder when error and helperMessage are not defined and required flag is not set.", () => {
// given & when
const { getByTestId } = renderComponent();
// then
expect(getByTestId(`${testId}__message-placeholder`)).toBeInTheDocument();
});
it("Should fire onChange callback when text gets typed into the input.", () => {
// given
const value = "text";
const onChange = jest.fn();
const { getByTestId } = renderComponent({ onChange });
// when
fireChangeEvent(getByTestId(testId), value);
// then
expect(onChange).toHaveBeenCalledWith(value);
});
it("Should fire onBlur callback input gets blurred.", () => {
// given
const onBlur = jest.fn();
const { getByTestId } = renderComponent({ onBlur });
// when
fireBlurEvent(getByTestId(testId));
// then
expect(onBlur).toHaveBeenCalled();
});
});
});
}); |
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* 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.
*/
#include "fd_holder.h"
#include <stdio.h>
#include <errno.h>
#include "beget_ext.h"
#include "fd_holder_internal.h"
#include "init_utils.h"
#include "securec.h"
static int BuildClientSocket(void)
{
int sockFd;
sockFd = socket(AF_UNIX, SOCK_DGRAM | SOCK_CLOEXEC, 0);
if (sockFd < 0) {
BEGET_LOGE("Failed to build socket, err = %d", errno);
return -1;
}
struct sockaddr_un addr;
(void)memset_s(&addr, sizeof(addr), 0, sizeof(addr));
addr.sun_family = AF_UNIX;
if (strncpy_s(addr.sun_path, sizeof(addr.sun_path), INIT_HOLDER_SOCKET_PATH,
strlen(INIT_HOLDER_SOCKET_PATH)) != 0) {
BEGET_LOGE("Failed to build socket path");
close(sockFd);
return -1;
}
socklen_t len = (socklen_t)(offsetof(struct sockaddr_un, sun_path) + strlen(addr.sun_path) + 1);
if (connect(sockFd, (struct sockaddr *)&addr, len) < 0) {
BEGET_LOGE("Failed to connect to socket, err = %d", errno);
close(sockFd);
return -1;
}
return sockFd;
}
STATIC int BuildSendData(char *buffer, size_t size, const char *serviceName, bool hold, bool poll)
{
if (buffer == NULL || size == 0 || serviceName == 0) {
return -1;
}
if (!hold && poll) {
BEGET_LOGE("Get fd with poll set, invalid parameter");
return -1;
}
char *holdString = ACTION_HOLD;
if (!hold) {
holdString = ACTION_GET;
}
char *pollString = WITHPOLL;
if (!poll) {
pollString = WITHOUTPOLL;
}
if (snprintf_s(buffer, size, size - 1, "%s|%s|%s", serviceName, holdString, pollString) == -1) {
BEGET_LOGE("Failed to build send data");
return -1;
}
return 0;
}
static int ServiceSendFds(const char *serviceName, int *fds, int fdCount, bool doPoll)
{
int sock = BuildClientSocket();
if (sock < 0) {
return -1;
}
struct iovec iovec = {};
struct msghdr msghdr = {
.msg_iov = &iovec,
.msg_iovlen = 1,
};
char sendBuffer[MAX_FD_HOLDER_BUFFER] = {};
if (BuildSendData(sendBuffer, sizeof(sendBuffer), serviceName, true, doPoll) < 0) {
BEGET_LOGE("Failed to build send data");
close(sock);
return -1;
}
BEGET_LOGV("Send data: [%s]", sendBuffer);
iovec.iov_base = sendBuffer;
iovec.iov_len = strlen(sendBuffer);
if (BuildControlMessage(&msghdr, fds, fdCount, true) < 0) {
BEGET_LOGE("Failed to build control message");
if (msghdr.msg_control != NULL) {
free(msghdr.msg_control);
}
msghdr.msg_controllen = 0;
close(sock);
return -1;
}
if (TEMP_FAILURE_RETRY(sendmsg(sock, &msghdr, MSG_NOSIGNAL)) < 0) {
BEGET_LOGE("Failed to send fds to init, err = %d", errno);
if (msghdr.msg_control != NULL) {
free(msghdr.msg_control);
}
msghdr.msg_controllen = 0;
close(sock);
return -1;
}
if (msghdr.msg_control != NULL) {
free(msghdr.msg_control);
}
msghdr.msg_controllen = 0;
BEGET_LOGI("Send fds done");
close(sock);
return 0;
}
int ServiceSaveFd(const char *serviceName, int *fds, int fdCount)
{
// Sanity checks
if (serviceName == NULL || fds == NULL ||
fdCount < 0 || fdCount > MAX_HOLD_FDS) {
BEGET_LOGE("Invalid parameters");
return -1;
}
return ServiceSendFds(serviceName, fds, fdCount, false);
}
int ServiceSaveFdWithPoll(const char *serviceName, int *fds, int fdCount)
{
// Sanity checks
if (serviceName == NULL || fds == NULL ||
fdCount < 0 || fdCount > MAX_HOLD_FDS) {
BEGET_LOGE("Invalid parameters");
return -1;
}
return ServiceSendFds(serviceName, fds, fdCount, true);
}
int *ServiceGetFd(const char *serviceName, size_t *outfdCount)
{
if (serviceName == NULL || outfdCount == NULL) {
BEGET_LOGE("Invalid parameters");
return NULL;
}
char path[MAX_FD_HOLDER_BUFFER] = {};
int ret = snprintf_s(path, MAX_FD_HOLDER_BUFFER, MAX_FD_HOLDER_BUFFER - 1, ENV_FD_HOLD_PREFIX"%s", serviceName);
BEGET_ERROR_CHECK(ret > 0, return NULL, "Failed snprintf_s err=%d", errno);
const char *value = getenv(path);
if (value == NULL) {
BEGET_LOGE("Cannot get env %s\n", path);
return NULL;
}
char fdBuffer[MAX_FD_HOLDER_BUFFER] = {};
ret = strncpy_s(fdBuffer, MAX_FD_HOLDER_BUFFER - 1, value, strlen(value));
BEGET_ERROR_CHECK(ret == 0, return NULL, "Failed strncpy_s err=%d", errno);
BEGET_LOGV("fds = %s", fdBuffer);
int fdCount = 0;
char **fdList = SplitStringExt(fdBuffer, " ", &fdCount, MAX_HOLD_FDS);
if (fdList == NULL) {
BEGET_LOGE("Cannot get fd list");
return NULL;
}
int *fds = calloc((size_t)fdCount, sizeof(int));
if (fds == NULL) {
BEGET_LOGE("Allocate memory for fd failed. err = %d", errno);
FreeStringVector(fdList, fdCount);
*outfdCount = 0;
return NULL;
}
bool encounterError = false;
for (int i = 0; i < fdCount; i++) {
errno = 0;
fds[i] = (int)strtol(fdList[i], NULL, DECIMAL_BASE);
if (errno != 0) {
BEGET_LOGE("Failed to convert \' %s \' to fd number", fdList[i]);
encounterError = true;
break;
}
}
if (encounterError) {
free(fds);
fds = NULL;
fdCount = 0;
}
*outfdCount = fdCount;
FreeStringVector(fdList, fdCount);
return fds;
} |
import React from 'react';
import './Track.css';
class Track extends React.Component {
constructor(props) {
super(props);
this.addTrack =
this.addTrack.bind(this);
this.removeTrack =
this.removeTrack.bind(this);
}
renderAction() {
if (this.props.isRemoval) {
return (
<button
onClick={this.removeTrack}
className="Track-action">
-
</button>);
}
return (
<button
onClick={this.addTrack}
className="Track-action">
+
</button>);
}
addTrack() {
this.props.onAdd(this.props.track);
}
removeTrack() {
this.props.onRemove(this.props.track);
}
render() {
const name = this.props.track.name;
const artist = this.props.track.artist;
const album = this.props.track.album;
return (
<div className="Track">
<div className="Track-information">
<h3>{name}</h3>
<p>{artist} | {album}</p>
</div>
<div>{this.renderAction()}</div>
</div>
);
}
}
export default Track; |
/*
* Copyright (c) 2002-2018 "Neo4j,"
* Neo4j Sweden AB [http://neo4j.com]
*
* This file is part of Neo4j Enterprise Edition. The included source
* code can be redistributed and/or modified under the terms of the
* GNU AFFERO GENERAL PUBLIC LICENSE Version 3
* (http://www.fsf.org/licensing/licenses/agpl-3.0.html) with the
* Commons Clause, as found in the associated LICENSE.txt file.
*
* 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.
*
* Neo4j object code can be licensed independently from the source
* under separate terms from the AGPL. Inquiries can be directed to:
* [email protected]
*
* More information is also available at:
* https://neo4j.com/licensing/
*/
package org.neo4j.cypher.internal.compatibility.v3_4.runtime.compiled.codegen.ir
import org.neo4j.cypher.internal.compatibility.v3_4.runtime.compiled.codegen.CodeGenContext
import org.neo4j.cypher.internal.compatibility.v3_4.runtime.compiled.codegen.ir.expressions.CodeGenExpression
import org.neo4j.cypher.internal.compatibility.v3_4.runtime.compiled.codegen.spi.{LessThanEqual, MethodStructure}
case class DecreaseAndReturnWhenZero(opName: String, variableName: String, action: Instruction, startValue: CodeGenExpression)
extends Instruction {
override def init[E](generator: MethodStructure[E])(implicit context: CodeGenContext): Unit = {
startValue.init(generator)
val expression = generator.box(startValue.generateExpression(generator), startValue.codeGenType)
generator.declareCounter(variableName, expression)
generator.ifStatement(generator.checkInteger(variableName, LessThanEqual, 0L)) { onTrue =>
onTrue.returnSuccessfully()
}
action.init(generator)
}
override def body[E](generator: MethodStructure[E])(implicit context: CodeGenContext): Unit = {
action.body(generator)
generator.trace(opName) { l1 =>
l1.incrementRows()
l1.decrementInteger(variableName)
l1.ifStatement(l1.checkInteger(variableName, LessThanEqual, 0L)) { l2 =>
l2.returnSuccessfully()
}
}
}
override protected def children: Seq[Instruction] = Seq(action)
override protected def operatorId = Set(opName)
} |
---------------------------------------------
---------from code, run locally--------------
---------------------------------------------
// to run mikan locally using sbt:
sbt run -Dhttp.port=9000
// then try the examples; clientA.html with clientB.html to see if they work.
// deployable server:
// create the play.crypto.secret:
sbt playGenerateSecret
// to run mikan in production mode, first:
sbt dist
// this produces a ZIP file containing all JAR files needed to run the application
// in the ./target/universal folder
// unzip the mikan-1.0-SNAPSHOT.zip
// then
// cd to the target/universal/mikan-1.0-SNAPSHOT/bin
// make sure have permission to execute
chmod +x mikan
// "sbt dist" has produced a script called "mikan" to run the application:
mikan -Dplay.crypto.secret=thesecretkeygeneratedbyplay
---------------------------------------------
-------------mongoDB-------------------------
---------------------------------------------
// install mongoDB
//see: https://docs.mongodb.com/manual/
// make sure the mongo server is running, in a terminal:
mongod
// in another terminal, the mongo shell:
mongo
// the name of the mongo database to use
use orange
// to show what is in the database
show collections
// to create a collection
db.createCollection("accounts")
db.createCollection("clientmsg")
// to delete a collection
db.accounts.drop()
db.clientmsg.drop()
// to list what is in a collection
db.accounts.find().pretty()
db.clientmsg.find().pretty()
---------------------------------------------
----------heroku-----------------------------
---------------------------------------------
// to deploy on heroku
heroku login
Email:
Password:
// to create an app:
heroku create servermikan
> ....lots of stuff, then something like
>https://servermikan.herokuapp.com/
// to push the mikan code to heroku:
git push heroku master
>https://servermikan.herokuapp.com/
// that's it, servermikan app should be running on your heroku
// try the examples; clientA.html with clientB.html to see if they work.
// to open heroku
heroku open
// to show some logs:
heroku logs -t
// to run heroku localy:
sbt compile stage
heroku local -p 7000 // because the default port 5000 maybe already taken
to restart:
heroku restart
heroku logs -t |
import {copyFile, mkdir, readdir, readFile, rm, stat, writeFile} from "fs/promises";
import {exec} from "child_process"
import {promisify} from "util";
const inputDefinitionFile = "res/space-open-api.json";
const tempDefinitionFile = "temp/space-open-api-fixed.json";
const tempGeneratedPath = "temp/generated";
const generatedIndexFile = `${tempGeneratedPath}/index.ts`
const outputGeneratedPath = "src/generated";
async function generateClient(): Promise<void> {
console.log("preparing directories")
await stat(tempGeneratedPath).then(() => rm(tempGeneratedPath, {recursive: true})).catch(() => /* ignore */ undefined);
await stat(outputGeneratedPath).then(() => rm(outputGeneratedPath, {recursive: true})).catch(() => /* ignore */ undefined);
await mkdir(tempGeneratedPath, {recursive: true});
await mkdir(outputGeneratedPath, {recursive: true});
console.log("reading open api definition")
const definition = JSON.parse(await readFile(inputDefinitionFile, "utf8")) as { info: { version: string }, tags: { name: string }[], paths: { [key: string]: { [key: string]: { tags: string[], description: string | { text: string } } } } };
console.log("fixing open api definition format")
definition.tags = [{name: "space"}];
for (const path of Object.values(definition.paths)) {
for (const method of Object.values(path)) {
method.tags = ["space"];
if (typeof method.description !== "string" && method.description) {
method.description = method.description.text;
}
}
}
console.log("writing fixed open api definition")
await writeFile(tempDefinitionFile, JSON.stringify(definition));
console.log("generating client files")
await promisify(exec)([
"npx",
"openapi-generator-cli",
"generate",
`-i ${tempDefinitionFile}`,
"-g typescript-axios",
`-o ${tempGeneratedPath}`,
`--additional-properties=${[
"withInterfaces=true",
"nullSafeAdditionalProps=true"
].join(",")}`
].join(" "));
console.log("updating generated index file")
let indexContents = await readFile(generatedIndexFile, {encoding: "utf8"});
indexContents += `export const apiVersion = "${definition.info.version}"\n`
await writeFile(generatedIndexFile, indexContents)
console.log("moving client files")
for (const file of await readdir(tempGeneratedPath)) {
if (file.endsWith(".ts")) {
await copyFile(`${tempGeneratedPath}/${file}`, `${outputGeneratedPath}/${file}`);
}
}
}
generateClient().then(() => {
console.log("done")
}).catch(error => {
console.error("failed", error)
}); |
<?php
// Include database connection code
include('config/constants.php');
// Check if the user is logged in
if(isset($_SESSION['user'])) {
// Retrieve the username from the session
$username = $_SESSION['user'];
// Query to fetch the user information based on the username
$sql = "SELECT id FROM tbl_user WHERE username = '$username'";
$res = mysqli_query($conn, $sql);
if ($res && mysqli_num_rows($res) > 0) {
// Fetch user ID from the database result
$row = mysqli_fetch_assoc($res);
$userId = $row['id'];
// Check if the product ID is received via GET
if (isset($_GET['id'])) {
// Retrieve product ID
$productId = $_GET['id'];
// Check if the product already exists in the cart for the current user
$existingCartItemSql = "SELECT * FROM tbl_cart WHERE user_id = '$userId' AND product_id = '$productId'";
$existingCartItemResult = mysqli_query($conn, $existingCartItemSql);
if (mysqli_num_rows($existingCartItemResult) > 0) {
// If the product already exists in the cart, update the quantity
$existingCartItem = mysqli_fetch_assoc($existingCartItemResult);
$qty = $existingCartItem['qty'] + 1; // Increment the quantity by 1
$total = $existingCartItem['price'] * $qty; // Calculate the new total
// Update the quantity and total in the cart table
$updateCartItemSql = "UPDATE tbl_cart SET qty = '$qty', total = '$total' WHERE user_id = '$userId' AND product_id = '$productId'";
$updateCartItemResult = mysqli_query($conn, $updateCartItemSql);
if ($updateCartItemResult) {
// Quantity updated successfully
// Redirect back to shop.php with a success message
header('location: shop.php?added=true');
exit();
} else {
// Failed to update quantity
echo "Failed to update quantity. Please try again.";
}
} else {
// If the product does not exist in the cart, insert a new record
// Query to fetch product information based on product ID
$sql2 = "SELECT * FROM tbl_product WHERE id='$productId'";
$res2 = mysqli_query($conn, $sql2);
if ($res2 && mysqli_num_rows($res2) > 0) {
// Fetch product details
$row2 = mysqli_fetch_assoc($res2);
$title = $row2['title'];
$price = $row2['price'];
$image_name = $row2['image_name'];
$qty = 1; // Assuming the quantity is fixed to 1 for now
$total = $price * $qty; // Calculate total price
$category_id = $row2['category_id'];
// Get current date and time for created_at
$created_at = date('Y-m-d H:i:s');
// Query to insert the item into the cart
$insertCartItemSql = "INSERT INTO tbl_cart (user_id, product_id, title, price, qty, total, category_id, created_at) VALUES ('$userId', '$productId','$title','$price','$qty','$total','$category_id','$created_at')";
$insertCartItemResult = mysqli_query($conn, $insertCartItemSql);
if ($insertCartItemResult) {
// Item added to cart successfully
// Redirect back to shop.php with a success message
header('location: shop.php?added=true');
exit();
} else {
// Failed to add item to cart
echo "Failed to add item to cart. Please try again.";
}
} else {
// If the product information is not found, return an error message
echo "Error: Product information not found.";
}
}
} else {
// If the product ID is not received, return an error message
echo "Error: Product ID not received.";
}
} else {
// If the user information is not found in the database, handle the error
echo "Error: User information not found.";
}
} else {
// If the user is not logged in, redirect them to the login page
header('location: user-login.php');
exit(); // Stop further execution
}
?> |
import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { Choice } from './../Choice';
import { Message } from './../Message';
export interface Poliza {
id: number;
descripcion?: string;
fecha: string;
}
@Injectable({
providedIn: 'root'
})
export class BhPolizaServiceService {
constructor(private http: HttpClient) { }
getPoliza(apiUrl: string, id: string): Observable<Poliza> {
return this.http.get<Poliza>(apiUrl + id);
}
getQuestions(apiUrl: string): Observable<Message[]> {
return this.http.get<Message[]>(apiUrl);
}
putDialog(id, formData): Observable<Message> {
return this.http.put<Message>("https://localhost:7247/Dialog/" + id, formData);
}
postDialog(formData): Observable<Message> {
return this.http.post<Message>("https://localhost:7247/Dialog/", formData);
}
deleteDialog(id): Observable<Message> {
return this.http.delete<Message>("https://localhost:7247/Dialog/" + id);
}
getChoices(apiUrl: string): Observable<Choice[]> {
return this.http.get<Choice[]>(apiUrl);
}
putChoice(id, formData): Observable<Choice> {
return this.http.put<Choice>("https://localhost:7247/Choice/" + id, formData);
}
postChoice(formData): Observable<Choice> {
return this.http.post<Choice>("https://localhost:7247/Choice/", formData);
}
deleteChoice(id): Observable<Choice> {
return this.http.delete<Choice>("https://localhost:7247/Choice/" + id);
}
} |
import {
Breadcrumb,
BreadcrumbItem,
BreadcrumbLink,
Box,
Container,
HStack,
Heading,
Menu,
MenuButton,
MenuList,
MenuItem,
Icon,
Stack,
List,
ListItem,
} from "@chakra-ui/react";
import { BiDotsVerticalRounded } from "react-icons/bi";
import Link from "next/link";
import { useRouter } from "next/router";
const Profile = (props) => {
const router = useRouter();
return (
<Container maxW={"container.xxl"}>
<Box
as="section"
bg={"white"}
mt={{ base: "24", lg: "32" }}
mb={{ base: "6" }}
px={{ base: "3", lg: "6" }}
py={{ base: "6" }}
rounded={"xl"}
shadow={"xl"}
>
{/* breadcrumb */}
<Box>
<Breadcrumb fontSize={"lg"}>
<BreadcrumbItem>
<Link href={"/"}>
<BreadcrumbLink
color={"primary"}
textDecor={"underline"}
>
Home
</BreadcrumbLink>
</Link>
</BreadcrumbItem>
<BreadcrumbItem isCurrentPage>
{props.list.map((link, i) => {
if (router.pathname == link.href) {
return (
<Link href={link.href} key={i}>
<BreadcrumbLink
_hover={{
color: "primary",
textDecor: "underline",
}}
>
{link.name}
</BreadcrumbLink>
</Link>
);
}
})}
</BreadcrumbItem>
</Breadcrumb>
</Box>
{/* title and nav */}
<HStack
justify={{ base: "space-between" }}
align={{ base: "center" }}
mt={{ base: "3" }}
>
<Heading>Account</Heading>
<Menu>
<MenuButton display={{ lg: "none" }}>
<Icon
as={BiDotsVerticalRounded}
fontSize={"3xl"}
cursor={"pointer"}
mb={-2}
/>
</MenuButton>
<MenuList mt={2} rounded={"xl"} shadow={"xl"}>
{props.list.map((link, i) => {
return (
<Link href={link.href} key={i}>
<MenuItem>{link.name}</MenuItem>
</Link>
);
})}
</MenuList>
</Menu>
</HStack>
</Box>
{/* page */}
<Box as="section" mb={{ base: "24", lg: "32" }}>
<Box gap={{ lg: "5" }} display={{ lg: "flex" }}>
{/* left */}
<Stack
display={{ base: "none", lg: "block" }}
bg={"white"}
p={5}
rounded={"xl"}
shadow={"xl"}
fontSize={"2xl"}
height={"max-content"}
>
<List
display={"flex"}
flexDirection={"column"}
gap={4}
w={"260px"}
>
{props.list.map((link, i) => {
return (
<Link href={link.href} key={i}>
<ListItem
py={"3"}
pl={"6"}
rounded={"xl"}
transition={"all 300ms ease-in-out"}
cursor={"pointer"}
_hover={{
bg: "primary",
color: "white",
}}
{...(router.pathname ==
link.href && {
bg: "primary",
color: "white",
})}
>
{link.name}
</ListItem>
</Link>
);
})}
</List>
</Stack>
{/* right */}
<Box
bg={"white"}
flexGrow={8}
px={{ base: "3", lg: "6" }}
py={{ base: "6" }}
rounded={"xl"}
shadow={"xl"}
>
<Box>{props.children}</Box>
</Box>
</Box>
</Box>
</Container>
);
};
export default Profile; |
import { ModuleWithProviders, NgModule } from '@angular/core';
import { NgxQueryBuilderComponent } from './ngx-ntk-query-builder.component';
import { FormsModule } from '@angular/forms';
import { CommonModule } from '@angular/common';
import { HttpClient } from '@angular/common/http';
import { TranslateHttpLoader } from '@ngx-translate/http-loader';
import { TranslateLoader, TranslateModule, TranslateService } from '@ngx-translate/core';
export function CreateTranslateLoader(http: HttpClient): any {
return new TranslateHttpLoader(http, '/assets/i18n/querybuilder/', '.json');
}
@NgModule({
declarations: [
NgxQueryBuilderComponent
],
imports: [
CommonModule,
FormsModule,
TranslateModule.forRoot({
loader: {
provide: TranslateLoader,
useFactory: (CreateTranslateLoader),
deps: [HttpClient]
}
}),
],
exports: [
NgxQueryBuilderComponent
],
providers: [
TranslateService,
]
})
export class NgxNtkQueryBuilderModule {
static forRoot(): ModuleWithProviders<NgxNtkQueryBuilderModule> {
return {
ngModule: NgxNtkQueryBuilderModule,
providers: [TranslateService]
};
}
} |
package com.example.weblab2.configuration;
import com.example.weblab2.services.impl.security.GoogleOAuth2UserService;
import com.example.weblab2.services.impl.security.OAuth2FailureHandler;
import com.example.weblab2.services.impl.security.OAuth2SuccessHandler;
import java.util.Arrays;
import java.util.List;
import lombok.RequiredArgsConstructor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration;
import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configurers.CsrfConfigurer;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
@Configuration
@EnableWebSecurity
@EnableMethodSecurity // for @PreAuthorize checking
@RequiredArgsConstructor
public class SecurityConfiguration {
private final AuthEntryPoint authEntryPoint;
private final OAuth2SuccessHandler successHandler;
private final OAuth2FailureHandler failureHandler;
private final UserDetailsService userDetailsService;
// Dependencies needed for default auth with JWT:
private final AuthTokenFilter tokenFilter;
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
@Bean
public AuthenticationManager authenticationManager(
AuthenticationConfiguration authenticationConfiguration) throws Exception {
return authenticationConfiguration.getAuthenticationManager();
}
@Bean
public DaoAuthenticationProvider authenticationProvider() {
DaoAuthenticationProvider authProvider = new DaoAuthenticationProvider();
authProvider.setUserDetailsService(userDetailsService);
authProvider.setPasswordEncoder(passwordEncoder());
return authProvider;
}
private final GoogleOAuth2UserService googleOAuth2UserService;
@Bean
@Primary
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http
.cors().disable()
.csrf(CsrfConfigurer::disable)
.authorizeHttpRequests(reg ->
reg.requestMatchers(
"/albums/**",
"/rest/labels/**",
"/artists/**",
"/songs/**",
"/labels/**",
"/secure/**",
"/login/oauth2/**",
"/",
"/resources/**",
"/error",
"favicon.ico"
)
.permitAll()
.anyRequest()
.authenticated()
)
.sessionManagement(
session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
.oauth2Login(oauth2 -> oauth2
.authorizationEndpoint()
.baseUri("/login/oauth2/authorize")
.and()
.redirectionEndpoint()
.baseUri("/login/oauth2/callback/*")
.and()
.successHandler(successHandler)
.failureHandler(failureHandler)
.userInfoEndpoint(f -> f.userService(googleOAuth2UserService))
)
.authenticationProvider(authenticationProvider())
.addFilterBefore(tokenFilter, UsernamePasswordAuthenticationFilter.class)
.exceptionHandling(e -> e.authenticationEntryPoint(authEntryPoint));
return http.build();
}
@Bean
public CorsConfigurationSource corsConfigurationSource() {
CorsConfiguration configuration = new CorsConfiguration();
configuration.setAllowedOrigins(List.of("http://localhost:3000, http://localhost:8080"));
configuration.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE"));
configuration.setAllowCredentials(true);
configuration.setAllowedHeaders(
Arrays.asList("Content-Type", "content-type", "x-requested-with",
"Access-Control-Allow-Origin",
"Access-Control-Allow-Headers",
"x-auth-token",
"x-app-id", "Origin", "Accept",
"X-Requested-With",
"Access-Control-Request-Method",
"Access-Control-Request-Headers",
"Authorization"));
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", configuration);
return source;
}
} |
/* Table of contents
––––––––––––––––––––––––––––––––––––––––––––––––––
- Grid
- Base Styles
- Typography
- Links
- Code
- Spacing
- Utilities
- Misc
- Credit footer
*/
/* Grid
–––––––––––––––––––––––––––––––––––––––––––––––––– */
.container {
position: relative;
width: 100%;
max-width: 800px;
text-align: center;
margin: 0 auto;
box-sizing: border-box; }
.column {
position: center;
width: 100%;
float: center;
box-sizing: border-box; }
/* For devices larger than 400px */
@media (min-width: 400px) {
.container {
width: 95%;
padding: 0; }
}
/* For devices larger than 550px */
@media (min-width: 550px) {
.container {
width: 90%; }
.column,
.columns {
margin-left: 0; }
.column:first-child,
.columns:first-child {
margin-left: 0; }
}
/* Base Styles
–––––––––––––––––––––––––––––––––––––––––––––––––– */
/* NOTE
html is set to 62.5% so that all the REM measurements throughout Skeleton
are based on 10px sizing. So basically 1.5rem = 15px :) */
html {
font-size: 100%; }
/* Dark/light mode detection (comment this section out and use the one below for a fixed background color) */
body {
font-size: 18px;
line-height: 24px;
font-weight: 400;
background: #111;
color: #FFFFFF; }
/* Use this for a fixed background color instead of dark and light mode
body {
font-size: 18px;
line-height: 24px;
font-weight: 400;
font-family: "Open Sans", "HelveticaNeue", "Helvetica Neue", Helvetica, Arial,
sans-serif;
}
*/
/* Typography
–––––––––––––––––––––––––––––––––––––––––––––––––– */
h1 {
margin-top: 0;
margin-bottom: 16px;
letter-spacing: 5px;
font-weight: 800;
line-height: 64px;
background: -webkit-radial-gradient(#CAC895, #000000);
-webkit-background-clip: text;
-webkit-text-fill-color: transparent;
-webkit-transform-origin: 50% 100%;
-moz-transform-origin: 50% 100%;
-ms-transform-origin: 50% 100%;
-o-transform-origin: 50% 100%;
transform-origin: 50% 100%;
-webkit-transform: perspective(300px) rotateX(15deg);
-moz-transform: perspective(300px) rotateX(15deg);
-ms-transform: perspective(300px) rotateX(15deg);
-o-transform: perspective(300px) rotateX(15deg);
transform: perspective(300px) rotateX(15deg);
filter: drop-shadow(-4px 4px 3px #3f0e48);
}
/* Larger than phablet */
@media (min-width: 550px) {
h1 { font-size: 96px; line-height: 96px;}
}
p {
margin-top: 0; }
/* Links
–––––––––––––––––––––––––––––––––––––––––––––––––– */
a {
color: #e1e1e1;
text-decoration: none;
}
a:hover {
color: #e1e1e1;-webkit-filter: brightness(70%); }
.spacing {
padding: 0 10px;
}
/* Code
–––––––––––––––––––––––––––––––––––––––––––––––––– */
code {
padding: .2rem .5rem;
margin: 0 .2rem;
font-size: 90%;
white-space: nowrap;
background: #F1F1F1;
border: 1px solid #E1E1E1;
border-radius: 4px; }
pre > code {
display: block;
padding: 1rem 1.5rem;
white-space: pre; }
/* Spacing
–––––––––––––––––––––––––––––––––––––––––––––––––– */
button,
.button {
margin-bottom: 1rem; }
input,
textarea,
select,
fieldset {
margin-bottom: 1.5rem; }
pre,
blockquote,
dl,
figure,
p,
ol {
margin-bottom: 2.5rem; }
/* Utilities
–––––––––––––––––––––––––––––––––––––––––––––––––– */
.u-full-width {
width: 100%;
box-sizing: border-box; }
.u-max-full-width {
max-width: 100%;
box-sizing: border-box; }
.u-pull-right {
float: right; }
.u-pull-left {
float: left; }
/* Misc
–––––––––––––––––––––––––––––––––––––––––––––––––– */
hr {
margin-top: 3rem;
margin-bottom: 3.5rem;
border-width: 0;
border-top: 1px solid #E1E1E1; }
/* ===== Scrollbar CSS ===== */
/* Firefox */
* {
scrollbar-width: thin;
scrollbar-color: #171a1d #31363b;
}
/* Chrome, Edge, and Safari */
*::-webkit-scrollbar {
width: 8px;
}
*::-webkit-scrollbar-track {
background: #31363b;
}
*::-webkit-scrollbar-thumb {
background-color: #171a1d;
border-radius: 30px;
border: 3px none #ffffff;
}
/* Credit footer
–––––––––––––––––––––––––––––––––––––––––––––––––– */
/* Styling for credit footer text */
.credit-txt {
font-weight: 700;
font-size: 15px;
text-decoration: none;
}
.credit-icon {
display: none; }
.credit-footer {
position: relative;
right: 15px; }
/* Switches text color for credit footer for dark/light mode */
.credit-txt-clr{
color: #FFF !important;
} |
import React from 'react';
import { useQuery } from 'react-query';
import axios from 'axios';
import AuctionCard from './AuctionCard';
const AuctionCardsList = () => {
const { isLoading, data } = useQuery('auction-list', () => {
return axios.get(
'https://run.mocky.io/v3/7f02819f-8254-410a-b8af-ab98572bd26b'
);
});
if (isLoading) {
return <h2>Loading</h2>;
}
console.log(data);
return (
<div className='border-1 border rounded-xl p-2 sm:p-6 mt-6 shadow-lg'>
<div className='flex justify-between items-center pb-[24px]'>
<p className='text-gray-900 text-lg font-semibold'>Featured Items</p>
<button className='border border-1 border-gray-300 pt-[8px] pb-[8px] pl-[14px] pr-[14px] font-semibold text-sm text-gray-700 rounded-lg shadow-xs'>
View Auction
</button>
</div>
<hr className='pb-[24px]' />
<div className='grid min-[1250px]:grid-cols-4 lg:grid-cols-3 gap-6 grid-cols-1 md:grid-cols-2 sm:grid-cols-2'>
{data.data.data.map((item, i) => (
<AuctionCard key={i} item={item} />
))}
</div>
</div>
);
};
export default AuctionCardsList; |
import { getFormatedDateTimeString } from 'utils/date/getFormatedDateTimeString/getFormatedDateTimeString'
import { STRING, translate } from 'utils/language'
import { UserPermission } from 'utils/user/types'
export type ServerJob = any // TODO: Update this type
export enum JobStatus {
Created = 'created',
Pending = 'pending',
Started = 'started',
Success = 'success',
Canceling = 'canceling',
Revoked = 'revoked',
Failed = 'failed',
Unknown = 'unknown',
}
export class Job {
protected readonly _job: ServerJob
public constructor(job: ServerJob) {
this._job = job
}
get canCancel(): boolean {
return (
this._job.user_permissions.includes(UserPermission.Update) &&
this.status === JobStatus.Started
)
}
get canDelete(): boolean {
return this._job.user_permissions.includes(UserPermission.Delete)
}
get canQueue(): boolean {
return (
this._job.user_permissions.includes(UserPermission.Update) &&
this.status === JobStatus.Created
)
}
get createdAt(): string | undefined {
if (!this._job.created_at) {
return
}
return getFormatedDateTimeString({ date: new Date(this._job.created_at) })
}
get finishedAt(): string | undefined {
if (!this._job.finished_at) {
return
}
return getFormatedDateTimeString({ date: new Date(this._job.finished_at) })
}
get id(): string {
return `${this._job.id}`
}
get startedAt(): string | undefined {
if (!this._job.started_at) {
return
}
return getFormatedDateTimeString({ date: new Date(this._job.started_at) })
}
get name(): string {
return this._job.name
}
get project(): string {
return this._job.project.name
}
get status(): JobStatus {
return this.getStatus(this._job.status)
}
get statusDetails(): string {
return this._job.progress?.summary.status_label
}
get statusValue(): number {
return this._job.progress?.summary.progress ?? this._job.status
}
get statusLabel(): string {
return this.getStatusLabel(this.status)
}
protected getStatus(status: string): JobStatus {
switch (status) {
case 'CREATED':
return JobStatus.Created
case 'PENDING':
return JobStatus.Pending
case 'STARTED':
return JobStatus.Started
case 'SUCCESS':
return JobStatus.Success
case 'CANCELING':
return JobStatus.Canceling
case 'REVOKED':
return JobStatus.Revoked
case 'FAILURE':
return JobStatus.Failed
default:
return JobStatus.Unknown
}
}
protected getStatusLabel(status: JobStatus): string {
switch (status) {
case JobStatus.Created:
return translate(STRING.CREATED)
case JobStatus.Pending:
return translate(STRING.PENDING)
case JobStatus.Started:
return translate(STRING.RUNNING)
case JobStatus.Success:
return translate(STRING.DONE)
case JobStatus.Canceling:
return translate(STRING.CANCELING)
case JobStatus.Revoked:
return translate(STRING.REVOKED)
case JobStatus.Failed:
return translate(STRING.FAILED)
default:
return translate(STRING.UNKNOWN)
}
}
} |
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Schedule</title>
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css"
rel="stylesheet"
integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC"
crossorigin="anonymous">
<style>
body {
background-color: #ebebeb; /* Цвет фона */
position: relative;
}
.container {
margin-top: 20px;
border-radius: 15px; /* Округленные углы */
box-shadow: 0 0 20px rgba(0, 0, 0, 0.1); /* Тень */
padding: 20px;
background-color: #f8f9fa; /* Цвет фона контейнера */
}
.navbar {
margin-bottom: 20px;
}
.navbar-brand {
font-size: 24px;
font-weight: bold;
}
.navbar-nav {
margin-left: auto;
}
.nav-link {
font-size: 18px;
color: #ffffff; /* Цвет текста ссылок в навигационной панели */
}
.card {
margin-top: 20px;
border-radius: 15px; /* Округленные углы */
box-shadow: 0 0 20px rgba(0, 0, 0, 0.1); /* Тень */
}
.card-header {
background-color: #007bff; /* Цвет фона заголовка карточки */
color: #ffffff; /* Цвет текста заголовка карточки */
text-align: center;
padding: 10px;
border-top-left-radius: 15px;
border-top-right-radius: 15px;
}
.card-body {
padding: 20px;
}
.form-group {
margin-bottom: 20px;
}
.form-label {
font-size: 18px;
margin-bottom: 5px;
}
.form-control {
font-size: 16px;
}
.btn-primary {
font-size: 18px;
}
.footer {
margin-top: 20px;
text-align: center;
font-size: 14px;
color: #6c757d; /* Серый цвет для текста подвала */
}
</style>
</head>
<body>
<nav class="navbar navbar-expand-lg navbar-dark bg-dark">
<div class="container-fluid">
<a class="navbar-brand" th:href="@{/index}">
<i class="bi bi-slash-square"></i> Shedule
</a> <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarSupportedContent"
aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarSupportedContent">
<ul class="navbar-nav ms-auto mb-2 mb-lg-0">
<li class="nav-item">
<a class="nav-link" th:href="@{/login}" th:classappend="${#request.getRequestURI() == '/login' ? 'active' : ''}">Log in</a>
</li>
<li class="nav-item">
<a class="nav-link" th:href="@{/register}" th:classappend="${#request.getRequestURI() == '/register' ? 'active' : ''}">Sign up</a>
</li>
</ul>
</div>
</div>
</nav>
<div class="container">
<div class="row col-md-8 offset-md-2">
<div class="card">
<div class="card-header">
<h2>Registrarion</h2>
</div>
<div th:if="${param.success}">
<div class="alert alert-info">
Registration was successfull!
</div>
</div>
<div class="card-body">
<form method="post" role="form" th:action="@{/register/save}" th:object="${user}">
<div class="form-group">
<label class="form-label" for="firstName">Your name</label>
<input class="form-control" id="firstName" name="firstName" placeholder="Enter name" th:field="*{firstName}" type="text"/>
<p th:errors="*{firstName}" class="text-danger" th:if="${#fields.hasErrors('firstName')}"></p>
</div>
<div class="form-group">
<label class="form-label" for="lastName">Your surname</label>
<input class="form-control" id="lastName" name="lastName" placeholder="Enter your surname" th:field="*{lastName}" type="text"/>
<p th:errors="*{lastName}" class="text-danger" th:if="${#fields.hasErrors('lastName')}"></p>
</div>
<div class="form-group">
<label class="form-label" for="email">Email</label>
<input class="form-control" id="email" name="email" placeholder="Enter your email" th:field="*{email}" type="email"/>
<p th:errors="*{email}" class="text-danger" th:if="${#fields.hasErrors('email')}"></p>
</div>
<div class="form-group">
<label class="form-label" for="password">Password</label>
<input class="form-control" id="password" name="password" placeholder="Enter password" th:field="*{password}" type="password"/>
<p th:errors="*{password}" class="text-danger" th:if="${#fields.hasErrors('password')}"></p>
</div>
<div class="form-group">
<button class="btn btn-primary" type="submit">Sign up</button>
<span>Already registered? <a th:href="@{/login}">Log in</a></span>
</div>
</form>
</div>
</div>
</div>
</div>
</body>
</html> |
import 'package:flutter/material.dart';
import 'package:mobile_app/components/my_textfield.dart';
import 'package:mobile_app/components/my_button.dart';
import 'package:mobile_app/components/square_tile.dart';
import 'package:mobile_app/pages/loginPage.dart';
import 'package:mobile_app/pages/registration.dart';
import 'package:jwt_decoder/jwt_decoder.dart';
import 'package:shared_preferences/shared_preferences.dart';
class SettingPage extends StatefulWidget{
final token;
const SettingPage({@required this.token,Key? key}) : super(key: key);
@override
State<SettingPage> createState() => _SettingPageState();
}
class _SettingPageState extends State<SettingPage>{
late SharedPreferences prefs;
late String email;
@override
void initState(){
//ToyBot: implement initState
super.initState();
initSharedPref();
if (widget.token == null) {
// Handle the null case, e.g., redirect or show an error
} else {
// Continue with your logic
Map<String,dynamic> jwtDecodedToken = JwtDecoder.decode(widget.token);
email = jwtDecodedToken['email'];
}
}
void initSharedPref() async {
prefs = await SharedPreferences.getInstance();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
leading: IconButton(
icon: Icon(Icons.arrow_back, color: Colors.white),
onPressed: () => Navigator.of(context).pop(),
),
title: Text('SETTINGS'),
backgroundColor: Colors.transparent,
elevation: 0,
actions: [
IconButton(
icon: Icon(Icons.more_vert, color: Colors.white),
onPressed: () {
// Open more options
},
),
],
),
extendBodyBehindAppBar: true,
body: Container(
decoration: BoxDecoration(
gradient: LinearGradient(
begin: Alignment.topRight,
end: Alignment.bottomLeft,
colors: [
Colors.purple.shade700,
Colors.purple.shade400,
],
),
),
child: ListView(
children: [
ListTile(
title: Text('Your Profile & Family', style: TextStyle(color: Colors.white)),
onTap: () {
// Navigate to Profile & Family settings
},
),
ListTile(
title: Text('Account Settings', style: TextStyle(color: Colors.white)),
onTap: () {
// Navigate to Account settings
},
),
ListTile(
title: Text('Device Settings', style: TextStyle(color: Colors.white)),
onTap: () {
// Navigate to Device settings
},
),
ListTile(
title: Text('App Settings', style: TextStyle(color: Colors.white)),
onTap: () {
// Navigate to App settings
},
),
],
),
),
bottomNavigationBar: BottomNavigationBar(
backgroundColor: Colors.transparent,
items: [
BottomNavigationBarItem(
icon: Icon(Icons.home),
label: 'Home',
backgroundColor: Colors.transparent,
),
BottomNavigationBarItem(
icon: Icon(Icons.store),
label: 'App Store',
),
BottomNavigationBarItem(
icon: Icon(Icons.devices),
label: 'Devices',
),
BottomNavigationBarItem(
icon: Icon(Icons.more_horiz),
label: 'More',
),
],
),
);
}
void logout() async{
print('logout');
prefs.remove('token');
Navigator.push(
context,
MaterialPageRoute(builder: (context) => LoginPage()),
);
}
} |
# 【事件对象与鼠标事件】
> 这里只是通过鼠标事件简单了解一下事件对象,后续会有专门的章节结合事件传播讲解事件对象
## 1.什么是事件对象
**任意事件类型被触发时与事件相关的信息会被以对象的形式记录下来**,我们称这个对象为事件对象。
这个参数通常用单词 `event` 或字母 `e` 来表示。
```
oBox.onmousemove = function(e) {
// 对象 e 就是这次事件的“事件对象”
}
```
> 这个对象 e 接受的值由浏览器或操作系统传递。
**Event.type**
`Event.type`属性返回一个字符串,表示事件类型。事件的类型是在生成事件的时候指定的。该属性只读。
## 2.鼠标位置
| 属性 | 属性描述 |
| --------- | ------------------------------------------------------------ |
| `clientX` | 鼠标指针相对于浏览器的水平坐标,默认值为0,设置该属性不会移动鼠标。 |
| `clientY` | 鼠标指针相对于浏览器的垂直坐标,其他与`clientX`相同。 |
| `pageX` | 鼠标指针相对于整张网页的水平坐标 |
| `pageY` | 鼠标指针相对于整张网页的垂直坐标,这两个属性都是只读。 |
| `offsetX` | 鼠标指针相对于目标节点左侧的`padding`边缘的水平距离(单位像素) |
| `offsetY` | 鼠标指针相对于目标节点上方的`padding`边缘的垂直距离,这两个属性都是只读属性。 |
### 2.1 clientX clientY

### 2.2 pageX pageY

### 2.3 offsetX offsetY

### 【注意事项】
对于 offsetX 和 offsetY 而言,总是以最内层元素为事件源。
> 所以应避免事件源盒子内部有小盒子的存在。
## 3.鼠标事件的种类
鼠标事件主要有下面这些,所有事件都继承了`MouseEvent`接口(详见后文)。
### 3.1 点击事件
鼠标点击相关的有四个事件。
- `click`:按下鼠标(通常是按下主按钮)时触发。
- `dblclick`:在同一个元素上双击鼠标时触发。
- `mousedown`:按下鼠标键时触发。
- `mouseup`:释放按下的鼠标键时触发。
`click`事件可以看成是两个事件组成的:用户在同一个位置先触发`mousedown`,再触发`mouseup`。因此,触发顺序是,`mousedown`首先触发,`mouseup`接着触发,`click`最后触发。
双击时,`dblclick`事件则会在`mousedown`、`mouseup`、`click`之后触发。
### 3.2 移动事件
鼠标移动相关的有五个事件。
- `mousemove`:当鼠标在一个节点内部移动时触发。当鼠标持续移动时,该事件会连续触发。为了避免性能问题,建议对该事件的监听函数做一些限定,比如限定一段时间内只能运行一次。
- `mouseenter`:鼠标进入一个节点时触发,进入子节点不会触发这个事件(详见后文)。
- `mouseover`:鼠标进入一个节点时触发,进入子节点会再一次触发这个事件(详见后文)。
- `mouseout`:鼠标离开一个节点时触发,离开子节点也会触发这个事件(详见后文)。
- `mouseleave`:鼠标离开一个节点时触发,离开子节点不会触发这个事件(详见后文)。
`mouseover`事件和`mouseenter`事件,都是鼠标进入一个节点时触发。两者的区别是,`mouseenter`事件只触发一次,而只要鼠标在节点内部移动,`mouseover`事件会在子节点上触发多次。
```JavaScript
/* HTML 代码如下
<ul>
<li>item 1</li>
<li>item 2</li>
<li>item 3</li>
</ul>
*/
var ul = document.querySelector('ul');
// 进入 ul 节点以后,mouseenter 事件只会触发一次
// 以后只要鼠标在节点内移动,都不会再触发这个事件
// event.target 是 ul 节点
ul.addEventListener('mouseenter', function (event) {
event.target.style.color = 'purple';
setTimeout(function () {
event.target.style.color = '';
}, 500);
}, false);
// 进入 ul 节点以后,只要在子节点上移动,mouseover 事件会触发多次
// event.target 是 li 节点
ul.addEventListener('mouseover', function (event) {
event.target.style.color = 'orange';
setTimeout(function () {
event.target.style.color = '';
}, 500);
}, false);
```
上面代码中,在父节点内部进入子节点,不会触发`mouseenter`事件,但是会触发`mouseover`事件。
`mouseout`事件和`mouseleave`事件,都是鼠标离开一个节点时触发。两者的区别是,在父元素内部离开一个子元素时,`mouseleave`事件不会触发,而`mouseout`事件会触发。
```JavaScript
/* HTML 代码如下
<ul>
<li>item 1</li>
<li>item 2</li>
<li>item 3</li>
</ul>
*/
var ul = document.querySelector('ul');
// 先进入 ul 节点,然后在节点内部移动,不会触发 mouseleave 事件
// 只有离开 ul 节点时,触发一次 mouseleave
// event.target 是 ul 节点
ul.addEventListener('mouseleave', function (event) {
event.target.style.color = 'purple';
setTimeout(function () {
event.target.style.color = '';
}, 500);
}, false);
// 先进入 ul 节点,然后在节点内部移动,mouseout 事件会触发多次
// event.target 是 li 节点
ul.addEventListener('mouseout', function (event) {
event.target.style.color = 'orange';
setTimeout(function () {
event.target.style.color = '';
}, 500);
}, false);
```
上面代码中,在父节点内部离开子节点,不会触发`mouseleave`事件,但是会触发`mouseout`事件。
(3)其他事件
- `contextmenu`:按下鼠标右键时(上下文菜单出现前)触发,或者按下“上下文”菜单键时触发。
- `wheel`:滚动鼠标的滚轮时触发,该事件继承的是`WheelEvent`接口。
## 4.鼠标滚动
### 4.1 scroll事件
**onscroll**
onscroll 在滚动条滚动的时候被触发。
onscroll 触发可以有多种方式,只要可以让滚动条发生滚动(X方向或Y方向)
- 鼠标滚轮
- 按 pageUp,pageDown,方向上键,方向下键,空格键 (还有其他?)
- 使用特定的滚动函数,如 scrollTo,scrollBy,scrollByLines, scrollByPages
当
- 滚动条不存在(容器的内容小于容器的大小)
- 手动隐藏(添加样式 overflow:hidden)
onscroll 就不会被触发
```JavaScript
HTML 中:
<element onscroll="myScript">
JavaScript 中:
object.onscroll=function(){myScript};
JavaScript 中, 使用 addEventListener() 方法:
object.addEventListener("scroll", myScript);
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>菜鸟教程(runoob.com)</title>
<style>
div {
border: 1px solid black;
width: 200px;
height: 100px;
overflow: scroll;
}
</style>
</head>
<body>
<p>尝试滚动 div。</p>
<div onscroll="myFunction()">In my younger and more vulnerable years my father gave me some advice that I've been turning over in my mind ever since.
<br><br>
'Whenever you feel like criticizing anyone,' he told me, just remember that all the people in this world haven't had the advantages that you've had.'</div>
<p>滚动 <span id="demo">0</span> 次。</p>
<script>
x = 0;
function myFunction() {
document.getElementById("demo").innerHTML = x += 1;
}
</script>
</body>
</html>
```
[](https://camo.githubusercontent.com/555e6a1797792ba48da5c9d88bc8e32d1a36c771f68f18617df68688ab586b46/68747470733a2f2f69302e6864736c622e636f6d2f6266732f616c62756d2f363136663137306439353061313661306164633530313463343432386466313933366530376663652e706e67)
**补充**
scrollTo(*xpos,ypos*)方法可把内容滚动到指定的坐标。
| 参数 | 描述 |
| ---- | --------------------------------------------------- |
| xpos | 必需。要在窗口文档显示区左上角显示的文档的 x 坐标。 |
| ypos | 必需。要在窗口文档显示区左上角显示的文档的 y 坐标。 |
例:`window.scrollTo(100,500);`
### 4.2 wheel事件
onwheel 在鼠标滚轮滚动的时候被触发
因为滚轮可以控制页面的滚动,所以在使用滚轮时,onwheel事件先被触发,滚动条滚动,接着是onscroll事件
如果想检测每次滚动的增量,应该查看 deltaX,deltaY,deltaZ
[WheelEvent](https://developer.mozilla.org/en-US/docs/Web/API/WheelEvent) 中指出 :在onwheel中,增量的值不一定要对应到滚动条改变的值,滚轮滚动的方向不一定是滚动条的方向,但我们可以从 deltaX,deltaY 知道滚轮滚动的具体方向(向上or向下)
- `deltaX`:数值,表示滚轮的水平滚动量,默认值是 0.0。
- `deltaY`:数值,表示滚轮的垂直滚动量,默认值是 0.0。
- `deltaZ`:数值,表示滚轮的 Z 轴滚动量,默认值是 0.0。
- `deltaMode`:数值,表示相关的滚动事件的单位,适用于上面三个属性。`0`表示滚动单位为像素,`1`表示单位为行,`2`表示单位为页,默认为`0`。
```JavaScript
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<style>
.box1{
width: 200px;
height: 200px;
background-color: #bfa;
}
</style>
</head>
<body style="height: 2000px;">
<div class="box1"></div>
<script type="text/javascript">
let box1 = document.querySelector(".box1");
//e.deltaY大于0表示向下滚,e.deltaY小于0表示向上滚
box1.onwheel = function(e){
box1.style.height = box1.clientHeight+(e.deltaY>0?10:-10)+"px";
/*
* 当滚轮滚动时,如果浏览器有滚动条,滚动条会随之滚动,
* 这是浏览器的默认行为,如果不希望发生,则可以取消默认行为
*/
/* 使用addEventListener()方法绑定响应函数,取消默认行为时不能使用return false
* 需要使用event来取消默认行为event.preventDefault();
*/
return false;
}
</script>
</body>
</html>
``` |
// Ресурси:
// mdn: https://developer.mozilla.org/en-US/
// learn.js: https://uk.javascript.info/
// const getTotalPrice = 100; // камелкейс - загальноприйнятий стандарт написання змінних
// const get_total_price = 100; // снейкейс
// const MAX_COUNT = 100; // якщо великими літерами, говорить, що не можна змінювати
// Значення, яке знаходиться в константі дає знати, що його не можна перевизначити, а let може бути і не визначений
// let totalPrice; //undefined
// console.log(totalPrice);
// totalPrice = 10; // 10
// console.log(totalPrice); //якщо перед, то буде undefined
// var totalPrice; // схожа до змінної let та має поведінку сплиття нагору(хостінга), що призводила до помилок.Він мав бути один на файл.
// totalPrice = 12;
// console.log(totalPrice); //11
//До 2015 року існував var, a коли з'явилася мова ESMA_Script6 виникли const та let
//Примітивні типи даних:
//1 Number
//2 String
//3 Boolean // true // false
//4 null
//5 undefined
//Значення, які приводяться до false
// '' - порожній рядок
// 0 - число
// false
// null - відсутність числа пустота
// undefined
// NaN
// console.log(Boolean(null)); //false
// console.log(Boolean(1)); //true
//Number
// console.log(typeof (0));//number
// console.log(typeof '0');//string
// console.log(typeof NaN);//number
// const result = 10 + "10";
// console.log(typeof result);//string
// const result = 10 + Number("10");
// console.log(result)//20
// console.log(typeof result);//number
// const result = 10 + Number("10px");
// console.log(isNaN(Nan));//true
// console.log(10 === 10);//true
// console.log(NaN === NaN);//false
// console.log(result)//NaN
// console.log(typeof result);//number
// console.log(Number("10px"));//NaN
// console.log(isNaN("10px"));// true // 1.конвертує до числа 2.перевіряє на NaN
// console.log(Number.isNaN("10px"));// false //1.перевірка на NaN
// const product1 = 100;
// const product2 = undefined;
// console.log(product1 * 2);//200
// console.log(product2 * 3);//NaN
// console.log(product1 * 1 + product2 * 3);//NaN
// const price = 100;
// const qty = 4;
// const total = price * qty;
// const total = price ** qty;// ** приводить до степеня
// console.log(total);//400
// let total = 90;
// total = total + price;//or total += price;
// console.log(total);//190
// total -= 10;
// total **= 2;
// console.log(total);//6400
//String - ітерабельний тип даних, його можна перебрати, та індекс починається з 0
// const str = 'va'lue';
// console.log(str);//помилка
// const str = "va'lue";
// console.log(str);//va'lue
// const str = `va'lue`;
// console.log(str);//va'lue
// const price = 100;
// const str = `va'lue ${price}`;
// console.log(str);//va'lue 100
//const str = `va'lue ${price * 12}`;//va'lue 1200
// const str = 'test value';
// console.log(str[1]);// e
// console.log(str.includes('x'));// false
// console.log(str.indexOf('s'));// 2
// console.log(str.indexOf('t', 4));// -1
// console.log(str.indexOf('t',1));// 3
// const value = "Hello"
// const result = value + 'world';
// console.log(result);//Helloworld
// const value = "Hello"
// const result = value + ' world';// or const value = "Hello " or const result = value + " " + 'world';
// const result2 = `${value} world`;
// console.log(result);//Hello world
// console.log(result2);//Hello world
// const value = 10;
// const result = value + '15';//1015
// const result = value + 10 + '15';//2015
// const result2 = "1" + value + 10 + '15';
// console.log(result2);//1101015
// const result = '15' - 10;// математика при відніманні, а при додаванні - канкадинація
// console.log(result);//5
// const result = 'a' - 'b';
// console.log(result);//NaN
// const arr = [1, 2, 3];
// arr.splice(0, 1);
// console.log(arr);//[2, 3] - мутабельний тип даних
// let str = 'Hello world';
// console.log(str.slice(1, 5));//ello
// console.log(str);//Hello world - імутабельний тип даних
//Приклад 1.Математичні оператори
//Виведи на екран загальну кількість яблук та винограду. Різницю яблук ьа винограду
// const apples = 47;
// const grapes = 135;
// const total = apples + grapes;
// console.log(total);
// const diff = grapes - apples;
// console.log(diff);
//Приклад 2.Комбіновані оператори
//Заміни вираз перевизначення комбінованим оператором +=
// let students = 100;
// students = students + 50;// or students += 50;
// console.log(students);
//Приклад 3.Пріоритет операторів
//Розбери пріоритет операторів в інструкції привласнення значення змінної result
// const result = 108 + 223 - 2 * 5;
// const result2 = 108 + (223 - 2) * 5;
// console.log(result);
// console.log(result2);
//Приклад 4.Клас Math
//Напиши скрипт, який виводить у консоль заокруглені вгору/вниз і т.д. значення змінної value.
// Використовуй методи Math.floor(), Math.ceil() та Math.round().
// Перевір що буде в консолі при значеннях 27.3 та 27.9
// const value = 27.51;
// console.log(Math.round(value));//28
// console.log(Math.floor(value));//27
// console.log(Math.ceil(value));//28
// console.log(value.toFixed(1));//27.5
//Приклад 5.Шаблонні рядки
//Складіть речення за допомогою рядків А has B bots in stock, де A, B - змінні вставлені в рядок
// const companyName = 'Cyberdyne Systems';
// const repairBots = 150;
// const defenceBots = 50;
// const message = `${companyName} has ${repairBots + defenceBots} bots in stock`;
// console.log(message);//Cyberdyne Systems has 200 bots in stock
//Приклад 6.Методи рядків та чейнінг
//Напиши скрипт, який розраховує індекс маса тіла людини.
//Для цього необхідно розділити вагу в кільметрах на квадрат висоти людини у метрах.
//Вага та висота зберігається у змінних weight та height, але не як числа, а в вигляді (спеціально за завданням).
//На цілі числа можуть бути задані у вигляді 24.7 або 24,7, тобто як роздільник дробової частини може бути кома.
//Індекс маси тіла необхідно округлити до однієї цифри після коми;
// let weight = '88,3';
// let height = '1.75';
// weight = Number(weight.replace(',', '.'));
// console.log(weight);//88.3
// const bmi = Number((weight / Math.pow(height, 2)).toFixed(1));
// console.log(bmi);//28.8
//Приклад 7.Яким буде результат виразів?
//https://unicode-table.com/en/#0031
// console.log(5 > 4);//true
// console.log(10 >= '77');//false
// console.log('2' >= '2');//true
// console.log('A' > 'a');//false
// console.log('2' < '12');//false
// console.log('4' == 4);//true
// console.log('6' === 6);//false
// console.log('false' === false);//false
// console.log(1 == true);//true
// console.log(1 === true);//false
// console.log('0' == false);//true
// console.log('0' === false);//false
// console.log('Papaya' < 'papaya');//true
// console.log('Papaya' === 'papaya');//false
//Логічні оператори: &&-i, ||-або,
// console.log(true && 3);//3
// console.log(false && 3);//false
// console.log(true && 4 && 'kiwi');//kiwi
// console.log(true && 0 && 'kiwi');//0
// console.log(true || 3);//true
// console.log(0 || true || 4);//true
// console.log('dfghhg' || false || 7);//dfghhg
// console.log(null || 2 || undefined);//2 |
<!DOCTYPE html>
<html>
<head>
<style>
body {
font-family: Monospace;
background-color: #000;
color: #fff;
margin: 0px;
overflow: hidden;
}
#info {
color: #fff;
position: absolute;
top: 10px;
width: 100%;
text-align: center;
z-index: 100;
display: block;
}
#info a,
.button {
color: #f00;
font-weight: bold;
text-decoration: underline;
cursor: pointer
}
</style>
</head>
<body>
<div id="info">
<a href="http://threejs.org" target="_blank">three.js</a> - OBJLoader + MTLLoader
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/84/three.min.js"></script>
<script src="https://threejs.org/examples/js/controls/OrbitControls.js">
</script>
<!--script src="https://rawgit.com/mrdoob/three.js/master/examples/js/loaders/DDSLoader.js"></script-->
<script src="https://rawgit.com/mrdoob/three.js/master/examples/js/loaders/MTLLoader.js"></script>
<script src="https://rawgit.com/mrdoob/three.js/master/examples/js/loaders/OBJLoader.js"></script>
<script src="https://code.jquery.com/jquery-2.1.4.min.js"></script>
<script>
class Button {
constructor(color, name) {
this.on = false;
this.hsl = color.getHSL();
this.obj = this.makeButton(name);
}
get isOn() {
return this.on;
}
toggle() {
this.on = !this.on;
this.update();
}
update() {
if (this.on) {
this.obj.scale.set (1,0.7,1);
this.obj.children[0].material.color.setHSL
(this.hsl.h, this.hsl.s, this.hsl.l);
} else {
this.obj.scale.set(1,1,1);
this.obj.children[0].material.color.setHSL
(this.hsl.h, this.hsl.s, this.hsl.l);
}
}
makeButton(name) {
let mesh = new THREE.Mesh(new THREE.BoxGeometry(1, 0.5, 1),
new THREE.MeshLambertMaterial());
let button = new THREE.Object3D();
button.add(mesh);
mesh.material.color.setHSL (this.hsl.h, this.hsl.s, this.hsl.l)
mesh.position.y=0.375;
button.name = name; // a string
return button;
}
}
var camera, scene, renderer, light,light2;
var controls;
var raycaster = new THREE.Raycaster();
var pickables = [];
var mouse = new THREE.Vector2()
init();
animate();
function init() {
container = document.createElement('div');
document.body.appendChild(container);
camera = new THREE.PerspectiveCamera(25, window.innerWidth / window.innerHeight, 1, 20000);
camera.position.y = 60;
// scene
scene = new THREE.Scene();
gridxz = new THREE.GridHelper (200, 20,'red','white');
scene.add (gridxz);
var ambient = new THREE.AmbientLight(0x444444);
scene.add(ambient);
var directionalLight = new THREE.DirectionalLight(0xffffff);
directionalLight.position.set(0, 1, 1).normalize();
scene.add(directionalLight);
// model
var onProgress = function(xhr) {
if (xhr.lengthComputable) {
var percentComplete = xhr.loaded / xhr.total * 100;
console.log(Math.round(percentComplete, 2) + '% downloaded');
}
};
var onError = function(xhr) {};
//THREE.Loader.Handlers.add(/\.dds$/i, new THREE.DDSLoader());
var mtlLoader1 = new THREE.MTLLoader();
mtlLoader1.setPath('resources/');
mtlLoader1.load('Chair.mtl', function(materials1) {
materials1.preload();
var objLoader1 = new THREE.OBJLoader();
objLoader1.setMaterials(materials1);
objLoader1.setPath('resources/');
objLoader1.load('Chair.obj', function(object) {
var theObject1 = unitize (object, 22);
scene.add (theObject1);
theObject1.position.set(0,0,15);
theObject1.rotation.y+=Math.PI/2;
//scene.add (new THREE.BoxHelper (theObject1));
// transparent window: double-side fix
object.traverse (
function(mesh) {
if (mesh instanceof THREE.Mesh) {
mesh.material.side = THREE.DoubleSide;
}
});
}, onProgress, onError);
});
var mtlLoader2 = new THREE.MTLLoader();
mtlLoader2.setPath('resources/');
mtlLoader2.load('desk.mtl', function(materials2) {
materials2.preload();
var objLoader2 = new THREE.OBJLoader();
objLoader2.setMaterials(materials2);
objLoader2.setPath('resources/');
objLoader2.load('desk.obj', function(object) {
var theObject2 = unitize (object, 20);
scene.add (theObject2);
//scene.add (new THREE.BoxHelper (theObject2));
// transparent window: double-side fix
object.traverse (
function(mesh) {
if (mesh instanceof THREE.Mesh) {
mesh.material.side = THREE.DoubleSide;
}
});
}, onProgress, onError);
});
var mtlLoader3 = new THREE.MTLLoader();
mtlLoader3.setPath('resources/');
mtlLoader3.load('DeskLamp.mtl', function(materials3) {
materials3.preload();
var objLoader3 = new THREE.OBJLoader();
objLoader3.setMaterials(materials3);
objLoader3.setPath('resources/');
objLoader3.load('DeskLamp.obj', function(object) {
var theObject3 = unitize (object, 10);
scene.add (theObject3);
theObject3.position.set(-6,20,-3);
theObject3.rotation.y-=Math.PI/6;
//scene.add (new THREE.BoxHelper (theObject3));
// transparent window: double-side fix
object.traverse (
function(mesh) {
if (mesh instanceof THREE.Mesh) {
mesh.material.side = THREE.DoubleSide;
}
});
}, onProgress, onError);
});
var remoteControl = new THREE.Object3D();
scene.add(remoteControl);
var materialArray = [
new THREE.MeshBasicMaterial({ // +x
color: 0x000000,
}),
new THREE.MeshBasicMaterial({ // -x
color: 0x000000,
}),
new THREE.MeshBasicMaterial({ // +y
color: 0x7a2421,
}),
new THREE.MeshBasicMaterial({ // -Y
color: 0x7a2421,
}),
new THREE.MeshBasicMaterial({ // +z
color: 0x000000
}),
new THREE.MeshBasicMaterial({ // -Z
color: 0x000000
})
];
var material4 = new THREE.MultiMaterial(materialArray);
var base = new THREE.Mesh(new THREE.BoxGeometry(1.5,0.75,3),material4);
remoteControl.add(base);
button = new Button(new THREE.Color (0x12ffff), 'cyan');
button.obj.position.z=-0.8;
remoteControl.add(button.obj);
pickables.push(button.obj);
button2 = new Button(new THREE.Color (0xff12ff), 'purple');
remoteControl.add(button2.obj);
button2.obj.position.z=0.8;
pickables.push(button2.obj);
remoteControl.position.set(7,20,3);
remoteControl.rotation.y+=Math.PI/6;
//spot light
light = new THREE.SpotLight(0xffffff, 0.8);
light.position.set(-5, 28, -2.5);
light.angle = 0.86;// alpha;
light.penumbra = 0.613;
light.rotation.x = -Math.PI/6; // wont affect the light ...
light.rotation.z = Math.PI/6;
//light.target = mesh; // does not change ligth matrix ...
light.castShadow = true;
light.shadow.mapSize.width = 1024;
light.shadow.mapSize.height = 1024;
light.shadow.camera.near = 50;
light.shadow.camera.far = 1000;
light.shadow.camera.fov = 30;
scene.add(light);
var spotLightHelper = new THREE.SpotLightHelper( light );
scene.add( spotLightHelper );
light2 = new THREE.SpotLight(0xffffff, 1.5);
light2.position.set(0, 50, 0);
//light2.angle = 0.86;// alpha;
light2.penumbra = 0.613;
light2.shadow.mapSize.width = 1024;
light2.shadow.mapSize.height = 1024;
light2.shadow.camera.near = 50;
light2.shadow.camera.far = 1000;
light2.shadow.camera.fov = 30;
//light2.rotation.x = -Math.PI/6; // wont affect the light ...
//light2.rotation.z = Math.PI/6;
//light.target = mesh; // does not change ligth matrix ...
scene.add(light2);
var spotLightHelper2 = new THREE.SpotLightHelper( light2 );
scene.add( spotLightHelper2 );
renderer = new THREE.WebGLRenderer();
renderer.setPixelRatio(window.devicePixelRatio);
renderer.setSize(window.innerWidth, window.innerHeight);
container.appendChild(renderer.domElement);
renderer.setClearColor (0x888888);
controls = new THREE.OrbitControls(camera, renderer.domElement);
document.body.appendChild(renderer.domElement);
document.addEventListener('mousedown', onDocumentMouseDown, false);
camera.position.z = 200;
window.addEventListener('resize', onWindowResize, false);
}
// shadow related
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
theObject1.castShadow = true;
theObject1.receiveShadow = true;
theObject2.castShadow = true;
theObject2.receiveShadow = true;
theObject3.castShadow = true;
theObject3.receiveShadow = true;
remoteControl.castShadow = true;
remoteControl.receiveShadow = true;
// create an Object3D of the given object
// so that it is centered at +Y axis
//
function unitize (object, targetSize) {
// find bounding box of 'object'
var box3 = new THREE.Box3();
box3.setFromObject (object);
var size = new THREE.Vector3();
size.subVectors (box3.max, box3.min);
var center = new THREE.Vector3();
center.addVectors(box3.max, box3.min).multiplyScalar (0.5);
console.log ('center: ' + center.x + ', '+center.y + ', '+center.z );
console.log ('size: ' + size.x + ', ' + size.y + ', '+size.z );
// uniform scaling according to objSize
var objSize = findMax (size);
var scaleSet = targetSize/objSize;
var theObject = new THREE.Object3D();
theObject.add (object);
object.scale.set (scaleSet, scaleSet, scaleSet);
object.position.set (-center.x*scaleSet, -center.y*scaleSet + size.y/2*scaleSet, -center.z*scaleSet);
return theObject;
// helper function
function findMax(v) {
if (v.x > v.y) {
return v.x > v.z ? v.x : v.z;
} else { // v.y > v.x
return v.y > v.z ? v.y : v.z;
}
}
}
function onDocumentMouseDown(event) {
event.preventDefault();
mouse.x = (event.clientX / window.innerWidth) * 2 - 1;
mouse.y = -(event.clientY / window.innerHeight) * 2 + 1;
// find intersections
raycaster.setFromCamera(mouse, camera);
var intersects = raycaster.intersectObjects(pickables, true);
if (intersects.length > 0) {
let picked = intersects[0].object.parent.name;
switch (picked) {
case 'cyan':
button.toggle();
break;
case 'purple':
button2.toggle();
break;
}
}
}
function onWindowResize() {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(window.innerWidth, window.innerHeight);
}
function animate() {
if(!button.on){
light.intensity = 0;
}
else{
light.intensity = .8;
}
if(!button2.on){
light2.intensity = 0;
}
else{
light2.intensity = 1.5;
}
controls.update();
requestAnimationFrame(animate);
render();
}
function render() {
renderer.render(scene, camera);
}
</script>
</body>
</html> |
import { Product } from './types';
import { formatPrice } from './helpers';
type Props = {
product: Product;
onSelectProduct: (product: Product) => void;
isSelected: boolean;
}
function ProductCard( { product, onSelectProduct, isSelected }: Props ) {
const { name, price, description, imageUri } = product
return (
<div className={`order-card-container ${isSelected ? 'selected' : ''}`}
onClick={_ => onSelectProduct(product) } >
<h3 className="order-card-title">
{name}
</h3>
<img src={imageUri} alt="Imagem ilustrativa da comida." className="order-card-image"/>
<h3 className="order-card-price">
{formatPrice(price)}
</h3>
<div className="order-card-description">
<h3>Descrição</h3>
<p>
{description}
</p>
</div>
</div>
)
}
export default ProductCard; |
// -*- Mode: C++; indent-tabs-mode: nil; c-basic-offset: 4; -*-
//
// OpenVRML
//
// Copyright (C) 1998 Chris Morley
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library 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
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
# ifndef OPENVRML_DOC_H
# define OPENVRML_DOC_H
# include <cstdio>
# include <iosfwd>
# include <string>
# include <openvrml/common.h>
namespace openvrml {
class doc2;
class doc {
char * url_;
std::ostream * out_;
FILE * fp_;
char * tmpfile_; // Local copy of http: files
public:
explicit doc(const std::string & url = std::string(),
const doc * relative = 0);
doc(const std::string & url, const doc2 * relative);
~doc();
void seturl(const char * url, const doc * relative = 0);
void seturl(const char * url, const doc2 * relative = 0);
const char * url() const; // "http://www.foo.com/dir/file.xyz#Viewpoint"
const char * url_base() const; // "file" or ""
const char * url_ext() const; // "xyz" or ""
const char * url_path() const; // "http://www.foo.com/dir/" or ""
const char * url_protocol() const; // "http"
const char * url_modifier() const; // "#Viewpoint" or ""
const char * local_name(); // "/tmp/file.xyz" or NULL
const char * local_path(); // "/tmp/" or NULL
FILE * fopen(const char * mode);
void fclose();
std::ostream & output_stream();
private:
// Non-copyable.
doc(doc const &);
doc & operator=(doc const &);
bool filename(char * fn, int nfn);
};
class doc2 {
std::string url_;
char * tmpfile_; // Local copy of http: files
std::istream * istm_;
std::ostream * ostm_;
public:
explicit doc2(const std::string & url = std::string(),
const doc2 * relative = 0);
~doc2();
void seturl(const std::string & url, const doc2 * relative = 0);
const std::string url() const; // "http://www.foo.com/dir/file.xyz#Viewpoint"
const std::string url_base() const; // "file" or ""
const std::string url_ext() const; // "xyz" or ""
const std::string url_path() const; // "http://www.foo.com/dir/" or ""
const std::string url_protocol() const; // "http"
const std::string url_modifier() const; // "#Viewpoint" or ""
const char * local_name(); // "/tmp/file.xyz" or NULL
const char * local_path(); // "/tmp/" or NULL
std::istream & input_stream();
std::ostream & output_stream();
private:
// Non-copyable.
doc2(const doc2 &);
doc2 & operator=(const doc2 &);
bool filename(char * fn, size_t nfn);
};
}
# endif |
import Lottie from 'react-lottie';
import loading from './loading.json'
const lottieOptions = {
animationData: loading,
loop: true,
autoplay: true,
};
interface Props {
width: string;
height: string
}
const LoadingLottie: React.FC<Props> = ({width, height}) => {
return (
<Lottie
options={lottieOptions}
isClickToPauseDisabled={false}
style={{ width: width, height: height }} // svg의 부모 div에 적용
eventListeners={[
{
eventName: 'complete',
callback: () => console.log('the animation completed'),
},
]}
/>
);
};
export default LoadingLottie; |
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <stdlib.h>
void wait();
int main()
{
int n = 5; // Cambia n al número deseado de subprocesos
for (int i = 0; i < n; i++)
{
pid_t child = fork();
if (child < 0)
{
fprintf(stderr, "Error al crear el subproceso %d\n", i);
return 1;
}
else if (child == 0)
{
// Código ejecutado por el subproceso hijo
printf("Soy el subproceso %d, mi PID es %d, y mi padre es %d\n", i, getpid(), getppid());
// Realiza tareas específicas para el subproceso hijo
exit(0); // Importante: asegúrate de que los subprocesos hijos terminen correctamente
}
}
// Código ejecutado por el proceso padre
printf("Soy el proceso padre, mi PID es %d\n", getpid());
// El proceso padre puede realizar tareas específicas aquí
// Esperar a que todos los subprocesos hijos terminen
for (int i = 0; i < n; i++)
{
wait(NULL);
}
return 0;
} |
package com.rmrtechs.springbootauthentjwtback.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.rmrtechs.springbootauthentjwtback.dto.UserDto;
import com.rmrtechs.springbootauthentjwtback.exception.RegistrationAuthenticationException;
import com.rmrtechs.springbootauthentjwtback.mapper.UserMapper;
import com.rmrtechs.springbootauthentjwtback.model.User;
import com.rmrtechs.springbootauthentjwtback.services.UserService;
import com.rmrtechs.springbootauthentjwtback.util.ErrorMessages;
import lombok.extern.slf4j.Slf4j;
@RestController
@RequestMapping("api/authent")
@Slf4j
@CrossOrigin(origins = "*")
public class AuthentController {
@Autowired
private UserService userService;
@Autowired
private UserMapper userMapper;
@Autowired
private PasswordEncoder passwordEncoder;
@PostMapping("/sign-up")
public ResponseEntity<?> signupUser(@RequestBody UserDto userDto) {
try {
String hashPwd = passwordEncoder.encode(userDto.getPassword());
userDto.setPassword(hashPwd);
User convertedUser = userMapper.userDtoToUser(userDto);
User savedUser = userService.createUser(convertedUser);
return ResponseEntity.ok(userMapper.userToUserDto(savedUser));
} catch (RegistrationAuthenticationException rae) {
log.error(rae.getMessage());
return ResponseEntity.status(HttpStatus.CONFLICT).body(rae.getMessage());
} catch (Exception e) {
log.error(e.getMessage());
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(ErrorMessages.INTERNAL_SERVER_ERROR);
}
}
} |
import { useEffect, useState } from "react";
import { useParams } from "react-router-dom";
const useInput = (initialValue, validator) => {
const [value, setValue] = useState(initialValue);
const onChange = (event) => {
const {
target: { value },
} = event;
let willUpdate = true;
if (typeof validator === "function") {
willUpdate = validator(value);
}
if (willUpdate) {
setValue(value);
}
};
return { value, onChange };
};
function Detail() {
const { id } = useParams();
const getMovie = async () => {
const json = await (
await fetch(`https://yts.mx/api/v2/movie_details.json?movie_id=${id}`)
).json();
};
useEffect(() => {
getMovie();
}, []);
const maxLen = (value) => value.length < 10;
const name = useInput("Mr", maxLen);
return (
<div>
<h1>Hello</h1>
<input placeholder="Name" {...name} />
</div> //value={name.value} onChange={name.onChange} >>>>> {...name}
);
}
export default Detail; |
/**
******************************************************************************
* @file stm32f0xx_hal_rtc_ex.c
* @author MCD Application Team
* @brief Extended RTC HAL module driver.
* This file provides firmware functions to manage the following
* functionalities of the Real Time Clock (RTC) Extended peripheral:
* + RTC Time Stamp functions
* + RTC Tamper functions
* + RTC Wake-up functions
* + Extended Control functions
* + Extended RTC features functions
*
@verbatim
##### How to use this driver #####
[..]
(+) Enable the RTC domain access.
(+) Configure the RTC Prescaler (Asynchronous and Synchronous) and RTC hour
format using the HAL_RTC_Init() function.
*** RTC Wake-up configuration ***
[..]
(+) To configure the RTC Wakeup Clock source and Counter use the HAL_RTCEx_SetWakeUpTimer()
function. You can also configure the RTC Wakeup timer with interrupt mode
using the HAL_RTCEx_SetWakeUpTimer_IT() function.
(+) To read the RTC WakeUp Counter register, use the HAL_RTCEx_GetWakeUpTimer()
function.
(@) Not available on F030x4/x6/x8 and F070x6
*** TimeStamp configuration ***
[..]
(+) Configure the RTC_AF trigger and enable the RTC TimeStamp using the
HAL_RTCEx_SetTimeStamp() function. You can also configure the RTC TimeStamp with
interrupt mode using the HAL_RTCEx_SetTimeStamp_IT() function.
(+) To read the RTC TimeStamp Time and Date register, use the HAL_RTCEx_GetTimeStamp()
function.
*** Tamper configuration ***
[..]
(+) Enable the RTC Tamper and configure the Tamper filter count, trigger Edge
or Level according to the Tamper filter (if equal to 0 Edge else Level)
value, sampling frequency, precharge or discharge and Pull-UP using the
HAL_RTCEx_SetTamper() function. You can configure RTC Tamper in interrupt
mode using HAL_RTCEx_SetTamper_IT() function.
*** Backup Data Registers configuration ***
[..]
(+) To write to the RTC Backup Data registers, use the HAL_RTCEx_BKUPWrite()
function.
(+) To read the RTC Backup Data registers, use the HAL_RTCEx_BKUPRead()
function.
(@) Not available on F030x6/x8/xC and F070x6/xB (F0xx Value Line devices)
@endverbatim
******************************************************************************
* @attention
*
* <h2><center>© Copyright (c) 2016 STMicroelectronics.
* All rights reserved.</center></h2>
*
* This software component is licensed by ST under BSD 3-Clause license,
* the "License"; You may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
* opensource.org/licenses/BSD-3-Clause
*
******************************************************************************
*/
/* Includes ------------------------------------------------------------------*/
#include "stm32f0xx_hal.h"
/** @addtogroup STM32F0xx_HAL_Driver
* @{
*/
/** @addtogroup RTCEx
* @brief RTC Extended HAL module driver
* @{
*/
#ifdef HAL_RTC_MODULE_ENABLED
/* Private typedef -----------------------------------------------------------*/
/* Private define ------------------------------------------------------------*/
/* Private macro -------------------------------------------------------------*/
/* Private variables ---------------------------------------------------------*/
/* Private function prototypes -----------------------------------------------*/
/* Exported functions ---------------------------------------------------------*/
/** @addtogroup RTCEx_Exported_Functions
* @{
*/
/** @addtogroup RTCEx_Exported_Functions_Group1
* @brief RTC TimeStamp and Tamper functions
*
@verbatim
##### RTC TimeStamp and Tamper functions #####
[..] This section provides functions allowing to configure TimeStamp feature
@endverbatim
* @{
*/
/**
* @brief Set TimeStamp.
* @note This API must be called before enabling the TimeStamp feature.
* @param hrtc RTC handle
* @param TimeStampEdge Specifies the pin edge on which the TimeStamp is
* activated.
* This parameter can be one of the following values:
* @arg RTC_TIMESTAMPEDGE_RISING: the Time stamp event occurs on the
* rising edge of the related pin.
* @arg RTC_TIMESTAMPEDGE_FALLING: the Time stamp event occurs on the
* falling edge of the related pin.
* @param RTC_TimeStampPin specifies the RTC TimeStamp Pin.
* This parameter can be one of the following values:
* @arg RTC_TIMESTAMPPIN_DEFAULT: PC13 is selected as RTC TimeStamp Pin.
* @retval HAL status
*/
HAL_StatusTypeDef HAL_RTCEx_SetTimeStamp(RTC_HandleTypeDef *hrtc, uint32_t TimeStampEdge, uint32_t RTC_TimeStampPin)
{
uint32_t tmpreg = 0U;
/* Check the parameters */
assert_param(IS_TIMESTAMP_EDGE(TimeStampEdge));
assert_param(IS_RTC_TIMESTAMP_PIN(RTC_TimeStampPin));
/* Process Locked */
__HAL_LOCK(hrtc);
hrtc->State = HAL_RTC_STATE_BUSY;
/* Get the RTC_CR register and clear the bits to be configured */
tmpreg = (uint32_t)(hrtc->Instance->CR & (uint32_t)~(RTC_CR_TSEDGE | RTC_CR_TSE));
tmpreg |= TimeStampEdge;
/* Disable the write protection for RTC registers */
__HAL_RTC_WRITEPROTECTION_DISABLE(hrtc);
/* Configure the Time Stamp TSEDGE and Enable bits */
hrtc->Instance->CR = (uint32_t)tmpreg;
__HAL_RTC_TIMESTAMP_ENABLE(hrtc);
/* Enable the write protection for RTC registers */
__HAL_RTC_WRITEPROTECTION_ENABLE(hrtc);
/* Change RTC state */
hrtc->State = HAL_RTC_STATE_READY;
/* Process Unlocked */
__HAL_UNLOCK(hrtc);
return HAL_OK;
}
/**
* @brief Set TimeStamp with Interrupt.
* @param hrtc RTC handle
* @note This API must be called before enabling the TimeStamp feature.
* @param TimeStampEdge Specifies the pin edge on which the TimeStamp is
* activated.
* This parameter can be one of the following values:
* @arg RTC_TIMESTAMPEDGE_RISING: the Time stamp event occurs on the
* rising edge of the related pin.
* @arg RTC_TIMESTAMPEDGE_FALLING: the Time stamp event occurs on the
* falling edge of the related pin.
* @param RTC_TimeStampPin Specifies the RTC TimeStamp Pin.
* This parameter can be one of the following values:
* @arg RTC_TIMESTAMPPIN_DEFAULT: PC13 is selected as RTC TimeStamp Pin.
* @retval HAL status
*/
HAL_StatusTypeDef HAL_RTCEx_SetTimeStamp_IT(RTC_HandleTypeDef *hrtc, uint32_t TimeStampEdge, uint32_t RTC_TimeStampPin)
{
uint32_t tmpreg = 0U;
/* Check the parameters */
assert_param(IS_TIMESTAMP_EDGE(TimeStampEdge));
assert_param(IS_RTC_TIMESTAMP_PIN(RTC_TimeStampPin));
/* Process Locked */
__HAL_LOCK(hrtc);
hrtc->State = HAL_RTC_STATE_BUSY;
/* Get the RTC_CR register and clear the bits to be configured */
tmpreg = (uint32_t)(hrtc->Instance->CR & (uint32_t)~(RTC_CR_TSEDGE | RTC_CR_TSE));
tmpreg |= TimeStampEdge;
/* Disable the write protection for RTC registers */
__HAL_RTC_WRITEPROTECTION_DISABLE(hrtc);
/* Configure the Time Stamp TSEDGE and Enable bits */
hrtc->Instance->CR = (uint32_t)tmpreg;
__HAL_RTC_TIMESTAMP_ENABLE(hrtc);
/* Enable IT timestamp */
__HAL_RTC_TIMESTAMP_ENABLE_IT(hrtc, RTC_IT_TS);
/* RTC timestamp Interrupt Configuration: EXTI configuration */
__HAL_RTC_TAMPER_TIMESTAMP_EXTI_ENABLE_IT();
__HAL_RTC_TAMPER_TIMESTAMP_EXTI_ENABLE_RISING_EDGE();
/* Enable the write protection for RTC registers */
__HAL_RTC_WRITEPROTECTION_ENABLE(hrtc);
hrtc->State = HAL_RTC_STATE_READY;
/* Process Unlocked */
__HAL_UNLOCK(hrtc);
return HAL_OK;
}
/**
* @brief Deactivate TimeStamp.
* @param hrtc RTC handle
* @retval HAL status
*/
HAL_StatusTypeDef HAL_RTCEx_DeactivateTimeStamp(RTC_HandleTypeDef *hrtc)
{
uint32_t tmpreg = 0U;
/* Process Locked */
__HAL_LOCK(hrtc);
hrtc->State = HAL_RTC_STATE_BUSY;
/* Disable the write protection for RTC registers */
__HAL_RTC_WRITEPROTECTION_DISABLE(hrtc);
/* In case of interrupt mode is used, the interrupt source must disabled */
__HAL_RTC_TIMESTAMP_DISABLE_IT(hrtc, RTC_IT_TS);
/* Get the RTC_CR register and clear the bits to be configured */
tmpreg = (uint32_t)(hrtc->Instance->CR & (uint32_t)~(RTC_CR_TSEDGE | RTC_CR_TSE));
/* Configure the Time Stamp TSEDGE and Enable bits */
hrtc->Instance->CR = (uint32_t)tmpreg;
/* Enable the write protection for RTC registers */
__HAL_RTC_WRITEPROTECTION_ENABLE(hrtc);
hrtc->State = HAL_RTC_STATE_READY;
/* Process Unlocked */
__HAL_UNLOCK(hrtc);
return HAL_OK;
}
/**
* @brief Get the RTC TimeStamp value.
* @param hrtc RTC handle
* @param sTimeStamp Pointer to Time structure
* @param sTimeStampDate Pointer to Date structure
* @param Format specifies the format of the entered parameters.
* This parameter can be one of the following values:
* @arg RTC_FORMAT_BIN: Binary data format
* @arg RTC_FORMAT_BCD: BCD data format
* @retval HAL status
*/
HAL_StatusTypeDef HAL_RTCEx_GetTimeStamp(RTC_HandleTypeDef *hrtc, RTC_TimeTypeDef *sTimeStamp, RTC_DateTypeDef *sTimeStampDate, uint32_t Format)
{
uint32_t tmptime = 0U, tmpdate = 0U;
/* Check the parameters */
assert_param(IS_RTC_FORMAT(Format));
/* Get the TimeStamp time and date registers values */
tmptime = (uint32_t)(hrtc->Instance->TSTR & RTC_TR_RESERVED_MASK);
tmpdate = (uint32_t)(hrtc->Instance->TSDR & RTC_DR_RESERVED_MASK);
/* Fill the Time structure fields with the read parameters */
sTimeStamp->Hours = (uint8_t)((tmptime & (RTC_TR_HT | RTC_TR_HU)) >> 16U);
sTimeStamp->Minutes = (uint8_t)((tmptime & (RTC_TR_MNT | RTC_TR_MNU)) >> 8U);
sTimeStamp->Seconds = (uint8_t)(tmptime & (RTC_TR_ST | RTC_TR_SU));
sTimeStamp->TimeFormat = (uint8_t)((tmptime & (RTC_TR_PM)) >> 16U);
sTimeStamp->SubSeconds = (uint32_t) hrtc->Instance->TSSSR;
/* Fill the Date structure fields with the read parameters */
sTimeStampDate->Year = 0;
sTimeStampDate->Month = (uint8_t)((tmpdate & (RTC_DR_MT | RTC_DR_MU)) >> 8U);
sTimeStampDate->Date = (uint8_t)(tmpdate & (RTC_DR_DT | RTC_DR_DU));
sTimeStampDate->WeekDay = (uint8_t)((tmpdate & (RTC_DR_WDU)) >> 13U);
/* Check the input parameters format */
if (Format == RTC_FORMAT_BIN)
{
/* Convert the TimeStamp structure parameters to Binary format */
sTimeStamp->Hours = (uint8_t)RTC_Bcd2ToByte(sTimeStamp->Hours);
sTimeStamp->Minutes = (uint8_t)RTC_Bcd2ToByte(sTimeStamp->Minutes);
sTimeStamp->Seconds = (uint8_t)RTC_Bcd2ToByte(sTimeStamp->Seconds);
/* Convert the DateTimeStamp structure parameters to Binary format */
sTimeStampDate->Month = (uint8_t)RTC_Bcd2ToByte(sTimeStampDate->Month);
sTimeStampDate->Date = (uint8_t)RTC_Bcd2ToByte(sTimeStampDate->Date);
sTimeStampDate->WeekDay = (uint8_t)RTC_Bcd2ToByte(sTimeStampDate->WeekDay);
}
/* Clear the TIMESTAMP Flag */
__HAL_RTC_TIMESTAMP_CLEAR_FLAG(hrtc, RTC_FLAG_TSF);
return HAL_OK;
}
/**
* @brief Set Tamper
* @note By calling this API we disable the tamper interrupt for all tampers.
* @param hrtc RTC handle
* @param sTamper Pointer to Tamper Structure.
* @retval HAL status
*/
HAL_StatusTypeDef HAL_RTCEx_SetTamper(RTC_HandleTypeDef *hrtc, RTC_TamperTypeDef *sTamper)
{
uint32_t tmpreg = 0U;
/* Check the parameters */
assert_param(IS_RTC_TAMPER(sTamper->Tamper));
assert_param(IS_RTC_TAMPER_TRIGGER(sTamper->Trigger));
assert_param(IS_RTC_TAMPER_FILTER(sTamper->Filter));
assert_param(IS_RTC_TAMPER_SAMPLING_FREQ(sTamper->SamplingFrequency));
assert_param(IS_RTC_TAMPER_PRECHARGE_DURATION(sTamper->PrechargeDuration));
assert_param(IS_RTC_TAMPER_PULLUP_STATE(sTamper->TamperPullUp));
assert_param(IS_RTC_TAMPER_TIMESTAMPONTAMPER_DETECTION(sTamper->TimeStampOnTamperDetection));
/* Process Locked */
__HAL_LOCK(hrtc);
hrtc->State = HAL_RTC_STATE_BUSY;
if (sTamper->Trigger != RTC_TAMPERTRIGGER_RISINGEDGE)
{
sTamper->Trigger = (uint32_t)(sTamper->Tamper << 1U);
}
tmpreg = ((uint32_t)sTamper->Tamper | (uint32_t)sTamper->Trigger | (uint32_t)sTamper->Filter | \
(uint32_t)sTamper->SamplingFrequency | (uint32_t)sTamper->PrechargeDuration | \
(uint32_t)sTamper->TamperPullUp | sTamper->TimeStampOnTamperDetection);
hrtc->Instance->TAFCR &= (uint32_t)~((uint32_t)sTamper->Tamper | (uint32_t)(sTamper->Tamper << 1U) | (uint32_t)RTC_TAFCR_TAMPTS | \
(uint32_t)RTC_TAFCR_TAMPFREQ | (uint32_t)RTC_TAFCR_TAMPFLT | (uint32_t)RTC_TAFCR_TAMPPRCH | \
(uint32_t)RTC_TAFCR_TAMPPUDIS | (uint32_t)RTC_TAFCR_TAMPIE);
hrtc->Instance->TAFCR |= tmpreg;
hrtc->State = HAL_RTC_STATE_READY;
/* Process Unlocked */
__HAL_UNLOCK(hrtc);
return HAL_OK;
}
/**
* @brief Sets Tamper with interrupt.
* @note By calling this API we force the tamper interrupt for all tampers.
* @param hrtc pointer to a RTC_HandleTypeDef structure that contains
* the configuration information for RTC.
* @param sTamper Pointer to RTC Tamper.
* @retval HAL status
*/
HAL_StatusTypeDef HAL_RTCEx_SetTamper_IT(RTC_HandleTypeDef *hrtc, RTC_TamperTypeDef *sTamper)
{
uint32_t tmpreg = 0U;
/* Check the parameters */
assert_param(IS_RTC_TAMPER(sTamper->Tamper));
assert_param(IS_RTC_TAMPER_TRIGGER(sTamper->Trigger));
assert_param(IS_RTC_TAMPER_FILTER(sTamper->Filter));
assert_param(IS_RTC_TAMPER_SAMPLING_FREQ(sTamper->SamplingFrequency));
assert_param(IS_RTC_TAMPER_PRECHARGE_DURATION(sTamper->PrechargeDuration));
assert_param(IS_RTC_TAMPER_PULLUP_STATE(sTamper->TamperPullUp));
assert_param(IS_RTC_TAMPER_TIMESTAMPONTAMPER_DETECTION(sTamper->TimeStampOnTamperDetection));
/* Process Locked */
__HAL_LOCK(hrtc);
hrtc->State = HAL_RTC_STATE_BUSY;
/* Configure the tamper trigger */
if (sTamper->Trigger != RTC_TAMPERTRIGGER_RISINGEDGE)
{
sTamper->Trigger = (uint32_t)(sTamper->Tamper << 1U);
}
tmpreg = ((uint32_t)sTamper->Tamper | (uint32_t)sTamper->Trigger | (uint32_t)sTamper->Filter | \
(uint32_t)sTamper->SamplingFrequency | (uint32_t)sTamper->PrechargeDuration | \
(uint32_t)sTamper->TamperPullUp | sTamper->TimeStampOnTamperDetection);
hrtc->Instance->TAFCR &= (uint32_t)~((uint32_t)sTamper->Tamper | (uint32_t)(sTamper->Tamper << 1U) | (uint32_t)RTC_TAFCR_TAMPTS | \
(uint32_t)RTC_TAFCR_TAMPFREQ | (uint32_t)RTC_TAFCR_TAMPFLT | (uint32_t)RTC_TAFCR_TAMPPRCH | \
(uint32_t)RTC_TAFCR_TAMPPUDIS);
hrtc->Instance->TAFCR |= tmpreg;
/* Configure the Tamper Interrupt in the RTC_TAFCR */
hrtc->Instance->TAFCR |= (uint32_t)RTC_TAFCR_TAMPIE;
/* RTC Tamper Interrupt Configuration: EXTI configuration */
__HAL_RTC_TAMPER_TIMESTAMP_EXTI_ENABLE_IT();
__HAL_RTC_TAMPER_TIMESTAMP_EXTI_ENABLE_RISING_EDGE();
hrtc->State = HAL_RTC_STATE_READY;
/* Process Unlocked */
__HAL_UNLOCK(hrtc);
return HAL_OK;
}
/**
* @brief Deactivate Tamper.
* @param hrtc RTC handle
* @param Tamper Selected tamper pin.
* This parameter can be any combination of RTC_TAMPER_1, RTC_TAMPER_2 and RTC_TAMPER_3.
* @retval HAL status
*/
HAL_StatusTypeDef HAL_RTCEx_DeactivateTamper(RTC_HandleTypeDef *hrtc, uint32_t Tamper)
{
assert_param(IS_RTC_TAMPER(Tamper));
/* Process Locked */
__HAL_LOCK(hrtc);
hrtc->State = HAL_RTC_STATE_BUSY;
/* Disable the selected Tamper pin */
hrtc->Instance->TAFCR &= (uint32_t)~Tamper;
hrtc->State = HAL_RTC_STATE_READY;
/* Process Unlocked */
__HAL_UNLOCK(hrtc);
return HAL_OK;
}
/**
* @brief Handle TimeStamp interrupt request.
* @param hrtc RTC handle
* @retval None
*/
void HAL_RTCEx_TamperTimeStampIRQHandler(RTC_HandleTypeDef *hrtc)
{
/* Get the TimeStamp interrupt source enable status */
if (__HAL_RTC_TIMESTAMP_GET_IT_SOURCE(hrtc, RTC_IT_TS) != RESET)
{
/* Get the pending status of the TIMESTAMP Interrupt */
if (__HAL_RTC_TIMESTAMP_GET_FLAG(hrtc, RTC_FLAG_TSF) != RESET)
{
/* TIMESTAMP callback */
#if (USE_HAL_RTC_REGISTER_CALLBACKS == 1)
hrtc->TimeStampEventCallback(hrtc);
#else
HAL_RTCEx_TimeStampEventCallback(hrtc);
#endif /* USE_HAL_RTC_REGISTER_CALLBACKS */
/* Clear the TIMESTAMP interrupt pending bit */
__HAL_RTC_TIMESTAMP_CLEAR_FLAG(hrtc, RTC_FLAG_TSF);
}
}
/* Get the Tamper interrupts source enable status */
if (__HAL_RTC_TAMPER_GET_IT_SOURCE(hrtc, RTC_IT_TAMP))
{
/* Get the pending status of the Tamper1 Interrupt */
if (__HAL_RTC_TAMPER_GET_FLAG(hrtc, RTC_FLAG_TAMP1F) != RESET)
{
/* Tamper1 callback */
#if (USE_HAL_RTC_REGISTER_CALLBACKS == 1)
hrtc->Tamper1EventCallback(hrtc);
#else
HAL_RTCEx_Tamper1EventCallback(hrtc);
#endif /* USE_HAL_RTC_REGISTER_CALLBACKS */
/* Clear the Tamper1 interrupt pending bit */
__HAL_RTC_TAMPER_CLEAR_FLAG(hrtc, RTC_FLAG_TAMP1F);
}
}
/* Get the Tamper interrupts source enable status */
if (__HAL_RTC_TAMPER_GET_IT_SOURCE(hrtc, RTC_IT_TAMP))
{
/* Get the pending status of the Tamper2 Interrupt */
if (__HAL_RTC_TAMPER_GET_FLAG(hrtc, RTC_FLAG_TAMP2F) != RESET)
{
/* Tamper2 callback */
#if (USE_HAL_RTC_REGISTER_CALLBACKS == 1)
hrtc->Tamper2EventCallback(hrtc);
#else
HAL_RTCEx_Tamper2EventCallback(hrtc);
#endif /* USE_HAL_RTC_REGISTER_CALLBACKS */
/* Clear the Tamper2 interrupt pending bit */
__HAL_RTC_TAMPER_CLEAR_FLAG(hrtc, RTC_FLAG_TAMP2F);
}
}
#if defined(STM32F071xB) || defined(STM32F072xB) || defined(STM32F078xx) || defined(STM32F091xC) || defined(STM32F098xx)
/* Get the Tamper interrupts source enable status */
if (__HAL_RTC_TAMPER_GET_IT_SOURCE(hrtc, RTC_IT_TAMP))
{
/* Get the pending status of the Tamper3 Interrupt */
if (__HAL_RTC_TAMPER_GET_FLAG(hrtc, RTC_FLAG_TAMP3F) != RESET)
{
/* Tamper3 callback */
#if (USE_HAL_RTC_REGISTER_CALLBACKS == 1)
hrtc->Tamper3EventCallback(hrtc);
#else
HAL_RTCEx_Tamper3EventCallback(hrtc);
#endif /* USE_HAL_RTC_REGISTER_CALLBACKS */
/* Clear the Tamper3 interrupt pending bit */
__HAL_RTC_TAMPER_CLEAR_FLAG(hrtc, RTC_FLAG_TAMP3F);
}
}
#endif
/* Clear the EXTI's Flag for RTC TimeStamp and Tamper */
__HAL_RTC_TAMPER_TIMESTAMP_EXTI_CLEAR_FLAG();
/* Change RTC state */
hrtc->State = HAL_RTC_STATE_READY;
}
/**
* @brief TimeStamp callback.
* @param hrtc RTC handle
* @retval None
*/
__weak void HAL_RTCEx_TimeStampEventCallback(RTC_HandleTypeDef *hrtc)
{
/* Prevent unused argument(s) compilation warning */
UNUSED(hrtc);
/* NOTE : This function should not be modified, when the callback is needed,
the HAL_RTCEx_TimeStampEventCallback could be implemented in the user file
*/
}
/**
* @brief Tamper 1 callback.
* @param hrtc RTC handle
* @retval None
*/
__weak void HAL_RTCEx_Tamper1EventCallback(RTC_HandleTypeDef *hrtc)
{
/* Prevent unused argument(s) compilation warning */
UNUSED(hrtc);
/* NOTE : This function should not be modified, when the callback is needed,
the HAL_RTCEx_Tamper1EventCallback could be implemented in the user file
*/
}
/**
* @brief Tamper 2 callback.
* @param hrtc RTC handle
* @retval None
*/
__weak void HAL_RTCEx_Tamper2EventCallback(RTC_HandleTypeDef *hrtc)
{
/* Prevent unused argument(s) compilation warning */
UNUSED(hrtc);
/* NOTE : This function should not be modified, when the callback is needed,
the HAL_RTCEx_Tamper2EventCallback could be implemented in the user file
*/
}
#if defined(STM32F071xB) || defined(STM32F072xB) || defined(STM32F078xx) || defined(STM32F091xC) || defined(STM32F098xx)
/**
* @brief Tamper 3 callback.
* @param hrtc RTC handle
* @retval None
*/
__weak void HAL_RTCEx_Tamper3EventCallback(RTC_HandleTypeDef *hrtc)
{
/* Prevent unused argument(s) compilation warning */
UNUSED(hrtc);
/* NOTE : This function should not be modified, when the callback is needed,
the HAL_RTCEx_Tamper3EventCallback could be implemented in the user file
*/
}
#endif
/**
* @brief Handle TimeStamp polling request.
* @param hrtc RTC handle
* @param Timeout Timeout duration
* @retval HAL status
*/
HAL_StatusTypeDef HAL_RTCEx_PollForTimeStampEvent(RTC_HandleTypeDef *hrtc, uint32_t Timeout)
{
uint32_t tickstart = HAL_GetTick();
while (__HAL_RTC_TIMESTAMP_GET_FLAG(hrtc, RTC_FLAG_TSF) == RESET)
{
if (__HAL_RTC_TIMESTAMP_GET_FLAG(hrtc, RTC_FLAG_TSOVF) != RESET)
{
/* Clear the TIMESTAMP OverRun Flag */
__HAL_RTC_TIMESTAMP_CLEAR_FLAG(hrtc, RTC_FLAG_TSOVF);
/* Change TIMESTAMP state */
hrtc->State = HAL_RTC_STATE_ERROR;
return HAL_ERROR;
}
if (Timeout != HAL_MAX_DELAY)
{
if ((Timeout == 0U) || ((HAL_GetTick() - tickstart) > Timeout))
{
hrtc->State = HAL_RTC_STATE_TIMEOUT;
return HAL_TIMEOUT;
}
}
}
/* Change RTC state */
hrtc->State = HAL_RTC_STATE_READY;
return HAL_OK;
}
/**
* @brief Handle Tamper 1 Polling.
* @param hrtc RTC handle
* @param Timeout Timeout duration
* @retval HAL status
*/
HAL_StatusTypeDef HAL_RTCEx_PollForTamper1Event(RTC_HandleTypeDef *hrtc, uint32_t Timeout)
{
uint32_t tickstart = HAL_GetTick();
/* Get the status of the Interrupt */
while (__HAL_RTC_TAMPER_GET_FLAG(hrtc, RTC_FLAG_TAMP1F) == RESET)
{
if (Timeout != HAL_MAX_DELAY)
{
if ((Timeout == 0U) || ((HAL_GetTick() - tickstart) > Timeout))
{
hrtc->State = HAL_RTC_STATE_TIMEOUT;
return HAL_TIMEOUT;
}
}
}
/* Clear the Tamper Flag */
__HAL_RTC_TAMPER_CLEAR_FLAG(hrtc, RTC_FLAG_TAMP1F);
/* Change RTC state */
hrtc->State = HAL_RTC_STATE_READY;
return HAL_OK;
}
/**
* @brief Handle Tamper 2 Polling.
* @param hrtc RTC handle
* @param Timeout Timeout duration
* @retval HAL status
*/
HAL_StatusTypeDef HAL_RTCEx_PollForTamper2Event(RTC_HandleTypeDef *hrtc, uint32_t Timeout)
{
uint32_t tickstart = HAL_GetTick();
/* Get the status of the Interrupt */
while (__HAL_RTC_TAMPER_GET_FLAG(hrtc, RTC_FLAG_TAMP2F) == RESET)
{
if (Timeout != HAL_MAX_DELAY)
{
if ((Timeout == 0U) || ((HAL_GetTick() - tickstart) > Timeout))
{
hrtc->State = HAL_RTC_STATE_TIMEOUT;
return HAL_TIMEOUT;
}
}
}
/* Clear the Tamper Flag */
__HAL_RTC_TAMPER_CLEAR_FLAG(hrtc, RTC_FLAG_TAMP2F);
/* Change RTC state */
hrtc->State = HAL_RTC_STATE_READY;
return HAL_OK;
}
#if defined(STM32F071xB) || defined(STM32F072xB) || defined(STM32F078xx) || defined(STM32F091xC) || defined(STM32F098xx)
/**
* @brief Handle Tamper 3 Polling.
* @param hrtc RTC handle
* @param Timeout Timeout duration
* @retval HAL status
*/
HAL_StatusTypeDef HAL_RTCEx_PollForTamper3Event(RTC_HandleTypeDef *hrtc, uint32_t Timeout)
{
uint32_t tickstart = HAL_GetTick();
/* Get the status of the Interrupt */
while (__HAL_RTC_TAMPER_GET_FLAG(hrtc, RTC_FLAG_TAMP3F) == RESET)
{
if (Timeout != HAL_MAX_DELAY)
{
if ((Timeout == 0U) || ((HAL_GetTick() - tickstart) > Timeout))
{
hrtc->State = HAL_RTC_STATE_TIMEOUT;
return HAL_TIMEOUT;
}
}
}
/* Clear the Tamper Flag */
__HAL_RTC_TAMPER_CLEAR_FLAG(hrtc, RTC_FLAG_TAMP3F);
/* Change RTC state */
hrtc->State = HAL_RTC_STATE_READY;
return HAL_OK;
}
#endif
/**
* @}
*/
#if defined(STM32F070xB) || defined(STM32F071xB) || defined(STM32F072xB) || defined(STM32F078xx) || defined(STM32F091xC) || defined(STM32F098xx) || defined(STM32F030xC)
/** @addtogroup RTCEx_Exported_Functions_Group2
* @brief RTC Wake-up functions
*
@verbatim
##### RTC Wake-up functions #####
[..] This section provides functions allowing to configure Wake-up feature
@endverbatim
* @{
*/
/**
* @brief Set wake up timer.
* @param hrtc RTC handle
* @param WakeUpCounter Wake up counter
* @param WakeUpClock Wake up clock
* @retval HAL status
*/
HAL_StatusTypeDef HAL_RTCEx_SetWakeUpTimer(RTC_HandleTypeDef *hrtc, uint32_t WakeUpCounter, uint32_t WakeUpClock)
{
uint32_t tickstart = 0U;
/* Check the parameters */
assert_param(IS_RTC_WAKEUP_CLOCK(WakeUpClock));
assert_param(IS_RTC_WAKEUP_COUNTER(WakeUpCounter));
/* Process Locked */
__HAL_LOCK(hrtc);
hrtc->State = HAL_RTC_STATE_BUSY;
/* Disable the write protection for RTC registers */
__HAL_RTC_WRITEPROTECTION_DISABLE(hrtc);
/*Check RTC WUTWF flag is reset only when wake up timer enabled*/
if ((hrtc->Instance->CR & RTC_CR_WUTE) != RESET)
{
tickstart = HAL_GetTick();
/* Wait till RTC WUTWF flag is reset and if Time out is reached exit */
while (__HAL_RTC_WAKEUPTIMER_GET_FLAG(hrtc, RTC_FLAG_WUTWF) == SET)
{
if ((HAL_GetTick() - tickstart) > RTC_TIMEOUT_VALUE)
{
/* Enable the write protection for RTC registers */
__HAL_RTC_WRITEPROTECTION_ENABLE(hrtc);
hrtc->State = HAL_RTC_STATE_TIMEOUT;
/* Process Unlocked */
__HAL_UNLOCK(hrtc);
return HAL_TIMEOUT;
}
}
}
__HAL_RTC_WAKEUPTIMER_DISABLE(hrtc);
tickstart = HAL_GetTick();
/* Wait till RTC WUTWF flag is set and if Time out is reached exit */
while (__HAL_RTC_WAKEUPTIMER_GET_FLAG(hrtc, RTC_FLAG_WUTWF) == RESET)
{
if ((HAL_GetTick() - tickstart) > RTC_TIMEOUT_VALUE)
{
/* Enable the write protection for RTC registers */
__HAL_RTC_WRITEPROTECTION_ENABLE(hrtc);
hrtc->State = HAL_RTC_STATE_TIMEOUT;
/* Process Unlocked */
__HAL_UNLOCK(hrtc);
return HAL_TIMEOUT;
}
}
/* Clear the Wakeup Timer clock source bits in CR register */
hrtc->Instance->CR &= (uint32_t)~RTC_CR_WUCKSEL;
/* Configure the clock source */
hrtc->Instance->CR |= (uint32_t)WakeUpClock;
/* Configure the Wakeup Timer counter */
hrtc->Instance->WUTR = (uint32_t)WakeUpCounter;
/* Enable the Wakeup Timer */
__HAL_RTC_WAKEUPTIMER_ENABLE(hrtc);
/* Enable the write protection for RTC registers */
__HAL_RTC_WRITEPROTECTION_ENABLE(hrtc);
hrtc->State = HAL_RTC_STATE_READY;
/* Process Unlocked */
__HAL_UNLOCK(hrtc);
return HAL_OK;
}
/**
* @brief Set wake up timer with interrupt.
* @param hrtc RTC handle
* @param WakeUpCounter Wake up counter
* @param WakeUpClock Wake up clock
* @retval HAL status
*/
HAL_StatusTypeDef HAL_RTCEx_SetWakeUpTimer_IT(RTC_HandleTypeDef *hrtc, uint32_t WakeUpCounter, uint32_t WakeUpClock)
{
uint32_t tickstart = 0U;
/* Check the parameters */
assert_param(IS_RTC_WAKEUP_CLOCK(WakeUpClock));
assert_param(IS_RTC_WAKEUP_COUNTER(WakeUpCounter));
/* Process Locked */
__HAL_LOCK(hrtc);
hrtc->State = HAL_RTC_STATE_BUSY;
/* Disable the write protection for RTC registers */
__HAL_RTC_WRITEPROTECTION_DISABLE(hrtc);
/*Check RTC WUTWF flag is reset only when wake up timer enabled*/
if ((hrtc->Instance->CR & RTC_CR_WUTE) != RESET)
{
tickstart = HAL_GetTick();
/* Wait till RTC WUTWF flag is reset and if Time out is reached exit */
while (__HAL_RTC_WAKEUPTIMER_GET_FLAG(hrtc, RTC_FLAG_WUTWF) == SET)
{
if ((HAL_GetTick() - tickstart) > RTC_TIMEOUT_VALUE)
{
/* Enable the write protection for RTC registers */
__HAL_RTC_WRITEPROTECTION_ENABLE(hrtc);
hrtc->State = HAL_RTC_STATE_TIMEOUT;
/* Process Unlocked */
__HAL_UNLOCK(hrtc);
return HAL_TIMEOUT;
}
}
}
/* Disable the Wake-Up timer */
__HAL_RTC_WAKEUPTIMER_DISABLE(hrtc);
/* Clear flag Wake-Up */
__HAL_RTC_WAKEUPTIMER_CLEAR_FLAG(hrtc, RTC_FLAG_WUTF);
tickstart = HAL_GetTick();
/* Wait till RTC WUTWF flag is set and if Time out is reached exit */
while (__HAL_RTC_WAKEUPTIMER_GET_FLAG(hrtc, RTC_FLAG_WUTWF) == RESET)
{
if ((HAL_GetTick() - tickstart) > RTC_TIMEOUT_VALUE)
{
/* Enable the write protection for RTC registers */
__HAL_RTC_WRITEPROTECTION_ENABLE(hrtc);
hrtc->State = HAL_RTC_STATE_TIMEOUT;
/* Process Unlocked */
__HAL_UNLOCK(hrtc);
return HAL_TIMEOUT;
}
}
/* Configure the Wakeup Timer counter */
hrtc->Instance->WUTR = (uint32_t)WakeUpCounter;
/* Clear the Wakeup Timer clock source bits in CR register */
hrtc->Instance->CR &= (uint32_t)~RTC_CR_WUCKSEL;
/* Configure the clock source */
hrtc->Instance->CR |= (uint32_t)WakeUpClock;
/* RTC WakeUpTimer Interrupt Configuration: EXTI configuration */
__HAL_RTC_WAKEUPTIMER_EXTI_ENABLE_IT();
__HAL_RTC_WAKEUPTIMER_EXTI_ENABLE_RISING_EDGE();
/* Configure the Interrupt in the RTC_CR register */
__HAL_RTC_WAKEUPTIMER_ENABLE_IT(hrtc, RTC_IT_WUT);
/* Enable the Wakeup Timer */
__HAL_RTC_WAKEUPTIMER_ENABLE(hrtc);
/* Enable the write protection for RTC registers */
__HAL_RTC_WRITEPROTECTION_ENABLE(hrtc);
hrtc->State = HAL_RTC_STATE_READY;
/* Process Unlocked */
__HAL_UNLOCK(hrtc);
return HAL_OK;
}
/**
* @brief Deactivate wake up timer counter.
* @param hrtc RTC handle
* @retval HAL status
*/
uint32_t HAL_RTCEx_DeactivateWakeUpTimer(RTC_HandleTypeDef *hrtc)
{
uint32_t tickstart = 0U;
/* Process Locked */
__HAL_LOCK(hrtc);
hrtc->State = HAL_RTC_STATE_BUSY;
/* Disable the write protection for RTC registers */
__HAL_RTC_WRITEPROTECTION_DISABLE(hrtc);
/* Disable the Wakeup Timer */
__HAL_RTC_WAKEUPTIMER_DISABLE(hrtc);
/* In case of interrupt mode is used, the interrupt source must disabled */
__HAL_RTC_WAKEUPTIMER_DISABLE_IT(hrtc, RTC_IT_WUT);
tickstart = HAL_GetTick();
/* Wait till RTC WUTWF flag is set and if Time out is reached exit */
while (__HAL_RTC_WAKEUPTIMER_GET_FLAG(hrtc, RTC_FLAG_WUTWF) == RESET)
{
if ((HAL_GetTick() - tickstart) > RTC_TIMEOUT_VALUE)
{
/* Enable the write protection for RTC registers */
__HAL_RTC_WRITEPROTECTION_ENABLE(hrtc);
hrtc->State = HAL_RTC_STATE_TIMEOUT;
/* Process Unlocked */
__HAL_UNLOCK(hrtc);
return HAL_TIMEOUT;
}
}
/* Enable the write protection for RTC registers */
__HAL_RTC_WRITEPROTECTION_ENABLE(hrtc);
hrtc->State = HAL_RTC_STATE_READY;
/* Process Unlocked */
__HAL_UNLOCK(hrtc);
return HAL_OK;
}
/**
* @brief Get wake up timer counter.
* @param hrtc RTC handle
* @retval Counter value
*/
uint32_t HAL_RTCEx_GetWakeUpTimer(RTC_HandleTypeDef *hrtc)
{
/* Get the counter value */
return ((uint32_t)(hrtc->Instance->WUTR & RTC_WUTR_WUT));
}
/**
* @brief Handle Wake Up Timer interrupt request.
* @param hrtc RTC handle
* @retval None
*/
void HAL_RTCEx_WakeUpTimerIRQHandler(RTC_HandleTypeDef *hrtc)
{
/* Get the WAKEUPTIMER interrupt source enable status */
if (__HAL_RTC_WAKEUPTIMER_GET_IT_SOURCE(hrtc, RTC_IT_WUT) != RESET)
{
/* Get the pending status of the WAKEUPTIMER Interrupt */
if (__HAL_RTC_WAKEUPTIMER_GET_FLAG(hrtc, RTC_FLAG_WUTF) != RESET)
{
/* WAKEUPTIMER callback */
#if (USE_HAL_RTC_REGISTER_CALLBACKS == 1)
hrtc->WakeUpTimerEventCallback(hrtc);
#else
HAL_RTCEx_WakeUpTimerEventCallback(hrtc);
#endif /* USE_HAL_RTC_REGISTER_CALLBACKS */
/* Clear the WAKEUPTIMER interrupt pending bit */
__HAL_RTC_WAKEUPTIMER_CLEAR_FLAG(hrtc, RTC_FLAG_WUTF);
}
}
/* Clear the EXTI's line Flag for RTC WakeUpTimer */
__HAL_RTC_WAKEUPTIMER_EXTI_CLEAR_FLAG();
/* Change RTC state */
hrtc->State = HAL_RTC_STATE_READY;
}
/**
* @brief Wake Up Timer callback.
* @param hrtc RTC handle
* @retval None
*/
__weak void HAL_RTCEx_WakeUpTimerEventCallback(RTC_HandleTypeDef *hrtc)
{
/* Prevent unused argument(s) compilation warning */
UNUSED(hrtc);
/* NOTE : This function should not be modified, when the callback is needed,
the HAL_RTCEx_WakeUpTimerEventCallback could be implemented in the user file
*/
}
/**
* @brief Handle Wake Up Timer Polling.
* @param hrtc RTC handle
* @param Timeout Timeout duration
* @retval HAL status
*/
HAL_StatusTypeDef HAL_RTCEx_PollForWakeUpTimerEvent(RTC_HandleTypeDef *hrtc, uint32_t Timeout)
{
uint32_t tickstart = HAL_GetTick();
while (__HAL_RTC_WAKEUPTIMER_GET_FLAG(hrtc, RTC_FLAG_WUTF) == RESET)
{
if (Timeout != HAL_MAX_DELAY)
{
if ((Timeout == 0U) || ((HAL_GetTick() - tickstart) > Timeout))
{
hrtc->State = HAL_RTC_STATE_TIMEOUT;
return HAL_TIMEOUT;
}
}
}
/* Clear the WAKEUPTIMER Flag */
__HAL_RTC_WAKEUPTIMER_CLEAR_FLAG(hrtc, RTC_FLAG_WUTF);
/* Change RTC state */
hrtc->State = HAL_RTC_STATE_READY;
return HAL_OK;
}
/**
* @}
*/
#endif /* defined(STM32F070xB) || defined(STM32F071xB) || defined(STM32F072xB) || defined(STM32F078xx) || defined(STM32F091xC) || defined(STM32F098xx) | defined(STM32F030xC) */
/** @addtogroup RTCEx_Exported_Functions_Group3
* @brief Extended Peripheral Control functions
*
@verbatim
##### Extended Peripheral Control functions #####
[..]
This subsection provides functions allowing to
(+) Write a data in a specified RTC Backup data register
(+) Read a data in a specified RTC Backup data register
(+) Set the Coarse calibration parameters.
(+) Deactivate the Coarse calibration parameters
(+) Set the Smooth calibration parameters.
(+) Configure the Synchronization Shift Control Settings.
(+) Configure the Calibration Pinout (RTC_CALIB) Selection (1Hz or 512Hz).
(+) Deactivate the Calibration Pinout (RTC_CALIB) Selection (1Hz or 512Hz).
(+) Enable the RTC reference clock detection.
(+) Disable the RTC reference clock detection.
(+) Enable the Bypass Shadow feature.
(+) Disable the Bypass Shadow feature.
@endverbatim
* @{
*/
#if !defined(STM32F030x6) && !defined(STM32F030x8) && !defined(STM32F070x6) && !defined(STM32F070xB) && !defined(STM32F030xC)
/**
* @brief Write a data in a specified RTC Backup data register.
* @param hrtc RTC handle
* @param BackupRegister RTC Backup data Register number.
* This parameter can be: RTC_BKP_DRx where x can be from 0 to 4 to
* specify the register.
* @param Data Data to be written in the specified RTC Backup data register.
* @retval None
*/
void HAL_RTCEx_BKUPWrite(RTC_HandleTypeDef *hrtc, uint32_t BackupRegister, uint32_t Data)
{
uint32_t tmp = 0U;
/* Check the parameters */
assert_param(IS_RTC_BKP(BackupRegister));
tmp = (uint32_t) & (hrtc->Instance->BKP0R);
tmp += (BackupRegister * 4U);
/* Write the specified register */
*(__IO uint32_t *)tmp = (uint32_t)Data;
}
/**
* @brief Reads data from the specified RTC Backup data Register.
* @param hrtc RTC handle
* @param BackupRegister RTC Backup data Register number.
* This parameter can be: RTC_BKP_DRx where x can be from 0 to 4 to
* specify the register.
* @retval Read value
*/
uint32_t HAL_RTCEx_BKUPRead(RTC_HandleTypeDef *hrtc, uint32_t BackupRegister)
{
uint32_t tmp = 0U;
/* Check the parameters */
assert_param(IS_RTC_BKP(BackupRegister));
tmp = (uint32_t) & (hrtc->Instance->BKP0R);
tmp += (BackupRegister * 4U);
/* Read the specified register */
return (*(__IO uint32_t *)tmp);
}
#endif /* !defined(STM32F030x6) && !defined(STM32F030x8) && !defined(STM32F070x6) && !defined(STM32F070xB) && !defined(STM32F030xC) */
/**
* @brief Set the Smooth calibration parameters.
* @param hrtc RTC handle
* @param SmoothCalibPeriod Select the Smooth Calibration Period.
* This parameter can be can be one of the following values :
* @arg RTC_SMOOTHCALIB_PERIOD_32SEC: The smooth calibration period is 32s.
* @arg RTC_SMOOTHCALIB_PERIOD_16SEC: The smooth calibration period is 16s.
* @arg RTC_SMOOTHCALIB_PERIOD_8SEC: The smooth calibration period is 8s.
* @param SmoothCalibPlusPulses Select to Set or reset the CALP bit.
* This parameter can be one of the following values:
* @arg RTC_SMOOTHCALIB_PLUSPULSES_SET: Add one RTCCLK pulse every 2*11 pulses.
* @arg RTC_SMOOTHCALIB_PLUSPULSES_RESET: No RTCCLK pulses are added.
* @param SmoothCalibMinusPulsesValue Select the value of CALM[8:0] bits.
* This parameter can be one any value from 0 to 0x000001FF.
* @note To deactivate the smooth calibration, the field SmoothCalibPlusPulses
* must be equal to SMOOTHCALIB_PLUSPULSES_RESET and the field
* SmoothCalibMinusPulsesValue mut be equal to 0.
* @retval HAL status
*/
HAL_StatusTypeDef HAL_RTCEx_SetSmoothCalib(RTC_HandleTypeDef *hrtc, uint32_t SmoothCalibPeriod, uint32_t SmoothCalibPlusPulses, uint32_t SmoothCalibMinusPulsesValue)
{
uint32_t tickstart = 0U;
/* Check the parameters */
assert_param(IS_RTC_SMOOTH_CALIB_PERIOD(SmoothCalibPeriod));
assert_param(IS_RTC_SMOOTH_CALIB_PLUS(SmoothCalibPlusPulses));
assert_param(IS_RTC_SMOOTH_CALIB_MINUS(SmoothCalibMinusPulsesValue));
/* Process Locked */
__HAL_LOCK(hrtc);
hrtc->State = HAL_RTC_STATE_BUSY;
/* Disable the write protection for RTC registers */
__HAL_RTC_WRITEPROTECTION_DISABLE(hrtc);
/* check if a calibration is pending*/
if ((hrtc->Instance->ISR & RTC_ISR_RECALPF) != RESET)
{
tickstart = HAL_GetTick();
/* check if a calibration is pending*/
while ((hrtc->Instance->ISR & RTC_ISR_RECALPF) != RESET)
{
if ((HAL_GetTick() - tickstart) > RTC_TIMEOUT_VALUE)
{
/* Enable the write protection for RTC registers */
__HAL_RTC_WRITEPROTECTION_ENABLE(hrtc);
/* Change RTC state */
hrtc->State = HAL_RTC_STATE_TIMEOUT;
/* Process Unlocked */
__HAL_UNLOCK(hrtc);
return HAL_TIMEOUT;
}
}
}
/* Configure the Smooth calibration settings */
hrtc->Instance->CALR = (uint32_t)((uint32_t)SmoothCalibPeriod | (uint32_t)SmoothCalibPlusPulses | (uint32_t)SmoothCalibMinusPulsesValue);
/* Enable the write protection for RTC registers */
__HAL_RTC_WRITEPROTECTION_ENABLE(hrtc);
/* Change RTC state */
hrtc->State = HAL_RTC_STATE_READY;
/* Process Unlocked */
__HAL_UNLOCK(hrtc);
return HAL_OK;
}
/**
* @brief Configure the Synchronization Shift Control Settings.
* @note When REFCKON is set, firmware must not write to Shift control register.
* @param hrtc RTC handle
* @param ShiftAdd1S Select to add or not 1 second to the time calendar.
* This parameter can be one of the following values :
* @arg RTC_SHIFTADD1S_SET: Add one second to the clock calendar.
* @arg RTC_SHIFTADD1S_RESET: No effect.
* @param ShiftSubFS Select the number of Second Fractions to substitute.
* This parameter can be one any value from 0 to 0x7FFF.
* @retval HAL status
*/
HAL_StatusTypeDef HAL_RTCEx_SetSynchroShift(RTC_HandleTypeDef *hrtc, uint32_t ShiftAdd1S, uint32_t ShiftSubFS)
{
uint32_t tickstart = 0U;
/* Check the parameters */
assert_param(IS_RTC_SHIFT_ADD1S(ShiftAdd1S));
assert_param(IS_RTC_SHIFT_SUBFS(ShiftSubFS));
/* Process Locked */
__HAL_LOCK(hrtc);
hrtc->State = HAL_RTC_STATE_BUSY;
/* Disable the write protection for RTC registers */
__HAL_RTC_WRITEPROTECTION_DISABLE(hrtc);
tickstart = HAL_GetTick();
/* Wait until the shift is completed*/
while ((hrtc->Instance->ISR & RTC_ISR_SHPF) != RESET)
{
if ((HAL_GetTick() - tickstart) > RTC_TIMEOUT_VALUE)
{
/* Enable the write protection for RTC registers */
__HAL_RTC_WRITEPROTECTION_ENABLE(hrtc);
hrtc->State = HAL_RTC_STATE_TIMEOUT;
/* Process Unlocked */
__HAL_UNLOCK(hrtc);
return HAL_TIMEOUT;
}
}
/* Check if the reference clock detection is disabled */
if ((hrtc->Instance->CR & RTC_CR_REFCKON) == RESET)
{
/* Configure the Shift settings */
hrtc->Instance->SHIFTR = (uint32_t)(uint32_t)(ShiftSubFS) | (uint32_t)(ShiftAdd1S);
/* If RTC_CR_BYPSHAD bit = 0, wait for synchro else this check is not needed */
if ((hrtc->Instance->CR & RTC_CR_BYPSHAD) == RESET)
{
if (HAL_RTC_WaitForSynchro(hrtc) != HAL_OK)
{
/* Enable the write protection for RTC registers */
__HAL_RTC_WRITEPROTECTION_ENABLE(hrtc);
hrtc->State = HAL_RTC_STATE_ERROR;
/* Process Unlocked */
__HAL_UNLOCK(hrtc);
return HAL_ERROR;
}
}
}
else
{
/* Enable the write protection for RTC registers */
__HAL_RTC_WRITEPROTECTION_ENABLE(hrtc);
/* Change RTC state */
hrtc->State = HAL_RTC_STATE_ERROR;
/* Process Unlocked */
__HAL_UNLOCK(hrtc);
return HAL_ERROR;
}
/* Enable the write protection for RTC registers */
__HAL_RTC_WRITEPROTECTION_ENABLE(hrtc);
/* Change RTC state */
hrtc->State = HAL_RTC_STATE_READY;
/* Process Unlocked */
__HAL_UNLOCK(hrtc);
return HAL_OK;
}
/**
* @brief Configure the Calibration Pinout (RTC_CALIB) Selection (1Hz or 512Hz).
* @param hrtc RTC handle
* @param CalibOutput Select the Calibration output Selection .
* This parameter can be one of the following values:
* @arg RTC_CALIBOUTPUT_512HZ: A signal has a regular waveform at 512Hz.
* @arg RTC_CALIBOUTPUT_1HZ: A signal has a regular waveform at 1Hz.
* @retval HAL status
*/
HAL_StatusTypeDef HAL_RTCEx_SetCalibrationOutPut(RTC_HandleTypeDef *hrtc, uint32_t CalibOutput)
{
/* Check the parameters */
assert_param(IS_RTC_CALIB_OUTPUT(CalibOutput));
/* Process Locked */
__HAL_LOCK(hrtc);
hrtc->State = HAL_RTC_STATE_BUSY;
/* Disable the write protection for RTC registers */
__HAL_RTC_WRITEPROTECTION_DISABLE(hrtc);
/* Clear flags before config */
hrtc->Instance->CR &= (uint32_t)~RTC_CR_COSEL;
/* Configure the RTC_CR register */
hrtc->Instance->CR |= (uint32_t)CalibOutput;
__HAL_RTC_CALIBRATION_OUTPUT_ENABLE(hrtc);
/* Enable the write protection for RTC registers */
__HAL_RTC_WRITEPROTECTION_ENABLE(hrtc);
/* Change RTC state */
hrtc->State = HAL_RTC_STATE_READY;
/* Process Unlocked */
__HAL_UNLOCK(hrtc);
return HAL_OK;
}
/**
* @brief Deactivate the Calibration Pinout (RTC_CALIB) Selection (1Hz or 512Hz).
* @param hrtc RTC handle
* @retval HAL status
*/
HAL_StatusTypeDef HAL_RTCEx_DeactivateCalibrationOutPut(RTC_HandleTypeDef *hrtc)
{
/* Process Locked */
__HAL_LOCK(hrtc);
hrtc->State = HAL_RTC_STATE_BUSY;
/* Disable the write protection for RTC registers */
__HAL_RTC_WRITEPROTECTION_DISABLE(hrtc);
__HAL_RTC_CALIBRATION_OUTPUT_DISABLE(hrtc);
/* Enable the write protection for RTC registers */
__HAL_RTC_WRITEPROTECTION_ENABLE(hrtc);
/* Change RTC state */
hrtc->State = HAL_RTC_STATE_READY;
/* Process Unlocked */
__HAL_UNLOCK(hrtc);
return HAL_OK;
}
/**
* @brief Enable the RTC reference clock detection.
* @param hrtc RTC handle
* @retval HAL status
*/
HAL_StatusTypeDef HAL_RTCEx_SetRefClock(RTC_HandleTypeDef *hrtc)
{
/* Process Locked */
__HAL_LOCK(hrtc);
hrtc->State = HAL_RTC_STATE_BUSY;
/* Disable the write protection for RTC registers */
__HAL_RTC_WRITEPROTECTION_DISABLE(hrtc);
/* Set Initialization mode */
if (RTC_EnterInitMode(hrtc) != HAL_OK)
{
/* Enable the write protection for RTC registers */
__HAL_RTC_WRITEPROTECTION_ENABLE(hrtc);
/* Set RTC state*/
hrtc->State = HAL_RTC_STATE_ERROR;
/* Process Unlocked */
__HAL_UNLOCK(hrtc);
return HAL_ERROR;
}
else
{
__HAL_RTC_CLOCKREF_DETECTION_ENABLE(hrtc);
/* Exit Initialization mode */
hrtc->Instance->ISR &= (uint32_t)~RTC_ISR_INIT;
}
/* Enable the write protection for RTC registers */
__HAL_RTC_WRITEPROTECTION_ENABLE(hrtc);
/* Change RTC state */
hrtc->State = HAL_RTC_STATE_READY;
/* Process Unlocked */
__HAL_UNLOCK(hrtc);
return HAL_OK;
}
/**
* @brief Disable the RTC reference clock detection.
* @param hrtc RTC handle
* @retval HAL status
*/
HAL_StatusTypeDef HAL_RTCEx_DeactivateRefClock(RTC_HandleTypeDef *hrtc)
{
/* Process Locked */
__HAL_LOCK(hrtc);
hrtc->State = HAL_RTC_STATE_BUSY;
/* Disable the write protection for RTC registers */
__HAL_RTC_WRITEPROTECTION_DISABLE(hrtc);
/* Set Initialization mode */
if (RTC_EnterInitMode(hrtc) != HAL_OK)
{
/* Enable the write protection for RTC registers */
__HAL_RTC_WRITEPROTECTION_ENABLE(hrtc);
/* Set RTC state*/
hrtc->State = HAL_RTC_STATE_ERROR;
/* Process Unlocked */
__HAL_UNLOCK(hrtc);
return HAL_ERROR;
}
else
{
__HAL_RTC_CLOCKREF_DETECTION_DISABLE(hrtc);
/* Exit Initialization mode */
hrtc->Instance->ISR &= (uint32_t)~RTC_ISR_INIT;
}
/* Enable the write protection for RTC registers */
__HAL_RTC_WRITEPROTECTION_ENABLE(hrtc);
/* Change RTC state */
hrtc->State = HAL_RTC_STATE_READY;
/* Process Unlocked */
__HAL_UNLOCK(hrtc);
return HAL_OK;
}
/**
* @brief Enable the Bypass Shadow feature.
* @param hrtc RTC handle
* @note When the Bypass Shadow is enabled the calendar value are taken
* directly from the Calendar counter.
* @retval HAL status
*/
HAL_StatusTypeDef HAL_RTCEx_EnableBypassShadow(RTC_HandleTypeDef *hrtc)
{
/* Process Locked */
__HAL_LOCK(hrtc);
hrtc->State = HAL_RTC_STATE_BUSY;
/* Disable the write protection for RTC registers */
__HAL_RTC_WRITEPROTECTION_DISABLE(hrtc);
/* Set the BYPSHAD bit */
hrtc->Instance->CR |= (uint8_t)RTC_CR_BYPSHAD;
/* Enable the write protection for RTC registers */
__HAL_RTC_WRITEPROTECTION_ENABLE(hrtc);
/* Change RTC state */
hrtc->State = HAL_RTC_STATE_READY;
/* Process Unlocked */
__HAL_UNLOCK(hrtc);
return HAL_OK;
}
/**
* @brief Disable the Bypass Shadow feature.
* @param hrtc RTC handle
* @note When the Bypass Shadow is enabled the calendar value are taken
* directly from the Calendar counter.
* @retval HAL status
*/
HAL_StatusTypeDef HAL_RTCEx_DisableBypassShadow(RTC_HandleTypeDef *hrtc)
{
/* Process Locked */
__HAL_LOCK(hrtc);
hrtc->State = HAL_RTC_STATE_BUSY;
/* Disable the write protection for RTC registers */
__HAL_RTC_WRITEPROTECTION_DISABLE(hrtc);
/* Reset the BYPSHAD bit */
hrtc->Instance->CR &= ((uint8_t)~RTC_CR_BYPSHAD);
/* Enable the write protection for RTC registers */
__HAL_RTC_WRITEPROTECTION_ENABLE(hrtc);
/* Change RTC state */
hrtc->State = HAL_RTC_STATE_READY;
/* Process Unlocked */
__HAL_UNLOCK(hrtc);
return HAL_OK;
}
/**
* @}
*/
/**
* @}
*/
#endif /* HAL_RTC_MODULE_ENABLED */
/**
* @}
*/
/**
* @}
*/
/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ |
<%= form_for :article, url: posts_path do |f| %>
<% if @article.errors.any? %>
<div id="error_explanation">
<h2>
<%= pluralize(@article.errors.count, "error") %> prohibited
this article from being saved:
</h2>
<ul>
<% @article.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
<p>
<%= f.label :title %><br>
<%= f.text_field :title %>
</p>
<p>
<%= f.label :body %><br>
<%= f.text_area :body %>
</p>
<p>
<%= f.label :tag_list %><br>
<%= f.text_field :tag_list %>
</p>
<%= f.hidden_field :user_id, :value => current_user.id %>
<p>
<%= f.submit %>
</p>
<% end %>
<%= link_to 'Back', posts_path %> |
package main
import (
"fmt"
)
type Node[T any] struct {
val T
next *Node[T]
}
func NewNode[T any](v T) *Node[T] {
return &Node[T]{val: v}
}
func (n *Node[T]) Push(v T) *Node[T] {
node := NewNode(v)
n.next = node
return node
}
func main() {
node1 := NewNode(1) // *Node[int] 타입
node1.Push(2).Push(3).Push(4)
for node1 != nil {
fmt.Print(node1.val, " - ")
node1 = node1.next
}
node2 := NewNode("Hi") // *Node[string] 타입
node2.Push("Hello").Push("How are you?")
for node2 != nil {
fmt.Print(node2.val, " - ")
node2 = node2.next
}
} |
/* eslint-disable react/forbid-prop-types */
import React from 'react';
import PropTypes from 'prop-types';
import { AvatarWrapper, AvatarInitial } from './Styled';
const propTypes = {
profile: PropTypes.object.isRequired,
square: PropTypes.bool,
className: PropTypes.string,
style: PropTypes.object
};
const defaultProps = {
square: true,
className: null,
style: null
};
const getInitials = string => {
const names = string.split(' ');
const initials = names[0].substring(0, 1).toUpperCase();
return initials;
};
const Avatar = ({ profile, square, className, style }) => (
<AvatarWrapper square={square} className={className} style={style}>
<AvatarInitial>{getInitials(`${profile.firstName}`)}</AvatarInitial>
<AvatarInitial>{getInitials(`${profile.lastName}`)}</AvatarInitial>
</AvatarWrapper>
);
Avatar.propTypes = propTypes;
Avatar.defaultProps = defaultProps;
export default Avatar; |
/******************************************************************
*
* comm_funcs.cpp
* version: 20170720-0 Doug Paradis
* Communication functions for DPRG Club Robot 2016.
* Based on ideas from Ron Grant
*
******************************************************************/
#include "comm_funcs.h"
#include "task_def.h"
#include "nav_funcs.h"
#include "ultrasonic_funcs.h"
#include "motor_funcs.h"
#include "scoop_sensor_funcs.h"
#include "gate_funcs.h"
#include "pixy_funcs.h"
#include "helpful_defines.h"
// global variables
uint8_t first_run_pass_flg = 0;
/*****************************************************
*
* data packet (min size 4 bytes, add 3 bytes
* per additional data value)
*
* start of packet 0xFF (0xFF reserved for header)
* for each data value
* byte 1 7 bits of lower byte of int (least significant)
* byte 2 8 bits of upper byte of int shifted to be the
8th thru 15th bits of the integer
* byte 3 sign byte (0xf0 = neg, else pos)
*
* Only the header can be 0xFF
*
* range of values is -32639 to 32639 (-0x7F7F to 0x7F7F)
* no chksum
*
******************************************************/
void send_data_to_display(int num_of_data_val,int *data_array){
int val = 0;
uint8_t sign = 0x00; // positive
uint8_t least_byte, most_byte;
// send the header
Serial3.write(0xFF);
for (int j = 0; j < num_of_data_val; j++) {
val = data_array[j];
if (val < 0) {
val *= -1; // make value pos
sign = 0xF0; // negative (dec = 240)
}
else {
sign = 0x0F; // positive (dec = 15)
}
least_byte = val & 0x7F;
most_byte = val>>7;
// Note: Serial3 used to communicate to UNO working with display
Serial3.write(least_byte); // send least significant 7 bits range 0..127
Serial3.write(most_byte); // send most significant bits (bits 8 thru 15)
Serial3.write(sign);
}
}
uint8_t get_cmd_from_display(){
uint8_t val = 0;
uint8_t sign = 0x00; // positive
uint8_t least_byte, most_byte;
// if there's any data available from the display, read it:
if (Serial3.available() >= 2) {
val = Serial3.read();
if (val == 0xFF){ // if header, read cmd
val = Serial3.read(); //cmd
}
else{
val = MISSING_HEADER;
}
}
else {
val = NO_CMD_SENT;
}
return (val); // cmd value
}
void communicate_display_data(uint8_t cmd) {
int num_of_data_val;
int data_values[10] = {0,0,0,0,0,0,0,0,0,0};
static uint8_t gate_servo_loop_cnt = 0;
switch ((int) cmd)
{
case SONAR_DATA_CMD:
num_of_data_val = 2;
//eval_ultrasonic_sensors(ptr_us_R,ptr_us_L); // for use when using 2 ultrasonic sensors
eval_ultrasonic_sensor(ptr_us); // comment if using 2 ultrasonic sensors
data_values[0] = ptr_us->dist;
data_values[1] = 0; // only using 1 us sensor, 2nd sensor dist would go here
if ((ptr_us->new_read_flg == ON)){ // && (ptr_us_L->new_read_flg == ON)){
send_data_to_display(num_of_data_val,data_values);
ptr_us->new_read_flg = OFF; // comment out if using 2 US sensors
//ptr_us_R->new_read_flg = OFF; // uncomment if using 2 US sensors
//ptr_us_L->new_read_flg = OFF; // uncomment if using 2 US sensors
}
break;
case SCOOP_SEN_DATA_CMD:
num_of_data_val = 1;
data_values[0] = eval_scoop_sensor(ptr_scoop_sen);
send_data_to_display(num_of_data_val,data_values);
break;
case GATE_SERVO_DATA_CMD:
num_of_data_val = 1;
SoftwareServo::refresh(); // not sure if this the best place - seems to work without
gate_servo_loop_cnt++ ;
if (gate_servo_loop_cnt >= 50){ // used with delay in display pgm to set toggle interval
toggle_gate_state(ptr_gate);
gate_servo_loop_cnt = 0;
}
data_values[0] = (int) ptr_gate->result;
send_data_to_display(num_of_data_val,data_values);
break;
case CAMERA_DATA_CMD:
num_of_data_val = 1;
readCamera(ptr_pixy);
data_values[0] = ptr_pixy->result;
send_data_to_display(num_of_data_val,data_values);
break;
case ENCODER_DATA_CMD:
num_of_data_val = 2;
data_values[0] = (int16_t) encRight.read();
data_values[1] = (int16_t) -encLeft.read();
send_data_to_display(num_of_data_val,data_values);
break;
case RUN_DATA_CMD:
if (first_run_pass_flg == 0){
first_run_pass_flg = 1;
// reset encoders and gate
init_encoders();
open_gate(ptr_gate);
// used with real time operating system
semaphore_release(&scoop_sem);
semaphore_release(&us_sem);
semaphore_release(&cam_sem);
semaphore_release(&move_sem);
}
num_of_data_val = 3;
data_values[0] = (int16_t) ptr_loc->x_pos;
data_values[1] = (int16_t) ptr_loc->y_pos;
data_values[2] = (int16_t) ptr_loc->deg_theta;
send_data_to_display(num_of_data_val,data_values);
break;
default:
break;
}
} |
#import <Foundation/Foundation.h>
@interface Bit:NSObject
{ int effect ;
int target ;
int type;
int parameter;
}
@property int effect;
@property int target;
@property int type;
@property int parameter;
- (void) setMask:(int) mask;
- (int) mask;
@end;
@implementation Bit
@synthesize effect,target,type,parameter;
- (void) setMask:(int)mask {
effect = (mask & 0xff000000)>> 24;
target = (mask & 0x00ff0000)>> 16;
type = (mask & 0x0000ff00)>> 8;
parameter = (mask & 0x000000ff);
}
- (int) mask {
return (effect << 24) + (target << 16) + (type << 8) + parameter;
}
@end;
int main (int argc, const char * argv[])
{
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
Bit*bit = [[Bit alloc]init];
[bit setMask:0xffffffff];
NSLog(@"\n mask = %i \n",[bit mask]);
NSLog(@"\n\n effect = %i\n"
" target = %i\n"
" type = %i\n"
" parameter = %i\n\n\n",bit.effect,bit.target,bit.type,bit.parameter);
NSLog (@"hello world");
[pool drain];
return 0;
} |
// /* eslint-disable @typescript-eslint/no-explicit-any */
// /* eslint-disable dot-notation */
// import { HttpClientTestingModule } from '@angular/common/http/testing';
// import { Injectable } from '@angular/core';
// import { ComponentFixture, TestBed } from '@angular/core/testing';
// import { MatDialogModule } from '@angular/material/dialog';
// import { MatSnackBarModule } from '@angular/material/snack-bar';
// import { RouterTestingModule } from '@angular/router/testing';
// import { IconComponent } from '@app/components/icon/icon.component';
// import { GameType } from '@app/constants/game-type';
// import HighScoresService from '@app/services/high-score-service/high-score.service';
// import { SingleHighScore } from '@common/models/high-score';
// import { AdminHighScoresComponent } from './admin-high-scores.component';
// @Injectable()
// export class HighScoresServiceSpy extends HighScoresService {
// // eslint-disable-next-line no-unused-vars
// getHighScores(gameType: GameType): SingleHighScore[] {
// return [];
// }
// handleHighScoresRequest(): void {
// return;
// }
// resetHighScores(): void {
// return;
// }
// }
// describe('AdminHighScoresComponent', () => {
// let component: AdminHighScoresComponent;
// let fixture: ComponentFixture<AdminHighScoresComponent>;
// let handleHighScoreRequestSpy: jasmine.Spy;
// let subscribeSpy: jasmine.Spy;
// let getHighScoresSpy: jasmine.Spy;
// let resetHighScoresSpy: jasmine.Spy;
// beforeEach(async () => {
// await TestBed.configureTestingModule({
// declarations: [AdminHighScoresComponent, IconComponent],
// imports: [RouterTestingModule, HttpClientTestingModule, MatDialogModule, MatSnackBarModule],
// providers: [{ provide: HighScoresService, useClass: HighScoresServiceSpy }],
// }).compileComponents();
// });
// beforeEach(() => {
// fixture = TestBed.createComponent(AdminHighScoresComponent);
// component = fixture.componentInstance;
// fixture.detectChanges();
// handleHighScoreRequestSpy = spyOn<any>(component['highScoresService'], 'handleHighScoresRequest').and.callFake(() => {
// return;
// });
// subscribeSpy = spyOn<any>(component['highScoresService'], 'subscribeToInitializedHighScoresListEvent').and.callFake(() => {
// return;
// });
// getHighScoresSpy = spyOn(component['highScoresService'], 'getHighScores').and.returnValues([]);
// resetHighScoresSpy = spyOn(component['highScoresService'], 'resetHighScores').and.callFake(() => {
// return;
// });
// });
// it('should create', () => {
// expect(component).toBeTruthy();
// });
// describe('ngOnInit', () => {
// it('should call highScoresService.handleHighScoresRequest and highScoresService.subscribeToInitializedHighScoresListEvent', () => {
// component.ngOnInit();
// expect(handleHighScoreRequestSpy).toHaveBeenCalled();
// expect(subscribeSpy).toHaveBeenCalled();
// });
// it('initializedHighScoreListEvent should set initialized to true', () => {
// component.isInitialized = false;
// component.ngOnInit();
// component['highScoresService']['highScoresListInitializedEvent'].next();
// expect(component.isInitialized).toBeTrue();
// });
// });
// describe('ngOnDestroy', () => {
// it('should call next', () => {
// const spy = spyOn(component['componentDestroyed$'], 'next');
// spyOn(component['componentDestroyed$'], 'complete');
// component.ngOnDestroy();
// expect(spy).toHaveBeenCalled();
// });
// it('should call complete', () => {
// spyOn(component['componentDestroyed$'], 'next');
// const spy = spyOn(component['componentDestroyed$'], 'complete');
// component.ngOnDestroy();
// expect(spy).toHaveBeenCalled();
// });
// });
// describe('getClassicHighScores', () => {
// it('should call highScoresService.getHighScores with game type classic', () => {
// expect(component.getClassicHighScores()).toEqual([]);
// expect(getHighScoresSpy).toHaveBeenCalledWith(GameType.Classic);
// });
// });
// describe('getLog2990HighScores', () => {
// it('should call highScoresService.getHighScores with game type log2990', () => {
// expect(component.getLog2990HighScores()).toEqual([]);
// expect(getHighScoresSpy).toHaveBeenCalledWith(GameType.LOG2990);
// });
// });
// describe('resetHighScores', () => {
// it('should call highScoresService.resetHighScores', () => {
// component.resetHighScores();
// expect(resetHighScoresSpy).toHaveBeenCalled();
// });
// });
// describe('askResetVirtualPlayers', () => {
// it('should call MatDialog open', () => {
// const spy = spyOn(component['dialog'], 'open');
// component.askResetVirtualPlayers();
// expect(spy).toHaveBeenCalled();
// });
// });
// }); |
<?php
namespace App\Http\Controllers;
use App\Http\Requests\StoreUpdateProductRequest;
use App\Models\Product;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\View;
class ProductController extends Controller
{
protected $request;
protected $repository;
public function __construct(Request $request, Product $product) {
$this->request = $request;
$this->repository = $product;
// $this->middleware('auth');
// $this->middleware('auth')->only([
// 'create', 'store'
// ]);
// $this->middleware('auth')->except([
// 'index', 'show'
// ]);
}
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
//$products = Product::all();
//$products = Product::get();
$products = $this->repository::paginate(10);
// return view('teste',['teste' => $teste ]);
return view('admin.pages.products.index',[
'products' => $products,
]);
}
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function create()
{
return view('admin.pages.products.create');
}
/**
* Store a newly created resource in storage.
*
* @param App\Http\Requests\StoreUpdateProductRequest #request
* @return \Illuminate\Http\Response
*/
public function store(StoreUpdateProductRequest $request)
{
$data = $request->only('name', 'price', 'description');
if ($request->hasFile('image') && $request->image->isValid() ):
$imagePath = $request->image->store('products');
$data['image'] = $imagePath;
endif;
$this->repository->create($data);
//Product::create($data);
return redirect()->route('products.index');
// $product = new Product;
// $product->name = $data['name'];
// $product->save();
}
/**
* Display the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function show($id)
{
// $product = Product::where('id', $id)->first();
$product = $this->repository::find( $id);
if (!$product):
return redirect()->back();
endif;
return view('admin.pages.products.show',[
'product'=>$product
]);
}
/**
* Show the form for editing the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function edit($id)
{
$product = $this->repository::find( $id);
if (!$product):
return redirect()->back();
endif;
return view('admin.pages.products.edit',[
'product'=>$product
]);
}
/**
* Update the specified resource in storage.
*
* @param \App\Http\Requests\StoreUpdateProductRequest $request
* @param int $id
* @return \Illuminate\Http\Response
*/
public function update(StoreUpdateProductRequest $request, $id)
{
if (!$product = $this->repository::find( $id)):
return redirect()->back();
endif;
$data = $request->all();
if ($request->hasFile('image') && $request->image->isValid() ):
if ($product->image && Storage::exists($product->image) ):
Storage::delete($product->image);
endif;
$imagePath = $request->image->store('products');
$data['image'] = $imagePath;
endif;
$product->update($data);
return redirect()->route('products.index');
}
/**
* Remove the specified resource from storage.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function destroy($id)
{
$product = $this->repository->where('id', $id)->first();
if (!$product):
return redirect()->back();
endif;
if ($product->image && Storage::exists($product->image) ):
Storage::delete($product->image);
endif;
$product->delete();
return redirect()->route('products.index');
}
public function search(Request $request)
{
$filters = $request->all();
$products = $this->repository->search($request->filter);
return view('admin.pages.products.index',[
'products' => $products,
'filters' => $filters,
]);
}
} |
import React, { useState, useEffect } from 'react';
import "./ViewApplicants.css";
import axios from 'axios';
import { useParams } from 'react-router-dom';
function ViewApplicants() {
const [applicantsData, setApplicantsData] = useState([]);
const { jobId } = useParams();
useEffect(() => {
// Retrieve the JWT token from localStorage
const token = localStorage.getItem('token');
// Make a GET request to fetch applicants
axios.get(`https://dbms-jgsk.onrender.com/api/list-job/application/${jobId}`, {
headers: {
Authorization: `Bearer ${token}`,
},
})
.then(response => {
setApplicantsData(response.data.data);
console.log(response.data.data);
})
.catch(error => {
console.error('Error fetching applicants:', error);
});
}, [jobId]);
return (
<>
<div className="view__applicants">
<h1>JOB APPLICANTS</h1>
<div>
{applicantsData.length > 0 ? (
<ul>
{applicantsData.map(applicant => (
<div className="card__container" key={applicant._id}>
<div>
<h2>{applicant.name}</h2>
<p>Email: {applicant.email}</p>
<p>Phone: {applicant.phone}</p>
<p>Location: {applicant.location}</p>
<p>Qualifications: {applicant.qualifications}</p>
<p>Skills: {applicant.skills.join(', ')}</p>
<p>Experience: {applicant.experience}</p>
<p>Applied At: {new Date(applicant.appliedAt).toLocaleString()}</p>
</div>
</div>
))}
</ul>
) : (
<p>No applicants available</p>
)}
</div>
</div>
</>
);
}
export default ViewApplicants; |
import * as React from 'react';
import TextField from '@mui/material/TextField';
import Autocomplete from '@mui/material/Autocomplete';
import CircularProgress from '@mui/material/CircularProgress';
import { createTheme, ThemeProvider } from '@mui/material/styles';
const theme = createTheme({
palette: {
primary: {
main: '#CA8A04',
},
secondary: {
main: '#4F46E5',
}
},
});
interface Empresa {
name: string;
}
function sleep(duration: number): Promise<void> {
return new Promise<void>((resolve) => {
setTimeout(() => {
resolve();
}, duration);
});
}
// ... (imports y definición de Empresa e sleep)
export default function AutocompleteCustom(props: any) {
const [open, setOpen] = React.useState(false);
const [options, setOptions] = React.useState<readonly Empresa[]>([]);
const [inputValue, setInputValue] = React.useState<string | null>(props.default ? props.default : '');
const loading = open && options.length === 0;
const initial = props.default ? props.default : '';
const [defaultInput, setDefaultInput] = React.useState<Empresa | null>({
name: props.default ? props.default : ''
});
const handleInput = (event: React.ChangeEvent<{}>, value: string) => {
setInputValue(value);
updateOptions(value);
props.handleChange(value);
console.log("Input: ", value);
console.log("Default: ", props.default);
};
const updateOptions = async (value: string) => {
let newOptions: Empresa[] = data;
if (value.trim() !== '' && inputValue !== data[0].name) {
newOptions.unshift({ name: `${value}` });
}
setOptions(newOptions);
};
const data = props.who === 'Receptor' ?
[
{ name: 'Techno'},
{ name: 'Procarsol'},
{ name: 'Fraccionaria'},
{ name: 'TechSolutions'},
{ name: 'InnoTech'},
{ name: 'Globex'},
{ name: 'InnovateCorp'},
{ name: 'Soriana'},
{ name: 'Oxxo'},
{ name: 'Costco'},
]
:
[
{ name: 'Proveedor XYZ'},
{ name: 'Proveedor LMN'},
{ name: 'Proveedor ABC'},
{ name: 'LEY'},
{ name: 'Soriana'},
{ name: 'Oxxo'},
{ name: 'Costco'},
];
React.useEffect(() => {
let active = true;
if (!loading) {
return undefined;
}
(async () => {
await sleep(1e3); // For demo purposes.
if (active) {
updateOptions(inputValue || ''); // Actualizar opciones al abrir
}
})();
return () => {
active = false;
};
}, [loading, inputValue]);
React.useEffect(() => {
if (!open) {
setOptions([]);
}
if (props.default) {
setInputValue(props.default);
}
}, [open]);
return (
<ThemeProvider theme={theme}>
<Autocomplete
id="asynchronous-demo"
sx={{ width: 200, borderWidth: (props.update && (initial !== props.post)) ? 2.2 : 0, borderColor: 'primary.main', borderRadius: 2, borderStyle: 'solid'}}
open={open}
onOpen={() => {
setOpen(true);
}}
onClose={() => {
setOpen(false);
}}
autoComplete={true}
autoCapitalize='true'
onInputChange={handleInput}
defaultValue={defaultInput}
isOptionEqualToValue={(option, value) => option.name === value.name}
getOptionLabel={(option) => option.name}
options={options}
loading={loading}
renderInput={(params) => (
<TextField
{...params}
error={props.error}
//variant='standard'
size='small'
sx={{padding: 0, margin: 0}}
color={props.update && (initial !== props.post) ? 'primary' : 'secondary'}
margin='dense'
InputProps={{
...params.InputProps,
endAdornment: (
<React.Fragment>
{loading ? <CircularProgress color="inherit" size={20} /> : null}
{params.InputProps.endAdornment}
</React.Fragment>
),
}}
/>
)}
/>
</ThemeProvider>
);
} |
pragma solidity ^0.4.10;
import "zeppelin-solidity/contracts/token/SimpleToken.sol";
import "zeppelin-solidity/contracts/token/ERC20Basic.sol";
import 'zeppelin-solidity/contracts/ownership/Ownable.sol';
contract PensionFundRelease {
address[] public validators;
address public worker;
address public master;
uint8 public firstPaymentPercent;
uint8 public recurrentPaymentPercent;
uint public paymentTime;
uint public recurrentPaymentInterval;
bool public firtPaymentReleased = false;
ERC20Basic public roots;
uint public initialFunds;
struct Vote {
bool approve;
address validator;
string justification;
}
mapping (address => uint) public voteIndex;
Vote[] public votes;
event Voted(bool approve, address validator, string justification);
event Released(uint amount, address worker);
event Refunded(uint amount, address master);
function PensionFundRelease(
address[] _validators,
address _worker,
address _master,
uint8 _firstPaymentPercent,
uint _firstPaymentTime,
uint _recurrentPaymentInterval,
uint8 _recurrentPaymentPercent,
address _rootsAddress
) {
require(_validators.length > 0);
require(_worker != 0x0);
require(_master != 0x0);
require(_firstPaymentPercent <= 100);
require(_recurrentPaymentPercent <= 100);
validators = _validators;
worker = _worker;
master = _master;
firstPaymentPercent = _firstPaymentPercent;
paymentTime = _firstPaymentTime;
recurrentPaymentInterval = _recurrentPaymentInterval;
roots = ERC20Basic(_rootsAddress);
recurrentPaymentPercent = _recurrentPaymentPercent;
votes.push(Vote(false, 0x0, "")); //first dummy vote
}
//ensure that only validator can perform the action
modifier onlyValidator() {
bool isValidator = false;
for (uint i = 0; i < validators.length; i++) {
isValidator = isValidator || (msg.sender == validators[i]);
}
require(isValidator);
_;
}
//vote for the fund release or burn
function vote(bool approve, string justification) onlyValidator returns (uint index) {
index = voteIndex[msg.sender];
Vote memory vote = Vote(approve, msg.sender, justification);
if (index == 0) {
index = votes.length;
voteIndex[msg.sender] = index;
votes.push(vote);
} else {
votes[index] = vote;
}
Voted(approve, msg.sender, justification);
}
// check wether validators have approved the release
function isReleaseApproved() constant returns (bool approved) {
uint num = 0;
for (uint i = 1; i < votes.length; i++) { //skip dummy vote
if (votes[i].approve)
num++;
}
return num == validators.length;
}
// Check whether the time period on fund dispersal has been reached
function isFundFreezePeriodEnded() constant returns (bool ended) {
return (block.timestamp > paymentTime);
}
// check wether validators have decided to burn the fund
function isBurnApproved() constant returns (bool approved) {
uint num = 0;
for (uint i = 1; i < votes.length; i++) { //skip dummy vote
if (!votes[i].approve)
num++;
}
return num == validators.length;
}
// calculate the amount of payment
function getPaymentAmount() constant returns (uint amount) {
if (!firtPaymentReleased) {
return initialFunds * firstPaymentPercent / 100;
} else {
return initialFunds * recurrentPaymentPercent / 100;
}
}
// get current fund balance in ROOTs
function balance() constant returns (uint amount) {
return roots.balanceOf(this);
}
// release the fund
function releaseRoots() returns (uint releasedAmount) {
// Confirm validators have released funds
require(isReleaseApproved());
// Confirm the next payment is due to be released
require(isFundFreezePeriodEnded());
if (!firtPaymentReleased) {
initialFunds = balance();
releasedAmount = getPaymentAmount();
firtPaymentReleased = true;
} else {
releasedAmount = getPaymentAmount();
}
if (releasedAmount > balance())
releasedAmount = balance();
// Assumes intended interval is meant to recur regardless of claiming funds
paymentTime = paymentTime + recurrentPaymentInterval;
roots.transfer(worker, releasedAmount);
Released(releasedAmount, worker);
}
function refundRoots() returns (uint refundedAmount) {
// Confirm validators have refunded funds
require(isBurnApproved());
// Assumes intended interval is meant to recur regardless of claiming funds
refundedAmount = balance();
roots.transfer(master, refundedAmount);
Refunded(refundedAmount, master);
}
} |
import {createAsyncThunk, createSlice} from "@reduxjs/toolkit";
import axios from "axios";
import {displayNotification} from "./notification.jsx";
import {history} from "../components/Navbar/HorizontalNavbar.jsx";
import base from '../api/baseService.jsx';
const api = base.service(true);
export const initialState = {
isAuthenticated: false,
loggedUser: null,
backendErrors: {},
}
export const userLogin = createAsyncThunk(
'auth/login', async ({username, password}, {dispatch, rejectWithValue}) => {
try {
const response = await axios.post('/api/users/login', {username, password});
const {accessToken} = response.data;
localStorage.setItem('token', accessToken);
dispatch(getLoggedUser({}))
dispatch(displayNotification({
notificationType: "success",
message: "Login successful!",
title: "Login"
}))
return response.data;
} catch (error) {
dispatch(displayNotification({
notificationType: "error",
message: "Login failed. Please try again.",
title: "Login"
}))
return rejectWithValue(error.response.data);
}
}
);
export const changePassword = createAsyncThunk(
'auth/change_password', async ({data}, {dispatch, rejectWithValue}) => {
try {
const response = await api.put('/api/users/change_password', data);
dispatch(getLoggedUser({}))
dispatch(displayNotification({
notificationType: "success",
message: "Password changed successfully!",
title: "Change password"
}))
return response.data;
} catch (error) {
dispatch(displayNotification({
notificationType: "error",
message: "Change password failed. Please try again.",
title: "Change password"
}))
return rejectWithValue(error.response.data);
}
}
);
export const getLoggedUser = createAsyncThunk(
'user/logged', async ({rejectWithValue}) => {
try {
const response = await api.get('/api/users/user/logged');
return response.data;
} catch (error) {
return rejectWithValue(error.response.data);
}
}
);
export const uploadAvatar = createAsyncThunk(
'auth/avatar', async ({formData, uid}, {rejectWithValue}) => {
try {
const response = await axios.post('/api/users/upload_avatar', formData, {
headers: {
'Content-Type': 'multipart/form-data'
},
params: {uid}
});
return response.data;
} catch (error) {
return rejectWithValue(error.response.data);
}
}
);
export const userRegister = createAsyncThunk(
'auth/register', async (data, {dispatch, rejectWithValue}) => {
try {
const response = await axios.post('/api/users/', data);
dispatch(displayNotification({
notificationType: "success",
message: "Registration successful. Your account will be approved shortly.",
title: "Registration"
}))
history.navigate("/")
return response.data;
} catch (error) {
return rejectWithValue(error.response.data);
}
}
);
export const updateUser = createAsyncThunk(
"users/update",
async ({data}, {dispatch, rejectWithValue}) => {
try {
const response = await api.patch(`/api/users/update/profile`, (data));
dispatch(getLoggedUser({}))
dispatch(displayNotification({
notificationType: "success",
message: "User updated successfully!",
title: "User"
}))
return response.data;
} catch (error) {
dispatch(displayNotification({
notificationType: "error",
message: "Error while updating profile!",
title: "User"
}))
return rejectWithValue(error.response.data);
}
}
)
export const authSlice = createSlice({
name: "auth",
initialState,
reducers: {
logout: (state) => {
state.isAuthenticated = false;
state.loading = false;
state.loggedUser = null;
localStorage.removeItem("token")
history.navigate("/")
},
resetAuthState: () => initialState,
},
extraReducers: builder => {
builder
.addCase(userLogin.pending, state => {
state.loading = true;
})
.addCase(userLogin.rejected, (state, action) => {
state.backendErrors = action.payload
state.isAuthenticated = false;
state.loading = false;
})
.addCase(userLogin.fulfilled, (state) => {
state.loading = false;
state.backendErrors = {};
state.isAuthenticated = true;
})
.addCase(userRegister.pending, state => {
state.loading = true;
})
.addCase(userRegister.rejected, (state, action) => {
state.backendErrors = action.payload
state.loading = false;
})
.addCase(userRegister.fulfilled, (state) => {
state.loading = false;
state.backendErrors = {};
})
.addCase(getLoggedUser.pending, state => {
state.loading = true;
})
.addCase(getLoggedUser.rejected, (state, action) => {
state.backendErrors = action.payload
state.loading = false;
})
.addCase(getLoggedUser.fulfilled, (state, action) => {
state.loading = false;
state.isAuthenticated = true;
state.loggedUser = action.payload
state.backendErrors = {};
})
.addCase(updateUser.pending, (state) => {
state.loading = true;
})
.addCase(updateUser.rejected, (state, action) => {
state.backendErrors = action.payload
state.loading = false;
})
.addCase(updateUser.fulfilled, (state) => {
state.loading = false;
state.backendErrors = {};
})
.addCase(changePassword.pending, state => {
state.loading = true;
})
.addCase(changePassword.rejected, (state, action) => {
state.backendErrors = action.payload
state.loading = false;
})
.addCase(changePassword.fulfilled, (state) => {
state.loading = false;
state.backendErrors = {};
})
}
})
export const {logout, resetAuthState} = authSlice.actions;
export const authReducer = authSlice.reducer; |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Bootstrap demo</title>
<link
href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css"
rel="stylesheet"
/>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"></script>
<style>
* {
box-sizing: border-box;
}
div {
border: 1px solid white;
}
</style>
</head>
<body>
<!-- Bootstrap 기본 grid 틀 ( 순서 중요 ) -->
<div class="container">
<div class="row">
<!-- col 기본 12칸 -->
<div id="carouselExampleCaptions" class="carousel slide col-12 g-0">
<div class="carousel-inner">
<div class="carousel-item active">
<img src="img/bike1.jpg" class="d-block w-100" alt="bg-1" />
</div>
<div class="carousel-item">
<img src="img/car1.jpg" class="d-block w-100" alt="bg-2" />
</div>
</div>
<button
class="carousel-control-prev"
type="button"
data-bs-target="#carouselExampleCaptions"
data-bs-slide="prev"
>
<span class="carousel-control-prev-icon" aria-hidden="true"></span>
<span class="visually-hidden">Previous</span>
</button>
<button
class="carousel-control-next"
type="button"
data-bs-target="#carouselExampleCaptions"
data-bs-slide="next"
>
<span class="carousel-control-next-icon" aria-hidden="true"></span>
<span class="visually-hidden">Next</span>
</button>
</div>
<div class="col-12 col-sm-6 col-md-4 col-lg-3 g-0">
<img src="img/shose1.png" class="w-100" alt="avatar1" />
</div>
<div class="col-12 col-sm-6 col-md-4 col-lg-3 g-0">
<img src="img/cloth1.jpg" class="w-100" alt="avatar2" />
</div>
<div class="col-12 col-sm-6 col-md-4 col-lg-3 g-0">
<img src="img/clock2.jpg" class="w-100" alt="avatar2" />
</div>
<div class="col-12 col-sm-6 col-md-4 col-lg-3 g-0">
<img src="img/camera1.jpg" class="w-100" alt="avatar2" />
</div>
</div>
</div>
<script>
const nextBtns = document.querySelectorAll(".carousel-control-next");
nextBtns.forEach((nextBtn) => {
setInterval(() => nextBtn.click(), 3000);
});
</script>
</body>
</html> |
<template>
<div class="file-window-container">
<DragBox
:class="{'is-active': isActive}"
class="file-window rounded-3xl rounded-br"
:id="id"
use-handle
:initial-z-index="initialZIndex"
:initial-x="initialX"
:initial-y="initialY"
@drag-box-clicked="(handleDragBoxClicked)"
@drag-box-mousedown="(handleDragBoxMouseDown)"
@drag-box-mouseup="(handleDragBoxMouseUp)"
>
<template #handle>
<FileWindowHeader
:id="id"
:title="title"
@close-window="handleCloseWindow"
/>
</template>
<template #default>
<div class="file-window__main flex h-full">
<div class="file-window__sidebar px-4 py-2">
sidebar <br>
{{initialX}}<br>
{{initialY}}
</div>
<div class="file-window__content px-4 py-2">
<component :is="contentComponent"></component>
</div>
</div>
</template>
</DragBox>
</div>
</template>
<script>
import {useUIStore} from '@/stores/ui';
import {mapStores} from 'pinia';
import FileWindowHeader from '@/components/FileWindow/FileWindowHeader.vue';
import FileWindowContent from '@/components/FileWindow/FileWindowContent.vue';
import DragBox from '@/components/DragBox.vue';
import ProjectsContent from '@/components/content/ProjectsContent.vue';
import AboutContent from '@/components/content/AboutContent.vue';
export default {
name: 'FileWindow',
components: {ProjectsContent, AboutContent, FileWindowContent, FileWindowHeader, DragBox},
props: {
id: {
type: String,
required: true,
default: 'fileWindow',
},
initialZIndex: {
type: Number,
default: 999
},
initialX: {
type: Number,
required: false,
default: 0,
},
initialY: {
type: Number,
required: false,
default: 0,
},
title: {
type: String,
default: '',
},
},
data() {
return {
closeBtnTriggered: false,
}
},
computed: {
...mapStores(useUIStore),
isActive() {
return this.uiStore.activeDragBox === this.id;
},
contentComponent () {
return this.capitalize(this.id)+'Content';
},
},
methods: {
capitalize(s) {
return s[0].toUpperCase() + s.slice(1);
},
setStoreData() {
this.uiStore.activeDragBox = this.id;
this.uiStore.setScreenBoxes(this.uiStore.activeDragBox);
},
handleCloseWindow() {
console.log('handleCloseWindow');
// this.uiStore.removeFileWindow(this.id)
// const activeWindow = this.uiStore.activeDragBox
// const activeWindows = this.uiStore.windowsOnScreen
// console.log(activeWindows.length > 0)
// if (activeWindows.length > 0) {
// this.$router.push(`/desktop/${activeWindow}`)
// } else {
// this.$router.push(`/`)
// }
},
handleDragBoxClicked() {
// await this.handleCloseWindow()
// if (this.closeBtnTriggered) {
// console.log('closeBtnTriggered');
// return;
// }
// console.log('handleDragBoxClicked');
this.setStoreData();
this.$router.push({name: 'window', params: {id: this.id}});
},
handleDragBoxMouseDown() {
this.setStoreData();
},
handleDragBoxMouseUp() {
console.log('handleDragBoxMouseUp');
// localStorage.setItem('windowsOnScreen', JSON.stringify(this.uiStore.windowsOnScreen));
},
},
};
</script>
<style scoped>
.file-window-container {
position: absolute;
max-width: 90vw;
min-width: 620px;
max-height: 85vh;
min-height: 320px;
}
.file-window {
resize: both;
overflow: auto;
width: 100%;
height: 100%;
background-color: #f1ebde;
border: 1px solid #414141;
}
.file-window.is-active {
box-shadow: 10px 10px 2px 0 rgba(0, 0, 0, 0.65);
}
.file-window__content {
border-left: 1px solid #414141;
}
.file-window__sidebar {
height: 100%;
width: 100%;
flex: 1 0 155px;
max-width: 155px;
min-width: 140px;
}
</style> |
:orphan: .. only available via index, not via toctree
.. title:: Package Recipe 'bioconductor-synlet'
.. highlight: bash
bioconductor-synlet
.. conda:recipe:: bioconductor-synlet
:replaces_section_title:
:noindex:
Hits Selection for Synthetic Lethal RNAi Screen Data
:homepage: https://bioconductor.org/packages/3.17/bioc/html/synlet.html
:license: GPL-3
:recipe: /`bioconductor-synlet <https://github.com/bioconda/bioconda-recipes/tree/master/recipes/bioconductor-synlet>`_/`meta.yaml <https://github.com/bioconda/bioconda-recipes/tree/master/recipes/bioconductor-synlet/meta.yaml>`_
:links: biotools: :biotools:`synlet`, doi: :doi:`10.1101/043570`
Select hits from synthetic lethal RNAi screen data. For example\, there are two identical celllines except one gene is knocked\-down in one cellline. The interest is to find genes that lead to stronger lethal effect when they are knocked\-down further by siRNA. Quality control and various visualisation tools are implemented. Four different algorithms could be used to pick up the interesting hits. This package is designed based on 384 wells plates\, but may apply to other platforms with proper configuration.
.. conda:package:: bioconductor-synlet
|downloads_bioconductor-synlet| |docker_bioconductor-synlet|
:versions:
.. raw:: html
<details><summary><span class="truncated-version-list"><code>2.0.0-0</code>, <code>1.28.0-0</code>, <code>1.24.0-0</code>, <code>1.22.0-0</code>, <code>1.20.0-1</code>, <code>1.20.0-0</code>, <code>1.18.0-0</code>, <code>1.16.0-0</code>, <code>1.14.0-1</code>, </span></summary>
``2.0.0-0``, ``1.28.0-0``, ``1.24.0-0``, ``1.22.0-0``, ``1.20.0-1``, ``1.20.0-0``, ``1.18.0-0``, ``1.16.0-0``, ``1.14.0-1``, ``1.14.0-0``, ``1.12.1-0``, ``1.12.0-0``, ``1.10.0-0``, ``1.8.0-0``
.. raw:: html
</details>
:depends bioconductor-rankprod: ``>=3.26.0,<3.27.0``
:depends r-base: ``>=4.3,<4.4.0a0``
:depends r-data.table:
:depends r-ggplot2:
:depends r-magrittr:
:depends r-patchwork:
:depends r-rcolorbrewer:
:requirements:
.. rubric:: Installation
You need a conda-compatible package manager
(currently either `micromamba <https://mamba.readthedocs.io>`_, `mamba <https://mamba.readthedocs.io>`_, or `conda <https://docs.conda.io/projects/conda>`_)
and the Bioconda channel already activated (see :ref:`set-up-channels`).
While any of above package managers is fine, it is currently recommended to use either
micromamba or mamba (see `here <https://mamba.readthedocs.io>`_ for installation instructions).
We will show all commands using mamba below, but the arguments are the same for the two
others.
Given that you already have a conda environment in which you want to have this package, install with::
mamba install bioconductor-synlet
and update with::
mamba update bioconductor-synlet
To create a new environment, run::
mamba create --name myenvname bioconductor-synlet
with ``myenvname`` being a reasonable name for the environment
(see e.g. the `mamba docs <https://mamba.readthedocs.io>`_ for details and further options).
Alternatively, use the docker container::
docker pull quay.io/biocontainers/bioconductor-synlet:<tag>
(see `bioconductor-synlet/tags`_ for valid values for ``<tag>``)
.. |downloads_bioconductor-synlet| image:: https://img.shields.io/conda/dn/bioconda/bioconductor-synlet.svg?style=flat
:target: https://anaconda.org/bioconda/bioconductor-synlet
:alt: (downloads)
.. |docker_bioconductor-synlet| image:: https://quay.io/repository/biocontainers/bioconductor-synlet/status
:target: https://quay.io/repository/biocontainers/bioconductor-synlet
.. _`bioconductor-synlet/tags`: https://quay.io/repository/biocontainers/bioconductor-synlet?tab=tags
.. raw:: html
<script>
var package = "bioconductor-synlet";
var versions = ["2.0.0","1.28.0","1.24.0","1.22.0","1.20.0"];
</script>
Download stats
-----------------
.. raw:: html
:file: ../../templates/package_dashboard.html
Link to this page
-----------------
Render an |install-with-bioconda| badge with the following MarkDown::
[](http://bioconda.github.io/recipes/bioconductor-synlet/README.html)
.. |install-with-bioconda| image:: https://img.shields.io/badge/install%20with-bioconda-brightgreen.svg?style=flat
:target: http://bioconda.github.io/recipes/bioconductor-synlet/README.html |
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Siswa extends Model
{
protected $table = 'siswa';
protected $fillable = [
'nisn',
'nama_siswa',
'tanggal_lahir',
'jenis_kelamin',
'id_kelas',
'foto',
];
protected $dates = ['tanggal_lahir'];
public function getNamaSiswaAttribute($nama_siswa)
{
return ucwords($nama_siswa);
}
public function setNamaSiswaAttribute($nama_siswa)
{
$this->attributes['nama_siswa'] = strtolower($nama_siswa);
}
public function telepon()
{
return $this->hasOne('App\Telepon', 'id_siswa');
}
public function kelas()
{
return $this->belongsTo('App\Kelas', 'id_kelas');
}
public function hobi()
{
return $this->belongsToMany(
'App\Hobi',
'hobi_siswa',
'id_siswa',
'id_hobi'
)->withTimestamps();
}
public function getHobiSiswaAttribute()
{
return $this->hobi->pluck('id')->toArray();
}
} |
import { Controller, Get, Logger, Post, Query, Body } from '@nestjs/common';
import { EventPattern } from "@nestjs/microservices";
import { NewCarPositionDto } from './dto/new-car-position.dto';
import { MainService } from "./main.service";
import { CarPosition } from './schema/car-position.schema';
import {PrometheusHistogram, PrometheusService} from "../prometheus/prometheus.service";
import {AskRouteDto} from "./dto/ask-route.dto";
// import { CarPosition } from './schema/car-position.schema';
import { Gauge } from "prom-client";
@Controller('')
export class MainController {
private readonly logger = new Logger(MainController.name);
private gauge = this.prometheusService.registerGauge("number_of_input_request", "Total number of input requests")
constructor(private readonly appService: MainService, private prometheusService: PrometheusService) {}
@Get('')
async getHello(): Promise<string> {
return await this.appService.getHello();
}
@Post('/position-tracking')
public async sendPositionCar(@Body() carPosition: NewCarPositionDto): Promise<string> {
this.gauge.inc(1);
this.logger.log(`Car ${carPosition.license_plate} send a new position (LonLat: ${carPosition.location.lon},${carPosition.location.lat})`);
return await this.appService.sendPosition(carPosition);
}
@Post('/start')
public async sendStartCar(@Body() carPosition: NewCarPositionDto): Promise<string> {
this.gauge.inc(1);
this.logger.log(`Car ${carPosition.license_plate} start driving (LonLat: ${carPosition.location.lon},${carPosition.location.lat})`);
return await this.appService.sendStart(carPosition);
}
@Post('/stop')
public async sendStopCar(@Body() carPosition: NewCarPositionDto): Promise<string> {
this.gauge.inc(1);
this.logger.log(`Car ${carPosition.license_plate} stop driving (LonLat: ${carPosition.location.lon},${carPosition.location.lat})`);
return await this.appService.sendStop(carPosition);
}
@Post('/ask-route')
public async sendAskRoute(@Body() askRoute : AskRouteDto): Promise<string>{
this.gauge.inc(1);
return await this.appService.sendAskRoute(askRoute);
}
} |
import 'package:cricketapp/models/batting.dart';
import 'package:cricketapp/models/bowling.dart';
import 'package:cricketapp/routes/app_pages.dart';
import 'package:cricketapp/utils/utils.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:google_mobile_ads/google_mobile_ads.dart';
import 'match_details_controller.dart';
class MatchDetailsView extends GetView<MatchDetailsController> {
const MatchDetailsView({super.key});
@override
Widget build(BuildContext context) {
return DefaultTabController(
initialIndex: 1,
length: controller.tabLength,
child: Obx(
() => Scaffold(
appBar: AppBar(
elevation: 0,
title: Text(
controller.fixture.value.type,
style: const TextStyle(
fontSize: 14.0,
fontWeight: FontWeight.bold,
letterSpacing: 1,
),
),
bottom: PreferredSize(
preferredSize: const Size.fromHeight(260.0),
child: !controller.loading.value
? Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisSize: MainAxisSize.min,
children: [
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Flexible(
child: Padding(
padding: const EdgeInsets.only(left: 14.0, top: 14.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisSize: MainAxisSize.min,
children: [
Text(
"${controller.fixture.value.status} • ${controller.fixture.value.type.toUpperCase()}",
style: const TextStyle(fontWeight: FontWeight.w500, fontSize: 14.0),
),
Text(
"${controller.fixture.value.round} • ${controller.fixture.value.venue.name}",
maxLines: 1,
style: TextStyle(
overflow: TextOverflow.ellipsis,
fontSize: 12,
fontWeight: FontWeight.w500,
color: Get.isDarkMode ? Colors.white60 : Colors.black54,
),
),
],
),
),
),
if (controller.fixture.value.status.toLowerCase() == "st" ||
controller.fixture.value.status.toLowerCase() == "1st innings" ||
controller.fixture.value.status.toLowerCase() == "2nd innings")
Align(
alignment: Alignment.topRight,
child: Container(
height: 36,
padding: const EdgeInsets.only(top: 5, right: 10, left: 20),
decoration: const BoxDecoration(
color: Colors.red,
borderRadius: BorderRadius.only(
topRight: Radius.circular(20),
bottomLeft: Radius.circular(60),
),
),
child: const Text(
"Live",
style: TextStyle(fontWeight: FontWeight.w500, color: Colors.white),
),
),
)
],
),
const SizedBox(
height: 10,
),
Divider(
height: 1.0,
color: Get.theme.dividerColor,
),
Padding(
padding: const EdgeInsets.all(14),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Row(
mainAxisSize: MainAxisSize.min,
children: [
ClipOval(
child: SizedBox.fromSize(
size: const Size.fromRadius(28), // Image radius
child: controller.fixture.value.visitorTeam.imagePath.isNotEmpty
? FadeInImage.assetNetwork(
width: 28,
height: 28,
fit: BoxFit.cover,
placeholder: "assets/images/loading.gif",
image: controller.fixture.value.visitorTeam.imagePath,
)
: Image.asset(
"assets/images/placeholder.png",
width: 28,
height: 28,
),
),
),
const SizedBox(
width: 10.0,
),
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
SizedBox(
width: 100,
child: Text(
controller.fixture.value.visitorTeam.code,
style: const TextStyle(
fontWeight: FontWeight.w500,
fontSize: 16.0,
overflow: TextOverflow.ellipsis,
),
),
),
Text(
"${controller.visitorTeamRuns.value.score}-${controller.visitorTeamRuns.value.wickets}",
style: const TextStyle(
fontWeight: FontWeight.w600,
fontSize: 22.0,
),
),
Text(
"${controller.visitorTeamRuns.value.overs} OVERS",
style: const TextStyle(
fontWeight: FontWeight.w400,
fontSize: 14.0,
),
),
],
)
],
),
Row(
mainAxisSize: MainAxisSize.min,
children: [
Column(
crossAxisAlignment: CrossAxisAlignment.end,
children: [
SizedBox(
width: 100,
child: Text(controller.fixture.value.localTeam.code,
textAlign: TextAlign.end,
maxLines: 1,
softWrap: false,
style: const TextStyle(
fontWeight: FontWeight.w500,
fontSize: 16.0,
overflow: TextOverflow.ellipsis,
)),
),
Text(
"${controller.localTeamRuns.value.score}-${controller.localTeamRuns.value.wickets}",
style: const TextStyle(
fontWeight: FontWeight.w600,
fontSize: 22.0,
),
),
Text(
"${controller.localTeamRuns.value.overs} OVERS",
style: const TextStyle(
fontWeight: FontWeight.w400,
fontSize: 14.0,
),
),
],
),
const SizedBox(
width: 10.0,
),
ClipOval(
child: SizedBox.fromSize(
size: const Size.fromRadius(28), // Image radius
child: controller.fixture.value.localTeam.imagePath.isNotEmpty
? FadeInImage.assetNetwork(
width: 28,
height: 28,
fit: BoxFit.cover,
placeholder: "assets/images/loading.gif",
image: controller.fixture.value.localTeam.imagePath,
)
: Image.asset(
"assets/images/placeholder.png",
width: 28,
height: 28,
),
),
),
],
),
],
),
),
Padding(
padding: const EdgeInsets.only(bottom: 20.0, left: 14.0, right: 14.0),
child: Center(
child: Text(
controller.fixture.value.note.toUpperCase(),
style: TextStyle(
overflow: TextOverflow.fade,
fontSize: 12,
fontWeight: FontWeight.w500,
color: Get.isDarkMode ? Colors.white60 : Colors.black54,
),
)),
),
TabBar(
controller: controller.tabController,
isScrollable: true,
onTap: (index) => {},
tabs: const [
Tab(
child: Text('Live'),
),
Tab(
child: Text('Scoreboard'),
),
Tab(
child: Text('Teams'),
),
],
),
],
)
: Utils.progressIndicator(animController: controller.animController)),
),
body: TabBarView(
controller: controller.tabController,
children: [
SingleChildScrollView(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
if (controller.liveBatting.isNotEmpty) tableBatters(context, controller.liveBatting),
if (controller.liveBowling.isNotEmpty) tableBowlers(context, controller.liveBowling),
Container(
margin: const EdgeInsets.only(top: 10.0, left: 10.0, bottom: 10.0, right: 10.0),
width: double.maxFinite,
decoration: BoxDecoration(
color: Theme.of(context).primaryColor,
borderRadius: const BorderRadius.all(
Radius.circular(10.0),
),
boxShadow: <BoxShadow>[
BoxShadow(
color: Colors.black.withOpacity(0.1),
blurRadius: 5.0,
spreadRadius: 1,
offset: const Offset(0.0, 0.0),
),
],
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisSize: MainAxisSize.min,
children: [
Padding(
padding: const EdgeInsets.only(left: 10.0, top: 12, right: 10, bottom: 12),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
const Text(
"Live Updates: (Ball By Ball)",
style: TextStyle(
fontWeight: FontWeight.w600,
fontSize: 14.0,
),
),
GestureDetector(
onTap: () => {Get.toNamed(Routes.LIVE_BALLS, arguments: controller.fixture.value.id)},
child: const Text(
"More",
style: TextStyle(
fontSize: 14.0,
),
),
),
],
),
),
Divider(height: 1.0, color: Get.theme.dividerColor),
Padding(
padding: const EdgeInsets.only(top: 5, bottom: 5),
child: SizedBox(
height: 60,
child: ListView.builder(
primary: false,
shrinkWrap: true,
scrollDirection: Axis.horizontal,
itemCount: controller.balls.length,
controller: controller.scrolController,
padding: const EdgeInsets.only(left: 5, right: 5),
itemBuilder: ((_, index) {
return Row(
mainAxisSize: MainAxisSize.min,
children: [
if (controller.balls[index].isOvered)
Center(
child: Padding(
padding: const EdgeInsets.only(right: 10.0),
child: Text(
"Overs: ${controller.balls[index].overs}",
style: const TextStyle(
fontWeight: FontWeight.w600,
fontSize: 12.0,
),
),
),
),
Container(
width: 30,
height: 30,
margin: const EdgeInsets.only(right: 10),
decoration: BoxDecoration(
color: controller.balls[index].score.isWicket
? Colors.red
: controller.balls[index].score.noball == 1 ||
controller.balls[index].score.legBye == 1 ||
controller.balls[index].score.bye == 1
? Colors.amber
: Colors.white10,
borderRadius: const BorderRadius.all(
Radius.circular(20.0),
),
boxShadow: <BoxShadow>[
BoxShadow(
color: Colors.black.withOpacity(0.1),
blurRadius: 1.0,
offset: const Offset(0.0, 0.0),
),
],
),
child: Center(
child: Text(
controller.balls[index].score.isWicket
? "W"
: controller.balls[index].score.noball == 1
? "NO${controller.balls[index].score.noballRuns}"
: controller.balls[index].score.legBye == 1
? "LB${controller.balls[index].score.legBye}"
: controller.balls[index].score.bye == 1
? "BY${controller.balls[index].score.bye}"
: controller.balls[index].score.runs.toString(),
style: TextStyle(
fontWeight: FontWeight.w600,
fontSize: 12.0,
color: controller.balls[index].score.noball == 1 ||
controller.balls[index].score.legBye == 1 ||
controller.balls[index].score.bye == 1
? Colors.black
: Colors.white,
),
),
),
)
],
);
}),
),
),
),
],
),
),
],
),
),
SingleChildScrollView(
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Padding(
padding: const EdgeInsets.only(left: 16.0, top: 10, right: 10, bottom: 10),
child: Row(
children: [
Text(
controller.fixture.value.visitorTeam.name,
style: const TextStyle(
fontWeight: FontWeight.w600,
fontSize: 16.0,
),
),
const SizedBox(width: 20),
Text(
"(${controller.visitorTeamRuns.value.score}-${controller.visitorTeamRuns.value.wickets})",
style: const TextStyle(
fontWeight: FontWeight.w600,
fontSize: 16.0,
),
),
],
),
),
!controller.scroeBoardLoading.value
? controller.visitorBatters.isNotEmpty
? tableBatters(context, controller.visitorBatters)
: const Center(child: Text("No Record found."))
: const Center(child: Text("Loading...")),
controller.visitorBowlers.isNotEmpty ? tableBowlers(context, controller.visitorBowlers) : const Text(""),
Padding(
padding: const EdgeInsets.only(left: 16.0, top: 10, right: 10, bottom: 10),
child: Row(
children: [
Text(
controller.fixture.value.localTeam.name,
style: const TextStyle(
fontWeight: FontWeight.w600,
fontSize: 16.0,
),
),
const SizedBox(width: 20),
Text(
"(${controller.localTeamRuns.value.score}-${controller.localTeamRuns.value.wickets})",
style: const TextStyle(
fontWeight: FontWeight.w600,
fontSize: 16.0,
),
),
],
),
),
controller.localBatters.isNotEmpty
? tableBatters(context, controller.localBatters)
: const Center(child: Text("No Record found.")),
controller.localBowlers.isNotEmpty ? tableBowlers(context, controller.localBowlers) : const Text("")
],
),
),
controller.loadingSquad.value
? Utils.progressIndicator(animController: controller.animController)
: controller.visitorTeamSquad.squad.isNotEmpty && controller.localTeamSquad.squad.isNotEmpty
? Column(
mainAxisSize: MainAxisSize.max,
children: [
const SizedBox(height: 16),
SizedBox(
width: Get.mediaQuery.size.width * 0.8,
child: SegmentedButton<int>(
segments: controller.segments,
selected: <int>{controller.segmentSelection.value},
onSelectionChanged: (Set<int> team) => {controller.loadPlayers(team)},
),
),
const SizedBox(height: 6),
Padding(
padding: const EdgeInsets.all(10.0),
child: Flex(
direction: Axis.horizontal,
children: [
Flexible(
flex: 1,
fit: FlexFit.tight,
child: Text(
"PLAYER",
style: TextStyle(
fontWeight: FontWeight.w500,
fontSize: 14.0,
color: Get.isDarkMode ? Colors.white70 : Colors.black54,
overflow: TextOverflow.ellipsis,
),
),
),
Flexible(
flex: 1,
fit: FlexFit.tight,
child: Text(
"ROLE",
style: TextStyle(
fontWeight: FontWeight.w500,
fontSize: 14.0,
color: Get.isDarkMode ? Colors.white70 : Colors.black54,
overflow: TextOverflow.ellipsis,
),
),
),
],
),
),
Expanded(
child: controller.loadingSquad.value
? Utils.progressIndicator(animController: controller.animController)
: controller.players.isNotEmpty
? ListView.builder(
primary: false,
shrinkWrap: true,
scrollDirection: Axis.vertical,
itemCount: controller.players.length,
itemBuilder: ((_, index) {
final player = controller.players[index];
return InkWell(
onTap: () => {},
child: SizedBox(
width: double.maxFinite,
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
const Divider(height: 1),
Padding(
padding: const EdgeInsets.all(10),
child: Flex(
direction: Axis.horizontal,
children: [
Flexible(
flex: 1,
fit: FlexFit.tight,
child: Text(
player.fullName,
style: const TextStyle(
fontWeight: FontWeight.w500,
fontSize: 14.0,
overflow: TextOverflow.ellipsis,
),
),
),
Flexible(
flex: 1,
fit: FlexFit.tight,
child: Text(
player.position.name,
style: TextStyle(
fontSize: 14.0,
color: Get.isDarkMode ? Colors.white70 : Colors.black54,
overflow: TextOverflow.ellipsis,
),
),
),
],
),
),
],
),
),
);
}),
)
: Center(child: Text(controller.squadErrorMessage)),
),
],
)
: const Center(
child: Text("No record found."),
)
],
),
bottomNavigationBar: controller.bannerLoaded.value
? SafeArea(
child: Container(
margin: const EdgeInsets.only(top: 12.0, bottom: 10.0),
color: Colors.transparent,
width: controller.bannerAd!.size.width.toDouble(),
height: controller.bannerAd!.size.height.toDouble(),
child: AdWidget(ad: controller.bannerAd!),
),
)
: const SizedBox(
width: 1,
),
),
),
);
}
Table tableBowlers(BuildContext context, List<Bowling> bowlingList) {
return Table(
columnWidths: const <int, TableColumnWidth>{
0: FlexColumnWidth(3),
1: FlexColumnWidth(),
2: FlexColumnWidth(),
3: FlexColumnWidth(),
4: FlexColumnWidth(),
5: FlexColumnWidth(),
},
defaultVerticalAlignment: TableCellVerticalAlignment.middle,
children: [
tableRowHeader(context, "BOWLERS", "O", "M", "R", "W", "ECO"),
for (final bowling in bowlingList)
tableRow(bowling.bowler.firstname, bowling.bowler.bowlingStyle, bowling.active, null, bowling.overs, bowling.medians,
bowling.runs, bowling.wickets, bowling.rate),
],
);
}
Table tableBatters(BuildContext context, List<Batting> battersList) {
return Table(
columnWidths: const <int, TableColumnWidth>{
0: FlexColumnWidth(3),
1: FlexColumnWidth(),
2: FlexColumnWidth(),
3: FlexColumnWidth(),
4: FlexColumnWidth(),
5: FlexColumnWidth(),
},
defaultVerticalAlignment: TableCellVerticalAlignment.middle,
children: [
tableRowHeader(context, "BATTERS", "R", "B", "4S", "6S", "SR"),
for (final batting in battersList)
tableRow(batting.batsman.firstname, batting.batsman.battingStyle, batting.active, batting.score, null, batting.ball,
batting.fourX, batting.sixX, batting.rate),
],
);
}
Widget pointHear(BuildContext context, String txt) {
return Text(
txt,
textAlign: TextAlign.center,
style: TextStyle(
color: Colors.transparent,
fontWeight: FontWeight.w600,
fontSize: 12.0,
shadows: [Shadow(color: Theme.of(context).tabBarTheme.unselectedLabelColor!, offset: const Offset(0, -3))],
decoration: TextDecoration.underline,
decorationColor: Theme.of(context).tabBarTheme.unselectedLabelColor,
decorationThickness: 2,
),
);
}
TableRow tableRowHeader(BuildContext context, String name, String v1, String v2, String v3, String v4, String v5) {
return TableRow(
decoration: BoxDecoration(
border: Border(
top: BorderSide(width: 0.8, color: Get.theme.dividerColor),
)),
children: <Widget>[
TableCell(
verticalAlignment: TableCellVerticalAlignment.top,
child: Padding(
padding: const EdgeInsets.only(left: 10.0, top: 5, bottom: 5),
child: Text(
name,
style: TextStyle(
fontWeight: FontWeight.w600,
fontSize: 12.0,
color: Theme.of(context).tabBarTheme.unselectedLabelColor,
),
),
),
),
TableCell(
verticalAlignment: TableCellVerticalAlignment.middle,
child: pointHear(context, v1),
),
TableCell(
verticalAlignment: TableCellVerticalAlignment.middle,
child: pointHear(context, v2),
),
TableCell(
verticalAlignment: TableCellVerticalAlignment.middle,
child: pointHear(context, v3),
),
TableCell(
verticalAlignment: TableCellVerticalAlignment.middle,
child: pointHear(context, v4),
),
TableCell(
verticalAlignment: TableCellVerticalAlignment.middle,
child: Padding(
padding: const EdgeInsets.only(right: 10),
child: pointHear(context, v5),
),
),
],
);
}
TableRow tableRow(String name, String playingStyle, bool active, int? v0, double? v1, int v2, int v3, int v4, double v5) {
return TableRow(
decoration: BoxDecoration(
color: Get.theme.primaryColor,
border: Border(
top: BorderSide(width: 0.5, color: Get.theme.dividerColor),
)),
children: <Widget>[
TableCell(
verticalAlignment: TableCellVerticalAlignment.top,
child: Padding(
padding: const EdgeInsets.only(left: 10.0, top: 5, bottom: 5),
child: Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
active ? "$name *" : name,
style: const TextStyle(
fontWeight: FontWeight.w600,
fontSize: 12.0,
overflow: TextOverflow.ellipsis,
),
),
Padding(
padding: const EdgeInsets.only(left: 3.0),
child: Text(
"($playingStyle)",
style: TextStyle(
fontWeight: FontWeight.w500,
fontSize: 12.0,
color: Theme.of(Get.context!).tabBarTheme.unselectedLabelColor,
overflow: TextOverflow.ellipsis,
),
),
),
],
),
),
),
TableCell(
verticalAlignment: TableCellVerticalAlignment.middle,
child: Text(
(v0 ?? (v1 ?? 0)).toString(),
textAlign: TextAlign.center,
style: const TextStyle(
fontSize: 12.0,
),
),
),
TableCell(
verticalAlignment: TableCellVerticalAlignment.middle,
child: Text(
v2.toString(),
textAlign: TextAlign.center,
style: const TextStyle(
fontSize: 12.0,
),
),
),
TableCell(
verticalAlignment: TableCellVerticalAlignment.middle,
child: Text(
v3.toString(),
textAlign: TextAlign.center,
style: const TextStyle(
fontSize: 12.0,
),
),
),
TableCell(
verticalAlignment: TableCellVerticalAlignment.middle,
child: Text(
v4.toString(),
textAlign: TextAlign.center,
style: const TextStyle(
fontSize: 12.0,
),
),
),
TableCell(
verticalAlignment: TableCellVerticalAlignment.middle,
child: Padding(
padding: const EdgeInsets.only(right: 10),
child: Text(
v5.toString(),
textAlign: TextAlign.center,
style: const TextStyle(
fontSize: 12.0,
),
),
),
),
],
);
}
} |
<?php
namespace Jplarar\SESBundle\DependencyInjection;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\Config\FileLocator;
use Symfony\Component\HttpKernel\DependencyInjection\Extension;
use Symfony\Component\DependencyInjection\Loader;
/**
* This is the class that loads and manages your bundle configuration
*
* To learn more see {@link http://symfony.com/doc/current/cookbook/bundles/extension.html}
*/
class JplararSESExtension extends Extension
{
/**
* {@inheritDoc}
*/
public function load(array $configs, ContainerBuilder $container)
{
$configuration = new Configuration();
$config = $this->processConfiguration($configuration, $configs);
$loader = new Loader\YamlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config'));
$loader->load('services.yml');
if (!isset($config['amazon_ses']['amazon_ses_key'])) {
throw new \InvalidArgumentException(
'The option "jplarar_ses.amazon_ses.amazon_ses_key" must be set.'
);
}
$container->setParameter(
'jplarar_ses.amazon_ses.amazon_ses_key',
$config['amazon_ses']['amazon_ses_key']
);
if (!isset($config['amazon_ses']['amazon_ses_secret'])) {
throw new \InvalidArgumentException(
'The option "jplarar_ses.amazon_ses.amazon_ses_secret" must be set.'
);
}
$container->setParameter(
'jplarar_ses.amazon_ses.amazon_ses_secret',
$config['amazon_ses']['amazon_ses_secret']
);
if (!isset($config['amazon_ses']['amazon_ses_region'])) {
throw new \InvalidArgumentException(
'The option "jplarar_ses.amazon_ses.amazon_ses_region" must be set.'
);
}
$container->setParameter(
'jplarar_ses.amazon_ses.amazon_ses_region',
$config['amazon_ses']['amazon_ses_region']
);
}
/**
* {@inheritdoc}
* @version 0.0.1
* @since 0.0.1
*/
public function getAlias()
{
return 'jplarar_ses';
}
} |
import React from "react"
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { faBars } from '@fortawesome/free-solid-svg-icons'
import $ from "jquery";
import "./NavBar.css";
import Container from "../components/Container";
import NavItem from "./NavItem";
import Title from "../components/Title";
const NavBar = () => {
const BarsClickHandler = () => {
$(".nav-item-list").toggleClass("showing");
};
return (
<header>
<nav>
<Container className="nav-bar">
<Container className="logo-container">
<Title className="logo">Denis Ladychenko</Title>
</Container>
<FontAwesomeIcon className="bars" icon={faBars} size="3x" color="white" onClick={BarsClickHandler} />
<ul className="nav-item-list">
<NavItem to="/home" className="nav-item-link" >Home</NavItem>
<NavItem to="/about" className="nav-item-link" >About</NavItem>
<NavItem to="/resume" className="nav-item-link" >Resume</NavItem>
<NavItem to="/projects" className="nav-item-link" >Projects</NavItem>
<NavItem to="/contact" className="nav-item-link" >Contact</NavItem>
</ul>
</Container>
</nav>
</header>
);
};
export default NavBar; |
(function (angular) {
/**
* @license angular-recaptcha build:2018-07-30
* https://github.com/vividcortex/angular-recaptcha
* Copyright (c) 2018 VividCortex
**/
'use strict';
var app = angular.module('vcRecaptcha', []);
function throwNoKeyException() {
throw new Error('You need to set the "key" attribute to your public reCaptcha key. If you don\'t have a key, please get one from https://www.google.com/recaptcha/admin/create');
}
/**
* An angular service to wrap the reCaptcha API
*/
app.factory('vcRecaptchaService', ['$rootScope', '$window', '$q', '$document', '$interval', function ($rootScope, $window, $q, $document, $interval) {
var deferred = $q.defer(), promise = deferred.promise, instances = {}, recaptcha;
var onLoadFunctionName = 'vcRecaptchaApiLoaded';
$window.vcRecaptchaApiLoadedCallback = $window.vcRecaptchaApiLoadedCallback || [];
var callback = function () {
recaptcha = $window.grecaptcha;
deferred.resolve(recaptcha);
};
$window.vcRecaptchaApiLoadedCallback.push(callback);
$window[onLoadFunctionName] = function () {
$window.vcRecaptchaApiLoadedCallback.forEach(function (callback) {
callback();
});
};
function getRecaptcha() {
if (!!recaptcha) {
return $q.when(recaptcha);
}
return promise;
}
function validateRecaptchaInstance() {
if (!recaptcha) {
throw new Error('reCaptcha has not been loaded yet.');
}
}
function isRenderFunctionAvailable() {
return angular.isFunction(($window.grecaptcha || {}).render);
}
// Check if grecaptcha.render is not defined already.
if (isRenderFunctionAvailable()) {
callback();
} else if ($window.document.querySelector('script[src^="https://www.google.com/recaptcha/api.js"]')) {
// wait for script to be loaded.
var intervalWait = $interval(function () {
if (isRenderFunctionAvailable()) {
$interval.cancel(intervalWait);
callback();
}
}, 25);
} else {
// Generate link on demand
var script = $window.document.createElement('script');
script.async = true;
script.defer = true;
script.src = 'https://www.google.com/recaptcha/api.js?onload=' + onLoadFunctionName + '&render=explicit';
$document.find('body')[0].appendChild(script);
}
return {
/**
* Creates a new reCaptcha object
*
* @param elm the DOM element where to put the captcha
* @param conf the captcha object configuration
* @throws NoKeyException if no key is provided in the provider config or the directive instance (via attribute)
*/
create: function (elm, conf) {
var config = {}
conf.sitekey = conf.key || config.key;
conf.theme = conf.theme || config.theme;
conf.stoken = conf.stoken || config.stoken;
conf.size = conf.size || config.size;
conf.type = conf.type || config.type;
conf.hl = conf.lang || config.lang;
conf.badge = conf.badge || config.badge;
if (!conf.sitekey) {
throwNoKeyException();
}
return getRecaptcha().then(function (recaptcha) {
var widgetId = recaptcha.render(elm, conf);
instances[widgetId] = elm;
elm.getElementsByTagName("iframe")[0].title = "Recaptcha Widget"
return widgetId;
});
},
/**
* Reloads the reCaptcha
*/
reload: function (widgetId) {
validateRecaptchaInstance();
recaptcha.reset(widgetId);
// Let everyone know this widget has been reset.
$rootScope.$broadcast('reCaptchaReset', widgetId);
},
/**
* Executes the reCaptcha
*/
execute: function (widgetId) {
validateRecaptchaInstance();
recaptcha.execute(widgetId);
},
/**
* Get/Set reCaptcha language
*/
useLang: function (widgetId, lang) {
var instance = instances[widgetId];
if (instance) {
var iframe = instance.querySelector('iframe');
if (lang) {
// Setter
if (iframe && iframe.src) {
var s = iframe.src;
if (/[?&]hl=/.test(s)) {
s = s.replace(/([?&]hl=)\w+/, '$1' + lang);
} else {
s += ((s.indexOf('?') === -1) ? '?' : '&') + 'hl=' + lang;
}
iframe.src = s;
}
} else {
// Getter
if (iframe && iframe.src && /[?&]hl=\w+/.test(iframe.src)) {
return iframe.src.replace(/.+[?&]hl=(\w+)([^\w].+)?/, '$1');
} else {
return null;
}
}
} else {
throw new Error('reCaptcha Widget ID not exists', widgetId);
}
},
/**
* Gets the response from the reCaptcha widget.
*
* @see https://developers.google.com/recaptcha/docs/display#js_api
*
* @returns {String}
*/
getResponse: function (widgetId) {
validateRecaptchaInstance();
return recaptcha.getResponse(widgetId);
},
/**
* Gets reCaptcha instance and configuration
*/
getInstance: function (widgetId) {
return instances[widgetId];
},
/**
* Destroy reCaptcha instance.
*/
destroy: function (widgetId) {
delete instances[widgetId];
}
};
}]);
app.directive('vcRecaptcha', ['$document', '$timeout', 'vcRecaptchaService', function ($document, $timeout, vcRecaptchaService) {
return {
restrict: 'A',
scope: {
response: '=?ngModel',
key: '=?',
stoken: '=?',
theme: '=?',
size: '=?',
type: '=?',
lang: '=?',
badge: '=?',
tabindex: '=?',
required: '=?',
onCreate: '&',
onSuccess: '&',
onExpire: '&',
onError: '&',
// form field attributes
field: '=',
registerControl: '&',
updateField: '&'
},
link: function (scope, elm, attrs, ctrl) {
scope.widgetId = null;
if (ctrl && angular.isDefined(attrs.required)) {
scope.$watch('required', validate);
}
scope.fieldParameters = scope.field.Parameters;
scope.fieldData = scope.$parent.form.fields[scope.field.TitleCompacted];
if (scope.fieldData.invisibleRecaptcha) { scope.size = "invisible" };
scope.registerControl({
control: {
field: scope.field,
onSubmit: function (fnCallWhenDone, fnCallOnError) {
fnCallWhenDone && fnCallWhenDone();
},
getValue: function () {
return scope.successToken;
}
}
});
var removeCreationListener = scope.$watch('key', function (captchaKey) {
var callback = function (gRecaptchaResponse) {
// Safe $apply
$timeout(function () {
scope.response = gRecaptchaResponse;
validate();
// Notify about the response availability
scope.onSuccess({ response: gRecaptchaResponse, widgetId: scope.widgetId });
scope.$parent.form.fields[scope.field.TitleCompacted].value = scope.successToken = scope.response;
});
};
vcRecaptchaService.create(elm[0], {
callback: callback,
key: captchaKey,
stoken: scope.stoken || attrs.stoken || null,
theme: scope.theme || attrs.theme || null,
type: scope.type || attrs.type || null,
lang: scope.lang || attrs.lang || null,
tabindex: scope.tabindex || attrs.tabindex || null,
size: scope.size || attrs.size || null,
badge: scope.badge || attrs.badge || null,
'expired-callback': expired,
'error-callback': attrs.onError ? error : undefined
}).then(function (widgetId) {
// The widget has been created
validate();
scope.$parent.widgetId = scope.widgetId = widgetId;
scope.onCreate({ widgetId: widgetId });
scope.$on('$destroy', destroy);
scope.$on('reCaptchaReset', function (event, resetWidgetId) {
if (angular.isUndefined(resetWidgetId) || widgetId === resetWidgetId) {
scope.response = "";
validate();
}
});
if (scope.fieldData.invisibleRecaptcha) {
vcRecaptchaService.reload(scope.widgetId);
$timeout(function () {
vcRecaptchaService.reload(scope.widgetId);
vcRecaptchaService.execute(scope.widgetId);
}, 10);
}
});
// Remove this listener to avoid creating the widget more than once.
removeCreationListener();
});
function destroy() {
if (ctrl) {
// reset the validity of the form if we were removed
ctrl.$setValidity('recaptcha', null);
}
cleanup();
}
function expired() {
// Safe $apply
$timeout(function () {
scope.response = "";
validate();
// Notify about the response availability
scope.onExpire({ widgetId: scope.widgetId });
});
}
function error() {
var args = arguments;
$timeout(function () {
scope.response = "";
validate();
// Notify about the response availability
scope.onError({ widgetId: scope.widgetId, arguments: args });
});
}
function validate() {
if (ctrl) {
ctrl.$setValidity('recaptcha', scope.required === false ? null : Boolean(scope.response));
}
}
function cleanup() {
vcRecaptchaService.destroy(scope.widgetId);
// removes elements reCaptcha added.
angular.element($document[0].querySelectorAll('.pls-container')).parent().remove();
}
}
};
}]);
})(window.dnnsfAngular15 || window.angular); |
import 'package:flutter/material.dart';
import 'package:font_awesome_flutter/font_awesome_flutter.dart';
import 'package:google_fonts/google_fonts.dart';
class DescriptionScreen extends StatelessWidget {
DescriptionScreen({required this.imageaddress, super.key});
final String imageaddress;
@override
Widget build(BuildContext context) {
return Scaffold(
floatingActionButton: Row(
mainAxisAlignment: MainAxisAlignment.end,
children: [
FloatingActionButton(
onPressed: () {},
child: Icon(Icons.share),
),
SizedBox(
width: 10,
),
FloatingActionButton(
onPressed: () {},
child: Icon(FontAwesomeIcons.whatsapp),
),
SizedBox(
width: 10,
),
FloatingActionButton(
onPressed: () {},
child: Icon(Icons.phone),
),
],
),
body: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Image.asset("assets/images/$imageaddress"),
Expanded(
child: Padding(
padding: const EdgeInsets.all(8.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
SizedBox(
height: 5,
),
Text(
"Property Title",
style: GoogleFonts.poppins(fontWeight: FontWeight.w500),
),
SizedBox(
height: 10,
),
Text(
"Discover modern luxury in our stunning high-rise, nestled in the heart of the city's vibrant skyline. nestled in the heart city's vibrant skyline again",
style: GoogleFonts.poppins(fontWeight: FontWeight.w500),
),
SizedBox(
height: 15,
),
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text(
"Price:25,000",
style: GoogleFonts.poppins(
fontWeight: FontWeight.w800, fontSize: 20),
),
ElevatedButton.icon(
onPressed: () {},
icon: Icon(Icons.location_on),
label: Text(
"View on Map",
style: GoogleFonts.poppins(
fontWeight: FontWeight.w500),
))
],
),
SizedBox(
height: 10,
),
],
),
),
),
],
),
);
}
} |
package controller;
import java.io.IOException;
import java.time.LocalDate;
import java.util.ArrayList;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.control.DatePicker;
import javafx.scene.control.Label;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.Pane;
import javafx.scene.layout.VBox;
import javafx.scene.shape.Line;
import model.Time;
import model.WeeklyList;
public class WeeklyPlanListController {
Controller controller = Controller.getInstance();
private int weekNum;
private int year;
private LocalDate startDay;
private LocalDate endDay;
@FXML
private VBox listBox;
@FXML
private VBox noListPane;
@FXML
private Pane newWeeklyPane;
@FXML
private DatePicker daySelector;
@FXML
private Pane selectionPane;
@FXML
private Label weekSelected;
@FXML
private Label dayRange;
@FXML
private void eventCreateWeeklyList() throws IOException {
if (selectionPane.isVisible()) {
if (controller.createEmptyWeeklyList(weekNum, year)) {
System.out.println("New Weekly list created for week n° " + weekNum);
toggleNewWeeklyPane();
updateWindow();
} else {
System.out.println("Weekly list creation failed");
}
}
}
@FXML
private void toggleNewWeeklyPane() throws IOException {
if (newWeeklyPane.isVisible()) {
newWeeklyPane.setVisible(false);
selectionPane.setVisible(false);
daySelector.setValue(null);
} else {
newWeeklyPane.setVisible(true);
}
}
@FXML
private void updateSelection() throws IOException {
LocalDate selectedDate = daySelector.getValue();
if (selectedDate == null) {
return;
}
selectionPane.setVisible(true);
Time time = new Time();
weekNum = time.getWeekNumberFromDate(selectedDate);
year = selectedDate.getYear();
startDay = time.getMondayFromWeekNumber(weekNum, year);
endDay = time.getSundayFromWeekNumber(weekNum, year);
weekSelected.setText("Week n° " + weekNum);
dayRange.setText("From " + startDay.toString() + " to " + endDay.toString());
}
public void updateWindow() {
listBox.getChildren().clear();
Line firstSeparator = new Line();
firstSeparator.setStartX(listBox.getLayoutX());
firstSeparator.setEndX(listBox.getLayoutX() + 1060);
listBox.getChildren().add(firstSeparator);
ArrayList<WeeklyList> planslist = controller.getActiveUser().getWeeklyPlanList();
for (WeeklyList list : planslist) {
try {
FXMLLoader loader = new FXMLLoader(getClass().getResource("/WeeklyPlanRow.fxml"));
AnchorPane root = (AnchorPane) loader.load();
WeeklyPlanRowController weeklyPlanRowController = (WeeklyPlanRowController) loader.getController();
weeklyPlanRowController.setWeeklyList(list);
weeklyPlanRowController.updateRow();
Line newSeparator = new Line();
newSeparator.setStartX(listBox.getLayoutX());
newSeparator.setEndX(listBox.getLayoutX() + 1060);
listBox.getChildren().addAll(root, newSeparator);
} catch (IOException e) {
e.printStackTrace(System.out);
throw new RuntimeException(e);
}
}
}
} |
# Writing a Workflow Definition
Now that you've learned the basic architecture and tools you'll use with
Temporal, it's time to learn how to create a Workflow. In this course,
you'll start with a basic example and build on it as you go.
<iframe width="1040" height="585"
src="https://www.youtube.com/embed/hK5qvFvNqDo?rel=0&iv_load_policy=3&modestbranding=1&showsearch=0&showinfo=0&wmode=transparent"
title="Writing a Workflow Definition in .NET (Temporal 101 - .NET)"
frameborder="0"
allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" allowfullscreen></iframe>
<details>
<summary>Video Transcript</summary>
In Temporal, you define a Workflow in C# and .NET by creating a method. The
code that makes up that method is known as the Workflow Definition.
I'm going to demonstrate how to create a Workflow Definition using the
Temporal C# and the .NET SDK. I'll start by writing the business logic, which won't
involve any Temporal-specific code at all.
When developing a C# and .NET application, the first step is often to create a
module, and I've named it `app` here, for the sake of simplicity. The
next step is writing the code itself, so I've defined a method that
takes a string representing a person's name as an input parameter and
returns another string as output, which is a greeting customized with that
person's name. That's the business logic for our first Workflow, but
it's not a Workflow yet, it's just a C# and .NET method for now.
```go
package app
func GreetSomeone(name string) string {
return "Hello " + name + "!"
}
```
I'll test that this method works as expected by writing a small C# and .NET
program to invoke it. This pattern matches what you'll do with Temporal,
where your Workflow contains the business logic, which is typically
separate from the code used to execute it. The program I'm writing
takes input from an argument specified on the command line, invokes
the business logic method by passing in that input, assigns the
string returned from the business logic method to a value named
`greeting`, and then prints that value to standard output.
```go
package main
import (
"app"
"fmt"
"os"
)
func main() {
name := os.Args[1]
greeting := app.GreetSomeone(name)
fmt.Println(greeting)
}
```
Now, I'll execute it, passing `Tom` as input. Looks like it works as
expected.
The next step is to turn this method into a Temporal Workflow
Definition.
Temporal doesn't impose any rules about how you name your Workflow
method, so there's no need to rename the method I already wrote.
By the way, every Temporal Workflow has a name, which Temporal refers
to as the Workflow Type. It's perhaps a confusing term because "type" can
mean so many things in English, but you can think of it like a "type"
in a programming language, which is a way to refer to an entity in your
code. For example, you might have a "Customer" type or a "Product"
type. In the C# and .NET SDK, by default, a Workflow's type is the name of the
method used to define that Workflow, but it is possible to override
it and provide a more user-friendly value since the Web UI displays
Workflow Executions by their type.
Turning this method into a Temporal Workflow Definition requires
just three steps. First, you'll need to import the `workflow` package
from the Temporal C# and .NET SDK. This is required because the `workflow`
package defines the `workflow.Context` type, which must be the first
input parameter to your method and is used (by the Temporal client
library) to pass execution context to the Workflow. Finally, your
method must include a return value of type `error`, either by itself if
your method otherwise had no return value, or in addition to whatever
value it returned, as I do here. In this particular case, I'm not
calling another method or doing anything else that could return an
error, so I just return the greeting and a `nil` value for the error.
<! -- TODO: Add .NET code to define a workflow and update paragraph above -->
```go
package hello
import (
"go.temporal.io/sdk/workflow"
)
func GreetSomeone(ctx workflow.Context, name string) (string, error) {
return "Hello " + name + "!", nil
}
```
The method you see here is now a Workflow Definition and is the
same code you'll use to execute the Workflow in the first hands-on
exercise.
</details>
As explained in the video, there are three steps for turning a C# and .NET method
into a Workflow Definition:
1. Import the `workflow` package from the SDK
2. Add `workflow.Context` as the first input parameter
3. Update the return value to include an `error` type (its value can be nil)
Also, this method must be exportable, which in C# and .NET simply means that
the method name must begin with a capital letter. |
package expression
import (
"context"
"github.com/VadimGossip/calculator/dbagent/internal/domain"
)
type service struct {
repo Repository
}
type Service interface {
CreateExpression(ctx context.Context, e *domain.Expression) error
GetExpressionByReqUid(ctx context.Context, userId int64, reqUid string) (*domain.Expression, error)
GetExpressions(ctx context.Context, userId int64) ([]domain.Expression, error)
SaveAgentHeartbeat(ctx context.Context, name string) error
GetAgents(ctx context.Context) ([]domain.Agent, error)
SaveOperationDuration(ctx context.Context, name string, duration uint32) error
GetOperationDurations(ctx context.Context) ([]domain.OperationDuration, error)
CreateSubExpression(ctx context.Context, se *domain.SubExpression) error
StartSubExpressionEval(ctx context.Context, seId int64, agent string) (bool, error)
StopSubExpressionEval(ctx context.Context, seId int64, result *float64, errMsg string) error
GetReadySubExpressions(ctx context.Context, eId *int64, skipTimeoutSec uint32) ([]domain.SubExpression, error)
SkipAgentSubExpressions(ctx context.Context, agent string) error
}
var _ Service = (*service)(nil)
func NewService(repo Repository) *service {
return &service{repo: repo}
}
func (s *service) CreateExpression(ctx context.Context, e *domain.Expression) error {
if e.ErrorMsg != "" {
e.State = domain.ExpressionStateError
}
e.State = domain.ExpressionStateNew
return s.repo.CreateExpression(ctx, e)
}
func (s *service) GetExpressionByReqUid(ctx context.Context, userId int64, reqUid string) (*domain.Expression, error) {
return s.repo.GetExpressionByReqUid(ctx, userId, reqUid)
}
func (s *service) GetExpressions(ctx context.Context, userId int64) ([]domain.Expression, error) {
return s.repo.GetExpressions(ctx, userId)
}
func (s *service) SaveAgentHeartbeat(ctx context.Context, name string) error {
success, err := s.repo.SetAgentHeartbeatAt(ctx, name)
if err != nil {
return err
}
if !success {
return s.repo.CreateAgent(ctx, name)
}
return nil
}
func (s *service) GetAgents(ctx context.Context) ([]domain.Agent, error) {
return s.repo.GetAgents(ctx)
}
func (s *service) SaveOperationDuration(ctx context.Context, name string, duration uint32) error {
success, err := s.repo.UpdateOperationDuration(ctx, name, duration)
if err != nil {
return err
}
if !success {
return s.repo.CreateOperationDuration(ctx, name, duration)
}
return nil
}
func (s *service) GetOperationDurations(ctx context.Context) ([]domain.OperationDuration, error) {
return s.repo.GetOperationDurations(ctx)
}
func (s *service) CreateSubExpression(ctx context.Context, se *domain.SubExpression) error {
return s.repo.CreateSubExpression(ctx, se)
}
func (s *service) StartSubExpressionEval(ctx context.Context, seId int64, agent string) (bool, error) {
e, err := s.repo.GetExpressionBySeId(ctx, seId)
if err != nil {
return false, err
}
if e.State == domain.ExpressionStateNew {
e.State = domain.ExpressionStateInProgress
if err = s.repo.UpdateExpression(ctx, *e); err != nil {
return false, err
}
}
return s.repo.StartSubExpressionEval(ctx, seId, agent)
}
func (s *service) StopSubExpressionEval(ctx context.Context, seId int64, result *float64, errMsg string) error {
if err := s.repo.StopSubExpressionEval(ctx, seId, result); err != nil {
return err
}
e, err := s.repo.GetExpressionSummaryBySeId(ctx, seId)
if err != nil {
return err
}
if result == nil {
e.ErrorMsg = errMsg
e.State = domain.ExpressionStateError
return s.repo.UpdateExpression(ctx, e)
}
isLast, err := s.repo.GetSubExpressionIsLast(ctx, seId)
if err != nil {
return err
}
if isLast {
e.State = domain.ExpressionStateOK
return s.repo.UpdateExpression(ctx, e)
}
return nil
}
func (s *service) GetReadySubExpressions(ctx context.Context, eId *int64, skipTimeoutSec uint32) ([]domain.SubExpression, error) {
return s.repo.GetReadySubExpressions(ctx, eId, skipTimeoutSec)
}
func (s *service) SkipAgentSubExpressions(ctx context.Context, agent string) error {
return s.repo.SkipAgentSubExpressions(ctx, agent)
} |
import { of as observableOf } from 'rxjs';
import { catchError, map, switchMap } from 'rxjs/operators';
import { Injectable } from '@angular/core';
import {Actions, Effect, ofType} from '@ngrx/effects';
import { UserListService } from './user-list.service';
import * as userListActions from './user-list.actions';
import { HttpErrorResponse } from '@angular/common/http';
@Injectable()
export class UserListEffect {
@Effect()
get_user_list$ = this.actions$
.pipe(ofType(userListActions.LOAD_USERS),
switchMap((action: userListActions.LoadUserList) => {
return this.userListService.getUserList(action.payload).pipe(
map(res => new userListActions.LoadUserListSuccess(res)),
catchError((err: HttpErrorResponse) => {
const errObj = new userListActions.LoadUserListFail(err.error);
return observableOf(errObj);
}));
}));
constructor(
private userListService: UserListService,
private actions$: Actions) {
}
} |
import math
import requests
import numpy as np
import pandas as pd
from sklearn.preprocessing import MinMaxScaler
class Scoring:
@staticmethod
def rank_and_sort_dataframe(df: pd.DataFrame, weights: dict) -> pd.DataFrame:
"""
Assigns a composite score to each row in the dataframe and assigns a signal based on this score.
"""
scaler = MinMaxScaler()
df[['SentimentScore', 'QuantitativeValueScore', 'PercentChange']] = scaler.fit_transform(df[['SentimentScore', 'QuantitativeValueScore', 'PercentChange']])
df['CompositeScore'] = (weights['SentimentScore'] * df['SentimentScore']
+ weights['PercentChange'] * df['PercentChange']
+ weights['QuantitativeValueScore'] / (df['QuantitativeValueScore'] + 0.0001))
# Compute thresholds based on percentiles of 'CompositeScore'
thresholds = [df['CompositeScore'].quantile(0.2), df['CompositeScore'].quantile(0.8)]
df['PrimarySignal'] = pd.cut(df['CompositeScore'], bins=[-np.inf, thresholds[0], thresholds[1], np.inf], labels=['Sell', 'Hold', 'Buy'])
df = df.sort_values('CompositeScore', ascending=False)
return df
@staticmethod
def process_single_ticker(ticker, api_token, final_df, position_size, max_position_size, high_risk_threshold, portfolio_size):
"""
Fetches current price for a ticker and updates the dataframe accordingly.
"""
url = f'https://www.alphavantage.co/query?function=GLOBAL_QUOTE&symbol={ticker}&apikey={api_token}'
r = requests.get(url)
data = r.json()
if 'Global Quote' in data and '05. price' in data['Global Quote']:
current_price = float(data['Global Quote']['05. price'])
final_df.loc[final_df['Ticker'] == ticker, 'Price'] = current_price
signal = final_df.loc[final_df['Ticker'] == ticker, 'PrimarySignal'].values[0]
shares_to_trade = math.floor(position_size / current_price)
if shares_to_trade * current_price > max_position_size:
shares_to_trade = math.floor(max_position_size / current_price)
weighted_avg_sentiment_score = final_df.loc[final_df['Ticker'] == ticker, 'WeightedAverageSentimentScore'].values[0]
if weighted_avg_sentiment_score < high_risk_threshold:
shares_to_trade = math.floor(shares_to_trade * 0.5) # Reduce the position size by 50%
if signal == 'Buy':
final_df.loc[final_df['Ticker'] == ticker, 'Number of Shares to Buy/Sell'] = shares_to_trade
elif signal == 'Sell':
final_df.loc[final_df['Ticker'] == ticker, 'Number of Shares to Buy/Sell'] = shares_to_trade
else:
final_df.loc[final_df['Ticker'] == ticker, 'Number of Shares to Buy/Sell'] = 0
# Calculate weight of each ticker in the portfolio
weight = (shares_to_trade * current_price) / portfolio_size if portfolio_size != 0 else 0
# Make the weight negative if the signal is 'Sell'
weight = -weight if signal == 'Sell' else weight
final_df.loc[final_df['Ticker'] == ticker, 'Weight'] = weight
else:
raise Exception(f"Failed to fetch price for {ticker}") |
<p align="center">
<img src="https://img.shields.io/badge/yarn-%232C8EBB.svg?style=for-the-badge&logo=yarn&logoColor=white" alt="yarn" />
<img src="https://img.shields.io/badge/nestjs-%23E0234E.svg?style=for-the-badge&logo=nestjs&logoColor=white" alt="NestJs" />
<img src="https://img.shields.io/badge/-ApolloGraphQL-311C87?style=for-the-badge&logo=apollo-graphql" alt="Graphql" />
<img src="https://img.shields.io/badge/Prisma-3982CE?style=for-the-badge&logo=Prisma&logoColor=white" alt="Prisma.io" />
<img src="https://img.shields.io/badge/docker-%230db7ed.svg?style=for-the-badge&logo=docker&logoColor=white" alt="Docker" />
<img src="https://img.shields.io/badge/postgres-%23316192.svg?style=for-the-badge&logo=postgresql&logoColor=white" alt="Postgres" />
<img src="https://img.shields.io/badge/-Swagger-%23Clojure?style=for-the-badge&logo=swagger&logoColor=white" alt="Prisma" />
</p>
## **💻 Projeto**
Criamos uma API GraphQL com autenticação JWT utilizando o framework [Nest](https://nestjs.com/). Assim um usuário autenticado poderá criar, deletar, pesquisar e atualizar uma tabela de usuários no banco de dados. Usamos também o [Prisma](https://www.prisma.io/) como ORM e criamos um container com o banco de dados postgres usando o [Docker Compose](https://docs.docker.com/compose/).
## **🚀 Get Started**
```bash
# Dependências
$ yarn
# Container com banco de dados postgress.
$ yarn up:db
# Migração dos models definidos no schema.prisma
$ yarn prisma migrate dev
# watch mode
$ yarn start:dev
```
Para remover o container com o postgres:
```bash
$ yarn rm:db
```
## **🛣️ Rotas**
Acesse o playground:
```url
http://localhost:3000/graphql
```
No playgorund temos um cliente http e a documentação da API gerada automaticamente.
## **🔎 Observações**
Somente as mutations authenticate e createUsers são públicas. Para tornar todas as querys e mutations públicas basta colocar o decorator <strong>@IsPublicRoute()</strong> no UsersResolver como no exemplo abaixo:
```typescript
@IsPublicRoute()
export class UsersResolver {
constructor(private readonly usersService: UsersService) {}
...//more
}
```
## **🔒 Login**
Usando o playground:
```url
http://localhost:3000/graphql
```
Você deve criar um novo usuário.
```graphql
mutation {
createUser(
createUserInput: {
name: "R2D2"
email: "[email protected]"
password: "r2d2"
}
) {
id
name
email
}
}
```
Após criar o novo usuário, realize a mutation:
```graphql
mutation {
authenticate(authInput: { email: "[email protected]", password: "r2d2" }) {
user {
id
email
name
}
access_token
}
}
```
Como resposta, receberá algo do tipo:
```graphql
{
"data": {
"authenticate": {
"user": {
"id": "cl2vf150x0007qvqm2m15wf5f",
"email": "[email protected]",
"name": "R2D2"
},
"access_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJjbDJ2ZjE1MHgwMDA3cXZxbTJtMTV3ZjVmIiwiZW1haWwiOiJkYXJ0aEB2YWRlci5jb20iLCJuYW1lIjoiZGFydCIsImlhdCI6MTY1MTkwMDg1NiwiZXhwIjoxNjU0NDkyODU2fQ.6MdzP1bktgtIL0xWqiPDl0NtP6g69u1cjnjYIH3aOzI"
}
}
}
```
Copie e cole o access_token conforme a figura abaixo:
<img src="./.assets/playground-gql.png"/>
## **📁 Upload de arquivos**
Faça login, obtenha um token valido e execute o script abaixo que esta no diretorio corrente do projeto, uploadRequest.sh:
```sh
token="seu_token"
path="./README.md"
curl http://localhost:3000/graphql \
-H "Authorization: Bearer $token" \
-H 'connection: keep-alive' \
-F 'operations="{\"query\":\"mutation($file: Upload!){\n\tuploadFile(file:$file)\n} \",\"variables\":{\"file\":null}}"' \
-F 'map={ "nFile": ["variables.file"] }' \
-F nFile=@$path
```
<img src="./.assets/curl.svg"/>
Após a execução do script o arquivo README.md estará na pasta uploads.
## **💥 Considerações**
A arbodagem das APIs GraphQL é bem diferente do padrão REST. No padrão REST temos os métodos **GET**, **POST**, **PUT**, **DELETE**, **UPDATE**. Enquanto que no padrão GraphQL existe somente o método **POST** com o conceito de **QUERY** e **MUTATION**. O GraphQL se destaca em resover os problemas de over-fetching e under-fetching recocorrente em grandes projetos, com um número muito grande de usuários, quando comparado ao padrão REST.
Na minha opiniçao não devemos ser amantes de tecnologias, pois elas sempre mudam com o tempo. Devemos escolher a tecnologia que melhor se adapta ao nosso problema.
## **👨🚀 Autor**
<a href="https://github.com/tpaphysics">
<img alt="Thiago Pacheco" src="https://images.weserv.nl/?url=avatars.githubusercontent.com/u/46402647?v=4?v=4&h=300&w=300&fit=cover&mask=circle&maxage=7d" width="100px"/>
<br />
<sub>
<b>Thiago Pacheco de Andrade</b>
</sub>
</a>
<br />
👋 Meus contatos!
[](https://www.linkedin.com/in/thiago-pacheco-200a1a86/)
[](mailto:[email protected])
## Licença
Veja o arquivo [MIT license](LICENSE ). |
/*
* SPDX-FileCopyrightText: 1999 Matthias Elter <[email protected]>
* SPDX-FileCopyrightText: 2002 Patrick Julien <[email protected]>
* SPDX-FileCopyrightText: 2004 Boudewijn Rempt <[email protected]>
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#ifndef KIS_BRUSH_
#define KIS_BRUSH_
#include <QImage>
#include <KoResource.h>
#include <kis_types.h>
#include <kis_shared.h>
#include <kis_dab_shape.h>
#include <kritabrush_export.h>
class QString;
class KoColor;
class KoColorSpace;
class KisPaintInformation;
class KisPaintopLodLimitations;
class KoAbstractGradient;
class KisOptimizedBrushOutline;
typedef QSharedPointer<KoAbstractGradient> KoAbstractGradientSP;
enum enumBrushType {
INVALID,
MASK,
IMAGE,
PIPE_MASK,
PIPE_IMAGE
};
enum enumBrushApplication {
ALPHAMASK,
IMAGESTAMP,
LIGHTNESSMAP,
GRADIENTMAP
};
static const qreal DEFAULT_SOFTNESS_FACTOR = 1.0;
static const qreal DEFAULT_LIGHTNESS_STRENGTH = 1.0;
class KisBrush;
typedef QSharedPointer<KisBrush> KisBrushSP;
/**
* KisBrush is the base class for brush resources. A brush resource
* defines one or more images that are used to potato-stamp along
* the drawn path. The brush type defines how this brush is used --
* the important difference is between masks (which take the current
* painting color) and images (which do not). It is up to the paintop
* to make use of this feature.
*
* Brushes must be serializable to an xml representation and provide
* a factory class that can recreate or retrieve the brush based on
* this representation.
*
* XXX: This api is still a big mess -- it needs a good refactoring.
* And the whole KoResource architecture is way over-designed.
*/
class BRUSH_EXPORT KisBrush : public KoResource
{
public:
class ColoringInformation
{
public:
virtual ~ColoringInformation();
virtual const quint8* color() const = 0;
virtual void nextColumn() = 0;
virtual void nextRow() = 0;
};
protected:
class PlainColoringInformation : public ColoringInformation
{
public:
PlainColoringInformation(const quint8* color);
~PlainColoringInformation() override;
const quint8* color() const override ;
void nextColumn() override;
void nextRow() override;
private:
const quint8* m_color;
};
class PaintDeviceColoringInformation : public ColoringInformation
{
public:
PaintDeviceColoringInformation(const KisPaintDeviceSP source, int width);
~PaintDeviceColoringInformation() override;
const quint8* color() const override ;
void nextColumn() override;
void nextRow() override;
private:
const KisPaintDeviceSP m_source;
KisHLineConstIteratorSP m_iterator;
};
public:
KisBrush();
KisBrush(const QString& filename);
~KisBrush() override;
KisBrush(const KisBrush &rhs);
KisBrush &operator=(const KisBrush &rhs) = delete;
virtual qreal userEffectiveSize() const = 0;
virtual void setUserEffectiveSize(qreal value) = 0;
QPair<QString, QString> resourceType() const override {
return QPair<QString, QString>(ResourceType::Brushes, "");
}
/**
* @brief brushImage the image the brush tip can paint with. Not all brush types have a single
* image.
* @return a valid QImage.
*/
virtual QImage brushTipImage() const;
/**
* Is a paint device of the brush that should be used for generation
* of the brush outline. Usually, it is the same device returned
* by brushTipImage(), but might be different in some types
* of brushes, like in KisAutoBrush.
*/
virtual KisFixedPaintDeviceSP outlineSourceImage() const;
/**
* Change the spacing of the brush.
* @param spacing a spacing of 1.0 means that strokes will be separated from one time the size
* of the brush.
*/
virtual void setSpacing(double spacing);
/**
* @return the spacing between two strokes for this brush
*/
double spacing() const;
void setAutoSpacing(bool active, qreal coeff);
bool autoSpacingActive() const;
qreal autoSpacingCoeff() const;
/**
* @return the width (for scale == 1.0)
*/
qint32 width() const;
/**
* @return the height (for scale == 1.0)
*/
qint32 height() const;
/**
* @return the width of the mask for the given scale and angle
*/
virtual qint32 maskWidth(KisDabShape const&, qreal subPixelX, qreal subPixelY, const KisPaintInformation& info) const;
/**
* @return the height of the mask for the given scale and angle
*/
virtual qint32 maskHeight(KisDabShape const&, qreal subPixelX, qreal subPixelY, const KisPaintInformation& info) const;
/**
* @return the logical size of the brush, that is the size measured
* in floating point value.
*
* This value should not be used for calculating future dab sizes
* because it doesn't take any rounding into account. The only use
* of this metric is calculation of brush-size derivatives like
* hotspots and spacing.
*/
virtual QSizeF characteristicSize(KisDabShape const&) const;
/**
* @return the angle of the mask adding the given angle
*/
double maskAngle(double angle = 0) const;
/**
* @return the currently selected index of the brush
* if the brush consists of multiple images
*
* @see prepareForSeqNo()
*/
virtual quint32 brushIndex() const;
/**
* The brush type defines how the brush is used.
*/
virtual enumBrushType brushType() const;
QPointF hotSpot(KisDabShape const&, const KisPaintInformation& info) const;
/**
* Returns true if this brush can return something useful for the info. This is used
* by Pipe Brushes that can't paint sometimes
**/
virtual bool canPaintFor(const KisPaintInformation& /*info*/);
/**
* Is called by the paint op when a paintop starts a stroke. The
* point is that we store brushes a server while the paint ops are
* are recreated all the time. Is means that upon a stroke start
* the brushes may need to clear its state.
*/
virtual void notifyStrokeStarted();
/**
* Is called by the paint op before it is going to clone the brush into
* multiple instances to pass to different threads. During this call the
* brush is free to prepare some structures that may be shared by all the
* clones without excessive recalculation.
*/
virtual void notifyBrushIsGoingToBeClonedForStroke();
/**
* Is called by the multithreaded queue to prepare a specific brush
* tip for the particular seqNo.
*
* NOTE: one should use always call prepareForSeqNo() before using the brush
*
* Currently, this is used by pipe'd brushes to implement
* incremental and random parasites
*/
virtual void prepareForSeqNo(const KisPaintInformation& info, int seqNo);
/**
* Return a fixed paint device that contains a correctly scaled image dab.
*/
virtual KisFixedPaintDeviceSP paintDevice(const KoColorSpace * colorSpace,
KisDabShape const&,
const KisPaintInformation& info,
double subPixelX = 0, double subPixelY = 0) const;
/**
* clear dst fill it with a mask colored with KoColor
*/
void mask(KisFixedPaintDeviceSP dst,
const KoColor& color,
KisDabShape const& shape,
const KisPaintInformation& info,
double subPixelX = 0, double subPixelY = 0,
qreal softnessFactor = DEFAULT_SOFTNESS_FACTOR, qreal lightnessStrength = DEFAULT_LIGHTNESS_STRENGTH) const;
/**
* clear dst and fill it with a mask colored with the corresponding colors of src
*/
void mask(KisFixedPaintDeviceSP dst,
const KisPaintDeviceSP src,
KisDabShape const& shape,
const KisPaintInformation& info,
double subPixelX = 0, double subPixelY = 0,
qreal softnessFactor = DEFAULT_SOFTNESS_FACTOR, qreal lightnessStrength = DEFAULT_LIGHTNESS_STRENGTH) const;
virtual enumBrushApplication brushApplication() const;
virtual void setBrushApplication(enumBrushApplication brushApplication);
virtual bool preserveLightness() const;
virtual bool applyingGradient() const;
virtual void setGradient(KoAbstractGradientSP gradient);
/**
* Create a mask and either mask dst (that is, change all alpha values of the
* existing pixels to those of the mask) or, if coloringInfo is present, clear
* dst and fill dst with pixels according to coloringInfo, masked according to the
* generated mask.
*
* @param dst the destination that will be draw on the image, and this function
* will edit its alpha channel
* @param coloringInfo coloring information that will be copied on the dab, it can be null
* @param shape a shape applied on the alpha mask
* @param info the painting information (this is only and should only be used by
* KisImagePipeBrush and only to be backward compatible with the Gimp,
* KisImagePipeBrush is ignoring scale and angle information)
* @param subPixelX sub position of the brush (contained between 0.0 and 1.0)
* @param subPixelY sub position of the brush (contained between 0.0 and 1.0)
* @param softnessFactor softness factor of the brush
*
* @return a mask computed from the grey-level values of the
* pixels in the brush.
*/
virtual void generateMaskAndApplyMaskOrCreateDab(KisFixedPaintDeviceSP dst,
ColoringInformation* coloringInfo,
KisDabShape const&,
const KisPaintInformation& info,
double subPixelX, double subPixelY,
qreal softnessFactor, qreal lightnessStrength) const;
void generateMaskAndApplyMaskOrCreateDab(KisFixedPaintDeviceSP dst,
ColoringInformation* coloringInfo,
KisDabShape const&,
const KisPaintInformation& info,
double subPixelX = 0, double subPixelY = 0,
qreal softnessFactor = DEFAULT_SOFTNESS_FACTOR) const;
/**
* Serialize this brush to XML.
*/
virtual void toXML(QDomDocument& , QDomElement&) const;
static KisBrushSP fromXML(const QDomElement& element, KisResourcesInterfaceSP resourcesInterface);
static KoResourceLoadResult fromXMLLoadResult(const QDomElement& element, KisResourcesInterfaceSP resourcesInterface);
virtual KisOptimizedBrushOutline outline(bool forcePreciseOutline = false) const;
virtual void setScale(qreal _scale);
qreal scale() const;
virtual void setAngle(qreal _angle);
qreal angle() const;
void clearBrushPyramid();
virtual void lodLimitations(KisPaintopLodLimitations *l) const;
virtual bool supportsCaching() const;
virtual void coldInitBrush();
static const QString brushTypeMetaDataKey;
protected:
void setWidth(qint32 width);
void setHeight(qint32 height);
void setHotSpot(QPointF);
/**
* XXX
*/
virtual void setBrushType(enumBrushType type);
public:
/**
* The image is used to represent the brush in the gui, and may also, depending on the brush type
* be used to define the actual brush instance.
*/
virtual void setBrushTipImage(const QImage& image);
/**
* Returns true if the brush has a bunch of pixels almost
* fully transparent in the very center. If the brush is pierced,
* then dulling mode may not work correctly due to empty samples.
*
* WARNING: this method is relatively expensive since it iterates
* up to 100 pixels of the brush.
*/
virtual bool isPiercedApprox() const;
protected:
void resetOutlineCache();
void generateOutlineCache();
bool outlineCacheIsValid() const;
void predefinedBrushToXML(const QString &type, QDomElement& e) const;
private:
struct Private;
Private* const d;
};
Q_DECLARE_METATYPE(KisBrushSP)
#endif // KIS_BRUSH_ |
package form;
import framework.Validation;
import misc.UnitConverter;
import framework.FormField;
import framework.Form;
import model.Patient;
/**
* A form that corresponds to the HTML form in questionnaire.jsp.
*/
public final class QuestionnaireForm extends Form
{
@FormField(displayName = "Age", min = 0, max = 130)
private int age;
@FormField(displayName = "Weight", min = 0)
private double weight;
@FormField(displayName = "Gender")
private Patient.Gender gender;
@FormField(displayName = "Weight unit")
private String weightUnit;
/**
* Checks if weight was supplied in pounds and, if so, converts it to
* kilograms for use by the risk prediction systems.
*/
@Validation
public void convertWeight()
{
if (weightUnit.equalsIgnoreCase("pounds"))
{
weight = UnitConverter.lbsToKg(weight);
}
}
/**
* @return the patient's age
*/
public int getAge()
{
return age;
}
/**
* @return the patient's weight
*/
public double getWeight()
{
return weight;
}
/**
* @return the patient's gender
*/
public Patient.Gender getGender()
{
return gender;
}
} |
import logging
import re
import threading
import time
from collections import Counter
from contextlib import contextmanager
from typing import List, Optional
from unittest.mock import patch
import numpy as np
import pytest
import ray
from ray._private.test_utils import wait_for_condition
from ray.data._internal.execution.backpressure_policy import (
ENABLED_BACKPRESSURE_POLICIES_CONFIG_KEY,
)
from ray.data._internal.execution.backpressure_policy.backpressure_policy import (
BackpressurePolicy,
)
from ray.data._internal.execution.interfaces.physical_operator import PhysicalOperator
from ray.data._internal.execution.streaming_executor_state import Topology
from ray.data._internal.stats import (
DatasetStats,
StatsManager,
_get_or_create_stats_actor,
_StatsActor,
)
from ray.data._internal.util import create_dataset_tag
from ray.data.block import BlockMetadata
from ray.data.context import DataContext
from ray.data.tests.util import column_udf
from ray.tests.conftest import * # noqa
def gen_expected_metrics(
is_map: bool,
spilled: bool = False,
task_backpressure: bool = False,
extra_metrics: Optional[List[str]] = None,
):
if is_map:
metrics = [
"'num_inputs_received': N",
"'bytes_inputs_received': N",
"'num_task_inputs_processed': N",
"'bytes_task_inputs_processed': N",
"'bytes_inputs_of_submitted_tasks': N",
"'num_task_outputs_generated': N",
"'bytes_task_outputs_generated': N",
"'rows_task_outputs_generated': N",
"'num_outputs_taken': N",
"'bytes_outputs_taken': N",
"'num_outputs_of_finished_tasks': N",
"'bytes_outputs_of_finished_tasks': N",
"'num_tasks_submitted': N",
"'num_tasks_running': Z",
"'num_tasks_have_outputs': N",
"'num_tasks_finished': N",
"'num_tasks_failed': Z",
"'block_generation_time': N",
(
"'task_submission_backpressure_time': "
f"{'N' if task_backpressure else 'Z'}"
),
"'obj_store_mem_internal_inqueue_blocks': Z",
"'obj_store_mem_internal_inqueue': Z",
"'obj_store_mem_internal_outqueue_blocks': Z",
"'obj_store_mem_internal_outqueue': Z",
"'obj_store_mem_pending_task_inputs': Z",
"'obj_store_mem_freed': N",
f"""'obj_store_mem_spilled': {"N" if spilled else "Z"}""",
"'obj_store_mem_used': A",
"'cpu_usage': Z",
"'gpu_usage': Z",
]
else:
metrics = [
"'num_inputs_received': N",
"'bytes_inputs_received': N",
"'num_outputs_taken': N",
"'bytes_outputs_taken': N",
(
"'task_submission_backpressure_time': "
f"{'N' if task_backpressure else 'Z'}"
),
"'obj_store_mem_internal_inqueue_blocks': Z",
"'obj_store_mem_internal_inqueue': Z",
"'obj_store_mem_internal_outqueue_blocks': Z",
"'obj_store_mem_internal_outqueue': Z",
"'obj_store_mem_used': A",
"'cpu_usage': Z",
"'gpu_usage': Z",
]
if extra_metrics:
metrics.extend(extra_metrics)
return "{" + ", ".join(metrics) + "}"
def gen_extra_metrics_str(metrics: str, verbose: bool):
return f"* Extra metrics: {metrics}" + "\n" if verbose else ""
def gen_runtime_metrics_str(op_names: List[str], verbose: bool) -> str:
if not verbose:
return ""
out = "\nRuntime Metrics:\n"
for op in op_names + ["Scheduling", "Total"]:
out += f"* {op}: T (N%)\n"
return out
STANDARD_EXTRA_METRICS = gen_expected_metrics(
is_map=True,
spilled=False,
extra_metrics=[
"'ray_remote_args': {'num_cpus': N, 'scheduling_strategy': 'SPREAD'}"
],
)
STANDARD_EXTRA_METRICS_TASK_BACKPRESSURE = gen_expected_metrics(
is_map=True,
spilled=False,
task_backpressure=True,
extra_metrics=[
"'ray_remote_args': {'num_cpus': N, 'scheduling_strategy': 'SPREAD'}"
],
)
LARGE_ARGS_EXTRA_METRICS = gen_expected_metrics(
is_map=True,
spilled=False,
extra_metrics=[
"'ray_remote_args': {'num_cpus': N, 'scheduling_strategy': 'DEFAULT'}"
],
)
LARGE_ARGS_EXTRA_METRICS_TASK_BACKPRESSURE = gen_expected_metrics(
is_map=True,
spilled=False,
task_backpressure=True,
extra_metrics=[
"'ray_remote_args': {'num_cpus': N, 'scheduling_strategy': 'DEFAULT'}"
],
)
MEM_SPILLED_EXTRA_METRICS = gen_expected_metrics(
is_map=True,
spilled=True,
extra_metrics=[
"'ray_remote_args': {'num_cpus': N, 'scheduling_strategy': 'SPREAD'}"
],
)
MEM_SPILLED_EXTRA_METRICS_TASK_BACKPRESSURE = gen_expected_metrics(
is_map=True,
spilled=True,
task_backpressure=True,
extra_metrics=[
"'ray_remote_args': {'num_cpus': N, 'scheduling_strategy': 'SPREAD'}"
],
)
CLUSTER_MEMORY_STATS = """
Cluster memory:
* Spilled to disk: M
* Restored from disk: M
"""
DATASET_MEMORY_STATS = """
Dataset memory:
* Spilled to disk: M
"""
EXECUTION_STRING = "N tasks executed, N blocks produced in T"
def canonicalize(stats: str, filter_global_stats: bool = True) -> str:
# Dataset UUID expression.
canonicalized_stats = re.sub("([a-f\d]{32})", "U", stats)
# Time expressions.
canonicalized_stats = re.sub("[0-9\.]+(ms|us|s)", "T", canonicalized_stats)
# Memory expressions.
canonicalized_stats = re.sub("[0-9\.]+(B|MB|GB)", "M", canonicalized_stats)
# For obj_store_mem_used, the value can be zero or positive, depending on the run.
# Replace with A to avoid test flakiness.
canonicalized_stats = re.sub(
r"(obj_store_mem_used: |'obj_store_mem_used': )\d+(\.\d+)?",
# Replaces the number with 'A' while keeping the key prefix intact.
r"\g<1>A",
canonicalized_stats,
)
# Handle floats in (0, 1)
canonicalized_stats = re.sub(" (0\.0*[1-9][0-9]*)", " N", canonicalized_stats)
# Handle zero values specially so we can check for missing values.
canonicalized_stats = re.sub(" [0]+(\.[0])?", " Z", canonicalized_stats)
# Scientific notation for small or large numbers
canonicalized_stats = re.sub("\d+(\.\d+)?[eE][-+]?\d+", "N", canonicalized_stats)
# Other numerics.
canonicalized_stats = re.sub("[0-9]+(\.[0-9]+)?", "N", canonicalized_stats)
# Replace tabs with spaces.
canonicalized_stats = re.sub("\t", " ", canonicalized_stats)
if filter_global_stats:
canonicalized_stats = canonicalized_stats.replace(CLUSTER_MEMORY_STATS, "")
canonicalized_stats = canonicalized_stats.replace(DATASET_MEMORY_STATS, "")
return canonicalized_stats
def dummy_map_batches(x):
"""Dummy function used in calls to map_batches below."""
return x
def dummy_map_batches_sleep(n):
"""Function used to create a function that sleeps for n seconds
to be used in map_batches below."""
def f(x):
time.sleep(n)
return x
return f
@contextmanager
def patch_update_stats_actor():
with patch(
"ray.data._internal.stats.StatsManager.update_execution_metrics"
) as update_fn:
yield update_fn
@contextmanager
def patch_update_stats_actor_iter():
with patch(
"ray.data._internal.stats.StatsManager.update_iteration_metrics"
) as update_fn, patch(
"ray.data._internal.stats.StatsManager.clear_iteration_metrics"
):
yield update_fn
def test_streaming_split_stats(ray_start_regular_shared, restore_data_context):
context = DataContext.get_current()
context.verbose_stats_logs = True
ds = ray.data.range(1000, override_num_blocks=10)
it = ds.map_batches(dummy_map_batches).streaming_split(1)[0]
list(it.iter_batches())
stats = it.stats()
extra_metrics_1 = STANDARD_EXTRA_METRICS_TASK_BACKPRESSURE # .replace(
# "'obj_store_mem_used': A", "'obj_store_mem_used': Z"
# )
extra_metrics_2 = gen_expected_metrics(
is_map=False,
extra_metrics=["'num_output_N': N", "'output_splitter_overhead_time': N"],
)
assert (
canonicalize(stats)
== f"""Operator N ReadRange->MapBatches(dummy_map_batches): {EXECUTION_STRING}
* Remote wall time: T min, T max, T mean, T total
* Remote cpu time: T min, T max, T mean, T total
* UDF time: T min, T max, T mean, T total
* Peak heap memory usage (MiB): N min, N max, N mean
* Output num rows per block: N min, N max, N mean, N total
* Output size bytes per block: N min, N max, N mean, N total
* Output rows per task: N min, N max, N mean, N tasks used
* Tasks per node: N min, N max, N mean; N nodes used
* Operator throughput:
* Ray Data throughput: N rows/s
* Estimated single node throughput: N rows/s
* Extra metrics: {extra_metrics_1}
Operator N split(N, equal=False): \n"""
# Workaround to preserve trailing whitespace in the above line without
# causing linter failures.
f"""* Extra metrics: {extra_metrics_2}\n"""
"""
Dataset iterator time breakdown:
* Total time overall: T
* Total time in Ray Data iterator initialization code: T
* Total time user thread is blocked by Ray Data iter_batches: T
* Total execution time for user thread: T
* Batch iteration time breakdown (summed across prefetch threads):
* In ray.get(): T min, T max, T avg, T total
* In batch creation: T min, T max, T avg, T total
* In batch formatting: T min, T max, T avg, T total
Streaming split coordinator overhead time: T
"""
f"{gen_runtime_metrics_str(['ReadRange->MapBatches(dummy_map_batches)', 'split(N, equal=False)'], True)}" # noqa: E501
)
@pytest.mark.parametrize("verbose_stats_logs", [True, False])
def test_large_args_scheduling_strategy(
ray_start_regular_shared, verbose_stats_logs, restore_data_context
):
context = DataContext.get_current()
context.verbose_stats_logs = verbose_stats_logs
ds = ray.data.range_tensor(100, shape=(100000,), override_num_blocks=1)
ds = ds.map_batches(dummy_map_batches, num_cpus=0.9).materialize()
stats = ds.stats()
read_extra_metrics = gen_extra_metrics_str(
STANDARD_EXTRA_METRICS_TASK_BACKPRESSURE,
verbose_stats_logs,
)
# if verbose_stats_logs:
# read_extra_metrics = read_extra_metrics#.replace(
# "'obj_store_mem_used': N",
# "'obj_store_mem_used': Z",
# )
map_extra_metrics = gen_extra_metrics_str(
LARGE_ARGS_EXTRA_METRICS_TASK_BACKPRESSURE,
verbose_stats_logs,
)
# if verbose_stats_logs:
# map_extra_metrics = map_extra_metrics.replace(
# "'obj_store_mem_used': N",
# "'obj_store_mem_used': Z",
# )
expected_stats = (
f"Operator N ReadRange: {EXECUTION_STRING}\n"
f"* Remote wall time: T min, T max, T mean, T total\n"
f"* Remote cpu time: T min, T max, T mean, T total\n"
f"* UDF time: T min, T max, T mean, T total\n"
f"* Peak heap memory usage (MiB): N min, N max, N mean\n"
f"* Output num rows per block: N min, N max, N mean, N total\n"
f"* Output size bytes per block: N min, N max, N mean, N total\n"
f"* Output rows per task: N min, N max, N mean, N tasks used\n"
f"* Tasks per node: N min, N max, N mean; N nodes used\n"
f"* Operator throughput:\n"
f" * Ray Data throughput: N rows/s\n"
f" * Estimated single node throughput: N rows/s\n"
f"{read_extra_metrics}\n"
f"Operator N MapBatches(dummy_map_batches): {EXECUTION_STRING}\n"
f"* Remote wall time: T min, T max, T mean, T total\n"
f"* Remote cpu time: T min, T max, T mean, T total\n"
f"* UDF time: T min, T max, T mean, T total\n"
f"* Peak heap memory usage (MiB): N min, N max, N mean\n"
f"* Output num rows per block: N min, N max, N mean, N total\n"
f"* Output size bytes per block: N min, N max, N mean, N total\n"
f"* Output rows per task: N min, N max, N mean, N tasks used\n"
f"* Tasks per node: N min, N max, N mean; N nodes used\n"
f"* Operator throughput:\n"
f" * Ray Data throughput: N rows/s\n"
f" * Estimated single node throughput: N rows/s\n"
f"{map_extra_metrics}"
f"\n"
f"Dataset throughput:\n"
f" * Ray Data throughput: N rows/s\n"
f" * Estimated single node throughput: N rows/s\n"
f"{gen_runtime_metrics_str(['ReadRange','MapBatches(dummy_map_batches)'], verbose_stats_logs)}" # noqa: E501
)
assert canonicalize(stats) == expected_stats
@pytest.mark.parametrize("verbose_stats_logs", [True, False])
def test_dataset_stats_basic(
ray_start_regular_shared,
enable_auto_log_stats,
verbose_stats_logs,
restore_data_context,
):
context = DataContext.get_current()
context.verbose_stats_logs = verbose_stats_logs
logger = logging.getLogger("ray.data._internal.execution.streaming_executor")
with patch.object(logger, "info") as mock_logger:
ds = ray.data.range(1000, override_num_blocks=10)
ds = ds.map_batches(dummy_map_batches).materialize()
if enable_auto_log_stats:
logger_args, logger_kwargs = mock_logger.call_args
assert canonicalize(logger_args[0]) == (
f"Operator N ReadRange->MapBatches(dummy_map_batches): "
f"{EXECUTION_STRING}\n"
f"* Remote wall time: T min, T max, T mean, T total\n"
f"* Remote cpu time: T min, T max, T mean, T total\n"
f"* UDF time: T min, T max, T mean, T total\n"
f"* Peak heap memory usage (MiB): N min, N max, N mean\n"
f"* Output num rows per block: N min, N max, N mean, N total\n"
f"* Output size bytes per block: N min, N max, N mean, N total\n"
f"* Output rows per task: N min, N max, N mean, N tasks used\n"
f"* Tasks per node: N min, N max, N mean; N nodes used\n"
f"* Operator throughput:\n"
f" * Ray Data throughput: N rows/s\n"
f" * Estimated single node throughput: N rows/s\n"
f"{gen_extra_metrics_str(STANDARD_EXTRA_METRICS_TASK_BACKPRESSURE, verbose_stats_logs)}" # noqa: E501
f"\n"
f"Dataset throughput:\n"
f" * Ray Data throughput: N rows/s\n"
f" * Estimated single node throughput: N rows/s\n"
f"{gen_runtime_metrics_str(['ReadRange->MapBatches(dummy_map_batches)'], verbose_stats_logs)}" # noqa: E501
)
ds = ds.map(dummy_map_batches).materialize()
if enable_auto_log_stats:
logger_args, logger_kwargs = mock_logger.call_args
assert canonicalize(logger_args[0]) == (
f"Operator N Map(dummy_map_batches): {EXECUTION_STRING}\n"
f"* Remote wall time: T min, T max, T mean, T total\n"
f"* Remote cpu time: T min, T max, T mean, T total\n"
f"* UDF time: T min, T max, T mean, T total\n"
f"* Peak heap memory usage (MiB): N min, N max, N mean\n"
f"* Output num rows per block: N min, N max, N mean, N total\n"
f"* Output size bytes per block: N min, N max, N mean, N total\n"
f"* Output rows per task: N min, N max, N mean, N tasks used\n"
f"* Tasks per node: N min, N max, N mean; N nodes used\n"
f"* Operator throughput:\n"
f" * Ray Data throughput: N rows/s\n"
f" * Estimated single node throughput: N rows/s\n"
f"{gen_extra_metrics_str(STANDARD_EXTRA_METRICS_TASK_BACKPRESSURE, verbose_stats_logs)}" # noqa: E501
f"\n"
f"Dataset throughput:\n"
f" * Ray Data throughput: N rows/s\n"
f" * Estimated single node throughput: N rows/s\n"
f"{gen_runtime_metrics_str(['ReadRange->MapBatches(dummy_map_batches)','Map(dummy_map_batches)'], verbose_stats_logs)}" # noqa: E501
)
for batch in ds.iter_batches():
pass
stats = canonicalize(ds.materialize().stats())
extra_metrics = gen_extra_metrics_str(
STANDARD_EXTRA_METRICS_TASK_BACKPRESSURE,
verbose_stats_logs,
)
assert stats == (
f"Operator N ReadRange->MapBatches(dummy_map_batches): {EXECUTION_STRING}\n"
f"* Remote wall time: T min, T max, T mean, T total\n"
f"* Remote cpu time: T min, T max, T mean, T total\n"
f"* UDF time: T min, T max, T mean, T total\n"
f"* Peak heap memory usage (MiB): N min, N max, N mean\n"
f"* Output num rows per block: N min, N max, N mean, N total\n"
f"* Output size bytes per block: N min, N max, N mean, N total\n"
f"* Output rows per task: N min, N max, N mean, N tasks used\n"
f"* Tasks per node: N min, N max, N mean; N nodes used\n"
f"* Operator throughput:\n"
f" * Ray Data throughput: N rows/s\n"
f" * Estimated single node throughput: N rows/s\n"
f"{extra_metrics}\n"
f"Operator N Map(dummy_map_batches): {EXECUTION_STRING}\n"
f"* Remote wall time: T min, T max, T mean, T total\n"
f"* Remote cpu time: T min, T max, T mean, T total\n"
f"* UDF time: T min, T max, T mean, T total\n"
f"* Peak heap memory usage (MiB): N min, N max, N mean\n"
f"* Output num rows per block: N min, N max, N mean, N total\n"
f"* Output size bytes per block: N min, N max, N mean, N total\n"
f"* Output rows per task: N min, N max, N mean, N tasks used\n"
f"* Tasks per node: N min, N max, N mean; N nodes used\n"
f"* Operator throughput:\n"
f" * Ray Data throughput: N rows/s\n"
f" * Estimated single node throughput: N rows/s\n"
f"{extra_metrics}\n"
f"Dataset iterator time breakdown:\n"
f"* Total time overall: T\n"
f" * Total time in Ray Data iterator initialization code: T\n"
f" * Total time user thread is blocked by Ray Data iter_batches: T\n"
f" * Total execution time for user thread: T\n"
f"* Batch iteration time breakdown (summed across prefetch threads):\n"
f" * In ray.get(): T min, T max, T avg, T total\n"
f" * In batch creation: T min, T max, T avg, T total\n"
f" * In batch formatting: T min, T max, T avg, T total\n"
f"\n"
f"Dataset throughput:\n"
f" * Ray Data throughput: N rows/s\n"
f" * Estimated single node throughput: N rows/s\n"
f"{gen_runtime_metrics_str(['ReadRange->MapBatches(dummy_map_batches)','Map(dummy_map_batches)'], verbose_stats_logs)}" # noqa: E501
)
def test_block_location_nums(ray_start_regular_shared, restore_data_context):
context = DataContext.get_current()
context.enable_get_object_locations_for_metrics = True
ds = ray.data.range(1000, override_num_blocks=10)
ds = ds.map_batches(dummy_map_batches).materialize()
for batch in ds.iter_batches():
pass
stats = canonicalize(ds.materialize().stats())
assert stats == (
f"Operator N ReadRange->MapBatches(dummy_map_batches): {EXECUTION_STRING}\n"
f"* Remote wall time: T min, T max, T mean, T total\n"
f"* Remote cpu time: T min, T max, T mean, T total\n"
f"* UDF time: T min, T max, T mean, T total\n"
f"* Peak heap memory usage (MiB): N min, N max, N mean\n"
f"* Output num rows per block: N min, N max, N mean, N total\n"
f"* Output size bytes per block: N min, N max, N mean, N total\n"
f"* Output rows per task: N min, N max, N mean, N tasks used\n"
f"* Tasks per node: N min, N max, N mean; N nodes used\n"
f"* Operator throughput:\n"
f" * Ray Data throughput: N rows/s\n"
f" * Estimated single node throughput: N rows/s\n"
f"\n"
f"Dataset iterator time breakdown:\n"
f"* Total time overall: T\n"
f" * Total time in Ray Data iterator initialization code: T\n"
f" * Total time user thread is blocked by Ray Data iter_batches: T\n"
f" * Total execution time for user thread: T\n"
f"* Batch iteration time breakdown (summed across prefetch threads):\n"
f" * In ray.get(): T min, T max, T avg, T total\n"
f" * In batch creation: T min, T max, T avg, T total\n"
f" * In batch formatting: T min, T max, T avg, T total\n"
f"Block locations:\n"
f" * Num blocks local: Z\n"
f" * Num blocks remote: Z\n"
f" * Num blocks unknown location: N\n"
f"\n"
f"Dataset throughput:\n"
f" * Ray Data throughput: N rows/s\n"
f" * Estimated single node throughput: N rows/s\n"
)
def test_dataset__repr__(ray_start_regular_shared, restore_data_context):
context = DataContext.get_current()
context.enable_get_object_locations_for_metrics = True
n = 100
ds = ray.data.range(n)
assert len(ds.take_all()) == n
ds = ds.materialize()
expected_stats = (
"DatasetStatsSummary(\n"
" dataset_uuid=N,\n"
" base_name=None,\n"
" number=N,\n"
" extra_metrics={},\n"
" operators_stats=[\n"
" OperatorStatsSummary(\n"
" operator_name='Read',\n"
" is_suboperator=False,\n"
" time_total_s=T,\n"
f" block_execution_summary_str={EXECUTION_STRING}\n"
" wall_time={'min': 'T', 'max': 'T', 'mean': 'T', 'sum': 'T'},\n"
" cpu_time={'min': 'T', 'max': 'T', 'mean': 'T', 'sum': 'T'},\n"
" memory={'min': 'T', 'max': 'T', 'mean': 'T'},\n"
" output_num_rows={'min': 'T', 'max': 'T', 'mean': 'T', 'sum': 'T'},\n"
" output_size_bytes={'min': 'T', 'max': 'T', 'mean': 'T', 'sum': 'T'},\n" # noqa: E501
" node_count={'min': 'T', 'max': 'T', 'mean': 'T', 'count': 'T'},\n"
" ),\n"
" ],\n"
" iter_stats=IterStatsSummary(\n"
" wait_time=T,\n"
" get_time=T,\n"
" iter_blocks_local=None,\n"
" iter_blocks_remote=None,\n"
" iter_unknown_location=None,\n"
" next_time=T,\n"
" format_time=T,\n"
" user_time=T,\n"
" total_time=T,\n"
" ),\n"
" global_bytes_spilled=M,\n"
" global_bytes_restored=M,\n"
" dataset_bytes_spilled=M,\n"
" parents=[],\n"
")"
)
def check_stats():
stats = canonicalize(repr(ds._plan.stats().to_summary()))
assert stats == expected_stats
return True
# TODO(hchen): The reason why `wait_for_condition` is needed here is because
# `to_summary` depends on an external actor (_StatsActor) that records stats
# asynchronously. This makes the behavior non-deterministic.
# See the TODO in `to_summary`.
# We should make it deterministic and refine this test.
wait_for_condition(
check_stats,
timeout=10,
retry_interval_ms=1000,
)
ds2 = ds.map_batches(lambda x: x).materialize()
assert len(ds2.take_all()) == n
expected_stats2 = (
"DatasetStatsSummary(\n"
" dataset_uuid=N,\n"
" base_name=MapBatches(<lambda>),\n"
" number=N,\n"
" extra_metrics={\n"
" num_inputs_received: N,\n"
" bytes_inputs_received: N,\n"
" num_task_inputs_processed: N,\n"
" bytes_task_inputs_processed: N,\n"
" bytes_inputs_of_submitted_tasks: N,\n"
" num_task_outputs_generated: N,\n"
" bytes_task_outputs_generated: N,\n"
" rows_task_outputs_generated: N,\n"
" num_outputs_taken: N,\n"
" bytes_outputs_taken: N,\n"
" num_outputs_of_finished_tasks: N,\n"
" bytes_outputs_of_finished_tasks: N,\n"
" num_tasks_submitted: N,\n"
" num_tasks_running: Z,\n"
" num_tasks_have_outputs: N,\n"
" num_tasks_finished: N,\n"
" num_tasks_failed: Z,\n"
" block_generation_time: N,\n"
" task_submission_backpressure_time: N,\n"
" obj_store_mem_internal_inqueue_blocks: Z,\n"
" obj_store_mem_internal_inqueue: Z,\n"
" obj_store_mem_internal_outqueue_blocks: Z,\n"
" obj_store_mem_internal_outqueue: Z,\n"
" obj_store_mem_pending_task_inputs: Z,\n"
" obj_store_mem_freed: N,\n"
" obj_store_mem_spilled: Z,\n"
" obj_store_mem_used: A,\n"
" cpu_usage: Z,\n"
" gpu_usage: Z,\n"
" ray_remote_args: {'num_cpus': N, 'scheduling_strategy': 'SPREAD'},\n"
" },\n"
" operators_stats=[\n"
" OperatorStatsSummary(\n"
" operator_name='MapBatches(<lambda>)',\n"
" is_suboperator=False,\n"
" time_total_s=T,\n"
f" block_execution_summary_str={EXECUTION_STRING}\n"
" wall_time={'min': 'T', 'max': 'T', 'mean': 'T', 'sum': 'T'},\n"
" cpu_time={'min': 'T', 'max': 'T', 'mean': 'T', 'sum': 'T'},\n"
" memory={'min': 'T', 'max': 'T', 'mean': 'T'},\n"
" output_num_rows={'min': 'T', 'max': 'T', 'mean': 'T', 'sum': 'T'},\n"
" output_size_bytes={'min': 'T', 'max': 'T', 'mean': 'T', 'sum': 'T'},\n" # noqa: E501
" node_count={'min': 'T', 'max': 'T', 'mean': 'T', 'count': 'T'},\n"
" ),\n"
" ],\n"
" iter_stats=IterStatsSummary(\n"
" wait_time=T,\n"
" get_time=T,\n"
" iter_blocks_local=None,\n"
" iter_blocks_remote=None,\n"
" iter_unknown_location=N,\n"
" next_time=T,\n"
" format_time=T,\n"
" user_time=T,\n"
" total_time=T,\n"
" ),\n"
" global_bytes_spilled=M,\n"
" global_bytes_restored=M,\n"
" dataset_bytes_spilled=M,\n"
" parents=[\n"
" DatasetStatsSummary(\n"
" dataset_uuid=N,\n"
" base_name=None,\n"
" number=N,\n"
" extra_metrics={},\n"
" operators_stats=[\n"
" OperatorStatsSummary(\n"
" operator_name='Read',\n"
" is_suboperator=False,\n"
" time_total_s=T,\n"
f" block_execution_summary_str={EXECUTION_STRING}\n"
" wall_time={'min': 'T', 'max': 'T', 'mean': 'T', 'sum': 'T'},\n"
" cpu_time={'min': 'T', 'max': 'T', 'mean': 'T', 'sum': 'T'},\n"
" memory={'min': 'T', 'max': 'T', 'mean': 'T'},\n"
" output_num_rows={'min': 'T', 'max': 'T', 'mean': 'T', 'sum': 'T'},\n" # noqa: E501
" output_size_bytes={'min': 'T', 'max': 'T', 'mean': 'T', 'sum': 'T'},\n" # noqa: E501
" node_count={'min': 'T', 'max': 'T', 'mean': 'T', 'count': 'T'},\n" # noqa: E501
" ),\n"
" ],\n"
" iter_stats=IterStatsSummary(\n"
" wait_time=T,\n"
" get_time=T,\n"
" iter_blocks_local=None,\n"
" iter_blocks_remote=None,\n"
" iter_unknown_location=None,\n"
" next_time=T,\n"
" format_time=T,\n"
" user_time=T,\n"
" total_time=T,\n"
" ),\n"
" global_bytes_spilled=M,\n"
" global_bytes_restored=M,\n"
" dataset_bytes_spilled=M,\n"
" parents=[],\n"
" ),\n"
" ],\n"
")"
)
def check_stats2():
stats = canonicalize(repr(ds2._plan.stats().to_summary()))
assert stats == expected_stats2
return True
wait_for_condition(
check_stats2,
timeout=10,
retry_interval_ms=1000,
)
def test_dataset_stats_shuffle(ray_start_regular_shared):
ds = ray.data.range(1000, override_num_blocks=10)
ds = ds.random_shuffle().repartition(1, shuffle=True)
stats = canonicalize(ds.materialize().stats())
assert (
stats
== """Operator N ReadRange->RandomShuffle: executed in T
Suboperator Z ReadRange->RandomShuffleMap: N tasks executed, N blocks produced
* Remote wall time: T min, T max, T mean, T total
* Remote cpu time: T min, T max, T mean, T total
* UDF time: T min, T max, T mean, T total
* Peak heap memory usage (MiB): N min, N max, N mean
* Output num rows per block: N min, N max, N mean, N total
* Output size bytes per block: N min, N max, N mean, N total
* Output rows per task: N min, N max, N mean, N tasks used
* Tasks per node: N min, N max, N mean; N nodes used
* Operator throughput:
* Ray Data throughput: N rows/s
* Estimated single node throughput: N rows/s
Suboperator N RandomShuffleReduce: N tasks executed, N blocks produced
* Remote wall time: T min, T max, T mean, T total
* Remote cpu time: T min, T max, T mean, T total
* UDF time: T min, T max, T mean, T total
* Peak heap memory usage (MiB): N min, N max, N mean
* Output num rows per block: N min, N max, N mean, N total
* Output size bytes per block: N min, N max, N mean, N total
* Output rows per task: N min, N max, N mean, N tasks used
* Tasks per node: N min, N max, N mean; N nodes used
* Operator throughput:
* Ray Data throughput: N rows/s
* Estimated single node throughput: N rows/s
Operator N Repartition: executed in T
Suboperator Z RepartitionMap: N tasks executed, N blocks produced
* Remote wall time: T min, T max, T mean, T total
* Remote cpu time: T min, T max, T mean, T total
* UDF time: T min, T max, T mean, T total
* Peak heap memory usage (MiB): N min, N max, N mean
* Output num rows per block: N min, N max, N mean, N total
* Output size bytes per block: N min, N max, N mean, N total
* Output rows per task: N min, N max, N mean, N tasks used
* Tasks per node: N min, N max, N mean; N nodes used
* Operator throughput:
* Ray Data throughput: N rows/s
* Estimated single node throughput: N rows/s
Suboperator N RepartitionReduce: N tasks executed, N blocks produced
* Remote wall time: T min, T max, T mean, T total
* Remote cpu time: T min, T max, T mean, T total
* UDF time: T min, T max, T mean, T total
* Peak heap memory usage (MiB): N min, N max, N mean
* Output num rows per block: N min, N max, N mean, N total
* Output size bytes per block: N min, N max, N mean, N total
* Output rows per task: N min, N max, N mean, N tasks used
* Tasks per node: N min, N max, N mean; N nodes used
* Operator throughput:
* Ray Data throughput: N rows/s
* Estimated single node throughput: N rows/s
Dataset throughput:
* Ray Data throughput: N rows/s
* Estimated single node throughput: N rows/s
"""
)
def test_dataset_stats_repartition(ray_start_regular_shared):
ds = ray.data.range(1000, override_num_blocks=10)
ds = ds.repartition(1, shuffle=False)
stats = ds.materialize().stats()
assert "Repartition" in stats, stats
def test_dataset_stats_union(ray_start_regular_shared):
ds = ray.data.range(1000, override_num_blocks=10)
ds = ds.union(ds)
stats = ds.materialize().stats()
assert "Union" in stats, stats
def test_dataset_stats_zip(ray_start_regular_shared):
ds = ray.data.range(1000, override_num_blocks=10)
ds = ds.zip(ds)
stats = ds.materialize().stats()
assert "Zip" in stats, stats
def test_dataset_stats_sort(ray_start_regular_shared):
ds = ray.data.range(1000, override_num_blocks=10)
ds = ds.sort("id")
stats = ds.materialize().stats()
assert "SortMap" in stats, stats
assert "SortReduce" in stats, stats
def test_dataset_stats_from_items(ray_start_regular_shared):
ds = ray.data.from_items(range(10))
stats = ds.materialize().stats()
assert "FromItems" in stats, stats
def test_dataset_stats_read_parquet(ray_start_regular_shared, tmp_path):
ds = ray.data.range(1000, override_num_blocks=10)
ds.write_parquet(str(tmp_path))
ds = ray.data.read_parquet(str(tmp_path)).map(lambda x: x)
stats = canonicalize(ds.materialize().stats())
assert stats == (
f"Operator N ReadParquet->Map(<lambda>): {EXECUTION_STRING}\n"
f"* Remote wall time: T min, T max, T mean, T total\n"
f"* Remote cpu time: T min, T max, T mean, T total\n"
f"* UDF time: T min, T max, T mean, T total\n"
f"* Peak heap memory usage (MiB): N min, N max, N mean\n"
f"* Output num rows per block: N min, N max, N mean, N total\n"
f"* Output size bytes per block: N min, N max, N mean, N total\n"
f"* Output rows per task: N min, N max, N mean, N tasks used\n"
f"* Tasks per node: N min, N max, N mean; N nodes used\n"
f"* Operator throughput:\n"
f" * Ray Data throughput: N rows/s\n"
f" * Estimated single node throughput: N rows/s\n"
f"\n"
f"Dataset throughput:\n"
f" * Ray Data throughput: N rows/s\n"
f" * Estimated single node throughput: N rows/s\n"
)
def test_dataset_split_stats(ray_start_regular_shared, tmp_path):
ds = ray.data.range(100, override_num_blocks=10).map(
column_udf("id", lambda x: x + 1)
)
dses = ds.split_at_indices([49])
dses = [ds.map(column_udf("id", lambda x: x + 1)) for ds in dses]
for ds_ in dses:
stats = canonicalize(ds_.materialize().stats())
assert stats == (
f"Operator N ReadRange->Map(<lambda>): {EXECUTION_STRING}\n"
f"* Remote wall time: T min, T max, T mean, T total\n"
f"* Remote cpu time: T min, T max, T mean, T total\n"
f"* UDF time: T min, T max, T mean, T total\n"
f"* Peak heap memory usage (MiB): N min, N max, N mean\n"
f"* Output num rows per block: N min, N max, N mean, N total\n"
f"* Output size bytes per block: N min, N max, N mean, N total\n"
f"* Output rows per task: N min, N max, N mean, N tasks used\n"
f"* Tasks per node: N min, N max, N mean; N nodes used\n"
f"* Operator throughput:\n"
f" * Ray Data throughput: N rows/s\n"
f" * Estimated single node throughput: N rows/s\n"
f"\n"
f"Operator N Split: {EXECUTION_STRING}\n"
f"* Remote wall time: T min, T max, T mean, T total\n"
f"* Remote cpu time: T min, T max, T mean, T total\n"
f"* UDF time: T min, T max, T mean, T total\n"
f"* Peak heap memory usage (MiB): N min, N max, N mean\n"
f"* Output num rows per block: N min, N max, N mean, N total\n"
f"* Output size bytes per block: N min, N max, N mean, N total\n"
f"* Output rows per task: N min, N max, N mean, N tasks used\n"
f"* Tasks per node: N min, N max, N mean; N nodes used\n"
f"* Operator throughput:\n"
f" * Ray Data throughput: N rows/s\n"
f" * Estimated single node throughput: N rows/s\n"
f"\n"
f"Operator N Map(<lambda>): {EXECUTION_STRING}\n"
f"* Remote wall time: T min, T max, T mean, T total\n"
f"* Remote cpu time: T min, T max, T mean, T total\n"
f"* UDF time: T min, T max, T mean, T total\n"
f"* Peak heap memory usage (MiB): N min, N max, N mean\n"
f"* Output num rows per block: N min, N max, N mean, N total\n"
f"* Output size bytes per block: N min, N max, N mean, N total\n"
f"* Output rows per task: N min, N max, N mean, N tasks used\n"
f"* Tasks per node: N min, N max, N mean; N nodes used\n"
f"* Operator throughput:\n"
f" * Ray Data throughput: N rows/s\n"
f" * Estimated single node throughput: N rows/s\n"
f"\n"
f"Dataset throughput:\n"
f" * Ray Data throughput: N rows/s\n"
f" * Estimated single node throughput: N rows/s\n"
)
def test_calculate_blocks_stats(ray_start_regular_shared, op_two_block):
block_params, block_meta_list = op_two_block
stats = DatasetStats(
metadata={"Read": block_meta_list},
parent=None,
)
calculated_stats = stats.to_summary().operators_stats[0]
assert calculated_stats.output_num_rows == {
"min": min(block_params["num_rows"]),
"max": max(block_params["num_rows"]),
"mean": np.mean(block_params["num_rows"]),
"sum": sum(block_params["num_rows"]),
}
assert calculated_stats.output_size_bytes == {
"min": min(block_params["size_bytes"]),
"max": max(block_params["size_bytes"]),
"mean": np.mean(block_params["size_bytes"]),
"sum": sum(block_params["size_bytes"]),
}
assert calculated_stats.wall_time == {
"min": min(block_params["wall_time"]),
"max": max(block_params["wall_time"]),
"mean": np.mean(block_params["wall_time"]),
"sum": sum(block_params["wall_time"]),
}
assert calculated_stats.cpu_time == {
"min": min(block_params["cpu_time"]),
"max": max(block_params["cpu_time"]),
"mean": np.mean(block_params["cpu_time"]),
"sum": sum(block_params["cpu_time"]),
}
node_counts = Counter(block_params["node_id"])
assert calculated_stats.node_count == {
"min": min(node_counts.values()),
"max": max(node_counts.values()),
"mean": np.mean(list(node_counts.values())),
"count": len(node_counts),
}
def test_summarize_blocks(ray_start_regular_shared, op_two_block):
block_params, block_meta_list = op_two_block
stats = DatasetStats(
metadata={"Read": block_meta_list},
parent=None,
)
stats.dataset_uuid = "test-uuid"
calculated_stats = stats.to_summary()
summarized_lines = calculated_stats.to_string().split("\n")
latest_end_time = max(m.exec_stats.end_time_s for m in block_meta_list)
earliest_start_time = min(m.exec_stats.start_time_s for m in block_meta_list)
assert (
"Operator 0 Read: 2 tasks executed, 2 blocks produced in {}s".format(
max(round(latest_end_time - earliest_start_time, 2), 0)
)
== summarized_lines[0]
)
assert (
"* Remote wall time: {}s min, {}s max, {}s mean, {}s total".format(
min(block_params["wall_time"]),
max(block_params["wall_time"]),
np.mean(block_params["wall_time"]),
sum(block_params["wall_time"]),
)
== summarized_lines[1]
)
assert (
"* Remote cpu time: {}s min, {}s max, {}s mean, {}s total".format(
min(block_params["cpu_time"]),
max(block_params["cpu_time"]),
np.mean(block_params["cpu_time"]),
sum(block_params["cpu_time"]),
)
== summarized_lines[2]
)
assert (
"* UDF time: {}s min, {}s max, {}s mean, {}s total".format(
min(block_params["udf_time"]),
max(block_params["udf_time"]),
np.mean(block_params["udf_time"]),
sum(block_params["udf_time"]),
)
== summarized_lines[3]
)
assert (
"* Peak heap memory usage (MiB): {} min, {} max, {} mean".format(
min(block_params["max_rss_bytes"]) / (1024 * 1024),
max(block_params["max_rss_bytes"]) / (1024 * 1024),
int(np.mean(block_params["max_rss_bytes"]) / (1024 * 1024)),
)
== summarized_lines[4]
)
assert (
"* Output num rows per block: {} min, {} max, {} mean, {} total".format(
min(block_params["num_rows"]),
max(block_params["num_rows"]),
int(np.mean(block_params["num_rows"])),
sum(block_params["num_rows"]),
)
== summarized_lines[5]
)
assert (
"* Output size bytes per block: {} min, {} max, {} mean, {} total".format(
min(block_params["size_bytes"]),
max(block_params["size_bytes"]),
int(np.mean(block_params["size_bytes"])),
sum(block_params["size_bytes"]),
)
== summarized_lines[6]
)
assert (
"* Output rows per task: {} min, {} max, {} mean, {} tasks used".format(
min(block_params["num_rows"]),
max(block_params["num_rows"]),
int(np.mean(list(block_params["num_rows"]))),
len(set(block_params["task_idx"])),
)
== summarized_lines[7]
)
node_counts = Counter(block_params["node_id"])
assert (
"* Tasks per node: {} min, {} max, {} mean; {} nodes used".format(
min(node_counts.values()),
max(node_counts.values()),
int(np.mean(list(node_counts.values()))),
len(node_counts),
)
== summarized_lines[8]
)
def test_get_total_stats(ray_start_regular_shared, op_two_block):
"""Tests a set of similar getter methods which pull aggregated
statistics values after calculating operator-level stats:
`DatasetStats.get_total_wall_time()`,
`DatasetStats.get_total_cpu_time()`,
`DatasetStats.get_max_heap_memory()`."""
block_params, block_meta_list = op_two_block
stats = DatasetStats(
metadata={"Read": block_meta_list},
parent=None,
)
dataset_stats_summary = stats.to_summary()
op_stats = dataset_stats_summary.operators_stats[0]
# simple case with only one block / summary, result should match difference between
# the start and end time
assert (
dataset_stats_summary.get_total_wall_time()
== op_stats.latest_end_time - op_stats.earliest_start_time
)
# total time across all blocks is sum of wall times of blocks
assert dataset_stats_summary.get_total_time_all_blocks() == sum(
block_params["wall_time"]
)
cpu_time_stats = op_stats.cpu_time
assert dataset_stats_summary.get_total_cpu_time() == cpu_time_stats.get("sum")
peak_memory_stats = op_stats.memory
assert dataset_stats_summary.get_max_heap_memory() == peak_memory_stats.get("max")
@pytest.mark.skip(
reason="Temporarily disable to deflake rest of test suite. "
"See: https://github.com/ray-project/ray/pull/40173"
)
def test_streaming_stats_full(ray_start_regular_shared, restore_data_context):
ds = ray.data.range(5, override_num_blocks=5).map(column_udf("id", lambda x: x + 1))
ds.take_all()
stats = canonicalize(ds.stats())
assert (
stats
== f"""Operator N ReadRange->Map(<lambda>): {EXECUTION_STRING}
* Remote wall time: T min, T max, T mean, T total
* Remote cpu time: T min, T max, T mean, T total
* UDF time: T min, T max, T mean, T total
* Peak heap memory usage (MiB): N min, N max, N mean
* Output num rows per block: N min, N max, N mean, N total
* Output size bytes per block: N min, N max, N mean, N total
* Output rows per task: N min, N max, N mean, N tasks used
* Tasks per node: N min, N max, N mean; N nodes used
* Operator throughput:
* Ray Data throughput: N rows/s
* Estimated single node throughput: N rows/s
Dataset iterator time breakdown:
* Total time overall: T
* Total time in Ray Data iterator initialization code: T
* Total time user thread is blocked by Ray Data iter_batches: T
* Total execution time for user thread: T
* Batch iteration time breakdown (summed across prefetch threads):
* In ray.get(): T min, T max, T avg, T total
* In batch creation: T min, T max, T avg, T total
* In batch formatting: T min, T max, T avg, T total
Dataset throughput:
* Ray Data throughput: N rows/s
* Estimated single node throughput: N rows/s
"""
)
def test_write_ds_stats(ray_start_regular_shared, tmp_path):
ds = ray.data.range(100, override_num_blocks=100)
ds.write_parquet(str(tmp_path))
stats = ds.stats()
assert (
canonicalize(stats)
== f"""Operator N ReadRange->Write: {EXECUTION_STRING}
* Remote wall time: T min, T max, T mean, T total
* Remote cpu time: T min, T max, T mean, T total
* UDF time: T min, T max, T mean, T total
* Peak heap memory usage (MiB): N min, N max, N mean
* Output num rows per block: N min, N max, N mean, N total
* Output size bytes per block: N min, N max, N mean, N total
* Output rows per task: N min, N max, N mean, N tasks used
* Tasks per node: N min, N max, N mean; N nodes used
* Operator throughput:
* Ray Data throughput: N rows/s
* Estimated single node throughput: N rows/s
Dataset throughput:
* Ray Data throughput: N rows/s
* Estimated single node throughput: N rows/s
"""
)
assert stats == ds._write_ds.stats()
ds = (
ray.data.range(100, override_num_blocks=100)
.map_batches(lambda x: x)
.materialize()
)
ds.write_parquet(str(tmp_path))
stats = ds.stats()
assert (
canonicalize(stats)
== f"""Operator N ReadRange->MapBatches(<lambda>): {EXECUTION_STRING}
* Remote wall time: T min, T max, T mean, T total
* Remote cpu time: T min, T max, T mean, T total
* UDF time: T min, T max, T mean, T total
* Peak heap memory usage (MiB): N min, N max, N mean
* Output num rows per block: N min, N max, N mean, N total
* Output size bytes per block: N min, N max, N mean, N total
* Output rows per task: N min, N max, N mean, N tasks used
* Tasks per node: N min, N max, N mean; N nodes used
* Operator throughput:
* Ray Data throughput: N rows/s
* Estimated single node throughput: N rows/s
Operator N Write: {EXECUTION_STRING}
* Remote wall time: T min, T max, T mean, T total
* Remote cpu time: T min, T max, T mean, T total
* UDF time: T min, T max, T mean, T total
* Peak heap memory usage (MiB): N min, N max, N mean
* Output num rows per block: N min, N max, N mean, N total
* Output size bytes per block: N min, N max, N mean, N total
* Output rows per task: N min, N max, N mean, N tasks used
* Tasks per node: N min, N max, N mean; N nodes used
* Operator throughput:
* Ray Data throughput: N rows/s
* Estimated single node throughput: N rows/s
Dataset throughput:
* Ray Data throughput: N rows/s
* Estimated single node throughput: N rows/s
"""
)
assert stats == ds._write_ds.stats()
def test_time_backpressure(ray_start_regular_shared, restore_data_context):
class TimedBackpressurePolicy(BackpressurePolicy):
COUNT = 0
def __init__(self, topology: "Topology"):
pass
def can_add_input(self, op: "PhysicalOperator") -> bool:
if TimedBackpressurePolicy.COUNT > 1:
time.sleep(0.01)
return True
else:
TimedBackpressurePolicy.COUNT += 1
return False
context = DataContext.get_current()
context.verbose_stats_logs = True
context.set_config(
ENABLED_BACKPRESSURE_POLICIES_CONFIG_KEY, [TimedBackpressurePolicy]
)
def f(x):
time.sleep(0.01)
return x
ds = ray.data.range(10000).map_batches(f).materialize()
assert ds._plan.stats().extra_metrics["task_submission_backpressure_time"] > 0
def test_runtime_metrics(ray_start_regular_shared):
from math import isclose
def time_to_seconds(time_str):
if time_str.endswith("us"):
# Convert microseconds to seconds
return float(time_str[:-2]) / (1000 * 1000)
elif time_str.endswith("ms"):
# Convert milliseconds to seconds
return float(time_str[:-2]) / 1000
elif time_str.endswith("s"):
# Already in seconds, just remove the 's' and convert to float
return float(time_str[:-1])
f = dummy_map_batches_sleep(0.01)
ds = ray.data.range(100).map(f).materialize().map(f).materialize()
metrics_str = ds._plan.stats().runtime_metrics()
# Dictionary to store the metrics for testing
metrics_dict = {}
# Regular expression to match the pattern of each metric line
pattern = re.compile(r"\* (.+?): ([\d\.]+(?:ms|s)) \(([\d\.]+)%\)")
# Split the input string into lines and iterate over them
for line in metrics_str.split("\n"):
match = pattern.match(line)
if match:
# Extracting the operator name, time, and percentage
operator_name, time_str, percent_str = match.groups()
# Converting percentage to float and keeping time as string
metrics_dict[operator_name] = (
time_to_seconds(time_str),
float(percent_str),
)
total_time, total_percent = metrics_dict.pop("Total")
assert total_percent == 100
for time_s, percent in metrics_dict.values():
assert time_s < total_time
# Check percentage, this is done with some expected loss of precision
# due to rounding in the intital output.
assert isclose(percent, time_s / total_time * 100, rel_tol=0.01)
# NOTE: All tests above share a Ray cluster, while the tests below do not. These
# tests should only be carefully reordered to retain this invariant!
def test_dataset_throughput():
ray.shutdown()
ray.init(num_cpus=2)
f = dummy_map_batches_sleep(0.01)
ds = ray.data.range(100).map(f).materialize().map(f).materialize()
# Pattern to match operator throughput
operator_pattern = re.compile(
r"Operator (\d+).*?Ray Data throughput: (\d+\.\d+) rows/s.*?Estimated single node throughput: (\d+\.\d+) rows/s", # noqa: E501
re.DOTALL,
)
# Ray data throughput should always be better than single node throughput for
# multi-cpu case.
for match in operator_pattern.findall(ds.stats()):
assert float(match[1]) >= float(match[2])
# Pattern to match dataset throughput
dataset_pattern = re.compile(
r"Dataset throughput:.*?Ray Data throughput: (\d+\.\d+) rows/s.*?Estimated single node throughput: (\d+\.\d+) rows/s", # noqa: E501
re.DOTALL,
)
dataset_match = dataset_pattern.search(ds.stats())
assert float(dataset_match[1]) >= float(dataset_match[2])
def test_stats_actor_cap_num_stats(ray_start_cluster):
actor = _StatsActor.remote(3)
metadatas = []
task_idx = 0
for uuid in range(3):
metadatas.append(
BlockMetadata(
num_rows=uuid,
size_bytes=None,
schema=None,
input_files=None,
exec_stats=None,
)
)
num_stats = uuid + 1
actor.record_start.remote(uuid)
assert ray.get(actor._get_stats_dict_size.remote()) == (
num_stats,
num_stats - 1,
num_stats - 1,
)
actor.record_task.remote(uuid, task_idx, [metadatas[-1]])
assert ray.get(actor._get_stats_dict_size.remote()) == (
num_stats,
num_stats,
num_stats,
)
for uuid in range(3):
assert ray.get(actor.get.remote(uuid))[0][task_idx] == [metadatas[uuid]]
# Add the fourth stats to exceed the limit.
actor.record_start.remote(3)
# The first stats (with uuid=0) should have been purged.
assert ray.get(actor.get.remote(0))[0] == {}
# The start_time has 3 entries because we just added it above with record_start().
assert ray.get(actor._get_stats_dict_size.remote()) == (3, 2, 2)
@pytest.mark.parametrize("verbose_stats_logs", [True, False])
def test_spilled_stats(shutdown_only, verbose_stats_logs, restore_data_context):
context = DataContext.get_current()
context.verbose_stats_logs = verbose_stats_logs
context.enable_get_object_locations_for_metrics = True
# The object store is about 100MB.
ray.init(object_store_memory=100e6)
# The size of dataset is 1000*80*80*4*8B, about 200MB.
ds = ray.data.range(1000 * 80 * 80 * 4).map_batches(lambda x: x).materialize()
extra_metrics = gen_extra_metrics_str(
MEM_SPILLED_EXTRA_METRICS_TASK_BACKPRESSURE,
verbose_stats_logs,
)
expected_stats = (
f"Operator N ReadRange->MapBatches(<lambda>): {EXECUTION_STRING}\n"
f"* Remote wall time: T min, T max, T mean, T total\n"
f"* Remote cpu time: T min, T max, T mean, T total\n"
f"* UDF time: T min, T max, T mean, T total\n"
f"* Peak heap memory usage (MiB): N min, N max, N mean\n"
f"* Output num rows per block: N min, N max, N mean, N total\n"
f"* Output size bytes per block: N min, N max, N mean, N total\n"
f"* Output rows per task: N min, N max, N mean, N tasks used\n"
f"* Tasks per node: N min, N max, N mean; N nodes used\n"
f"* Operator throughput:\n"
f" * Ray Data throughput: N rows/s\n"
f" * Estimated single node throughput: N rows/s\n"
f"{extra_metrics}\n"
f"Cluster memory:\n"
f"* Spilled to disk: M\n"
f"* Restored from disk: M\n"
f"\n"
f"Dataset memory:\n"
f"* Spilled to disk: M\n"
f"\n"
f"Dataset throughput:\n"
f" * Ray Data throughput: N rows/s\n"
f" * Estimated single node throughput: N rows/s\n"
f"{gen_runtime_metrics_str(['ReadRange->MapBatches(<lambda>)'], verbose_stats_logs)}" # noqa: E501
)
assert canonicalize(ds.stats(), filter_global_stats=False) == expected_stats
# Around 100MB should be spilled (200MB - 100MB)
assert ds._plan.stats().dataset_bytes_spilled > 100e6
ds = (
ray.data.range(1000 * 80 * 80 * 4)
.map_batches(lambda x: x)
.materialize()
.map_batches(lambda x: x)
.materialize()
)
# two map_batches operators, twice the spillage
assert ds._plan.stats().dataset_bytes_spilled > 200e6
# The size of dataset is around 50MB, there should be no spillage
ds = (
ray.data.range(250 * 80 * 80 * 4, override_num_blocks=1)
.map_batches(lambda x: x)
.materialize()
)
assert ds._plan.stats().dataset_bytes_spilled == 0
def test_stats_actor_metrics():
ray.init(object_store_memory=100e6)
with patch_update_stats_actor() as update_fn:
ds = ray.data.range(1000 * 80 * 80 * 4).map_batches(lambda x: x).materialize()
# last emitted metrics from map operator
final_metric = update_fn.call_args_list[-1].args[1][-1]
assert final_metric.obj_store_mem_spilled == ds._plan.stats().dataset_bytes_spilled
assert (
final_metric.obj_store_mem_freed
== ds._plan.stats().extra_metrics["obj_store_mem_freed"]
)
assert (
final_metric.bytes_task_outputs_generated == 1000 * 80 * 80 * 4 * 8
) # 8B per int
assert final_metric.rows_task_outputs_generated == 1000 * 80 * 80 * 4
# There should be nothing in object store at the end of execution.
args = update_fn.call_args_list[-1].args
assert args[0] == f"dataset_{ds._uuid}"
assert args[2][0] == "Input0"
assert args[2][1] == "ReadRange->MapBatches(<lambda>)1"
def sleep_three(x):
import time
time.sleep(3)
return x
with patch_update_stats_actor() as update_fn:
ds = ray.data.range(3).map_batches(sleep_three, batch_size=1).materialize()
final_metric = update_fn.call_args_list[-1].args[1][-1]
assert final_metric.block_generation_time >= 9
def test_stats_actor_iter_metrics():
ds = ray.data.range(1e6).map_batches(lambda x: x)
with patch_update_stats_actor_iter() as update_fn:
ds.take_all()
ds_stats = ds._plan.stats()
final_stats = update_fn.call_args_list[-1].args[0]
assert final_stats == ds_stats
assert f"dataset_{ds._uuid}" == update_fn.call_args_list[-1].args[1]
def test_dataset_name():
ds = ray.data.range(100, override_num_blocks=20).map_batches(lambda x: x)
ds._set_name("test_ds")
assert ds._name == "test_ds"
assert str(ds) == (
"MapBatches(<lambda>)\n"
"+- Dataset(name=test_ds, num_rows=100, schema={id: int64})"
)
with patch_update_stats_actor() as update_fn:
mds = ds.materialize()
assert update_fn.call_args_list[-1].args[0] == f"test_ds_{mds._uuid}"
# Names persist after an execution
ds = ds.random_shuffle()
assert ds._name == "test_ds"
with patch_update_stats_actor() as update_fn:
mds = ds.materialize()
assert update_fn.call_args_list[-1].args[0] == f"test_ds_{mds._uuid}"
ds._set_name("test_ds_two")
ds = ds.map_batches(lambda x: x)
assert ds._name == "test_ds_two"
with patch_update_stats_actor() as update_fn:
mds = ds.materialize()
assert update_fn.call_args_list[-1].args[0] == f"test_ds_two_{mds._uuid}"
ds._set_name(None)
ds = ds.map_batches(lambda x: x)
assert ds._name is None
with patch_update_stats_actor() as update_fn:
mds = ds.materialize()
assert update_fn.call_args_list[-1].args[0] == f"dataset_{mds._uuid}"
ds = ray.data.range(100, override_num_blocks=20)
ds._set_name("very_loooooooong_name")
assert (
str(ds)
== "Dataset(name=very_loooooooong_name, num_rows=100, schema={id: int64})"
)
def test_op_metrics_logging():
logger = logging.getLogger("ray.data._internal.execution.streaming_executor")
with patch.object(logger, "debug") as mock_logger:
ray.data.range(100).map_batches(lambda x: x).materialize()
logs = [canonicalize(call.args[0]) for call in mock_logger.call_args_list]
input_str = (
"Operator InputDataBuffer[Input] completed. Operator Metrics:\n"
+ gen_expected_metrics(is_map=False)
) # .replace("'obj_store_mem_used': N", "'obj_store_mem_used': Z")
map_str = (
"Operator InputDataBuffer[Input] -> "
"TaskPoolMapOperator[ReadRange->MapBatches(<lambda>)] completed. "
"Operator Metrics:\n"
) + STANDARD_EXTRA_METRICS_TASK_BACKPRESSURE
# Check that these strings are logged exactly once.
assert sum([log == input_str for log in logs]) == 1, (logs, input_str)
assert sum([log == map_str for log in logs]) == 1, (logs, map_str)
def test_op_state_logging():
logger = logging.getLogger("ray.data._internal.execution.streaming_executor")
with patch.object(logger, "debug") as mock_logger:
ray.data.range(100).map_batches(lambda x: x).materialize()
logs = [canonicalize(call.args[0]) for call in mock_logger.call_args_list]
times_asserted = 0
for i, log in enumerate(logs):
if log == "Execution Progress:":
times_asserted += 1
assert "Input" in logs[i + 1]
assert "ReadRange->MapBatches(<lambda>)" in logs[i + 2]
assert times_asserted > 0
def test_stats_actor_datasets(ray_start_cluster):
ds = ray.data.range(100, override_num_blocks=20).map_batches(lambda x: x)
ds._set_name("test_stats_actor_datasets")
ds.materialize()
stats_actor = _get_or_create_stats_actor()
datasets = ray.get(stats_actor.get_datasets.remote())
dataset_name = list(filter(lambda x: x.startswith(ds._name), datasets))
assert len(dataset_name) == 1
dataset = datasets[dataset_name[0]]
assert dataset["state"] == "FINISHED"
assert dataset["progress"] == 20
assert dataset["total"] == 20
assert dataset["end_time"] is not None
operators = dataset["operators"]
assert len(operators) == 2
assert "Input0" in operators
assert "ReadRange->MapBatches(<lambda>)1" in operators
for value in operators.values():
assert value["progress"] == 20
assert value["total"] == 20
assert value["state"] == "FINISHED"
@patch.object(StatsManager, "STATS_ACTOR_UPDATE_INTERVAL_SECONDS", new=0.5)
@patch.object(StatsManager, "_stats_actor_handle")
@patch.object(StatsManager, "UPDATE_THREAD_INACTIVITY_LIMIT", new=1)
def test_stats_manager(shutdown_only):
ray.init()
num_threads = 10
datasets = [None] * num_threads
# Mock clear methods so that _last_execution_stats and _last_iteration_stats
# are not cleared. We will assert on them afterwards.
with patch.object(StatsManager, "clear_execution_metrics"), patch.object(
StatsManager, "clear_iteration_metrics"
):
def update_stats_manager(i):
datasets[i] = ray.data.range(10).map_batches(lambda x: x)
for _ in datasets[i].iter_batches(batch_size=1):
pass
threads = [
threading.Thread(target=update_stats_manager, args=(i,), daemon=True)
for i in range(num_threads)
]
for thread in threads:
thread.start()
for thread in threads:
thread.join()
assert len(StatsManager._last_execution_stats) == num_threads
assert len(StatsManager._last_iteration_stats) == num_threads
# Clear dataset tags manually.
for dataset in datasets:
dataset_tag = create_dataset_tag(dataset._name, dataset._uuid)
assert dataset_tag in StatsManager._last_execution_stats
assert dataset_tag in StatsManager._last_iteration_stats
StatsManager.clear_execution_metrics(
dataset_tag, ["Input0", "ReadRange->MapBatches(<lambda>)1"]
)
StatsManager.clear_iteration_metrics(dataset_tag)
wait_for_condition(lambda: not StatsManager._update_thread.is_alive())
prev_thread = StatsManager._update_thread
ray.data.range(100).map_batches(lambda x: x).materialize()
# Check that a new different thread is spawned.
assert StatsManager._update_thread != prev_thread
wait_for_condition(lambda: not StatsManager._update_thread.is_alive())
if __name__ == "__main__":
import sys
sys.exit(pytest.main(["-vv", __file__])) |
import 'package:flutter/material.dart';
import 'package:scroll_problem/top.dart';
class HomePage extends StatefulWidget {
const HomePage({Key? key}) : super(key: key);
@override
State<HomePage> createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
@override
Widget build(BuildContext context) {
return DefaultTabController(
length: 3,
child: Scaffold(
appBar: AppBar(
title: Text('No Problem'),
bottom: const TabBar(
tabs: [
Tab(icon: Icon(Icons.contacts), text: "Tab 1"),
Tab(icon: Icon(Icons.camera_alt), text: "Tab 2"),
Tab(icon: Icon(Icons.camera_front), text: "Tab 3"),
],
),
),
body: SingleChildScrollView(
child: SizedBox(
height: MediaQuery.of(context).size.height,
child: TabBarView(
children: [
Column(
children: [
Container(
height: 100,
color: Colors.redAccent,
child: const Center(
child: Text('First tab content with 100 height'),
),
),
const SizedBox(
height: 200,
child: Center(
child: Text('Second tab content with 200 height'),
),
),
for (int i = 0; i < 1; i++) ...{TopWidget()},
],
),
Column(
children: [
Container(
height: 100,
color: Colors.redAccent,
child: const Center(
child: Text('First tab content with 100 height'),
),
),
const SizedBox(
height: 200,
child: Center(
child: Text('Second tab content with 200 height'),
),
),
for (int i = 0; i < 1; i++) ...{TopWidget()},
],
),
Column(
children: [
Container(
height: 100,
color: Colors.redAccent,
child: const Center(
child: Text('First tab content with 100 height'),
),
),
const SizedBox(
height: 200,
child: Center(
child: Text('Second tab content with 200 height'),
),
),
for (int i = 0; i < 1; i++) ...{TopWidget()},
],
),
],
),
),
),
),
);
}
} |
import 'package:flutter/material.dart';
import '../palatte.dart';
class TextInputInverse extends StatelessWidget {
const TextInputInverse({
Key? key,
required this.icon,
required this.hint,
required this.inputType,
required this.inputAction,
}) : super(key: key);
final IconData icon;
final String hint;
final TextInputType inputType;
final TextInputAction inputAction;
@override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.symmetric(
vertical: 12.0), // creates space between text boxes
child: Container(
decoration: BoxDecoration(
color: (Color.fromRGBO(146, 61, 65, 1)), // sets email icon color
borderRadius: BorderRadius.circular(16),
),
child: TextField(
decoration: InputDecoration(
contentPadding: const EdgeInsets.symmetric(vertical: 20),
border: InputBorder.none,
hintText: hint, // default text for email input
prefixIcon: Padding(
padding: const EdgeInsets.symmetric(horizontal: 20.0),
child: Icon(icon, //specifies icon
color: Colors.white,
size: 30),
),
hintStyle: inputText,
),
style: inputText,
keyboardType: inputType, //email vs password
textInputAction: inputAction, // action button
),
),
);
}
} |
# Markdown examples
## code blocks
=== "python"
```python
# Hello world example (Python)
print("Hello World!")
zero_to_ten_double = [2*x for x in range(10)]
```
=== "shell"
```shell
# Hello world example (Python)
print("Hello World!")
zero_to_ten_double = [2*x for x in range(10)]
```
## code blocks with title
```python title="hello-world.py"
# Hello world example (Python)
print("Hello World!")
zero_to_ten_double = [2*x for x in range(10)]
```
## code blocks with linenumbers
```python linenums="1"
# Hello world example (Python)
print("Hello World!")
zero_to_ten_double = [2*x for x in range(10)]
```
## emojis
:flag_be: :heart: :beer:
:beer: :beers: :beer: :arrow_right: :nauseated_face:
## add Notes
!!! Note
This is a note
!!! Danger
This is a Danger
!!! Warning
This is a warning
!!! Example
This is an Example |
import { BrowserModule } from '@angular/platform-browser';
import { ErrorHandler, NgModule } from '@angular/core';
import { IonicApp, IonicErrorHandler, IonicModule } from 'ionic-angular';
import { SplashScreen } from '@ionic-native/splash-screen';
import { StatusBar } from '@ionic-native/status-bar';
import { AngularFireModule } from 'angularfire2';
import { AngularFireDatabaseModule } from 'angularfire2/database';
import { AngularFireAuthModule } from 'angularfire2/auth';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';
import { MyApp } from './app.component';
import { HomePage } from '../pages/home/home';
import { AutenticarProvider } from '../providers/autenticar/autenticar';
import { FirebasemoradiaProvider } from '../providers/firebasemoradia/firebasemoradia';
import { CepProvider } from '../providers/cep/cep';
import { BuscarTodosProvider } from '../providers/buscar-todos/buscar-todos';
export const firebaseConfig = {
apiKey: "AIzaSyCg_sOPp4_wVpOFURldKtPhP-89j104iNw",
authDomain: "pwaalugaqui.firebaseapp.com",
databaseURL: "https://pwaalugaqui.firebaseio.com",
projectId: "pwaalugaqui",
storageBucket: "pwaalugaqui.appspot.com",
messagingSenderId: "569252443849"
};
@NgModule({
declarations: [
MyApp,
HomePage
],
imports: [
BrowserModule,
IonicModule.forRoot(MyApp),
AngularFireModule.initializeApp(firebaseConfig),
AngularFireDatabaseModule,
AngularFireAuthModule,
FormsModule,
HttpModule
],
bootstrap: [IonicApp],
entryComponents: [
MyApp,
HomePage
],
providers: [
StatusBar,
SplashScreen,
{provide: ErrorHandler, useClass: IonicErrorHandler},
AutenticarProvider,
FirebasemoradiaProvider,
CepProvider,
BuscarTodosProvider
]
})
export class AppModule {} |
import React, { useRef, useState } from "react";
import default_avatar from "../static/default_avatar.png";
import styled from "styled-components";
import { largeMobile, mobile } from "../utils/responsive";
import { useDispatch, useSelector } from "react-redux";
import { individualUpload } from "../utils/fileUpload";
import { axiosBaseURL } from "../utils/axiosBaseURL";
import { updateUser } from "../redux/userSlice";
const Container = styled.div`
width: 100%;
display: flex;
align-items: center;
justify-content: flex-start;
flex: 1;
${largeMobile({
justifyContent: "center",
})}
${mobile({
justifyContent: "center",
})}
`;
const InformationWrapper = styled.div`
width: 90%;
max-width: 500px;
padding: 20px 0px;
height: max-content;
display: flex;
align-items: center;
flex-direction: column;
justify-content: center;
border: 1px solid lightgray;
${largeMobile({
maxWidth: "300px",
})}
${mobile({
maxWidth: "250px",
})}
`;
const ImageContainer = styled.div`
width: 80%;
aspect-ratio: 1/1;
overflow: hidden;
display: flex;
align-items: center;
justify-content: center;
`;
const Img = styled.img`
height: 90%;
width: 90%;
border-radius: 100%;
border: 1px solid gray;
object-fit: cover;
`;
const ImageOption = styled.button`
margin-top: 10px;
font-family: "Roboto", sans-serif;
font-size: 16px;
width: 150px;
padding: 10px 0px;
cursor: pointer;
color: white;
border: none;
border-radius: 5px;
background-color: ${(props) =>
props.type === "upload" ? "#0ead69" : "black"};
:hover {
opacity: 0.5;
transition: 0.5 all;
}
:disabled {
cursor: not-allowed;
}
`;
const ImageUplaoding = styled.p`
padding-top: 10px;
font-family: "Bree Serif", serif;
`;
const Input = styled.input`
margin-top: 4px;
outline: ${(props) => (props.enableEdit === true ? "" : "none")};
border: ${(props) =>
props.enableEdit === true ? "0.5px solid #d3d3d3" : "none"};
background-color: white;
font-family: "Josefin Sans", sans-serif;
font-size: 1rem;
padding: 2px;
width: 100%;
::placeholder {
font-size: 1rem;
font-family: "Josefin Sans", sans-serif;
}
`;
const ProfileAvatar = ({ profileImage, setProfileImage }) => {
/* Get the Logged-In user from Redux State */
const user = useSelector((store) => store.user.currentUser);
/* upload icon ref: */
const hiddenFileInput = useRef();
/* upload icon ref controller */
const handleClick = (event) => {
hiddenFileInput.current.click();
};
const dispatch = useDispatch();
/* State to Make buttons diabled while Profile photo is uploading. */
const [uploading, setUploading] = useState(false);
/* uploading profile photo: */
const uploadProfilePhoto = async (file) => {
setUploading(true);
/* upload the avatar to the cloudinary: */
const avatar = await individualUpload(file);
/* upload the avatar url to the Mongodb Database: */
const updatedInfo = await axiosBaseURL.post(
`user/updateInfo/${user._id}`,
{ avatar: avatar.url },
{ withCredentials: true }
);
/* Display Avatar to user: */
setProfileImage(avatar.url);
/* update the Global Redux State: */
dispatch(updateUser(updatedInfo.data));
setUploading(false);
};
/* Remove profile photo: */
const removeProfilePhoto = async () => {
setUploading(true);
/* upload the avatar url to the Mongodb Database: */
const updatedInfo = await axiosBaseURL.post(
`user/updateInfo/${user._id}`,
{ avatar: "default_avatar" },
{ withCredentials: true }
);
/* update the Global Redux State: */
dispatch(updateUser(updatedInfo.data));
/* Display Avatar to user: */
setProfileImage("default_avatar");
setUploading(false);
};
/* profile photo trigger function */
const handleAvatarInput = (event) => {
const fileUploaded = event.target.files[0];
uploadProfilePhoto(fileUploaded);
};
return (
<Container>
<InformationWrapper>
<ImageContainer>
<Img
src={
profileImage === "default_avatar" ? default_avatar : profileImage
}
/>
</ImageContainer>
<ImageOption onClick={handleClick} type="upload" disabled={uploading}>
upload
</ImageOption>
<ImageOption
onClick={removeProfilePhoto}
type="remove"
disabled={uploading}>
Remove
</ImageOption>
{uploading && (
<ImageUplaoding>uploading! Please Wait...</ImageUplaoding>
)}
<Input
type="file"
ref={hiddenFileInput}
onChange={handleAvatarInput}
style={{ display: "none" }}
/>
</InformationWrapper>
</Container>
);
};
export default ProfileAvatar; |
import {
Chart as ChartJS,
CategoryScale,
LinearScale,
PointElement,
LineElement,
Tooltip,
Legend,
} from "chart.js";
import { Line } from "react-chartjs-2";
import { WidgetWrapper } from "../WidgetWrapper";
import { FC } from "react";
import { PropsWithClassName } from "@/shared/types";
import cn from "clsx";
import styles from "./styles.module.scss";
import { InfoBlock } from "./ui/InfoBlock";
ChartJS.register(
CategoryScale,
LinearScale,
PointElement,
LineElement,
Tooltip,
Legend
);
export const Interest: FC<PropsWithClassName> = ({ className }) => {
const options: any = {
responsive: true,
maintainAspectRatio: false,
plugins: {
legend: {
display: false,
},
},
elements: {
point: {
radius: 0,
},
line: {
tension: 0.2,
},
},
scales: {
y: {
ticks: {
callback: function (value: any) {
return value + "%";
},
stepSize: 20, // Use stepSize to control the interval between ticks
max: 100,
min: 20,
},
border: {
display: false,
},
},
x: {
grid: {
display: false,
},
border: {
display: false,
},
},
},
};
const labels = ["Январь", "Февраль", "Март", "Апрель", "Май"];
const data = {
labels,
datasets: [
{
data: [0, 20, 40, 30, 100],
borderColor: "#0064FA",
borderWidth: 0.5,
},
],
};
return (
<WidgetWrapper className={cn(className)} title="Заинтересованность">
<div className={styles.wrapper}>
<div className={styles.graph}>
<Line options={options} data={data} />
</div>
<div className={styles.info}>
<div className={styles.list}>
<InfoBlock />
<InfoBlock />
<InfoBlock />
<InfoBlock />
</div>
</div>
</div>
</WidgetWrapper>
);
}; |
<template>
<div>
<h2 id="page-heading">
<span v-text="$t('cstoneApp.person.home.title')" id="person-heading">People</span>
<router-link :to="{name: 'PersonCreate'}" tag="button" id="jh-create-entity" class="btn btn-primary float-right jh-create-entity create-person">
<font-awesome-icon icon="plus"></font-awesome-icon>
<span v-text="$t('cstoneApp.person.home.createLabel')">
Create a new Person
</span>
</router-link>
</h2>
<b-alert :show="dismissCountDown"
dismissible
:variant="alertType"
@dismissed="dismissCountDown=0"
@dismiss-count-down="countDownChanged">
{{alertMessage}}
</b-alert>
<br/>
<div class="alert alert-warning" v-if="!isFetching && people && people.length === 0">
<span v-text="$t('cstoneApp.person.home.notFound')">No people found</span>
</div>
<div class="table-responsive" v-if="people && people.length > 0">
<table class="table table-striped">
<thead>
<tr>
<th><span v-text="$t('global.field.id')">ID</span></th>
<th><span v-text="$t('cstoneApp.person.firstName')">First Name</span></th>
<th><span v-text="$t('cstoneApp.person.lastName')">Last Name</span></th>
<th><span v-text="$t('cstoneApp.person.email')">Email</span></th>
<th><span v-text="$t('cstoneApp.person.phone')">Phone</span></th>
<th></th>
</tr>
</thead>
<tbody>
<tr v-for="person in people"
:key="person.id">
<td>
<router-link :to="{name: 'PersonView', params: {personId: person.id}}">{{person.id}}</router-link>
</td>
<td>{{person.firstName}}</td>
<td>{{person.lastName}}</td>
<td>{{person.email}}</td>
<td>{{person.phone}}</td>
<td class="text-right">
<div class="btn-group">
<router-link :to="{name: 'PersonView', params: {personId: person.id}}" tag="button" class="btn btn-info btn-sm details">
<font-awesome-icon icon="eye"></font-awesome-icon>
<span class="d-none d-md-inline" v-text="$t('entity.action.view')">View</span>
</router-link>
<router-link :to="{name: 'PersonEdit', params: {personId: person.id}}" tag="button" class="btn btn-primary btn-sm edit">
<font-awesome-icon icon="pencil-alt"></font-awesome-icon>
<span class="d-none d-md-inline" v-text="$t('entity.action.edit')">Edit</span>
</router-link>
<b-button v-on:click="prepareRemove(person)"
variant="danger"
class="btn btn-sm"
v-b-modal.removeEntity>
<font-awesome-icon icon="times"></font-awesome-icon>
<span class="d-none d-md-inline" v-text="$t('entity.action.delete')">Delete</span>
</b-button>
</div>
</td>
</tr>
</tbody>
</table>
</div>
<b-modal ref="removeEntity" id="removeEntity" >
<span slot="modal-title"><span id="cstoneApp.person.delete.question" v-text="$t('entity.delete.title')">Confirm delete operation</span></span>
<div class="modal-body">
<p id="jhi-delete-person-heading" v-text="$t('cstoneApp.person.delete.question', {'id': removeId})">Are you sure you want to delete this Person?</p>
</div>
<div slot="modal-footer">
<button type="button" class="btn btn-secondary" v-text="$t('entity.action.cancel')" v-on:click="closeDialog()">Cancel</button>
<button type="button" class="btn btn-primary" id="jhi-confirm-delete-person" v-text="$t('entity.action.delete')" v-on:click="removePerson()">Delete</button>
</div>
</b-modal>
</div>
</template>
<script lang="ts" src="./person.component.ts">
</script> |
//
// CoinRepository.swift
// ToughCookie
//
// Created by 이중엽 on 5/21/24.
//
import Foundation
import UIKit.UIColor
class CoinRepository {
static let shared = CoinRepository()
private init() { }
var marketData: [MarketData] = []
var tickerDict: [String: TickerPresentData] = [:]
var searchFilter: String?
var languageType: CoinLanguageType = .korean
var sortedType: CoinSortedType = .nothing
func updateTickerDict(_ data: TickerPresentData) {
if data.accTradePrice24H < 1000000 { return }
guard let oldData = tickerDict[data.code] else {
tickerDict[data.code] = data
return
}
var newData = data
if oldData.tradePrice > newData.tradePrice {
newData.updateTradePriceSign = .fall
} else if oldData.tradePrice < newData.tradePrice {
newData.updateTradePriceSign = .rise
}
tickerDict[data.code] = newData
}
func sortedTickerList() -> [TickerPresentData] {
var values: [TickerPresentData] = tickerDict.values.compactMap { $0 }
if let searchFilter {
values = values.filter { data in
let marketData = getMarketDatumByTickerPresentData(data)
let code = data.code.uppercased().contains(searchFilter.uppercased())
let koreanName = marketData.koreanName.uppercased().contains(searchFilter.uppercased())
let englishName = marketData.englishName.uppercased().contains(searchFilter.uppercased())
return code || koreanName || englishName
}
}
switch sortedType {
case .nothing:
return values.sorted { $0.accTradePrice24H > $1.accTradePrice24H }.compactMap { $0 }
case .tradePriceASC:
return values.sorted { $0.tradePrice < $1.tradePrice }.compactMap { $0 }
case .tradePriceDESC:
return values.sorted { $0.tradePrice > $1.tradePrice }.compactMap { $0 }
case .changeASC:
return values.sorted { $0.changeRate < $1.changeRate }.compactMap { $0 }
case .changeDESC:
return values.sorted { $0.changeRate > $1.changeRate }.compactMap { $0 }
case .accTradePriceASC:
return values.sorted { $0.accTradePrice24H < $1.accTradePrice24H }.compactMap { $0 }
case .accTradePriceDESC:
return values.sorted { $0.accTradePrice24H > $1.accTradePrice24H }.compactMap { $0 }
default:
return values.sorted { $0.accTradePrice24H > $1.accTradePrice24H }.compactMap { $0 }
}
}
func getMarketDatumByTickerPresentData(_ data: TickerPresentData) -> MarketData {
guard let marketDatum = self.marketData.filter({ $0.market == data.code }).first else { return MarketData(market: "", koreanName: "", englishName: "")}
return marketDatum
}
}
enum CoinLanguageType {
case korean
case english
}
enum CoinSortedType {
case nothing
case tradePrice
case tradePriceASC
case tradePriceDESC
case change
case changeASC
case changeDESC
case accTradePrice
case accTradePriceASC
case accTradePriceDESC
var title: String {
switch self {
case .tradePrice, .tradePriceASC, .tradePriceDESC:
return "현재가"
case .change, .changeASC, .changeDESC:
return "전일대비"
case .accTradePrice, .accTradePriceASC , .accTradePriceDESC:
return "누적대금"
case .nothing:
return ""
}
}
var imageName: String {
switch self {
case .tradePrice, .tradePriceASC, .change, .changeASC, .accTradePrice, .accTradePriceASC:
return "arrow.up"
case .accTradePriceDESC, .changeDESC, .tradePriceDESC:
return "arrow.down"
case .nothing:
return ""
}
}
var color: UIColor {
switch self {
case .nothing, .accTradePrice ,.change ,.tradePrice:
return UIColor.black
default:
return UIColor.systemYellow
}
}
} |
quodlibet
--------------------------------
audio library manager and player
--------------------------------
:Manual section: 1
SYNOPSIS
========
| **quodlibet** [ **--print-playing** | *control* ]
| **exfalso** [ *directory* ]
DESCRIPTION
Quod Libet is a music management program. It provides several different
ways to view your audio library, as well as support for Internet radio and
audio feeds. It has extremely flexible metadata tag editing and searching
capabilities.
This manual page is only a short reference for Quod Libet. Complete
documentation is available at http://code.google.com/p/quodlibet/wiki/Guide.
OPTIONS
=======
--enqueue filename|query
Enqueue a filename or query results
--filter tag=value
Filter on a tag value
--focus
Focus the running player
--hide-window
Hide main window
--next
Jump to next song
--list-browsers
List available browsers
--open-browser=BrowserName
Open a new browser
--order=inorder|shuffle|weighted|onesong|toggle
Set or toggle the playback order
--pause
Pause playback
--play
Start playback
--play-file=filename
Play a file
--play-pause
Toggle play/pause mode
--previous
Jump to previous song or restart if near the beginning
--force-previous
Jump to previous song
--print-playlist
Print the current playlist
--print-queue
Print the contents of the queue
--print-playing
Print out information about the currently playing song. You may
provide in a string like the kind described in the RENAMING FILES
section below.
--query=search-string
Search your audio library
--quit
Exit Quod Libet
--random=tag
Filter on a random value
--repeat=off|on|t
Turn repeat off, on, or toggle
--seek=[+|-][HH:]MM:SS
Seek within the playing song
--set-browser=BrowserName
Set the current browser
--set-rating=0.0..1.0
Rate the playing song
--show-window
Hide main window
--start-playing
Begin playing immediately
--status
Print playing status
--toggle-window
Toggle main window visibility
--unfilter
Remove active browser filters
--unqueue=filename|query
Unqueue a file or query
--volume=(+\|-\|)0..100
Set the volume
ALBUM COVERS
Album covers should be put in the same directory as the songs they apply
to, and have "folder", "front", or "cover" in their filenames. If you want
to store multiple albums in the same directory but keep distinct cover
images, the name of the appropriate image file must contain the labelid tag
value, e.g. COCX-32760 cover.jpg.
TIED TAGS
=========
Many places in Quod Libet allow you to use "tied tags". Tied tags are two
tag names joined together with a "~" like "title~version" or "album~part".
Tied tags result in "nice" displays even when one of the tags is missing;
for example, "title~version" will result in Title - Version when a version
tag is present, but only Title when one isn't. You can tie any number of
tags together.
SEARCH SYNTAX
All of Quod Libet's search boxes support advanced searches of the
following forms:
\
| tag = value
| tag = !value
| tag = "value"
| tag = /value/
| tag = &(value1, value2)
| tag = \|(value1, value2)
| !tag = value
| \|(tag1 = value1, tag2 = value2)
| &(tag1 = value1, tag2 = value2)
| #(numerictag < value)
| #(numerictag = value)
| #(numerictag > value)
\
The 'c' postfix on strings or regular expressions makes the search
case-sensitive. Numeric values may be given as integers, floating-point
numbers, MM:SS format, or simple English, e.g. "3 days", "2 hours".
See http://code.google.com/p/quodlibet/wiki/Guide_Searching.
All internal tags begin with a ~ character. Non-numeric internal tags are
~base‐ name, ~dirname, ~filename, ~format, ~length, ~people, and ~rating.
Numeric internal tags are ~#added, ~#bitrate, ~#disc, ~#lastplayed,
~#laststarted, ~#length, ~#mtime, ~#playcount, ~#skipcount, and ~#track.
See http://code.google.com/p/quodlibet/wiki/Guide_InternalTags.
RENAMING FILES
Quod Libet allows you to rename files based on their tags. In some cases
you may wish to alter the filename depending on whether some tags are
present or missing, in addition to their values. A common pattern might be
``<tracknumber>. <title~version>``
You can use a '|' to only text when a tag is present:
``<tracknumber|<tracknumber>. ><title~version>``
You can also specify literal text to use if the tag is missing by adding another '|':
``<album|<album>|No Album> - <title>``
See http://code.google.com/p/quodlibet/wiki/Guide_Renaming.
AUDIO BACKENDS
Quod Libet uses GStreamer for audio playback. It tries to read your GConf
GStreamer configuration, but if that fails it falls back to osssink. You can
change the pipeline option in ~/.quodlibet/config to use a different sink, or
pass options to the sink. For example, you might use esdsink or alsasink
device=hw:1.
See http://code.google.com/p/quodlibet/wiki/Guide_AudioBackends.
FILES
=====
~/.quodlibet/songs
A pickled Python dict of cached metadata. Deleting this file will remove all
songs from your library.
~/.quodlibet/config
Quod Libet's configuration file. This file is overwritten when Quod Libet
exits.
~/.quodlibet/current
A "key=value" file containing information about the currently playing song.
~/.quodlibet/control
A FIFO connected to the most-recently-started instance of the program.
--next, --previous, etc., use this to control the player.
~/.quodlibet/plugins/
Put plugins (from http://code.google.com/p/quodlibet/wiki/Guide_Plugins)
here.
~/.quodlibet/browsers/
Put custom library browsers here.
See http://code.google.com/p/quodlibet/wiki/Guide_Extending.
BUGS
====
See http://code.google.com/p/quodlibet/issues/list for a list of all
currently open bugs and feature requests.
AUTHORS
=======
Joe Wreschnig and Michael Urman are the primary authors of Quod Libet.
SEE ALSO
========
| http://code.google.com/p/quodlibet/wiki/Guide,
| http://code.google.com/p/quodlibet/wiki/FAQ,
| ``regex``\(7), ``gst-launch``\(1) |
package com;
public class Testlambda {
//3.静态内部类
static class Like2 implements I{
@Override
public void lambda() {
System.out.println("I like lambda2");
}
}
public static void main(String[] args) {
I i = new Like();
i.lambda();
i = new Like2();
i.lambda();
//4.局部内部类
class Like3 implements I{
@Override
public void lambda() {
System.out.println("I like lambda3");
}
}
i = new Like3();
i.lambda();
//5.匿名内部类
i = new I(){
@Override
public void lambda() {
System.out.println("I like lambda4");
}
};
i.lambda();
//6.lambda简化
i = () -> {
System.out.println("I like lambda5");
};
i.lambda();
}
}
//1.定义一个函数式接口
interface I{
void lambda();
}
//2.实现类
class Like implements I{
@Override
public void lambda() {
System.out.println("I like lambda");
}
} |
"use client"
import useOtherUser from '@/app/hooks/useOtherUser';
import {Conversation, User} from '@prisma/client';
import { useMemo } from 'react';
import { HiChevronLeft } from 'react-icons/hi';
import Link from 'next/link';
import Avatar from '@/app/components/Avatar';
import { HiEllipsisHorizontal } from 'react-icons/hi2';
interface HeaderProps {
conversation: Conversation & {
users: User[]
}
}
const Header: React.FC<HeaderProps> = ({
conversation
}) => {
const otherUser = useOtherUser(conversation);
const statusText = useMemo(() => {
if(conversation.isGroup) {
return `${conversation.users.length} members`;
}
return 'Active';
}, [conversation]);
return (
<div className='bg-white w-full flex border-b-[1px] sm:px-4 py-3 px-4 lg:px-6 justify-between items-center shadow-sm'>
<div className='flex gap-3 items-center'>
<Link className='lg:hidden block text-sky-500 hover:text-sky-600 transition cursor-pointer' href='/conversations'>
<HiChevronLeft size={32}/>
</Link>
<Avatar user={otherUser}/>
<div className='flex flex-col'>
<div> {conversation.name || otherUser.name} </div>
<div className='text-sm font-light text-neutral-500'>{statusText}</div>
</div>
</div>
<HiEllipsisHorizontal size={32} onClick={()=> {}} className='text-sky-500 cursor-pointer hover:text-sky-600 transition'/>
</div>
)
}
export default Header; |
package com.angelina.dreamtracker.model;
import com.angelina.dreamtracker.model.enums.Role;
import jakarta.persistence.*;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import java.util.Collection;
import java.util.List;
import java.util.UUID;
@Entity
@Table(name = "users")
@Data
@AllArgsConstructor
@NoArgsConstructor
@Builder
public class User implements UserDetails {
@Id
@GeneratedValue(strategy = GenerationType.UUID)
@Column(name = "id")
private UUID id;
private String nickname;
private String email;
private String password;
@Enumerated(EnumType.STRING)
private Role role;
@OneToMany(mappedBy = "user")
private List<Dream> dreams;
@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
return List.of(new SimpleGrantedAuthority(role.name()));
}
@Override
public String getPassword() {
return password;
}
@Override
public String getUsername() {
return email;
}
@Override
public boolean isAccountNonExpired() {
return true;
}
@Override
public boolean isAccountNonLocked() {
return true;
}
@Override
public boolean isCredentialsNonExpired() {
return true;
}
@Override
public boolean isEnabled() {
return true;
}
} |
import { ChevronLeftIcon } from "@chakra-ui/icons";
import { Logo } from "./Logo";
import { Button, FormControl, FormLabel, Input, Text } from "@chakra-ui/react";
import { useForm } from "react-hook-form";
import { useState } from "react";
import { InfoErrorInput } from "./InfoErrorInput";
import { AiFillEye, AiFillEyeInvisible } from "react-icons/ai";
import SignUpStep2 from "./PageSignUpStep2";
import SignUp from "./PageSignUp";
import { useDispatch, useSelector } from "react-redux";
import { setPassword } from "../features/signUp/signUpSlice";
export default function SignUpStep1() {
const dispatch = useDispatch();
const {
handleSubmit,
register,
formState: { errors, isSubmitting },
} = useForm();
const password = useSelector((state) => state.signUp.password);
const [isShowPassword, setIsShowPassword] = useState(false);
const [inputPassword, setInputPassword] = useState(password);
const [isContinue, setIsContinue] = useState(false);
const [clickBack, setClickBack] = useState(false);
function containsDigit(inputString) {
for (var i = 0; i < inputString.length; i++) {
// Kiểm tra xem ký tự hiện tại có phải là chữ số không
if (!isNaN(parseInt(inputString[i]))) {
return true; // Nếu là chữ số, trả về true
}
}
return false; // Nếu không có chữ số nào, trả về false
}
function containsSpecialCharacter(inputString) {
var specialChars = `!@#$%^&*()_+-=[]{};':\\"\\|,.<>/?`;
for (var i = 0; i < inputString.length; i++) {
// Kiểm tra xem ký tự hiện tại có nằm trong danh sách ký tự đặc biệt không
if (specialChars.includes(inputString[i])) {
return true; // Nếu có ký tự đặc biệt, trả về true
}
}
return false; // Nếu không có ký tự đặc biệt nào, trả về false
}
const lengthLower8 = inputPassword.length < 8;
const isInvalidPassword =
!containsDigit(inputPassword) || !containsSpecialCharacter(inputPassword);
const togglePassword = (e) => {
setIsShowPassword(!isShowPassword);
};
const handleInputPasswordChange = (e) => {
setInputPassword(e.target.value);
};
const store = (password) => dispatch(setPassword(password));
function onSubmit(values) {
if (!lengthLower8 && !isInvalidPassword) {
store(values.password);
setIsContinue(true);
}
}
function clickBackFunc() {
setClickBack(true);
}
if (clickBack) {
return <SignUp />;
}
if (isContinue) return <SignUpStep2 />;
return (
<>
<Logo />
<div className="w-[450px] h-[600px] mx-auto">
<div class="h-1 relative max-w-xl rounded-full overflow-hidden">
<div class="w-full h-full bg-gray-200 absolute"></div>
<div class="h-full bg-[#1ED760] absolute w-1/3"></div>
</div>
<div className="mt-6 mb-6 flex">
<ChevronLeftIcon
boxSize={10}
color="#a7a7a7"
className="mt-2 hover:text-white cursor-pointer"
onClick={clickBackFunc}
/>
<div className="ms-3">
<Text className="text-[#a7a7a7] font-bold">Step 1 of 3</Text>
<Text className="text-white font-bold mt-1">Create a password</Text>
</div>
</div>
<form onSubmit={handleSubmit(onSubmit)}>
<FormControl
isInvalid={isInvalidPassword || lengthLower8}
className="px-[50px]"
>
<FormLabel className={"text-white mt-[10px] font-[500]"}>
Password
</FormLabel>
<Input
id="password"
type={isShowPassword ? "text" : "password"}
className={
"w-full mt-[5px] bg-[rgb(20, 20, 20)] text-white border-[#aaaaaa]"
}
placeholder="Password"
h="50px"
value={inputPassword}
name={register("password").name}
onBlur={register("password").onBlur}
ref={register("password").ref}
onChange={handleInputPasswordChange}
/>
{isShowPassword ? (
<AiFillEye
className={
"absolute text-[25px] text-[#dddddd] right-[65px] top-[50px] z-[999]"
}
onClick={togglePassword}
/>
) : (
<AiFillEyeInvisible
className={
"absolute text-[25px] text-[#dddddd] right-[65px] top-[50px] z-[999]"
}
onClick={togglePassword}
/>
)}
{lengthLower8 ? (
<InfoErrorInput message="Password should contain at least 8 characters." />
) : isInvalidPassword ? (
<InfoErrorInput message="Your password is too weak. Set a stronger one." />
) : (
""
)}
<Text className="mt-4 text-[#a7a7a7] fold-bold" fontSize={"15px"}>
The password must contain at least 8 characters. We recommend
including at least 1 number and 1 special character.
</Text>
<Button
type="submit"
class={`font-bold bg-[rgb(30,215,96)] w-full h-[50px] rounded-lg mt-5`}
isLoading={isSubmitting}
>
Next
</Button>
</FormControl>
</form>
</div>
</>
);
} |
import {NgModule} from '@angular/core';
import {Routes, RouterModule} from '@angular/router';
import {ListComponent} from './list/list.component';
import {CreateComponent} from './create/create.component';
import {UpdateComponent} from './update/update.component';
import {DeleteComponent} from './delete/delete.component';
import {LoginComponent} from './login/login.component';
import {ForgotpasswordComponent} from './forgotpassword/forgotpassword.component';
import {ErrorComponent} from './error/error.component';
import {AuthGuardService} from "../../../service/auth-guard.service";
import {UserRole} from "../../../models/UserRole";
const routes: Routes = [
{
path: '', component: ListComponent, canActivate: [AuthGuardService]
},
{
path: 'create', component: CreateComponent, canActivate: [AuthGuardService], data: {roles: [UserRole.Admin]}
},
{
path: 'update', component: UpdateComponent, canActivate: [AuthGuardService]
},
{
path: 'delete', component: DeleteComponent, canActivate: [AuthGuardService]
},
{
path: 'login', component: LoginComponent
},
{
path: 'forgot', component: ForgotpasswordComponent
}
, {
path: 'error', component: ErrorComponent
}];
@NgModule({
imports: [RouterModule.forChild(routes)],
exports: [RouterModule]
})
export class UserRoutingModule {
} |
## Author: Jack Boyce
## Comparing growth from planting to 2010 census to 2023 census in Burgaue Plots
library(tidyverse)
library(openxlsx)
library(patchwork)
library(cowplot)
######## Loading in data -----------------------------------------------
# 2010 femels data
GJ_Census <- read.xlsx("[insert file path]") %>% mutate(PlotID = Feld, Species = Baumart, DBH = Durchmesser)%>% select(-Bemerkung, -Feld, -Baumart, -Durchmesser)
GJ_15 <- GJ_Census %>% filter(PlotID == "15") %>% filter(Species == "SEI")
GJ_16 <- GJ_Census %>% filter(PlotID == "16") %>% filter(Species == "SEI")
GJ_17 <- GJ_Census %>% filter(PlotID == "17") %>% filter(Species == "SEI")
GJ_18 <- GJ_Census %>% filter(PlotID == "18") %>% filter(Species == "SEI")
GJ_bound <- rbind(
GJ_15, GJ_16, GJ_17, GJ_18)
GJ_bound$PlotID <- as.character(GJ_bound$PlotID)
Janus_1 <- GJ_bound %>% group_by(PlotID, Species) %>% mutate(`Mean DBH 2010` = mean(DBH)) %>% ungroup() %>%
group_by(PlotID, Species, `Mean DBH 2010`) %>% summarise() %>% ungroup()
Janus_2 <- GJ_bound %>% group_by(PlotID, Species) %>% count() %>% ungroup()
GJ_summary <- Janus_1 %>% left_join(Janus_2) %>% mutate(`N 2010` = n) %>% select(-n)
# 2023 femels data
Fieldwork_Census <- read.xlsx("[insert file path]", sheet = 2) %>%
mutate(DBH = DBH_mm/10) %>% select(-c(DBH_mm, Comments, TreeID, StemID)) %>% relocate(DBH, .after = Species)
Fieldwork_15 <- Fieldwork_Census %>% filter(PlotID == "15") %>% filter(Species_Adjusted == "SEI")
Fieldwork_16 <- Fieldwork_Census %>% filter(PlotID == "16") %>% filter(Species_Adjusted == "SEI")
Fieldwork_17 <- Fieldwork_Census %>% filter(PlotID == "17") %>% filter(Species_Adjusted == "SEI")
Fieldwork_18 <- Fieldwork_Census %>% filter(PlotID == "18") %>% filter(Species_Adjusted == "SEI")
Fieldwork_bound <- rbind(
Fieldwork_15, Fieldwork_16, Fieldwork_17, Fieldwork_18)
Fieldwork_1 <- Fieldwork_bound %>% group_by(PlotID, Species_Adjusted, Shaded) %>% mutate(`Mean DBH 2023` = mean(DBH)) %>% ungroup() %>%
group_by(PlotID, Species_Adjusted, Shaded, `Mean DBH 2023`) %>% summarise() %>% ungroup()
Fieldwork_2 <- Fieldwork_bound %>% group_by(PlotID, Species_Adjusted, Shaded) %>% count() %>% ungroup()
Fieldwork_summary <- Fieldwork_1 %>% left_join(Fieldwork_2) %>% rename(`N 2023` = n)
Fieldwork_summary$PlotID <- as.character(Fieldwork_summary$PlotID)
# preparing Paußnitz data separately
Fieldwork_Paußnitz <- Fieldwork_Census %>%
filter(PlotID == "P") %>% filter(Species_Adjusted == "SEI")
P_summary <- Fieldwork_Paußnitz %>% group_by(PlotID, Species_Adjusted, Shaded) %>% mutate(`Mean DBH 2023` = mean(DBH)) %>% ungroup() %>%
group_by(PlotID, Species_Adjusted, Shaded, `Mean DBH 2023`) %>% summarise() %>% ungroup() %>% mutate(`Mean DBH 2014` = 0) %>% mutate(`Planting_Year` = "2011") %>% rename(Species = `Species_Adjusted`) %>%
relocate(`Mean DBH 2014`, .before = `Mean DBH 2023`) %>%
mutate(`Years Null DBH to 2023 DBH` = 9) %>%
mutate(`Null to 2023 Growth Rate` = `Mean DBH 2023`/`Years Null DBH to 2023 DBH`) %>%
mutate(Plot_Label = "P")
P_simplified <- P_summary %>% select(PlotID, Species, Shaded, `Planting_Year`, `Null to 2023 Growth Rate`) %>% rename(Growth_Rate = `Null to 2023 Growth Rate`) %>%
mutate(Age = 12) %>% mutate(Femel_size = 0.1) %>% filter(Shaded != "p")
colnames(P_simplified)
# joining Sachsenforst femels
All_joined <- Fieldwork_summary %>% left_join(GJ_summary) %>% relocate(`Mean DBH 2010`, .after = Shaded) %>% relocate(`N 2010`, .after = `Mean DBH 2010`) %>% relocate(Shaded, .after = `N 2023`) %>%
mutate(
`Planting Year` = case_when(PlotID %in% c("15") ~ "1997",
TRUE ~ `PlotID`),
`Planting Year` = case_when(PlotID %in% c("16") ~ "1997",
TRUE ~ `Planting Year`),
`Planting Year` = case_when(PlotID %in% c("17") ~ "1997",
TRUE ~ `Planting Year`),
`Planting Year` = case_when(PlotID %in% c("18") ~ "1996",
TRUE ~ `Planting Year`)
) %>%
relocate(`Planting Year`, .after = Species) %>%
select(-Species_Adjusted)
All_joined$`Planting Year` <- as.numeric(All_joined$`Planting Year`)
# Time from 0 DBH at planting to 2010 DBH (2007 and 2020 used instead of 2010 and 2023 because foresters said trees take ~3 years to reach 1.3m DBH)
Null_2010_2023_DBH <- All_joined %>% mutate(`Years Null DBH to 2010 DBH` = 2007-`Planting Year`) %>% relocate(`Years Null DBH to 2010 DBH`, .after = `Planting Year`) %>%
mutate(`Years Null DBH to 2023 DBH` = 2020-`Planting Year`) %>% relocate(`Years Null DBH to 2023 DBH`, .before = `Mean DBH 2023`)
######## Calculating Sachsenforst femels growth rates -----------------------------------------------
# Calculating DBH growth per year
Growth_rates <- Null_2010_2023_DBH %>% mutate(`Null to 2010 Growth Rate` = `Mean DBH 2010`/`Years Null DBH to 2010 DBH`) %>% relocate(`Null to 2010 Growth Rate`, .after = `N 2010`) %>%
mutate(`2010 to 2023 Growth Rate` = (`Mean DBH 2023`-`Mean DBH 2010`)/13) %>%
mutate(`Null to 2023 Growth Rate` = `Mean DBH 2023`/`Years Null DBH to 2023 DBH`) %>%
relocate(Shaded, .after = `Mean DBH 2023`) %>% filter(Shaded != "p")
## condensing Sachsenforst rates
Sachsenforst_Paußnitz_condensed <- Growth_rates %>%
rename(`Census Period 1 Growth` = `Null to 2010 Growth Rate`) %>%
rename(`Census Period 2 Growth` = `2010 to 2023 Growth Rate`) %>%
rename(`Census Period 3 Growth` = `Null to 2023 Growth Rate`) %>%
rename(`Age Census Period 1` = `Years Null DBH to 2010 DBH`) %>%
rename(`Age Census Period 2` = `Years Null DBH to 2023 DBH`) %>%
mutate(Femel_size = case_when(
as.character(PlotID) %in% c("15") ~ "0.4",
TRUE ~ as.character(PlotID))) %>%
mutate(Femel_size = case_when(
as.character(PlotID) %in% c("16") ~ "0.5",
TRUE ~ as.character(Femel_size))) %>%
mutate(Femel_size = case_when(
as.character(PlotID) %in% c("17") ~ "0.6",
TRUE ~ as.character(Femel_size))) %>%
mutate(Femel_size = case_when(
as.character(PlotID) %in% c("18") ~ "0.3",
TRUE ~ as.character(Femel_size))) %>%
select(PlotID, Shaded, Species, `Planting Year`, Femel_size, `Age Census Period 2`,`Census Period 3 Growth`) %>%
rename(Growth_Rate = `Census Period 3 Growth`, Age = `Age Census Period 2`, Planting_Year = `Planting Year`) %>%
rbind(P_simplified) %>% filter(Shaded != "p") %>% filter(PlotID == "15" | PlotID == "16" | PlotID == "17" | PlotID == "18" | PlotID == "P") %>%
mutate(Shaded = case_when(as.character(Shaded) %in% "n" ~ "overstory", TRUE ~ as.character(Shaded)),
Shaded = case_when(as.character(Shaded) %in% "y" ~ "understory", TRUE ~ as.character(Shaded)))
Sachsenforst_Paußnitz_condensed$Planting_Year <- as.numeric(Sachsenforst_Paußnitz_condensed$Planting_Year)
Sachsenforst_Paußnitz_condensed$`Growth_Rate` <- as.numeric(Sachsenforst_Paußnitz_condensed$`Growth_Rate`)
Sachsenforst_Paußnitz_condensed$Age <- as.numeric(Sachsenforst_Paußnitz_condensed$Age)
Sachsenforst_Paußnitz_condensed$Femel_size <- as.character(Sachsenforst_Paußnitz_condensed$Femel_size)
## Bringing in LL rates (already calculated by Lucian)
LL_rates <- read.csv("[insert file path]") %>% select(sp_adj, cl, period, growth_rate, mort_annual) %>% rename(Species = sp_adj) %>%
rename(Growth_Rate = growth_rate) %>% rename(Mortality_Rate = mort_annual) %>%
mutate(Shaded = case_when(as.character(cl) %in% "1" ~ "n",
TRUE ~ as.character(cl)),
Shaded = case_when(as.character(cl) %in% "2" ~ "y",
TRUE ~ as.character(Shaded))) %>%
mutate(Age = 20) %>%
mutate(Femel_size = "NA", PlotID = "Forest inventory average") %>% mutate(Mortality_Rate = Mortality_Rate*100) %>%
relocate(c(PlotID, Femel_size, Species, Shaded, Growth_Rate), .before = Mortality_Rate) %>%
select(-cl, -period)
LL_oak_growth <- LL_rates %>% filter(Species == "SEI") %>% select(PlotID, Femel_size, Species, Shaded, Growth_Rate) %>%
mutate(Shaded = case_when(as.character(Shaded) %in% "n" ~ "overstory", TRUE ~ as.character(Shaded)),
Shaded = case_when(as.character(Shaded) %in% "y" ~ "understory", TRUE ~ as.character(Shaded)),
Shaded = case_when(as.character(Shaded) %in% "u" ~ "unspecified", TRUE ~ as.character(Shaded)))
LL_mortality <- LL_rates %>% select(PlotID, Femel_size, Species, Shaded, Mortality_Rate)
######## Calculating Sachsenforst Mortality Rates -----------------------------------------------
# getting total sums for each species in 2010 and 2023 to get mortality rates per species (regardless of canopy layer)
# 2010 trees per species
trees_species_2010 <- GJ_summary %>% mutate(
`N per Ha 2010` = case_when(PlotID %in% c("15") ~ "2378",
TRUE ~ `PlotID`),
`N per Ha 2010` = case_when(PlotID %in% c("16") ~ "2182",
TRUE ~ `N per Ha 2010`),
`N per Ha 2010` = case_when(PlotID %in% c("17") ~ "1938",
TRUE ~ `N per Ha 2010`),
`N per Ha 2010` = case_when(PlotID %in% c("18") ~ "2375",
TRUE ~ `N per Ha 2010`)
)
trees_species_2010$`N per Ha 2010` <- as.numeric(trees_species_2010$`N per Ha 2010`)
trees_species_2023 <- Fieldwork_bound %>% group_by(PlotID, Species) %>% count() %>% rename(`N 2023` = n) %>% mutate(
`N per Ha 2023` = case_when(PlotID %in% c("15") ~ "979",
TRUE ~ PlotID),
`N per Ha 2023` = case_when(PlotID %in% c("16") ~ "803",
TRUE ~ `N per Ha 2023`),
`N per Ha 2023` = case_when(PlotID %in% c("17") ~ "767",
TRUE ~ `N per Ha 2023`),
`N per Ha 2023` = case_when(PlotID %in% c("18") ~ "843",
TRUE ~ `N per Ha 2023`)
)
trees_species_2023$`N per Ha 2023` <- as.numeric(trees_species_2023$`N per Ha 2023`)
mortality_all_trees <- trees_species_2010 %>% left_join(trees_species_2023) %>% mutate(`N Ha Dead` = `N per Ha 2010` - `N per Ha 2023`) %>%
mutate(`Mortality p` = `N Ha Dead`/`N per Ha 2010`) %>%
mutate(`Annual Mortality Rate` = round(-log(1-`Mortality p`)/13, digits = 3)) %>%
relocate(`N 2023`, .after = `N 2010`) %>% mutate(`Annual Mortality Rate` = `Annual Mortality Rate`*100)
### joining growth and mortality rates for Sachsenforst femels
All_Rates <- mortality_all_trees %>% select(-c(`N 2023`)) %>% right_join(Growth_rates) %>% relocate(`N per Ha 2010`, .after = `Null to 2023 Growth Rate`) %>%
relocate(`N per Ha 2023`, .after = `N per Ha 2010`) %>%
relocate(`N Ha Dead`, .after = `N per Ha 2023`) %>%
relocate(`Mortality p`, .after = `N Ha Dead`) %>%
relocate(`Annual Mortality Rate`, .after = `Mortality p`)
Sachsenforst_growth_mortality <- All_Rates %>% select(PlotID, Species, Shaded, `Null to 2023 Growth Rate`, `Annual Mortality Rate`) %>%
mutate(
Femel_size = case_when(
as.character(PlotID) %in% "15" ~ "0.4",
TRUE ~ as.character(PlotID)),
Femel_size = case_when(
as.character(PlotID) %in% "16" ~ "0.5",
TRUE ~ as.character(Femel_size)),
Femel_size = case_when(
as.character(PlotID) %in% "17" ~ "0.6",
TRUE ~ as.character(Femel_size)),
Femel_size = case_when(
as.character(PlotID) %in% "18" ~ "0.3",
TRUE ~ as.character(Femel_size)),
) %>% relocate(Femel_size, .after = PlotID) %>%
rename(Growth_Rate = `Null to 2023 Growth Rate`) %>% rename(Mortality_Rate = `Annual Mortality Rate`)
####### Filtering down to Oak rates -----------------------------------------------
## Oak growth
Oak_Rates_growth <- Sachsenforst_Paußnitz_condensed %>%
full_join(LL_rates) %>%
filter(Species == "SEI") %>%
mutate(Shaded = case_when(as.character(Shaded) %in% "n" ~ "overstory",
TRUE ~ as.character(Shaded)),
Shaded = case_when(as.character(Shaded) %in% "y" ~ "understory",
TRUE ~ as.character(Shaded))) %>%
mutate(Femel_size = case_when(as.character(Femel_size) %in% "NA" ~ "LL",
TRUE ~ as.character(Femel_size))) %>%
#filter(PlotID != "Forest inventory average") %>%
select(-Mortality_Rate)
Oak_Rates_growth$Age <- as.numeric(Oak_Rates_growth$Age)
Oak_Rates_growth$Femel_size <- as.character(Oak_Rates_growth$Femel_size)
Oak_Rates_growth$Growth_Rate <- as.numeric(Oak_Rates_growth$Growth_Rate)
Oak_Rates_growth_no_LL <- Oak_Rates_growth %>% filter(PlotID != "Forest inventory average")
Oak_Rates_growth_no_LL$Femel_size <- as.numeric(Oak_Rates_growth_no_LL$Femel_size)
Oak_femels_overstory_growth_avg <- Oak_Rates_growth_no_LL %>% filter(Shaded == "overstory") %>% mutate(avg_growth = mean(Growth_Rate))
Oak_femels_understory_growth_avg <- Oak_Rates_growth_no_LL %>% filter(Shaded == "understory") %>% mutate(avg_growth = mean(Growth_Rate))
## Oak mortality
Oak_Rates_mortality <- Sachsenforst_growth_mortality %>%
full_join(LL_mortality) %>%
filter(Species == "SEI") %>%
mutate(Shaded = case_when(as.character(Shaded) %in% "n" ~ "overstory",
TRUE ~ as.character(Shaded)),
Shaded = case_when(as.character(Shaded) %in% "y" ~ "understory",
TRUE ~ as.character(Shaded)),
Shaded = case_when(as.character(Shaded) %in% "u" ~ "unspecified",
TRUE ~ as.character(Shaded))) %>%
mutate(Femel_size = case_when(Femel_size %in% "0,3" ~ "0.3", TRUE ~ Femel_size),
Femel_size = case_when(Femel_size %in% "0,4" ~ "0.4", TRUE ~ Femel_size),
Femel_size = case_when(Femel_size %in% "0,5" ~ "0.5", TRUE ~ Femel_size),
Femel_size = case_when(Femel_size %in% "0,6" ~ "0.6", TRUE ~ Femel_size),
Femel_size = case_when(Femel_size %in% "NA" ~ "LL", TRUE ~ Femel_size)
) %>% select(-Growth_Rate)
# Oak_Rates_mortality_no_LL <- Oak_Rates_mortality %>% filter(PlotID != "Forest inventory average")
# Oak_Rates_mortality_no_LL$Femel_size <- as.numeric(Oak_Rates_mortality_no_LL$Femel_size)
######## Plotting Rate Comparisons -----------------------------------------------
### Plotting Growth Rate Comparisons
## Plotting Femel Growth with LL rates - Age & Size comparison
Femel_Growth_Rates <- ggplot(Oak_Rates_growth, aes(x = `Femel_size`, y = `Growth_Rate`, shape = Shaded, label = Femel_size)) +
geom_point(size = 8)+
scale_x_discrete(breaks = c(0.1,0.2,0.3,0.4,0.5,0.6,"LL")) +
scale_y_continuous(breaks = c(0,0.2,0.4,0.6,0.8,1.0,1.2), limits = c(0,1.2)) +
scale_size_continuous(range = c(0, 15),
limits = c(0,25),
breaks = c(12,23)) +
labs(x = "Femel Size (ha)", y = "DBH Growth Rate (cm / year)",
#title = "Oak Growth Rate per Femel Size",
shape = "Canopy Layer"
) +
guides(shape = guide_legend(override.aes = list(size=8, alpha = 1)), order = 2) +
theme(plot.title=element_text(size=22),
axis.text=element_text(size=20),
axis.title=element_text(size=20),
legend.title=element_text(size=20),
legend.text=element_text(size=20)) +
theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank(),
panel.background = element_blank(), axis.line = element_line(colour = "black"))+
theme(legend.position = "none")
Femel_Growth_Rates
# Plotting Femel Mortality with LL rates
Oak_Rates_mortality$Femel_size <- as.character(Oak_Rates_mortality$Femel_size)
Oak_Rates_mortality <- Oak_Rates_mortality %>% mutate(Shaded = case_when(as.character(Femel_size) %in% c("0.3","0.4","0.5","0.6") ~ "unspecified",
TRUE ~ as.character(Shaded)))
Oak_Mortality_Sachsenforst_LL <- ggplot(Oak_Rates_mortality, aes(x = Femel_size, y = Mortality_Rate, shape = Shaded)) +
geom_point(size = 8) +
labs(x = "Femel Size (ha)", y = "Mortality Rate (% / year)", shape = "Canopy Layer",
#title = "Oak Mortality Rate per Femel Size"
) +
theme(plot.title=element_text(size=22),
axis.text=element_text(size=20),
axis.title=element_text(size=20),
legend.title=element_text(size=20),
legend.text=element_text(size=20)) +
theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank(),
panel.background = element_blank(), axis.line = element_line(colour = "black")) +
theme(legend.text = element_text(size = 20),
legend.title = element_text(size = 20))+
ylim(0, 16)
Oak_Mortality_Sachsenforst_LL
### plotting growth and mortality together
Femel_Growth_Rates + Oak_Mortality_Sachsenforst_LL + plot_annotation(tag_levels = c('A'), tag_suffix = ')') &
theme(plot.tag = element_text(size = 24, face = 'bold'))
#plot_grid(Femel_Growth_Rates, Oak_Mortality_Sachsenforst_LL, labels = c('a','b)'), label_size = 22, label_fontface = "bold") |
// Date.cpp - Defines all functions of the Date class
// Module 13 Lab 13
// Author: Kevin Hu
/* Description: Implementation of functions for Date class
Constructor should only accept reasonable values for month, day, and year.
If user tries to create a Date object with any invalid argument, create the Date object with default values.
*/
#include "Date.h"
#include <string>
#include <iomanip>
#include <iostream>
using namespace std;
// Constructor
Date::Date(int selected_month, int selected_day, int selected_year)
{
int daysInMonth; // Used to verify days in month
cout << "The Date object is being created with month " << selected_month << ", day " << selected_day << ", and year " << selected_year << endl;
if (selected_month < 1 || selected_month > 12) // Verify that inserted month is valid
{
setDefault();
return;
}
switch(selected_month) // establish max days in selected month and sets a string for later print functions
{
case 1:
daysInMonth = 31;
setMonthString("January");
break;
case 2:
daysInMonth = 29;
setMonthString("February");
break;
case 3:
daysInMonth = 31;
setMonthString("March");
break;
case 4:
daysInMonth = 30;
setMonthString("April");
break;
case 5:
daysInMonth = 31;
setMonthString("May");
break;
case 6:
daysInMonth = 30;
setMonthString("June");
break;
case 7:
daysInMonth = 31;
setMonthString("July");
break;
case 8:
daysInMonth = 31;
setMonthString("August");
break;
case 9:
daysInMonth = 30;
setMonthString("September");
break;
case 10:
daysInMonth = 31;
setMonthString("October");
break;
case 11:
daysInMonth = 30;
setMonthString("November");
break;
case 12:
daysInMonth = 31;
setMonthString("December");
break;
}
if (selected_day > daysInMonth || selected_day < 1 || selected_year < 1900 || selected_year > 2099) // Errant day and year checks
{
setDefault();
return;
}
else
{
month = selected_month;
day = selected_day;
year = selected_year;
}
}
// setter definitions
void Date::setDay(int inputDay)
{
day = inputDay;
}
void Date::setMonth(int inputMonth)
{
month = inputMonth;
}
void Date::setYear(int inputYear)
{
year = inputYear;
}
void Date::setMonthString(string inputMonthString)
{
month_string = inputMonthString;
}
// member function print definitions
void Date::printDateOne()
{
cout << month << "/" << day << "/"<< year << endl; // prints in x/y/z
}
void Date::printDateTwo()
{
cout << month_string << " " << day << ", " << year << endl; // prints in x(word).y.z
}
void Date::printDateThree()
{
cout << day << "." << month_string << "." << year << endl; // prints y.x(word).z
}
void Date::printDateFour()
{
string s;
string m;
cout << year << "." << s.append(string((month < 10) ? "0" + to_string(month): to_string(month))) << "." << m.append(string((day < 10) ? "0" + to_string(day): to_string(day))) << endl; // prints z.x.y
}
void Date::setDefault() // sets default arguments in case of errant instantiation
{
month = 1;
day = 1;
year = 2000;
setMonthString("January");
} |
/** Proofs GPU - Space and Time's cryptographic proof algorithms on the CPU and GPU.
*
* Copyright 2023-present Space and Time Labs, Inc.
*
* 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.
*/
#include "sxt/base/device/event.h"
#include <cuda_runtime.h>
#include <utility>
#include "sxt/base/error/panic.h"
namespace sxt::basdv {
//--------------------------------------------------------------------------------------------------
// constructor
//--------------------------------------------------------------------------------------------------
event::event() noexcept {
auto rcode = cudaEventCreateWithFlags(&event_, cudaEventDisableTiming);
if (rcode != cudaSuccess) {
baser::panic("cudaEventCreate failed: {}", cudaGetErrorString(rcode));
}
}
event::event(event&& other) noexcept : event_{std::exchange(other.event_, nullptr)} {}
//--------------------------------------------------------------------------------------------------
// assignment
//--------------------------------------------------------------------------------------------------
event& event::operator=(event&& other) noexcept {
this->clear();
event_ = std::exchange(other.event_, nullptr);
return *this;
}
//--------------------------------------------------------------------------------------------------
// clear
//--------------------------------------------------------------------------------------------------
void event::clear() noexcept {
if (event_ == nullptr) {
return;
}
auto rcode = cudaEventDestroy(event_);
if (rcode != cudaSuccess) {
baser::panic("cudaEventDestroy failed: {}", cudaGetErrorString(rcode));
}
event_ = nullptr;
}
//--------------------------------------------------------------------------------------------------
// query_is_ready
//--------------------------------------------------------------------------------------------------
bool event::query_is_ready() noexcept {
auto rcode = cudaEventQuery(event_);
if (rcode == cudaSuccess) {
return true;
}
if (rcode == cudaErrorNotReady) {
return false;
}
baser::panic("cudaEventQuery failed: {}", cudaGetErrorString(rcode));
}
//--------------------------------------------------------------------------------------------------
// destructor
//--------------------------------------------------------------------------------------------------
event::~event() noexcept { this->clear(); }
} // namespace sxt::basdv |
# CSS3
## 생성자
### id
```html
<style>
#select {...}
</style>
<h1 id="select">동해물과 백두산이</h1>
```
### class
```html
<style>
.select {...}
.header {...}
.item {...}
</style>
<h1 class="select header item">동해물과 백두산이</h1>
```
### child
## 속성
### shadow
```css
/*box-shadow : x-position y-position blur spread color
x-position : 가로 위치, 양수면 오른쪽, 음수면 왼쪽에 그림자가 만들어진다.
y-position : 세로 위치, 양수면 아래쪽, 음수면 위쪽에 그림자가 만들어진다.
blur : 그림자를 흐릿하게 만든다. 값이 클수록 더욱 흐려진다.
spread : 양수면 그림자를 확장하고, 음수이면 축소한다.
color : 그림자의 색을 정한다.
inset : 그림자를 요소의 안쪽에 만든다.
initial : 기본값으로 설정한다.
ingerit : 부모 요소의 값을 상속받는다.*/
```
### position
### Grid
### hover |
import React, { useCallback, useMemo, useState } from 'react';
import './multi-data-entry.css';
import { BaseDataEntryProps } from '../data-entry';
import { DataEntryInput, TextDataEntryInputProps } from '../data-entry-input';
import { DataTitleCopyable } from '../data-title';
import { CloseIcon, SaveIcon } from '../../../components/icons';
interface MultiDataEntryProps extends BaseDataEntryProps, TextDataEntryInputProps {
value: string[];
copyable?: boolean;
editableEntries?: boolean;
confirmOnEnter?: boolean;
}
export const MultiDataEntry: React.FC<MultiDataEntryProps> = ({
editableEntries = false,
copyable = true,
confirmOnEnter = true,
...props
}) => {
const [newValue, setNewValue] = useState<string>();
const values = useMemo(() => props.value ?? [], [props.value]);
const edit = useCallback((index: number, value: string) => {
const editedValues = values.slice();
editedValues.splice(index, 1, value);
props.onChange(props.slug, editedValues);
}, [values, props.onChange, props.slug]);
/* accept a newValue parameter to handle cases where the value is set and submitted at the same time
* (like with autofill select enabled) - but otherwise use the current newValue saved in state
*/
const addNew = useCallback((newValueArg?: string) => {
const val = newValueArg ?? newValue;
if(val == undefined) return;
const editedValues = values.slice().concat(val);
setNewValue(null);
props.onChange(props.slug, editedValues);
}, [newValue, values, props.onChange, props.slug]);
const clearNew = useCallback(() => {
setNewValue(null);
}, []);
const remove = useCallback((index: number) => {
const editedValues = values.slice();
editedValues.splice(index, 1);
props.onChange(props.slug, editedValues);
}, [values, props.onChange, props.slug]);
const isEditing = props.mode === 'edit';
const isDisabled = !isEditing || props.disabled;
const slugWithModifier = props.slug + (props.slugModifier ?? '');
return (<>
<DataTitleCopyable
slug={props.slug}
slugModifier={props.slugModifier}
title={props.title}
tooltip={props.tooltip}
disabled={props.disabled || props.value == undefined || props.value.length === 0}
copy={copyable ? props.copy : undefined}
/>
<div id={`${props.slug}-wrapper`}>
{
values.length === 0 && !isEditing &&
<div className="input-group">
<input className="form-control no-entries" type="text" value="No entries" disabled={true} />
</div>
}
<ul className="data-entry-list">
{
isEditing && isDisabled && values.length === 0 &&
<div className="input-group">
<input className="form-control no-entries" type="text" value="Please add a link below" disabled={true} />
</div>
}
{
values.map((val, i) => (
<li className="input-group" key={i /* i as key prevents input component recreation on edit */}>
<DataEntryInput
slug={props.slug}
name={`${slugWithModifier}-${i}`}
id={`${slugWithModifier}-${i}`}
value={val}
disabled={!editableEntries || isDisabled}
onChange={(_key, val) => edit(i, val)}
maxLength={props.maxLength}
isUrl={props.isUrl}
valueTransform={props.valueTransform}
autofill={props.autofill}
showAllOptionsOnEmpty={props.showAllOptionsOnEmpty}
/>
{
!isDisabled &&
<div className="input-group-append">
<button type="button" onClick={() => remove(i)}
title="Remove"
data-index={i} className="btn btn-outline-dark data-entry-list-button"><CloseIcon /></button>
</div>
}
</li>
))
}
{
!isDisabled &&
<li className="input-group">
<DataEntryInput
slug={props.slug}
name={slugWithModifier}
id={slugWithModifier}
value={newValue}
disabled={props.disabled}
required={props.required && values.length < 1}
onChange={(_key, val) => setNewValue(val)}
onConfirm={(_key, val) => addNew(val)}
maxLength={props.maxLength}
placeholder={props.placeholder}
isUrl={props.isUrl}
valueTransform={props.valueTransform}
confirmOnEnter={confirmOnEnter}
autofill={props.autofill}
showAllOptionsOnEmpty={props.showAllOptionsOnEmpty}
confirmOnAutofillSelect={true}
/>
{
newValue != undefined &&
<>
<div className="input-group-append">
<button type="button"
className="btn btn-primary data-entry-list-button"
title="Confirm new value"
onClick={() => addNew()}
><SaveIcon /></button>
</div>
<div className="input-group-append">
<button type="button" onClick={() => clearNew()}
title="Clear new value"
className="btn btn-warning data-entry-list-button"><CloseIcon /></button>
</div>
</>
}
</li>
}
</ul>
</div>
</>)
}; |
#ifndef CAFFE_LAYER_H_
#define CAFFE_LAYER_H_
#include <algorithm>
#include <string>
#include <vector>
#include "caffe/blob.hpp"
#include "caffe/common.hpp"
#include "caffe/layer_factory.hpp"
#include "caffe/proto/caffe.pb.h"
#include "caffe/util/math_functions.hpp"
/**
Forward declare boost::thread instead of including boost/thread.hpp
to avoid a boost/NVCC issues (#1009, #1010) on OSX.
*/
namespace boost { class mutex; }/*应该和这个boost/nvcc问题有关*/
namespace caffe {
/**
* @brief An interface for the units of computation which can be composed into a
* Net.
*
* Layer%s must implement a Forward function, in which they take their input
* (bottom) Blob%s (if any) and compute their output Blob%s (if any).
* They may also implement a Backward function, in which they compute the error
* gradients with respect to their input Blob%s, given the error gradients with
* their output Blob%s.
*/
template<typename Dtype>
class Layer {
public:
/**
* You should not implement your own constructor. Any set up code should go
* to SetUp(), where the dimensions of the bottom blobs are provided to the
* layer.
*/
explicit Layer(const LayerParameter ¶m)
: layer_param_(param), is_shared_(false) {
// Set phase and copy blobs (if there are any).设置phase并且拷贝blob(如果有的话)
phase_ = param.phase();
if (layer_param_.blobs_size() > 0) {
blobs_.resize(layer_param_.blobs_size());
for (int i = 0; i < layer_param_.blobs_size(); ++i) {
blobs_[i].reset(new Blob<Dtype>());
blobs_[i]->FromProto(layer_param_.blobs(i));
}
}
}
virtual ~Layer() {}
/**
* @brief Implements common layer setup functionality.
* 设置函数
*
* @param bottom the preshaped input blobs
* @param top
* the allocated but unshaped output blobs, to be shaped by Reshape
*
* Checks that the number of bottom and top blobs is correct.
* Calls LayerSetUp to do special layer setup for individual layer types,
* followed by Reshape to set up sizes of top blobs and internal buffers.
* Sets up the loss weight multiplier blobs for any non-zero loss weights.
* This method may not be overridden.
*/
void SetUp(const vector<Blob<Dtype> *> &bottom,
const vector<Blob<Dtype> *> &top) {
InitMutex();
CheckBlobCounts(bottom, top);/*检测bottom和top的bolb数量是否正确*/
LayerSetUp(bottom, top);/*真正的SetUp函数,由子类自定义*/
Reshape(bottom, top);/*将top blob调整为需要的大小*/
/* 设置储存loss权重的blob(diff blob),
* 一般来说在前向传播过程中只有最后一层会计算loss,
* 其余层的loss都要反向传播过程中才会获得
* */
SetLossWeights(top);
}
/**
* @brief Does layer-specific setup: your layer should implement this function
* as well as Reshape.
*
* @param bottom
* the preshaped input blobs, whose data fields store the input data for
* this layer
* @param top
* the allocated but unshaped output blobs
*
* This method should do one-time layer specific setup. This includes reading
* and processing relevent parameters from the <code>layer_param_</code>.
* Setting up the shapes of top blobs and internal buffers should be done in
* <code>Reshape</code>, which will be called before the forward pass to
* adjust the top blob sizes.
* 读取并处理相关参数(layer_param_)
* 实现Reshape函数,该函数需要设置top blob的shape和其内存空间
* Reshape这个函数会在forward函数之前执行以调整top blob的size
*/
virtual void LayerSetUp(const vector<Blob<Dtype> *> &bottom,
const vector<Blob<Dtype> *> &top) {}
/**
* @brief Whether a layer should be shared by multiple nets during data
* parallelism. By default, all layers except for data layers should
* not be shared. data layers should be shared to ensure each worker
* solver access data sequentially during data parallelism.
*/
virtual inline bool ShareInParallel() const { return false; }
/** @brief Return whether this layer is actually shared by other nets.
* If ShareInParallel() is true and using more than one GPU and the
* net has TRAIN phase, then this function is expected return true.
*/
inline bool IsShared() const { return is_shared_; }
/** @brief Set whether this layer is actually shared by other nets
* If ShareInParallel() is true and using more than one GPU and the
* net has TRAIN phase, then is_shared should be set true.
*/
inline void SetShared(bool is_shared) {
CHECK(ShareInParallel() || !is_shared)
<< type() << "Layer does not support sharing.";
is_shared_ = is_shared;
}
/**
* @brief Adjust the shapes of top blobs and internal buffers to accommodate
* the shapes of the bottom blobs.
* 调整blob的shape并且根据bottom blob分配合适的缓冲区大小
*
* @param bottom the input blobs, with the requested input shapes
* @param top the top blobs, which should be reshaped as needed
*
* This method should reshape top blobs as needed according to the shapes
* of the bottom (input) blobs, as well as reshaping any internal buffers
* and making any other necessary adjustments so that the layer can
* accommodate the bottom blobs.
*/
virtual void Reshape(const vector<Blob<Dtype> *> &bottom, const vector<Blob<Dtype> *> &top) = 0;
/**
* @brief Given the bottom blobs, compute the top blobs and the loss.
* 前向运算函数
*
* @param bottom
* the input blobs, whose data fields store the input data for this layer
* @param top
* the preshaped output blobs, whose data fields will store this layers'
* outputs
* \return The total loss from the layer.
*
* The Forward wrapper calls the relevant device wrapper function
* (Forward_cpu or Forward_gpu) to compute the top blob values given the
* bottom blobs. If the layer has any non-zero loss_weights, the wrapper
* then computes and returns the loss.
*
* Your layer should implement Forward_cpu and (optionally) Forward_gpu.
* 前向传播与反向传播包装器,注意这个只是一个包装器,还需要实现的是forward_cpu&gpu函数,
* 如果没有反向运算则可以不实现反向传播函数
*/
inline Dtype Forward(const vector<Blob<Dtype> *> &bottom,
const vector<Blob<Dtype> *> &top);
/**
* @brief Given the top blob error gradients, compute the bottom blob error
* gradients.
*
* @param top
* the output blobs, whose diff fields store the gradient of the error
* with respect to themselves
* @param propagate_down 与bottom大小相同,元素是bool类型,用于判断哪些diff需要进行反向传播
* a vector with equal length to bottom, with each index indicating
* whether to propagate the error gradients down to the bottom blob at
* the corresponding index
* @param bottom
* the input blobs, whose diff fields will store the gradient of the error
* with respect to themselves after Backward is run
*
* The Backward wrapper calls the relevant device wrapper function
* (Backward_cpu or Backward_gpu) to compute the bottom blob diffs given the
* top blob diffs.
*
* Your layer should implement Backward_cpu and (optionally) Backward_gpu.
* 前向传播与反向传播包装器,注意这个只是一个包装器,还需要实现的是forward_cpu&gpu函数,
* 如果没有反向运算则可以不实现反向传播函数
*/
inline void Backward(const vector<Blob<Dtype> *> &top,
const vector<bool> &propagate_down,/*和bottom的shape大小相同,用于决定bottom哪些需要反传*/
const vector<Blob<Dtype> *> &bottom);
/**
* @brief Returns the vector of learnable parameter blobs.
* 返回一个包含所有需要参与训练的blob列表
*/
vector<shared_ptr<Blob<Dtype> > > &blobs() {
return blobs_;
}
/**
* @brief Returns the layer parameter. 返回当前层的参数
*/
const LayerParameter &layer_param() const { return layer_param_; }
/**
* @brief Writes the layer parameter to a protocol buffer
* 将当前层的参数写成一个protocol文件
*/
virtual void ToProto(LayerParameter *param, bool write_diff = false);
/**
* @brief Returns the scalar loss associated with a top blob at a given index.
* 根据top blob idx返回对应blob的loss值
*/
inline Dtype loss(const int top_index) const {
return (loss_.size() > top_index) ? loss_[top_index] : Dtype(0);/*如果输入的index越过数组则返回0*/
}
/**
* @brief Sets the loss associated with a top blob at a given index.
* 手动设置loss值
*/
inline void set_loss(const int top_index, const Dtype value) {
if (loss_.size() <= top_index) {
loss_.resize(top_index + 1, Dtype(0));/*如果loss的大小过小,则resize成指定的大小*/
}
loss_[top_index] = value;
}
/**
* @brief Returns the layer type.
*/
virtual inline const char *type() const { return ""; }
/**
* @brief Returns the exact number of bottom blobs required by the layer,
* or -1 if no exact number is required.
* 用于验证接入层的bottom数量
*
* This method should be overridden to return a non-negative value if your
* layer expects some exact number of bottom blobs.
*/
virtual inline int ExactNumBottomBlobs() const { return -1; }
/**
* @brief Returns the minimum number of bottom blobs required by the layer,
* or -1 if no minimum number is required.
* 同上,用于验证接入层的bottom数量,不同在于这个是最小数量
*
* This method should be overridden to return a non-negative value if your
* layer expects some minimum number of bottom blobs.
*/
virtual inline int MinBottomBlobs() const { return -1; }
/**
* @brief Returns the maximum number of bottom blobs required by the layer,
* or -1 if no maximum number is required.
*
* This method should be overridden to return a non-negative value if your
* layer expects some maximum number of bottom blobs.
*/
virtual inline int MaxBottomBlobs() const { return -1; }
/**
* @brief Returns the exact number of top blobs required by the layer,
* or -1 if no exact number is required.
*
* This method should be overridden to return a non-negative value if your
* layer expects some exact number of top blobs.
*/
virtual inline int ExactNumTopBlobs() const { return -1; }
/**
* @brief Returns the minimum number of top blobs required by the layer,
* or -1 if no minimum number is required.
*
* This method should be overridden to return a non-negative value if your
* layer expects some minimum number of top blobs.
*/
virtual inline int MinTopBlobs() const { return -1; }
/**
* @brief Returns the maximum number of top blobs required by the layer,
* or -1 if no maximum number is required.
*
* This method should be overridden to return a non-negative value if your
* layer expects some maximum number of top blobs.
*/
virtual inline int MaxTopBlobs() const { return -1; }
/**
* @brief Returns true if the layer requires an equal number of bottom and
* top blobs.
*
* This method should be overridden to return true if your layer expects an
* equal number of bottom and top blobs.
* 如果你需要一个bottom与top数量相等的layer时必须要重写这个方法阐明如何判断bottom与top的数量
*/
virtual inline bool EqualNumBottomTopBlobs() const { return false; }
/**
* @brief Return whether "anonymous" top blobs are created automatically
* by the layer.
* 如果返回True,则会自动生成并填充 ExactNumTopBlobs函数中指定数量的top blobs
*
* If this method returns true, Net::Init will create enough "anonymous" top
* blobs to fulfill the requirement specified by ExactNumTopBlobs() or
* MinTopBlobs().
*/
virtual inline bool AutoTopBlobs() const { return false; }
/**
* @brief Return whether to allow force_backward for a given bottom blob
* index.
* 是否允许强制反传
*
* If AllowForceBackward(i) == false, we will ignore the force_backward
* setting and backpropagate to blob i only if it needs gradient information
* (as is done when force_backward == false).
* 当允许强制反传=False时,程序会忽略force_backward函数
*/
virtual inline bool AllowForceBackward(const int bottom_index) const {
return true;
}
/**
* @brief Specifies whether the layer should compute gradients w.r.t. a
* parameter at a particular index given by param_id.
* 返回指定参数是否需要参与梯度计算
*
* You can safely ignore false values and always compute gradients
* for all parameters, but possibly with wasteful computation.
* 你可以安全的忽略函数返回的false值,并始终计算所有参数的梯度,但是这可能会浪费一些算力
*/
inline bool param_propagate_down(const int param_id) {
return (param_propagate_down_.size() > param_id) ?
param_propagate_down_[param_id] : false;
}
/**
* @brief Sets whether the layer should compute gradients w.r.t. a
* parameter at a particular index given by param_id.
* 设置是否要参与梯度计算
*/
inline void set_param_propagate_down(const int param_id, const bool value) {
if (param_propagate_down_.size() <= param_id) {
param_propagate_down_.resize(param_id + 1, true);
}
param_propagate_down_[param_id] = value;
}
protected:
/** The protobuf that stores the layer parameters */
LayerParameter layer_param_;
/** The phase: TRAIN or TEST */
Phase phase_;
/** The vector that stores the learnable parameters as a set of blobs. */
vector<shared_ptr<Blob<Dtype> > > blobs_;/*存储各类blobs*/
/** Vector indicating whether to compute the diff of each param blob. */
vector<bool> param_propagate_down_;
/** The vector that indicates whether each top blob has a non-zero weight in
* the objective function. */
vector<Dtype> loss_;
/** @brief Using the CPU device, compute the layer output. */
virtual void Forward_cpu(const vector<Blob<Dtype> *> &bottom,
const vector<Blob<Dtype> *> &top) = 0;
/**
* @brief Using the GPU device, compute the layer output.
* Fall back to Forward_cpu() if unavailable.
*/
virtual void Forward_gpu(const vector<Blob<Dtype> *> &bottom,
const vector<Blob<Dtype> *> &top) {
// LOG(WARNING) << "Using CPU code as backup.";
return Forward_cpu(bottom, top);
}
/**
* @brief Using the CPU device, compute the gradients for any parameters and
* for the bottom blobs if propagate_down is true.
*/
virtual void Backward_cpu(const vector<Blob<Dtype> *> &top,
const vector<bool> &propagate_down,
const vector<Blob<Dtype> *> &bottom) = 0;
/**
* @brief Using the GPU device, compute the gradients for any parameters and
* for the bottom blobs if propagate_down is true.
* Fall back to Backward_cpu() if unavailable.
*/
virtual void Backward_gpu(const vector<Blob<Dtype> *> &top,
const vector<bool> &propagate_down,
const vector<Blob<Dtype> *> &bottom) {
// LOG(WARNING) << "Using CPU code as backup.";
Backward_cpu(top, propagate_down, bottom);
}
/**
* Called by the parent Layer's SetUp to check that the number of bottom
* and top Blobs provided as input match the expected numbers specified by
* the {ExactNum,Min,Max}{Bottom,Top}Blobs() functions.
* 检查blob的数量是否符合要求
*/
virtual void CheckBlobCounts(const vector<Blob<Dtype> *> &bottom,
const vector<Blob<Dtype> *> &top) {
if (ExactNumBottomBlobs() >= 0) {
CHECK_EQ(ExactNumBottomBlobs(), bottom.size())/*检查bottom blob的数量是否符合ExactNumBottomBlos函数中设置的需求*/
<< type() << " Layer takes " << ExactNumBottomBlobs()
<< " bottom blob(s) as input.";
}
if (MinBottomBlobs() >= 0) {
CHECK_LE(MinBottomBlobs(), bottom.size())/*同上*/
<< type() << " Layer takes at least " << MinBottomBlobs()
<< " bottom blob(s) as input.";
}
if (MaxBottomBlobs() >= 0) {
CHECK_GE(MaxBottomBlobs(), bottom.size())
<< type() << " Layer takes at most " << MaxBottomBlobs()
<< " bottom blob(s) as input.";
}
if (ExactNumTopBlobs() >= 0) {
CHECK_EQ(ExactNumTopBlobs(), top.size())
<< type() << " Layer produces " << ExactNumTopBlobs()
<< " top blob(s) as output.";
}
if (MinTopBlobs() >= 0) {
CHECK_LE(MinTopBlobs(), top.size())
<< type() << " Layer produces at least " << MinTopBlobs()
<< " top blob(s) as output.";
}
if (MaxTopBlobs() >= 0) {
CHECK_GE(MaxTopBlobs(), top.size())
<< type() << " Layer produces at most " << MaxTopBlobs()
<< " top blob(s) as output.";
}
if (EqualNumBottomTopBlobs()) {
CHECK_EQ(bottom.size(), top.size())
<< type() << " Layer produces one top blob as output for each "
<< "bottom blob input.";
}
}
/**
* Called by SetUp to initialize the weights associated with any top blobs in
* the loss function. Store non-zero loss weights in the diff blob.
* 由SetUp调用,用于初始化与loss函数中的任何与top blob相关联的权重。在diff blob中存储非零的损失权重。
* 一般来说在前向传播过程中只有最后一个layer会计算loss,其余layer的loss则是在反向传播时才会得到(保存在diff blob中,由top传入)
*/
inline void SetLossWeights(const vector<Blob<Dtype> *> &top) {
const int num_loss_weights = layer_param_.loss_weight_size();
if (num_loss_weights) {
CHECK_EQ(top.size(), num_loss_weights) << "loss_weight must be "
"unspecified or specified once per top blob.";
for (int top_id = 0; top_id < top.size(); ++top_id) {
const Dtype loss_weight = layer_param_.loss_weight(top_id);
if (loss_weight == Dtype(0)) { continue; }
this->set_loss(top_id, loss_weight);
const int count = top[top_id]->count();
Dtype *loss_multiplier = top[top_id]->mutable_cpu_diff();/*取出存放diff的内存指针*/
caffe_set(count, loss_weight, loss_multiplier);/*将loss_weight复制到loss_multiplier中*/
}
}
}
private:
/** Whether this layer is actually shared by other nets*/
bool is_shared_;
/** The mutex for sequential forward if this layer is shared */
shared_ptr<boost::mutex> forward_mutex_;
/** Initialize forward_mutex_ */
void InitMutex();
/** Lock forward_mutex_ if this layer is shared */
void Lock();
/** Unlock forward_mutex_ if this layer is shared */
void Unlock();
DISABLE_COPY_AND_ASSIGN(Layer);/*关闭拷贝和赋值操作符*/
}; // class Layer
/* Forward and backward wrappers. You should implement the cpu and
* gpu specific implementations instead, and should not change these
* functions.
* 作者自己写的forward函数,可以作为自己Forward函数的参考,但是不要修改
* 同时应该去重写Forward_cpu&gpu函数
*/
template<typename Dtype>
inline Dtype Layer<Dtype>::Forward(const vector<Blob<Dtype> *> &bottom,
const vector<Blob<Dtype> *> &top) {
// Lock during forward to ensure sequential forward
Lock();
Dtype loss = 0;
Reshape(bottom, top);/*reshape不单会对blob进行reshape,还会负责缓存的分配,注意这里bottom和top的shape之间没什么关系*/
switch (Caffe::mode()) {
case Caffe::CPU:
Forward_cpu(bottom, top);
for (int top_id = 0; top_id < top.size(); ++top_id) {
if (!this->loss(top_id)) { continue; }
const int count = top[top_id]->count();/*计算blob的内存大小*/
const Dtype *data = top[top_id]->cpu_data();/*取出data指针*/
const Dtype *loss_weights = top[top_id]->cpu_diff();/*取出diff指针*/
loss += caffe_cpu_dot(count, data, loss_weights);/*点乘,根据导函数*diff=导数的公式得到本层的diff(即loss)*/
}
break;
case Caffe::GPU:
Forward_gpu(bottom, top);
#ifndef CPU_ONLY
for (int top_id = 0; top_id < top.size(); ++top_id) {
if (!this->loss(top_id)) { continue; }
const int count = top[top_id]->count();
const Dtype *data = top[top_id]->gpu_data();
const Dtype *loss_weights = top[top_id]->gpu_diff();
Dtype blob_loss = 0;
caffe_gpu_dot(count, data, loss_weights, &blob_loss);
loss += blob_loss;
}
#endif
break;
default:
LOG(FATAL) << "Unknown caffe mode.";
}
Unlock();
return loss;
}
template<typename Dtype>
inline void Layer<Dtype>::Backward(const vector<Blob<Dtype> *> &top,
const vector<bool> &propagate_down,
const vector<Blob<Dtype> *> &bottom) {
switch (Caffe::mode()) {
case Caffe::CPU:
Backward_cpu(top, propagate_down, bottom);
break;
case Caffe::GPU:
Backward_gpu(top, propagate_down, bottom);
break;
default:
LOG(FATAL) << "Unknown caffe mode.";
}
}
// Serialize LayerParameter to protocol buffer
template<typename Dtype>
void Layer<Dtype>::ToProto(LayerParameter *param, bool write_diff) {
param->Clear();
param->CopyFrom(layer_param_);
param->clear_blobs();
for (int i = 0; i < blobs_.size(); ++i) {
blobs_[i]->ToProto(param->add_blobs(), write_diff);
}
}
} // namespace caffe
#endif // CAFFE_LAYER_H_ |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html lang="en">
<head>
<meta name="copyright" content="Copyright (c) IBM Corporation and others 2000, 2011. This page is made available under license. For full details see the LEGAL in the documentation book that contains this page." >
<LINK REL="STYLESHEET" HREF="../../book.css" CHARSET="ISO-8859-1" TYPE="text/css">
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<title>Keys</title>
<script language="JavaScript" src="PLUGINS_ROOT/org.eclipse.help/livehelp.js" type="text/javascript"> </script>
</head>
<body>
<h1>Keys</h1>
<p>
The function of the keyboard can be extensively customized in Eclipse using the
<a class="command-link" href='javascript:executeCommand("org.eclipse.ui.window.preferences(preferencePageId=org.eclipse.ui.preferencePages.Keys)")'>
<img src="PLUGINS_ROOT/org.eclipse.help/command_link.png" alt="command link">
<strong>General > Keys</strong></a>
preference page. Within Eclipse, key strokes and key sequences are assigned to
invoke particular commands.
</p>
<h2>Key Strokes, Key Sequences, and Key Bindings</h2>
<p>
A 'key stroke' is the pressing of a key on the keyboard, while optionally holding down one
or more of these modifier keys: <code>Ctrl</code>, <code>Alt</code> (<code>Option</code> on the Macintosh), <code>Shift</code>, or
<code>Command</code> (only on the Macintosh.) For example, holding down <code>Ctrl</code> then
pressing <code>A</code> produces the key stroke <code>Ctrl+A</code>. The pressing of the modifier keys themselves
do not constitute key strokes.
</p>
<p>
A 'key sequence' is one or more key strokes. Traditionally, Emacs assigned two or three key stroke key sequences to particular
commands. For example, the normal key sequence assigned to <code>Close All</code> in emacs is <code>Ctrl+X Ctrl+C</code>.
To enter this key sequence, one presses the key stroke <code>Ctrl+X</code> followed by the key stroke <code>Ctrl+C</code>.
While Eclipse supports key sequences of arbitrary lengths, it is recommended
that keyboard shortcuts be four key strokes in length (or less).
</p>
<p>
A 'key binding' is the assignment of a key sequence to a command.
</p>
<h2>Schemes</h2>
<p>
A 'scheme' is a set of bindings. Eclipse includes two schemes:
</p>
<ul>
<li>Default</li>
<li>Emacs (extends Default)</li>
</ul>
<p>
The <em>Default</em> scheme contains a general set of bindings, in many cases recognizable
as traditional key sequences for well known commands. For instance, <code>Ctrl+A</code>
is assigned to <code>Select All</code>, and <code>Ctrl+S</code> is assigned to <code>Save</code>.
</p>
<p>
The <em>Emacs</em> scheme contains a set of key bindings familiar to users of Emacs.
For instance, <code>Ctrl+X H</code> is assigned to <code>Select All</code>, and <code>Ctrl+X S</code> is assigned to <code>Save</code>.
</p>
<p>
It is important to understand why the <em>Emacs</em> scheme says that it 'extends Default'. The <em>Emacs</em> scheme
is not a complete set of bindings like the <em>Default</em> scheme. Rather, it borrows from the <em>Default</em>
scheme where possible, only defining explicit Emacs-style bindings where they vary from the
<em>Default</em> scheme. Generally, only well known commands like <code>Select All</code>, <code>Save</code>, etc. have specific Emacs key sequences associated with them.
</p>
<p>Choose the scheme you are most comfortable with by changing the 'Scheme' setting on the
keys preference page. If you choose the <em>Default</em> scheme, all <em>Emacs</em> bindings are ignored. If you choose
the <em>Emacs</em> scheme, explicit Emacs-style key sequence assignments take precedence over any conflicting assignments in the <em>Default</em> scheme.
</p>
<h2>Contexts</h2>
<p>
Key bindings can vary based on the current context of Eclipse.
</p>
<p> Sometimes the active part might be a Java file editor, for instance, where
a different set of key sequence assignments may be more appropriate than if
the active part was an html file editor. As a specific example, typically <code>Ctrl+B</code>
is assigned to <code>Build</code> in a context such as Java file editing, while
<code>Ctrl+B</code> is assigned to <code>Make Text Bold</code> in a context
such as HTML file editing. This context is usually determined by the active
part, but it can be influenced by the active window or dialog as well. If the
active part does not choose a particular context, the workbench will set the
active context to <em>In Windows</em>.</p>
<p>Eclipse includes a number of different contexts. Some examples are: </p>
<ul>
<li>In Dialogs and Windows</li>
<li>In Windows (extends In Dialogs and Windows)</li>
<li>In Dialogs (extends In Dialogs and Windows)</li>
<li>Editing Text (extends In Windows)</li>
<li>Editing Java Source (extends Editing Text)</li>
<li>Debugging (extends In Windows)</li>
<li>Debugging Java (extends Debugging)</li>
<li>In Console</li>
<li>Editing Ant buildfiles<br>
<br>
</li>
</ul>
<p> Much like configurations, contexts can extend other contexts. For example,
the <em>Editing Java Source</em> context borrows key bindings from the <em>Editing Text</em>
context, which in turn borrows key bindings from the <em>In Windows</em> context.
</p>
<p>Note: It is not recommended to promote a key binding to a context which it
extends. For example, it is not recommended to move an <em>Editing Text</em> key
binding to the <em>In Dialogs and Windows</em> context. This may have unexpected
results.</p>
<p>It is possible for some key bindings to work in dialogs. Those key bindings
are assigned to the <em>In Dialogs and Windows</em> context. One example of such a
key binding is the key binding for "cut". It is possible to change these key
bindings. For example, it is possible to have Ctrl+X as cut in dialogs, but
Ctrl+W as cut in windows.</p>
<h2>Platform and Locale</h2>
<p>
Key bindings also vary by platform and locale. On the Macintosh platform, <code>Command+S</code> is assigned to <code>Save</code>, instead of the usual <code>Ctrl+S</code>. On Chinese locales (zh), <code>Alt+/</code> is assigned to <code>Content Assist</code>, instead of the usual <code>Ctrl+Space</code>.
</p>
<p>
The current platform and locale is determined when Eclipse starts, and does not vary over the course of an Eclipse instance.
</p>
<h2>Customizing Key bindings</h2>
<p> With multi-stroke key sequences, schemes, and contexts, there are a
lot of things to keep in mind when customizing key bindings. To make things
easier, all key customization is done on the
<a class="command-link" href='javascript:executeCommand("org.eclipse.ui.window.preferences(preferencePageId=org.eclipse.ui.preferencePages.Keys)")'>
<img src="PLUGINS_ROOT/org.eclipse.help/command_link.png" alt="command link">
<b>General > Keys</b></a> preference page.
</p>
<p> <img src="../../images/keys1.png" alt="Keys preference page the About command with no binding" >
</p>
<p>
In this example we want to bind <b>CTRL+5</b> to the About command. By default
the keys preference page will show you all possible keybindings. You can see
the About command listed in the Help category. You can bind the command
by putting focus in the Binding text box and pressing CTRL and 5 like you
would if you were executing the command.
</p>
<p> <img src="../../images/keys2.png" alt="Keys preference page the About command bound to CTRL+5" ></p>
<p>
When you type CTRL+5 you have created a binding for About. The right-most column
will indicate that this is a user binding by displaying a <b>U</b>. If there was
a conflict with another key, this column would also display a <b>C</b>. The binding
will be in the default context, "In Windows". You can now
use the When combo box to change the key binding context (for example, to move
this binding to "Editing Text").
</p>
<p>
If you wanted to add a second key binding to About, you can use the
<b>Copy Command</b> button to create a second command entry for you to bind
another key to. If you want to delete a binding, you can either use the
<b>Remove Binding</b> button or simply give focus to the Binding text box
and hit <b>Backspace</b>.
</p>
<h2>The Dynamic Nature of Key bindings</h2>
<p>
Key bindings are provided by plug-ins, and in Eclipse, plug-ins can be added or removed.
This can cause key bindings declared by these plug-ins to be added or removed.
Eclipse stores custom key bindings in a way to compensate for this.
Consider the example above where <code>CTRL+6</code> was assigned
to <code>About</code> in the <em>Default</em> scheme. Say you install a new
plug-in that assigns <code>CTRL+6</code> to a particular
command. Eclipse will preserve your assignment to <code>About</code>.
</p>
<h2>Conflict Resolution</h2>
<p> There are only a finite number of simple, common key strokes available to
assign to a multitude of commands. We have seen that scheme, context,
platform, and locale all partition key sequence assignments into domains where
they don't conflict with one another. Consider the case for <code>Ctrl+B</code>
above if contexts did not exist. One plug-in would assign <code>Ctrl+B</code>
to <code>Build</code>, the other plug-in would assign <code>Ctrl+B</code> to
<code>Make Bold Text</code>. How would Eclipse properly resolve this conflict?
</p>
<p> Though conflicts are drastically reduced by employing the above mechanisms,
they can still occur. Two plug-ins, independent of one another, could assign
the same key sequence to different commands with the same context, scheme,
platform, and locale. Consider if a plug-in assigned <code>Ctrl+F4</code> in
the <em>In Windows</em> context and <em>Default</em> scheme to one of its
commands. This directly conflicts with Eclipse assigning <code>Ctrl+F4</code>
to the close command in the same context and scheme. </p>
<p>
This is a conflict. It wouldn't be proper to invoke both commands, nor would it be proper to simply choose one of the two commands to receive the key stroke.
We pop up the Key Assist Dialog with the conflicting commands and allow the user
to select one. The Key Assist Dialog is the same dialog that displays
command choices for multiple key stroke key bindings. For example, if 2 commands
were bound to <b>F12</b> you might see:
</p>
<p> <img src="../../images/keys3.png" alt="Keys Assist dialog" ></p>
<p>
If the user sets a keybinding and creates a conflict, the conflicting bindings
will be displayed in the conflicts list. This can be used to navigate between
conflicting keybindings so that they can be changed.
</p>
<p> <img src="../../images/keys4.png" alt="Keys preference page conflict list" ></p>
<p> These types of conflicts can be resolved by explicitly assigning
the key sequence to one of the commands, or remove it from the other. </p>
<p>
Another type of conflict can be caused by multiple-key stroke key sequences. For example, in the <em>Emacs</em> scheme, there are many multiple-key stroke key sequences beginning with the key stroke <code>Ctrl+X</code>. <code>Ctrl+X K</code> is assigned to <code>Close</code>. <code>Ctrl+X H</code> is assigned to <code>Select All</code>.
</p>
<p>
As previously mentioned, the <em>Emacs</em> scheme borrows key bindings from the <em>Default</em> scheme. In the default scheme, <code>Ctrl+X</code> is assigned to <code>Cut</code>. Though the <em>Emacs</em> scheme doesn't explicitly redefine <code>Ctrl+X</code>, pressing <code>Ctrl+X</code> is required as part of many of its key bindings. In the <em>Emacs</em> scheme, when one presses <code>Ctrl+X</code>, one is half way to entering one of many possible assigned key sequences. One would not expect the <code>Cut</code> action to be invoked at this time.
</p>
<p>
For this type of conflict, the rule is that the <code>Ctrl+X</code> key sequence assigned to <code>Cut</code> would be ignored. Otherwise, it would not be possible to complete many of the key bindings in the <em>Emacs</em> configuration.
</p>
<p><img src="../../images/ngrelc.png" alt="Related concepts" ><br>
<a href="accessmain.htm">Accessibility features in Eclipse</a><br>
<a href="../../tasks/tkeybindings.htm">Changing the key bindings</a><br>
<a href="../help.htm">Help</a></p>
<p><img src="../../images/ngrelr.png" alt="Related references" ><br>
<a href="fontsandcolors.htm">Font and color settings in Eclipse</a></p>
</body>
</html> |
import React from 'react';
import PropTypes from 'prop-types';
// Components
import SVG from 'utils/svg-wrap';
import SectionBlock from '../../../containers/dapp/DexSwap/components/SectionBlock/SectionBlock';
import { Button, Input } from 'src/ui';
// Utils
import { getLang } from 'utils';
// Styles
import './SwapSettings.less';
function SwapSettings({
setSlippage,
slippageTolerance,
slippageNumbers,
setDeadline,
deadline,
showTitle,
onClose,
}) {
const transactionSpeeds = [
{ id: 0, title: getLang('dapp_swap_settings_speed_standart'), amount: 7 },
{ id: 2, title: getLang('dapp_swap_settings_speed_fast'), amount: 3 },
{ id: 3, title: getLang('dapp_swap_settings_speed_instant'), amount: 8 },
];
const [transactionSpeed, setTransactionSpeed] = React.useState(0);
const [slippageValue, setSlippageValue] = React.useState(slippageTolerance);
const [deadlineValue, setDeadlineValue] = React.useState(deadline);
const handleSlippage = (_value) => {
let value = Number(_value);
if (value < 0.1) value = 0.1;
if (value > 100) value = 100;
setSlippageValue(_value);
setSlippage(value);
window.localStorage.setItem('nrfx-slippage', value);
};
const handleDeadline = (_value) => {
let value = Number(_value);
if (value < 1) value = 1;
if (value > 60) value = 60;
setDeadlineValue(_value);
setDeadline(value);
};
return (
<div className="SwapSettings">
{showTitle && (
<h2>
<span>{getLang('dapp_swap_settings_title')}</span>
<span className="SwapSettings__close" onClick={onClose}>
<SVG src={require('src/asset/24px/close-large.svg')} />
</span>
</h2>
)}
<SectionBlock
title={getLang('dapp_swap_settings_speed_title')}
// title="Default Transaction Speed (GWEI)"
className="transaction-speed"
>
{transactionSpeeds.map((item, index) => {
return (
<Button
type="secondary-blue"
size="medium"
className={item.id === transactionSpeed ? 'active' : ''}
onClick={() => setTransactionSpeed(item.id)}
key={index}
>
{item.title} ({item.amount})
</Button>
);
})}
</SectionBlock>
<SectionBlock
title={
<>
<span>{getLang('dapp_swap_settings_slippage_title')}</span>
<SVG src={require('src/asset/icons/cabinet/question-icon.svg')} />
</>
}
className="slippage"
>
{slippageNumbers.map((number, key) => (
<Button
type="secondary-blue"
onClick={() => handleSlippage(number)}
size="medium"
key={key}
>
{number}%
</Button>
))}
<div className="Input__container">
<Input
type="number"
value={slippageValue}
onTextChange={(value) => handleSlippage(value)}
/>
<div className="Input__icon">%</div>
</div>
</SectionBlock>
<div className="deadline">
<div className="deadline__title">
{getLang('dapp_swap_settings_deadline_title')}
<SVG src={require('src/asset/icons/cabinet/question-icon.svg')} />
</div>
<div className="Input__container">
<Input
type="number"
value={deadlineValue}
onTextChange={(value) => handleDeadline(value)}
/>
<div className="Input__icon">
{getLang('dapp_global_minutes').toLowerCase()}
</div>
</div>
</div>
</div>
);
}
SwapSettings.propTypes = {
setSlippage: PropTypes.func,
slippageTolerance: PropTypes.number,
slippageNumbers: PropTypes.arrayOf(PropTypes.number),
setDeadline: PropTypes.func,
deadline: PropTypes.number,
showTitle: PropTypes.bool,
onClose: PropTypes.func,
};
SwapSettings.defaultProps = {
setSlippage: () => {},
slippageTolerance: 0,
slippageNumbers: [0.5],
setDeadline: () => {},
deadline: 0,
showTitle: false,
onClose: () => {},
};
export default SwapSettings; |
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package th.co.geniustree.springrelationshif.model;
import java.io.Serializable;
import java.util.List;
import java.util.Objects;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
/**
*
* @author Best
*/
@Entity
public class Teacher implements Serializable{
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Integer id;
private String name;
private String tel;
@ManyToMany
@JoinTable(name = "TEACHERANDSTUDENT")
private List<Student> students;
public List<Student> getStudents() {
return students;
}
public void setStudents(List<Student> students) {
this.students = students;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getTel() {
return tel;
}
public void setTel(String tel) {
this.tel = tel;
}
@Override
public int hashCode() {
int hash = 3;
hash = 37 * hash + Objects.hashCode(this.id);
return hash;
}
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final Teacher other = (Teacher) obj;
if (!Objects.equals(this.id, other.id)) {
return false;
}
return true;
}
} |
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import '../blocs/user_detail/user_detail_bloc.dart';
import '../blocs/user_detail/user_detail_event.dart';
import '../blocs/user_detail/user_detail_state.dart';
import '../repositories/user_repository.dart';
import '../utils/image_resource.dart';
class UserDetailScreen extends StatelessWidget {
final int userId;
UserDetailScreen({required this.userId});
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text('User Detail', style: TextStyle(fontFamily: FontResousrce.SF_Pro_Bold),)),
body: BlocProvider(
create: (context) => UserDetailBloc(UserRepository())..add(FetchUserDetail(userId)),
child: BlocBuilder<UserDetailBloc, UserDetailState>(
builder: (context, state) {
if (state is UserDetailLoading) {
return Center(child: CircularProgressIndicator());
} else if (state is UserDetailLoaded) {
final user = state.user;
return Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
CircleAvatar(
backgroundImage: NetworkImage(user.avatar),
radius: 50,
),
SizedBox(height: 20),
Text(
'${user.firstName} ${user.lastName}',
style: TextStyle(fontSize: 24,fontFamily: FontResousrce.SF_Pro_Bold),
),
Text(user.email, style: TextStyle(fontFamily: FontResousrce.SF_Pro_Regular),),
],
),
);
} else if (state is UserDetailError) {
return Center(child: Text('Failed to load user detail', style: TextStyle(fontFamily: FontResousrce.SF_Pro_Regular),));
}
return Container();
},
),
),
);
}
} |
<?php
namespace App\Exceptions;
use Exception;
class SlugIsAlreadyTakenException extends Exception
{
public function __construct(
private string $slug,
private string $savedFilePath,
private string $newFilePath)
{
parent::__construct("The slug {$slug} is already taken : see {$savedFilePath} and {$newFilePath}");
}
public function context(): array
{
return [
'slug' => $this->slug,
'savedFilePath' => $this->savedFilePath,
'newFilePath' => $this->newFilePath,
];
}
} |
import { AuthProvider } from "@/features/auth/contexts/AuthContext";
import {
AppConfigProvider,
useAppConfig,
} from "@/features/common/contexts/AppConfigContext";
import { LoadingProvider } from "@/features/companies/hooks/LoadingCompany";
import router from "@/router";
import theme from "@/theme";
import { ChakraProvider, ColorModeScript } from "@chakra-ui/react";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { ReactQueryDevtools } from "@tanstack/react-query-devtools";
import { PropsWithChildren } from "react";
import { RouterProvider } from "react-router-dom";
const queryClient = new QueryClient({
defaultOptions: {
queries: {
refetchOnWindowFocus: false,
retry: false,
},
},
});
const ChakraWrapper: React.FC<PropsWithChildren> = ({ children }) => {
const { colors } = useAppConfig();
return (
<>
<ColorModeScript initialColorMode={theme.config.initialColorMode} />
<ChakraProvider
theme={{
...theme,
colors: {
...theme.colors,
primary: { ...theme.colors.primary, ...(colors.primary || {}) },
gray: { ...theme.colors.gray, ...(colors.gray || {}) },
},
}}
resetCSS
>
{children}
</ChakraProvider>
</>
);
};
function App() {
return (
<QueryClientProvider client={queryClient}>
<LoadingProvider>
<AppConfigProvider>
<AuthProvider>
<ChakraWrapper>
<RouterProvider router={router} />
</ChakraWrapper>
</AuthProvider>
</AppConfigProvider>
<ReactQueryDevtools initialIsOpen={false} />
</LoadingProvider>
</QueryClientProvider>
);
}
export default App; |
package com.example.sales.payload.requests
import com.example.sales.model.enums.CommunicationType
import com.example.sales.model.enums.DecisionType
import jakarta.persistence.*
import jakarta.validation.constraints.NotNull
import java.time.LocalDate
data class OfferedPromotionRequest(
@field:NotNull(message = "Customer id cannot be blank")
var customerId: Long,
@field:NotNull(message = "Promotion id cannot be null")
var promotionId: Long,
@field:NotNull(message = "Communication type cannot be empty")
@Enumerated(EnumType.STRING)
var communicationType: CommunicationType,
@Enumerated(EnumType.STRING)
@field:NotNull(message = "Decision type cannot be blank")
var decision: DecisionType,
var decisionDate: LocalDate? = null
){
init {
if (decision == DecisionType.ACCEPTED || decision == DecisionType.REJECTED) {
decisionDate = LocalDate.now()
}
}
} |
import { Schema, model } from "mongoose";
import bcrypt from "bcryptjs";
import jwt from "jsonwebtoken";
import { IUser } from "../types/users.types";
const usersSchema = new Schema<IUser>(
{
email: {
type: String,
required: true,
unique: true,
trim: true,
lowercase: true,
},
fullName: {
type: String,
required: true,
trim: true,
},
phone: {
type: String,
trim: true,
},
password: {
type: String,
required: true,
trim: true,
},
emailVerification: {
type: Boolean,
default: false,
required: true,
},
phoneVerification: {
type: Boolean,
default: false,
required: true,
},
isDeleted: {
type: Boolean,
default: false,
required: true,
},
isActive: {
type: Boolean,
default: true,
required: true,
},
},
{
id: false,
timestamps: true,
versionKey: false,
}
);
usersSchema.statics.encryptPassword = async (password) => {
const salt = await bcrypt.genSalt(12);
const passHashed = await bcrypt.hash(password, salt);
return passHashed;
};
usersSchema.statics.generateToken = async (payload, expireInHours) => {
const token = await jwt.sign(payload, process.env.SECRET_FOR_TOKEN || "", {
expiresIn: expireInHours * 60 * 60,
});
return token;
};
usersSchema.statics.comparePassword = async (password, receivedPassword) => {
return await bcrypt.compare(password, receivedPassword);
};
usersSchema.set("toObject", {
virtuals: true,
transform: function (doc, ret) {
delete ret.password;
},
});
usersSchema.set("toJSON", {
virtuals: true,
transform: function (doc, ret) {
delete ret.password;
},
});
export default model<IUser>("Users", usersSchema); |
import { Component, ViewChild, ElementRef, AfterViewInit } from '@angular/core';
import * as THREE from 'three-full';
import * as TWEEN from '@tweenjs/tween.js';
import * as D3 from 'd3';
import { PolyCube } from '../../classes/polycube.interface';
import { GeoCube } from '../../classes/geocube';
import { SetCube } from '../../classes/setcube';
import { NetCube } from '../../classes/netcube';
import { Camera } from '../../classes/camera';
import { GoogleDriveProvider } from '../../services/google.drive.service';
import { GraphPositionService } from '../../services/graph.position.service';
import { VIEW_STATES } from '../../classes/viewStates';
import { GUI } from '../../classes/gui';
import { DataManager } from '../../classes/datamanager';
import { CUBE_CONFIG } from '../../cube.config';
import * as moment from'moment';
@Component({
selector: 'app-cube',
templateUrl: './cube.component.html',
styleUrls: ['./cube.component.css', '../../bootstrap.min.css']
})
/**
* PolyCube main controller
* - loads and parses data
* - initializes threejs scene
* - initializes cube components
*/
export class CubeComponent implements AfterViewInit {
// Canvases
@ViewChild('webGLCanvas') webGLContainer: ElementRef;
@ViewChild('cssCanvas') cssContainer: ElementRef;
// spreadsheet input field
@ViewChild('spreadsheetInput') spreadsheetId: ElementRef;
// detail panel
@ViewChild('modal') modalContainer: ElementRef;
@ViewChild('img') imgContainer: ElementRef;
@ViewChild('caption') captionContainer: ElementRef;
// toggle buttons for cubes
@ViewChild('geobtn') gBtn: ElementRef;
@ViewChild('setbtn') sBtn: ElementRef;
@ViewChild('netbtn') nBtn: ElementRef;
// tooltip html element for d3
@ViewChild('tooltip') tooltip: ElementRef;
title = 'PolyCube';
// processing & updating
processingChange: boolean = true;
processingMessage: string = 'Loading dataset...';
previewPanel: boolean = false;
previewItem: any;
currentlySelectedCategory: string;
currentlySelectedDateExtent: Array<Date>;
// ThreeJS things
gui: GUI;
webGLScene: THREE.Scene;
cssScene: THREE.Scene;
camera: THREE.Camera; //PerspectiveCamera or OrthographicCamera;
perspectiveCamera: THREE.PerspectiveCamera;
orthographicCamera: THREE.OrthographicCamera;
light: THREE.Light;
controls: THREE.OrbitControls;
webGLRenderer: THREE.WebGLRenderer;
css3DRenderer: any;
camToSave: any;
// Cubes
gCube: PolyCube; sCube: PolyCube; nCube: PolyCube;
// set default view to display all cubes
currentViewState: VIEW_STATES = VIEW_STATES.POLY_CUBE;
// data management
loadingDataset: boolean = true;
dataLoaded: boolean = false;
// error management
errorOccurred: boolean = false;
errorMessage: string;
// animation duration
duration: number;
// frontend things
categoriesAndColors: Map<string, string>;
showColorCodingLegend: boolean = true;
categories: Array<string>;
// inject google
constructor(private google: GoogleDriveProvider, private gps: GraphPositionService, private dataManager: DataManager, private compRef: ElementRef) {
this.previewItem = null;
this.categories = new Array<string>();
this.categoriesAndColors = new Map<string, string>();
this.duration = CUBE_CONFIG.DURATION ? CUBE_CONFIG.DURATION : 2000;
this.currentlySelectedCategory = '';
this.currentlySelectedDateExtent = new Array<Date>();
}
/**
* Lifecycle hook called when the DOM is initialized
*/
ngAfterViewInit() {
// set initial classses
this.gBtn.nativeElement.className = 'btn btn-secondary';
this.sBtn.nativeElement.className = 'btn btn-secondary';
this.nBtn.nativeElement.className = 'btn btn-secondary';
this.initDataset();
}
/**
* Initializes the THREEJS scene
* - creating renderers
* - creating camera
* - creating scenes
* - creating controls
* - creating lighting
* - call the animation loop
*/
initScene = () => {
this.webGLScene = new THREE.Scene();
this.cssScene = new THREE.Scene();
const WIDTH = this.webGLContainer.nativeElement.offsetWidth;
const HEIGHT = this.webGLContainer.nativeElement.offsetHeight;
this.webGLRenderer = new THREE.WebGLRenderer({ canvas: this.webGLContainer.nativeElement as HTMLCanvasElement, alpha: true });
this.webGLRenderer.setSize(WIDTH, HEIGHT);
this.webGLRenderer.setClearColor(0xffffff, 0);
this.css3DRenderer = new THREE.CSS3DRenderer();
this.css3DRenderer.setSize(WIDTH, HEIGHT);
this.cssContainer.nativeElement.appendChild(this.css3DRenderer.domElement);
this.orthographicCamera = new THREE.OrthographicCamera(WIDTH/-2, WIDTH/2, HEIGHT/2, HEIGHT/-2, -10000, 10000);
this.perspectiveCamera = new THREE.PerspectiveCamera(20, WIDTH / HEIGHT, 1, 100000);
this.camera = this.perspectiveCamera;
// this.camera = this.orthographicCamera;
this.camera.up.set(0, 1, 0);
// this.camera.position.set(200, 200, 4800); // for orthocamera
this.camera.position.set(803, 912, 4755)
this.camera.lookAt(this.webGLScene.position.x, this.webGLScene.position.y, this.webGLScene.position.z);
this.controls = new THREE.OrbitControls(this.camera, this.webGLRenderer.domElement);
this.controls.target = new THREE.Vector3(1000, 0, 0);
this.controls.enableZoom = true;
this.controls.zoomSpeed = 1.2;
//hold initial camera and position values
this.camToSave = {};
this.camToSave.position = this.camera.position.clone();
this.camToSave.rotation = this.camera.rotation.clone();
this.camToSave.controlCenter = this.controls.target.clone();
}
/**
* Initializes the component with the default (Cushman) dataset
* Once data is loaded initializes the scene, cubes, and GUI
*/
initDataset(): void {
this.loadingDataset = true;
let _id = CUBE_CONFIG.DATA_SET.id; // Cushman dataset ID
let dataset_name = CUBE_CONFIG.DATA_SET.name;
// perform request to get spreadsheet json
// parse it when done and pass to datamanager
this.google.load(_id).then((success: any) => {
// only overwrite if we have no data in the data manager
// otherwise we probably got data from another endpoint
if(!this.dataManager.data) {
console.log('no data init cushman')
this.dataManager.data = success;
this.gps.defaultDataSet();
}
this.processingChange = false;
this.processingMessage = '';
this.loadingDataset = false;
this.dataLoaded = true;
// default date extent for filtering
this.currentlySelectedDateExtent.push(this.dataManager.getMinDate());
this.currentlySelectedDateExtent.push(this.dataManager.getMaxDate());
this.categories = Array.from(this.dataManager.categories.keys());
this.categoriesAndColors = this.dataManager.categories;
this.initScene();
this.initCubes();
this.initGUI();
this.addEventListeners();
this.animate();
this.defaultSetup(dataset_name); // just the default setup
});
}
/**
* function for default cube inital setup
*/
defaultSetup(dataset_id): void {
this.nCube.updateTime('absolute');
if(dataset_id=="Cushman"){
this.updateNodeColor('categorical');
}
else{//IMDB or others
this.updateNodeColor('monochrome');
}
}
/**
* Updates the data set with a new dataset
* We get the ID from the text input
*/
updateDataset(): void {
this.loadingDataset = true;
let id = this.spreadsheetId.nativeElement.value;
if(!id) {
console.error('No spredsheet id provided.');
this.loadingDataset = false;
this.errorOccurred = true;
this.errorMessage = 'No spreadsheet id provided.';
return;
}
this.google.load(id).then((success: any) => {
// only overwrite if we have no data in the data manager
// otherwise we probably got data from another endpoint
if(!this.dataManager.data) {
this.dataManager.data = success;
this.gps.defaultDataSet();
}
this.loadingDataset = false;
}).catch((err: any) => {
this.errorOccurred = true;
this.errorMessage = err;
});
}
/**
* Initializes the cubes, assigns the data manager and passes the
* webGL and css3D scenes so that the cubes can create their objects
* and append themselves to the scene
*/
initCubes = () => {
// initialize cubes
this.gCube = new GeoCube(this.dataManager, this.camera, this.webGLScene, this.cssScene);
this.sCube = new SetCube(this.dataManager, this.camera, this.webGLScene, this.cssScene);
this.nCube = new NetCube(this.dataManager, this.camera, this.webGLScene, this.cssScene);
// setup gps service
(this.nCube as NetCube).setGraphPositionService(this.gps);
};
/**
* This function is called when the dataset has been changed
* to notify the cubes that they should update the dataset
* and re-initialize themselves
*/
updateCubes = () => {
this.gCube.updateData();
this.sCube.updateData();
this.nCube.updateData();
}
addEventListeners = () => {
this.webGLContainer.nativeElement.addEventListener('click', ($event) => {
$event.preventDefault();
let foundItem = this.getClickedItem($event);
if(foundItem) {
this.previewItem = {
title: `Picture #${foundItem.id}`, // foundItem.title is empty so just use ID
id: foundItem.id,
mediaURL: foundItem.external_url,
date: moment(foundItem.date_time).format('DD-MM-YYYY'),
location: foundItem.location_name,
description: foundItem.description,
externalURL: foundItem.media_url,
related: foundItem.target_nodes,
categories: [foundItem.category_1, foundItem.category_2, foundItem.category_3, foundItem.category_4, foundItem.category_5],
network_degree_in: foundItem.network_degree_in,
network_degree_out: foundItem.network_degree_out,
network_degree_overall: foundItem.network_degree_overall,
};
this.openPreview();
} else {
this.previewItem = null;
this.tooltip.nativeElement.style.display = 'none';
this.tooltip.nativeElement.style.opacity = '0';
this.closePreview();
}
});
}
getClickedItem = ($event) =>{
// look for item across cubes
let foundItem = this.gCube.onClick($event, this.tooltip, this.webGLContainer.nativeElement );
if(!foundItem) foundItem = this.sCube.onClick($event, this.tooltip, this.webGLContainer.nativeElement );
if(!foundItem) foundItem = this.nCube.onClick($event, this.tooltip, this.webGLContainer.nativeElement );
// if item clicked highlight accross cubes
if(foundItem) {
this.gCube.highlightObject(foundItem.id);
this.sCube.highlightObject(foundItem.id);
this.nCube.highlightObject(foundItem.id);
}
return foundItem;
}
/**
* Open / Close the preview panel (details on the side)
*/
openPreview(): void {
this.previewPanel = true;
}
closePreview(): void {
this.previewPanel = false;
}
/**
* Return details about related nodes
* @param id Node ID
*/
getRelatedNode(id: number): any {
let found = this.dataManager.data.find((d: any) => {
return d.id === id;
});
return found;
}
selectNode(id: number): void {
let selected = this.dataManager.data.find((d: any) => {
return d.id === id;
});
// update this.preview
this.previewItem = {
title: `Picture #${selected.id}`, // selected.title is empty so just use ID
id: selected.id,
mediaURL: selected.external_url,
date: moment(selected.date_time).format('DD-MM-YYYY'),
related: selected.target_nodes,
location: selected.location_name,
description: selected.description,
externalURL: selected.media_url,
categories: [selected.category_1, selected.category_2, selected.category_3, selected.category_4, selected.category_5]
};
// highlight in cubes
this.gCube.highlightObject(selected.id);
this.sCube.highlightObject(selected.id);
this.nCube.highlightObject(selected.id);
}
getPrevious(): void {
this.processingChange = true;
this.processingMessage = 'Loading image...';
let currentItem = this.previewItem;
let foundIdx = this.dataManager.data.map((d: any) => { return d.id; }).indexOf(currentItem.id);
let foundItem = this.dataManager.data[(foundIdx - 1) % this.dataManager.data.length];
this.previewItem = {
title: `Picture #${foundItem.id}`, // foundItem.title is empty so just use ID
id: foundItem.id,
mediaURL: foundItem.external_url,
date: moment(foundItem.date_time).format('DD-MM-YYYY'),
location: foundItem.location_name,
related: foundItem.target_nodes,
description: foundItem.description,
externalURL: foundItem.media_url,
categories: [foundItem.category_1, foundItem.category_2, foundItem.category_3, foundItem.category_4, foundItem.category_5]
};
this.imgContainer.nativeElement.src = this.previewItem.mediaURL;
this.captionContainer.nativeElement.innerHTML = `${this.previewItem.description} , ${this.previewItem.date}`;
}
getNext(): void {
this.processingChange = true;
this.processingMessage = 'Loading image...';
let currentItem = this.previewItem;
let foundIdx = this.dataManager.data.map((d: any) => { return d.id; }).indexOf(currentItem.id);
let foundItem = this.dataManager.data[(foundIdx + 1) % this.dataManager.data.length];
this.previewItem = {
title: `Picture #${foundItem.id}`, // foundItem.title is empty so just use ID
id: foundItem.id,
mediaURL: foundItem.external_url,
date: moment(foundItem.date_time).format('DD-MM-YYYY'),
related: foundItem.target_nodes,
location: foundItem.location_name,
description: foundItem.description,
externalURL: foundItem.media_url,
categories: [foundItem.category_1, foundItem.category_2, foundItem.category_3, foundItem.category_4, foundItem.category_5]
};
this.imgContainer.nativeElement.src = this.previewItem.mediaURL;
this.captionContainer.nativeElement.innerHTML = `${this.previewItem.description} , ${this.previewItem.date}`;
}
imageLoaded(): void {
this.processingChange = false;
this.processingMessage = '';
console.log('image loaded');
}
updateNodeColor(nodeColor){
this.showColorCodingLegend = nodeColor !== 'categorical' ? false : true;
this.gCube.updateNodeColor(nodeColor);
this.sCube.updateNodeColor(nodeColor);
this.nCube.updateNodeColor(nodeColor);
//update timeline color
nodeColor == 'temporal' ? this.displayTimelineColor(true) : this.displayTimelineColor(false);
}
/**
* Initializes the GUI elements including button event listeners
*/
initGUI = () => {
this.gui = new GUI();
// general settings
this.processingMessage = 'Processing new configuration...';
this.gui.pCubeConfigEmitter.on('processing', (change: any) => {
this.processingChange = change;
});
this.gui.pCubeConfigEmitter.on('change', (change: any) => {
if(change.dataSet) {
this.initDataset();
}
if(change.backgroundColor) {
this.compRef.nativeElement.ownerDocument.body.style.backgroundColor = change.backgroundColor;
}
if(change.time) {
this.gCube.updateTime(change.time);
// this.sCube.updateTime(change.time);
this.nCube.updateTime(change.time);
}
if(change.numSlices) {
this.dataManager.numSlices = change.numSlices;
this.gCube.updateNumSlices(change.numSlices);
this.sCube.updateNumSlices(change.numSlices);
this.nCube.updateNumSlices(change.numSlices);
// this.processingChange = false;
}
if(change.nodeSize) {
this.gCube.updateNodeSize(change.nodeSize);
this.sCube.updateNodeSize(change.nodeSize);
this.nCube.updateNodeSize(change.nodeSize);
}
if(change.nodeColor) {
this.updateNodeColor(change.nodeColor);
}
// camera switch
if(change.cameraType) {
if(change.cameraType === 'Perspective'){
this.usePerspectiveCamera();
} else if (change.cameraType === 'Orthographic'){
this.useOrthographicCamera();
}
}
// reset scene
if(change.reset) {
this.resetScene()
}
// we should be done processing changes
this.processingChange = false;
});
// geocube settings
this.gui.gCubeConfigEmitter.on('change', (change: any) => {
if(change.jitter) {
(this.gCube as GeoCube).updateJitter(change.jitter)
}
});
// setcube settings
this.gui.sCubeConfigEmitter.on('change', (change: any) => {
if(change.sLayout) {
(this.sCube as SetCube).updateLayout(change.sLayout)
}
//hull button
if(change.hull == true){
if(!(this.sCube as SetCube).getHullState()){
(this.sCube as SetCube).drawHull();
}else{
(this.sCube as SetCube).showHull();
}
}else{
(this.sCube as SetCube).hideHull()
}
});
// netcube settings
this.gui.nCubeConfigEmitter.on('change', (change: any) => {
if(change.nNodeSize) {
(this.nCube as NetCube).changeNodeSizeEncode(change.nNodeSize)
}
if(change.nCharge) {
(this.nCube as NetCube).changeChargeFactor(change.nCharge)
}
// hide and show links button
if(change.nLinks == false) {
(this.nCube as NetCube).hideAllLinks();
}else{
(this.nCube as NetCube).showCubeLinks_absolute();
}
});
// button event listeners
this.gui.geoBtn.addEventListener('click', () => { this.setCubeView(VIEW_STATES.GEO_CUBE); });
this.gui.setBtn.addEventListener('click', () => { this.setCubeView(VIEW_STATES.SET_CUBE); });
this.gui.netBtn.addEventListener('click', () => { this.setCubeView(VIEW_STATES.NET_CUBE); });
this.gui.stcBtn.addEventListener('click', () => {
this.updateNodeColor('categorical');
this.gCube.transitionSTC();
this.sCube.transitionSTC();
this.nCube.transitionSTC();
//rotate camera to STC
this.transitionSTCCamera();
});
this.gui.jpBtn.addEventListener('click', () => {
this.updateNodeColor('categorical');
this.gCube.transitionJP();
this.sCube.transitionJP();
this.nCube.transitionJP();
//rotate camera to JP
this.transitionJPCamera();
});
this.gui.siBtn.addEventListener('click', () => {
this.updateNodeColor('temporal');
this.gCube.transitionSI();
this.sCube.transitionSI();
this.nCube.transitionSI();
//rotate camera to SI
this.transitionSICamera();
});
}
/**
* Rotate Camera to SI view
*/
transitionSICamera(): void{
//update timeline color as true
this.displayTimelineColor(true);
this.restoreCamera(this.camToSave.position, this.camToSave.rotation, this.camToSave.controlCenter);
//stop rotation
this.controls.enableRotate = false;
let duration = 1000;
let targetVector = new THREE.Vector3();
let tweenPos = new TWEEN.Tween(this.camera.position);
targetVector.set(1000, 4826, 428);
tweenPos.to(targetVector, duration);
tweenPos.start().onComplete(() => {
this.controls.update();
this.camera.lookAt(targetVector);
});
this.camera.zoom = 1;
this.camera.updateProjectionMatrix();
}
/**
* Rotate Camera to STC view
*/
transitionSTCCamera(): void{
//update timeline color as false
this.displayTimelineColor(false)
this.restoreCamera(this.camToSave.position, this.camToSave.rotation, this.camToSave.controlCenter);
//allow rotation
this.controls.enableRotate = true;
let duration = 1000;
let targetVector = new THREE.Vector3();
let tweenPos = new TWEEN.Tween(this.camera.position);
targetVector.set(800, 912, 4755);
tweenPos.to(targetVector, duration);
tweenPos.start().onComplete(() => {
this.controls.update();
this.camera.lookAt(targetVector);
});
this.camera.zoom = 1;
this.camera.updateProjectionMatrix();
}
transitionJPCamera(): void {
// update timeline color
this.displayTimelineColor(false);
this.restoreCamera(this.camToSave.position, this.camToSave.rotation, this.camToSave.controlCenter);
// stop rotation
this.controls.enableRotate = false;
let duration = 1000;
let targetVector = new THREE.Vector3();
let targetVector2 = new THREE.Vector3();
let tweenPos = new TWEEN.Tween(this.camera.position);
let tweenRot = new TWEEN.Tween(this.camera.position);
// targetVector.set(1000, 4826, 428);
targetVector.set(1000, 10826, 428);
tweenPos.to(targetVector, duration);
tweenPos.start().onComplete(() => {
this.controls.update();
this.camera.lookAt(targetVector);
//
this.camera.zoom = 0.7;
this.camera.updateProjectionMatrix();
targetVector2.set(644.2056736616696, 9000.63192337427, -5.384615481310194);
tweenRot.to(targetVector2, 2000);
tweenRot.start().onComplete(() => {
this.camera.lookAt(targetVector2);
this.controls.update();
});
});
}
resetScene(): void {
this.restoreCamera(this.camToSave.position, this.camToSave.rotation, this.camToSave.controlCenter);
this.gCube.transitionSTC();
this.sCube.transitionSTC();
this.nCube.transitionSTC();
//rotate camera to STC
this.transitionSTCCamera();
}
restoreCamera(position:THREE.Vector3, rotation: THREE.Euler, controlCenter: THREE.Vector3) {
let targetVector = new THREE.Vector3();
let targetVector2 = new THREE.Vector3();
let tweenPos = new TWEEN.Tween(this.camera.position);
let tweenRot = new TWEEN.Tween(this.camera.position);
// this.camera.position.set(position.x, position.y, position.z);
targetVector.set(position.x, position.y, position.z);
tweenPos.to(targetVector, 1000);
tweenPos.start().onComplete(() => {
this.controls.target.set(controlCenter.x, controlCenter.y, controlCenter.z);
this.controls.update();
});
// this.camera.rotation.set(rotation.x, rotation.y, rotation.z);
targetVector2.set(rotation.x, rotation.y, rotation.z);
tweenRot.to(targetVector2, 1000);
tweenRot.start().onComplete(() => {
this.controls.target.set(controlCenter.x, controlCenter.y, controlCenter.z);
this.controls.update();
});
// this.controls.target.set(controlCenter.x, controlCenter.y, controlCenter.z);
// this.controls.update();
}
/**
* This function is used to update brush timeline color
*/
displayTimelineColor(visible: boolean):void{
if(visible){
// D3.select('#timeLegend').classed('hide', false)
D3.select('#timeLegend').style('display','block')
} else{
// D3.select('#timeLegend').classed('hide', true)
D3.select('#timeLegend').style('display','none')
}
}
usePerspectiveCamera(): void {
let cameraPosition = this.orthographicCamera.position.clone();
let cameraZoom = this.orthographicCamera.zoom;
this.camera = this.perspectiveCamera;
this.camera.zoom = cameraZoom;
this.camera.position.copy(cameraPosition);
this.camera.updateProjectionMatrix();
this.controls.object = this.camera;
}
useOrthographicCamera(): void {
let cameraPosition = this.perspectiveCamera.position.clone();
let cameraZoom = this.perspectiveCamera.zoom;
this.camera = this.orthographicCamera;
this.camera.zoom = cameraZoom;
this.camera.position.copy(cameraPosition);
this.camera.updateProjectionMatrix();
this.controls.object = this.camera;
}
/**
* Clears the current (webGL) scene from all cube groups
*/
removeAllCubeViews = (): void => {
this.gCube.hideCube();
this.sCube.hideCube();
this.nCube.hideCube();
}
/**
* This function is used to position the camera
*/
positionCamera = (): void => {
let targetVector = new THREE.Vector3();
let camLookAt = new THREE.Vector3(0, 0, -1);
let cubePos: THREE.Vector3;
let tweenPos = new TWEEN.Tween(this.camera.position);
let tweenLookAt = new TWEEN.Tween(camLookAt.applyQuaternion(this.camera.quaternion));
switch (this.currentViewState) {
case 'GEO_CUBE':
cubePos = this.gCube.getCubePosition();
break;
case 'SET_CUBE':
cubePos = this.sCube.getCubePosition();
break;
case 'NET_CUBE':
cubePos = this.nCube.getCubePosition();
break;
case 'POLY_CUBE':
cubePos = this.sCube.getCubePosition();
break;
default: break;
}
let currentXPos = 0;
if(this.gCube.cubeToggle) {
// pos gCube
this.gCube.cubeGroupGL.position.set(currentXPos, 0, 0);
this.gCube.cubeGroupCSS.position.set(currentXPos, 0, 0);
currentXPos += CUBE_CONFIG.WIDTH + CUBE_CONFIG.GUTTER;
}
if(this.sCube.cubeToggle) {
this.sCube.cubeGroupGL.position.set(currentXPos, 0, 0);
this.sCube.cubeGroupCSS.position.set(currentXPos, 0, 0);
currentXPos += CUBE_CONFIG.WIDTH + CUBE_CONFIG.GUTTER;
}
if(this.nCube) {
this.nCube.cubeGroupGL.position.set(currentXPos, 0, 0);
this.nCube.cubeGroupCSS.position.set(currentXPos, 0, 0);
}
// targetVector.set(cubePos.x + CUBE_CONFIG.WIDTH/2, this.camera.position.y, this.camera.position.z);
// tweenPos.to(targetVector, 250);
// tweenLookAt.to(cubePos, 250);
// tweenPos.start().onComplete(() => {
// tweenLookAt.start().onUpdate((target: THREE.Vector3) => {
// this.camera.lookAt(target);
// this.controls.update();
// });
// });
};
closePicture(): void {
this.modalContainer.nativeElement.style.display = 'none';
this.imgContainer.nativeElement.style.display = 'none';
this.imgContainer.nativeElement.src = '';
this.captionContainer.nativeElement.innerHTML = '';
}
openPicture(url: string, desc: string, date: string): void {
this.modalContainer.nativeElement.style.display = 'block';
this.imgContainer.nativeElement.style.display = 'block';
this.imgContainer.nativeElement.src = url;
this.captionContainer.nativeElement.innerHTML = `${desc} , ${date}`;
}
/**
* Updates which cubes are shown based on user selection
*/
updateCubesView = (): void => {
this.removeAllCubeViews();
this.gCube.updateView(this.currentViewState);
this.sCube.updateView(this.currentViewState);
this.nCube.updateView(this.currentViewState);
this.positionCamera();
};
/**
* Starts the animation (rendering) loop
*/
animate = () => {
requestAnimationFrame(this.animate);
this.render();
}
/**
* Function called each iteration of the rendering loop
* Renders the scene from the cameras PoV
*/
render() {
TWEEN.update();
this.controls.update();
this.webGLRenderer.render(this.webGLScene, this.camera);
this.css3DRenderer.render(this.cssScene, this.camera);
}
/**
* Updates the current view with the users section
* @param view - string: user selection stating which cube should be displayed
*/
setCubeView(view: string): void {
switch (view) {
case 'GEO_CUBE':
this.gCube.toggleDisplayCube();
this.gBtn.nativeElement.className = this.gCube.cubeToggle ? 'btn btn-secondary' : 'btn btn-outline-secondary';
break;
case 'SET_CUBE':
this.sCube.toggleDisplayCube();
this.sBtn.nativeElement.className = this.sCube.cubeToggle ? 'btn btn-secondary' : 'btn btn-outline-secondary';
break;
case 'NET_CUBE':
this.nCube.toggleDisplayCube();
this.nBtn.nativeElement.className = this.nCube.cubeToggle ? 'btn btn-secondary' : 'btn btn-outline-secondary';
break;
// case 'POLY_CUBE': this.currentViewState = VIEW_STATES.POLY_CUBE; break; -- doesn't exist
default:
return;
}
this.updateCubesView();
}
filterDataWithTimeSlider($event: any): void {
this.currentlySelectedDateExtent[0] = $event[0];
this.currentlySelectedDateExtent[1] = $event[1];
this.applyFilter();
}
clearCategoryFilter(): void {
this.currentlySelectedCategory = "";
this.applyFilter();
}
filterDataByCategory(category: string): void {
this.currentlySelectedCategory = category;
this.applyFilter();
}
applyFilter(): void {
this.gCube.filterData(this.currentlySelectedCategory, this.currentlySelectedDateExtent[0], this.currentlySelectedDateExtent[1]);
this.sCube.filterData(this.currentlySelectedCategory, this.currentlySelectedDateExtent[0], this.currentlySelectedDateExtent[1]);
this.nCube.filterData(this.currentlySelectedCategory, this.currentlySelectedDateExtent[0], this.currentlySelectedDateExtent[1]);
}
formatDate(date: Date): string {
return moment(date).format('DD/MM/YYYY');
}
/**
*
*/
getMinDate(): Date { return this.dataManager.getMinDate(); }
/**
*
*/
getMaxDate(): Date { return this.dataManager.getMaxDate(); }
/**
*
*/
getWindowInnerHeight(): number { return window.innerHeight; }
} |
import express from "express";
import cors from "cors";
import { errorHandler } from "./middlewares/error-handler";
import 'express-async-errors';
import authenticate from "./middlewares/authenticate";
import userRouter from "./user/router";
import profileRouter from "./profile/router";
import postRouter from "./post/router";
import likeRouter from "./like/router";
import commentRouter from "./comment/router";
import followRouter from "./follow/router";
const PORT = 3002;
const app: express.Application = express();
app.use(cors())
app.use(express.json());
app.use('/profile-picture', express.static('profile-pictures'));
app.use('/post-image', express.static('post-images'));
app.use('/user', userRouter);
app.use('/profile', profileRouter);
app.use('/post', postRouter);
app.use('/like', likeRouter);
app.use('/comment', commentRouter);
app.use('/follow', followRouter);
app.use(errorHandler);
app.listen(PORT, () => {
console.log(`Server online on port ${PORT}`)
}) |
## **itertools.permutations()**
### Problem
itertools.permutations(iterable[, r])
This tool returns successive \( r \) length permutations of elements in an iterable.
If \( r \) is not specified or is None, then \( r \) defaults to the length of the iterable, and all possible full-length permutations are generated.
Permutations are printed in a lexicographic sorted order. So, if the input iterable is sorted, the permutation tuples will be produced in a sorted order.
#### **Task**
You are given a string \( S \).
Your task is to print all possible permutations of size \( k \) of the string in lexicographically sorted order.
#### **Input Format**
A single line containing the space separated string \( S \) and the integer value \( k \).
#### **Constraints**
* \( 0 < k \leq \text{len}(S) \)
* The string contains only UPPERCASE characters.
#### **Output Format**
Print the permutations of the string \( S \) on separate lines.
#### **Sample Input**
```
HACK 2
```
#### **Sample Output**
```
AC
AH
AK
CA
CH
CK
HA
HC
HK
KA
KC
KH
```
#### **Note**
All possible permutation of string size \( k \) for the string \( S \) are:
```
AC, AH, AK, CA, CH, CK, HA, HC, HK, KA, KC, KH
```
## Input from ChatGPT
None - referred to own previous work for `split` and `join` syntax |
#include "binary_trees.h"
/**
* binary_tree_size - count the size of the binary tree
* @tree: the tree to count in
* Return: the size
**/
size_t binary_tree_size(const binary_tree_t *tree)
{
size_t bt_size = 0;
if (tree == NULL)
return (0);
if (tree->left != NULL)
bt_size = bt_size + binary_tree_size(tree->left);
if (tree->right != NULL)
bt_size = bt_size + binary_tree_size(tree->right);
bt_size = bt_size + 1;
return (bt_size);
}
/**
* binary_tree_is_perfect - checks if the binary tree is perfect
* @tree: the tree to check in
* Return: 1 if ture 0 if fasle
*/
int binary_tree_is_perfect(const binary_tree_t *tree)
{
int left_size, right_size;
if (tree == NULL)
return (0);
left_size = binary_tree_size(tree->left);
right_size = binary_tree_size(tree->right);
if (left_size == right_size)
return (1);
return (0);
}
/**
* heap_check_father- check the root
* @father: pointes to the father
* @son:pointes to the son
*/
void heap_check_father(heap_t **son, heap_t **father)
{
heap_t *c_left, *c_right, *child = *son, *parent = *father;
c_right = (*son)->right, c_left = (*son)->left;
if (child->n > parent->n)
{
if (child->left)
child->left->parent = parent;
if (child->right)
child->right->parent = parent;
if (parent->left == child)
{
if (parent->right)
parent->right->parent = child;
child->right = parent->right;
child->left = parent;
}
else
{
parent->left->parent = child;
child->left = parent->left;
child->right = parent;
}
if (parent->parent)
{
if (parent->parent->left == parent)
parent->parent->left = child;
else
parent->parent->right = child;
}
else
{
*father = child;
}
child->parent = parent->parent;
parent->parent = child;
parent->left = c_left;
parent->right = c_right;
}
}
/**
* heap_insert- insert in the heap
* @root: pointer the root
* @value: the value to insert*
* Return: 1 on succes 0 if nothing done
*/
heap_t *heap_insert(heap_t **root, int value)
{
heap_t *newNode;
if ((*root) == NULL)
{
*root = binary_tree_node(NULL, value);
return (*root);
}
if (binary_tree_is_perfect(*root) || (!binary_tree_is_perfect((*root)->left)))
{
if ((*root)->left != NULL)
{
newNode = heap_insert(&((*root))->left, value);
heap_check_father(&((*root)->left), root);
return (newNode);
}
else
{
newNode = binary_tree_node(*root, value);
(*root)->left = newNode;
heap_check_father(&((*root)->left), root);
return (newNode);
}
}
else
{
if ((*root)->right != NULL)
{
newNode = heap_insert(&((*root)->right), value);
heap_check_father(&((*root)->right), root);
return (newNode);
}
else
{
newNode = binary_tree_node(*root, value);
(*root)->right = newNode;
heap_check_father(&((*root)->right), root);
return (newNode);
}
}
return (NULL);
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.