text stringlengths 184 4.48M |
|---|
<div class="row" style="margin-left:40px">
<div class="col">
<span class="rounded float-start">
<button class="btn btn-success btn-lg"
*ngIf = "editMode"
data-bs-toggle="modal" data-bs-target="#experienceModal"
(click)="clearExperience()"
>Añadir</button>
</span>
</div>
</div>
<ul>
<li *ngFor="let experience of experienceList" style="list-style-type: none;">
<div class="card-container">
<div class="card">
<div class="row align-items-center">
<div class="col-md-2 col-sm-12">
<img [src]="experience.img" class="logo" style="">
</div>
<div class="col-lg" style="justify-content:center">
<div class="card-item">
<h3>{{experience.company}}</h3>
<h5>{{experience.position}}</h5>
<h6><time>Desde {{experience.start}}</time> hasta <time>{{experience.end}}</time></h6>
<p>{{experience.ubication}}</p>
</div>
</div>
<div class="col-sm">
<div class="contenedor" *ngIf="editMode">
<i class="bi bi-pencil-fill"
style="margin-right: 10px"
data-bs-toggle="modal" data-bs-target="#experienceModal"
(click)="setExperience(experience)"
></i>
<i class="bi bi-trash-fill"
style="color:red"
(click) = "onDelete(experience)"
></i>
</div>
</div>
</div>
</div>
<div class="modal" id="experienceModal" >
<div class="modal-dialog" >
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="staticBackdropLabel">{{title}}</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body">
<form [formGroup]="formGroup"
(ngSubmit)="onSubmit(experiencia)"
>
<div class="form-group">
<label for="company">* Empresa</label>
<input class="form-control"
type="text"
formControlName="company"
placeholder="{{experiencia.company}}"
/>
<p *ngIf="Company?.hasError('required')" class="text-danger">Este campo es obligatorio</p>
</div>
<div class="form-group">
<label for="ubication">Ubicacion</label>
<input class="form-control"
type="text"
formControlName="ubication"
placeholder="{{experiencia.ubication}}"
/>
</div>
<div class="form-group">
<label for="position">Posición</label>
<input class="form-control"
type="text"
formControlName="position"
placeholder="{{experiencia.position}}"
/>
</div>
<div class="form-group">
<label for="start">Desde</label>
<input class="form-control"
type="text"
formControlName="start"
placeholder="{{experiencia.start}}"
/>
</div>
<div class="form-group">
<label for="end">Hasta</label>
<input class="form-control"
type="text"
formControlName="end"
placeholder="{{experiencia.end}}"
/>
</div>
<div class="form-group">
<label for="timeElapsed">Tiempo Estimado</label>
<input class="form-control"
type="text"
formControlName="timeElapsed"
placeholder="{{experiencia.timeElapsed}}"
/>
</div>
<div class="form-group">
<label for="img">Imagen</label>
<div class="input-group mb-3">
<input class="form-control"
type="file"
(change)="onSelectNewFile($event)"
/><div class="input-group-append">
<button class="btn btn-outline-danger" *ngIf="sizeImage" (click)="clearImage(experiencia.img)" type="button">Limpiar</button>
</div>
</div>
</div>
<p *ngIf="sizeImage" class="text-danger">El tamaño de la imagen es demasiado grande</p>
<div class="modal-footer">
<button type="submit" class="btn btn-success" [disabled]="!formGroup.valid || sizeImage" data-bs-dismiss="modal">Guardar</button>
<button type="button" class="btn btn-danger" data-bs-dismiss="modal">Salir</button>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
</li>
</ul> |
import base64
import io
import json
import logging
import aiohttp
from redbot.core import Config, commands
from tenacity import retry, stop_after_attempt, stop_after_delay, wait_random
from aiuser.response.image.generator import ImageGenerator
logger = logging.getLogger("red.bz_cogs.aiuser")
class RunPodGenerator(ImageGenerator):
STATUS_COMPLETED = 'COMPLETED'
def __init__(self, ctx: commands.Context, config: Config, apikey: str):
self.apikey = apikey
super().__init__(ctx, config)
async def _prepare_payload(self, caption):
parameters = await self.config.guild(self.ctx.guild).image_requests_parameters()
parameters = json.loads(parameters) if parameters else {}
prompt = (
await self.config.guild(self.ctx.guild).image_requests_preprompt()
+ " "
+ caption
)
parameters["prompt"] = prompt
return {
"input": {
"api": {
"method": "POST",
"endpoint": "/sdapi/v1/txt2img"
},
"payload": parameters
}
}
@retry(wait=wait_random(min=2, max=3), stop=stop_after_attempt(2) | stop_after_delay(190), reraise=True)
async def generate_image(self, caption):
url = await self.config.guild(self.ctx.guild).image_requests_endpoint()
if not "runsync" in url:
raise Exception("Incompatible Runpod endpoint, use /runsync instead of /run")
payload = await self._prepare_payload(caption)
headers = {"Authorization": "Bearer " + self.apikey}
logger.debug(
f"Sending SD request to runpod-worker-a1111 Runpod with payload: {json.dumps(payload, indent=4)}")
image = await self._post_request(url, headers, payload)
return image
async def _post_request(self, url, headers, payload):
headers = {"Authorization": "Bearer " + self.apikey}
async with aiohttp.ClientSession() as session:
async with session.post(url=url, headers=headers, json=payload) as response:
response.raise_for_status()
response = await response.json()
if response['status'] != self.STATUS_COMPLETED:
raise Exception(f"Invalid response from Runpod: {response['status']}")
image_data = base64.b64decode(response["output"]["images"][0])
return io.BytesIO(image_data) |
import { Fragment, useState } from "react";
import MovieList from "./components/MovieList";
import { Row } from "react-bootstrap";
import Container from "react-bootstrap/Container";
import Forum from "./components/Forum";
import Filter from "./components/Filter";
function App() {
const [Movies, setMovies] = useState([
{
id: 1,
title: "The Shawshank Redemption",
description:
"Two convicts, forming a friendship over years, seek solace and eventual redemption through the power of basic compassion in prison.",
posterURL:
"https://www.themoviedb.org/t/p/w600_and_h900_bestv2/q6y0Go1tsGEsmtFryDOJo3dEmqu.jpg",
rating: 5,
},
{
id: 2,
title: "Gladiator",
description:
"A former Roman General seeks vengeance against the corrupt emperor who murdered his family, driving him into slavery—an epic tale of revenge.",
posterURL:
"https://www.themoviedb.org/t/p/w600_and_h900_bestv2/ty8TGRuvJLPUmAR1H1nRIsgwvim.jpg",
rating: 4,
},
{
id: 3,
title: "The Matrix",
description:
"Neo, a hacker, follows a stranger into a dark underworld, discovering a shocking truth about his life—a deceptive creation of evil cyber-intelligence.",
posterURL:
"https://www.themoviedb.org/t/p/w600_and_h900_bestv2/f89U3ADr1oiB1s9GkdPOEpXUk5H.jpg",
rating: 4,
},
{
id: 4,
title: "The Blind Side",
description:
"Michael Oher, a homeless boy, transforms into an All-American football player and NFL draft pick with support from a compassionate woman and her family.",
posterURL:
"https://www.themoviedb.org/t/p/w600_and_h900_bestv2/bMgq7VBriuBFknXEe9E9pVBYGZq.jpg",
rating: 4,
},
]);
const [filteredMovies, setFilteredMovies] = useState(Movies);
const handleAddMovie = (newMovie) => {
setMovies([...Movies, newMovie]);
};
const handleFilterChange = (searchText) => {
const filtered = Movies.filter((Movie) =>
Movie.title.toLowerCase().includes(searchText.toLowerCase())
);
setFilteredMovies(filtered);
};
return (
<Fragment>
<Filter onFilterChange={handleFilterChange} />{" "}
<Forum onAddMovie={handleAddMovie} />
<Container className="mt-3">
<Row>
<MovieList Movies={filteredMovies} />
</Row>
</Container>
</Fragment>
);
}
export default App; |
import 'package:flutter/material.dart';
import 'package:nomeerrado_charts/pie_chart/core/chart_values_options.dart';
import 'package:nomeerrado_charts/pie_chart/core/degree_options.dart';
import 'package:nomeerrado_charts/pie_chart/core/legend_options.dart';
import 'package:nomeerrado_charts/pie_chart/core/utils.dart';
import 'components/legend.dart';
import 'painter/pie_chart_painter.dart';
enum LegendPosition { top, bottom, left, right }
enum ChartType { disc, ring }
class PieChart extends StatefulWidget {
const PieChart({
required this.dataMap,
this.chartType = ChartType.disc,
this.chartRadius,
this.animationDuration,
this.chartLegendSpacing = 48,
this.colorList = defaultColorList,
this.initialAngleInDegree,
this.formatChartValues,
this.centerText,
this.centerTextStyle,
this.ringStrokeWidth = 20.0,
this.legendOptions = const LegendOptions(),
this.chartValuesOptions = const ChartValuesOptions(),
this.emptyColor = Colors.white,
this.gradientList,
this.emptyColorGradient = const [Colors.white70, Colors.white70],
Key? key,
this.degreeOptions = const DegreeOptions(),
}) : super(key: key);
final Map<String, double>? dataMap;
final ChartType chartType;
final double? chartRadius;
final Duration? animationDuration;
final double chartLegendSpacing;
final List<Color> colorList;
final List<List<Color>>? gradientList;
@Deprecated('use degreeOptions. instead')
final double? initialAngleInDegree;
final Function? formatChartValues;
final String? centerText;
final TextStyle? centerTextStyle;
final double ringStrokeWidth;
final LegendOptions legendOptions;
final ChartValuesOptions chartValuesOptions;
final Color emptyColor;
final List<Color> emptyColorGradient;
final DegreeOptions degreeOptions;
@override
_PieChartState createState() => _PieChartState();
}
class _PieChartState extends State<PieChart>
with SingleTickerProviderStateMixin {
late Animation<double> animation;
AnimationController? controller;
double _animFraction = 0.0;
List<String>? legendTitles;
late List<double> legendValues;
void initLegends() {
legendTitles = widget.dataMap!.keys.toList(growable: false);
}
void initValues() {
legendValues = widget.dataMap!.values.toList(growable: false);
}
void initData() {
assert(
widget.dataMap != null && widget.dataMap!.isNotEmpty,
"dataMap passed to pie chart cant be null or empty",
);
initLegends();
initValues();
}
@override
void initState() {
super.initState();
initData();
controller = AnimationController(
duration: widget.animationDuration ?? const Duration(milliseconds: 800),
vsync: this,
);
final Animation curve = CurvedAnimation(
parent: controller!,
curve: Curves.decelerate,
);
animation =
Tween<double>(begin: 0, end: 1).animate(curve as Animation<double>)
..addListener(() {
setState(() {
_animFraction = animation.value;
});
});
controller!.forward();
}
Widget _getChart() {
return Flexible(
child: LayoutBuilder(
builder: (_, c) => SizedBox(
height: widget.chartRadius != null
? c.maxWidth < widget.chartRadius!
? c.maxWidth
: widget.chartRadius
: null,
child: CustomPaint(
painter: PieChartPainter(
_animFraction,
widget.chartValuesOptions.showChartValues,
widget.chartValuesOptions.showChartValuesOutside,
widget.colorList,
chartValueStyle: widget.chartValuesOptions.chartValueStyle,
chartValueBackgroundColor:
widget.chartValuesOptions.chartValueBackgroundColor,
values: legendValues,
titles: legendTitles,
showValuesInPercentage:
widget.chartValuesOptions.showChartValuesInPercentage,
decimalPlaces: widget.chartValuesOptions.decimalPlaces,
showChartValueLabel:
widget.chartValuesOptions.showChartValueBackground,
chartType: widget.chartType,
centerText: widget.centerText,
centerTextStyle: widget.centerTextStyle,
formatChartValues: widget.formatChartValues,
strokeWidth: widget.ringStrokeWidth,
emptyColor: widget.emptyColor,
gradientList: widget.gradientList,
emptyColorGradient: widget.emptyColorGradient,
degreeOptions: widget.degreeOptions.copyWith(
// because we've deprecated initialAngleInDegree,
// we want the old value to be used if it's not null
// ignore: deprecated_member_use_from_same_package
initialAngle: widget.initialAngleInDegree,
),
),
child: const AspectRatio(aspectRatio: 1),
),
),
),
);
}
Widget _getPieChart() {
switch (widget.legendOptions.legendPosition) {
case LegendPosition.top:
return Column(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
_getLegend(
padding: EdgeInsets.only(
bottom: widget.chartLegendSpacing,
),
),
_getChart(),
],
);
case LegendPosition.bottom:
return Column(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
_getChart(),
_getLegend(
padding: EdgeInsets.only(
top: widget.chartLegendSpacing,
),
),
],
);
case LegendPosition.left:
return Row(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
_getLegend(
padding: EdgeInsets.only(
right: widget.chartLegendSpacing,
),
),
_getChart(),
],
);
case LegendPosition.right:
return Row(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
_getChart(),
_getLegend(
padding: EdgeInsets.only(
left: widget.chartLegendSpacing,
),
),
],
);
default:
return Row(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
_getChart(),
_getLegend(
padding: EdgeInsets.only(
left: widget.chartLegendSpacing,
),
),
],
);
}
}
_getLegend({EdgeInsets? padding}) {
if (widget.legendOptions.showLegends) {
final isGradientPresent = widget.gradientList?.isNotEmpty ?? false;
final isNonGradientElementPresent =
(widget.dataMap!.length - (widget.gradientList?.length ?? 0)) > 0;
return Padding(
padding: padding!,
child: Wrap(
direction: widget.legendOptions.showLegendsInRow
? Axis.horizontal
: Axis.vertical,
runSpacing: 8,
crossAxisAlignment: WrapCrossAlignment.start,
children: legendTitles!
.map(
(item) => Legend(
title: item,
color: isGradientPresent
? getGradient(
widget.gradientList!, legendTitles!.indexOf(item),
isNonGradientElementPresent:
isNonGradientElementPresent,
emptyColorGradient: widget.emptyColorGradient)[0]
: getColor(
widget.colorList,
legendTitles!.indexOf(item),
),
style: widget.legendOptions.legendTextStyle,
legendShape: widget.legendOptions.legendShape,
),
)
.toList(),
),
);
} else {
return const SizedBox(height: 0, width: 0);
}
}
@override
Widget build(BuildContext context) {
return Container(
alignment: Alignment.center,
padding: const EdgeInsets.all(8.0),
child: _getPieChart(),
);
}
@override
void didUpdateWidget(PieChart oldWidget) {
initData();
super.didUpdateWidget(oldWidget);
}
@override
void dispose() {
controller?.dispose();
super.dispose();
}
} |
<!DOCTYPE html>
{% load static %}
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-T3c6CoIi6uLrA9TneNEoa7RxnatzjcDSCmG1MXxSR1GAsXEV/Dwwykc2MPK8M2HN" crossorigin="anonymous">
<link rel="stylesheet" href="{% static 'app/css/owl.carousel.min.css' %}" />
<link rel="stylesheet" href="{% static 'app/css/all.min.css' %}" />
<link rel="stylesheet" href="{% static 'app/css/owl.carousel.min' %}" />
<title> Daily Products | {% block title %}{% endblock title %}</title>
</head>
<body>
<nav class="navbar navbar-expand-lg navbar-dark bg-success">
<div class="container-fluid">
<a class="navbar-brand" href="#"><img src="{% static "app/images/neel.png" %}" width="70" height="70" /></a>
<button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarSupportedContent">
<ul class="navbar-nav me-auto mb-2 mb-lg-0">
<li class="nav-item">
<a class="nav-link active" aria-current="page" href="/">Home</a>
</li>
<li class="nav-item dropdown">
<a class="nav-link dropdown-toggle" href="#" role="button" data-bs-toggle="dropdown" aria-expanded="false">Products</a>
<ul class="dropdown-menu">
<li><a class="dropdown-item" href="{% url 'category' 'ML' %}">Milk</a></li>
<li><a class="dropdown-item" href="{% url 'category' 'MS' %}">Milkshanke</a></li>
<li><a class="dropdown-item" href="{% url 'category' 'CR' %}">Curd</a></li>
<li><a class="dropdown-item" href="{% url 'category' 'LS' %}">Lassi</a></li>
<li><a class="dropdown-item" href="{% url 'category' 'GH' %}">Ghee</a></li>
<li><a class="dropdown-item" href="{% url 'category' 'PN' %}">Paneer</a></li>
<li><a class="dropdown-item" href="{% url 'category' 'CZ' %}">Cheese</a></li>
<li><a class="dropdown-item" href="{% url 'category' 'IC' %}">Ice-Cream</a></li>
</ul>
</li>
<li class="nav-item">
<a class="nav-link text-white" href="{% url 'about' %}">About Us</a>
</li>
<li class="nav-item">
<a class="nav-link text-white" href="{% url 'contact' %}">Contact Us</a>
</li>
</ul>
<form class="d-flex" role="search">
<input class="form-control me-2" type="search" placeholder="Search" aria-label="Search">
<button class="btn btn-outline-success" type="submit">Search</button>
</form>
<u1 class="navbar-nav me-auto mb-2 mb-lg-0">
<li class="nav-item dropdown mx-2"></li>
<a class="nav-link dropdown-toggle text-white" href="#" id="profileDropdown" role="button" data-bs-toggle="dropdown" aria-expanded="false">Dhanu</a>
<u1 class="dropdown-menu" aria-labelledby="profileDropdown">
<li><a class="dropdown-item" href="{% url 'profile' %}">Profile</a></li>
<li><a class="dropdown-item" href="#">Orders</a></li>
<li><a class="dropdown-item" href="{% url 'passwordchange' %}">Change Password</a></li>
<li><a class="dropdown-item" href="#">Logout</a></li>
</ul>
</ul>
</div>
</div>
<ul class="navbar-nav me-auto mb-2 mb-lg-0">
<li class="nav-item mx-2"><a href="#" class="nav-link text-white">Cart</a></li>
<li class="nav-item mx-2"><a href="#" class="nav-link text-white">Wishlist</a></li>
<li class="nav-item mx-2"><a href="{% url 'login' %}" class="nav-link text-white">Login</a></li>
<li class="nav-item mx-2"><a href="{% url 'customerregistration' %}" class="nav-link text-white">Register</a></li>
</u1>
</nav>
{% block banner_slider %}{% endblock banner_slider %}
{% block information %}{% endblock information %}
{% block main-content %}{% endblock main-content %}
<footer class="container-fluid fixed-bottom bg-success text-center p-2 mt-5">Copyright : 2023 || Develop by : Dhanupriya</footer>
<script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.11.8/dist/umd/popper.min.js" integrity="sha384-I7E8VVD/ismYTF4hNIPjVp/Zjvgyol6VFvRkX/vR+Vc4jQkC+hVqc2pM8ODewa9r" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.min.js" integrity="sha384-BBtl+eGJRgqQAUMxJ7pMwbEyER4l1g+O15P+16Ep7Q9Q+zqX6gSbd85u4mG4QzX+" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js" /></script>
<script script="{% static 'app/js/all.min.js' %}"></script>
<script script="{% static 'app/js/myscript.js' %}"></script>
<script script="{% static 'app/js/owl.carousel.min.js' %}"></script>
</body>
</html> |
<chapter id="technical-infrastructure">
<title>Technical Infrastructure</title>
<simplesect>
<para>Free software projects rely on technologies that support the
selective capture and integration of information. The more skilled
you are at using these technologies, and at persuading others to use
them, the more successful your project will be.</para>
<para>This only becomes
more true as the project grows. Good information management is what
prevents open source projects from collapsing under the weight of
Brooks' Law<footnote><para>From his book <citetitle>The Mythical Man
Month</citetitle>, 1975. See <ulink
url="http://en.wikipedia.org/wiki/The_Mythical_Man-Month"
>en.wikipedia.org/wiki/The_Mythical_Man-Month</ulink>, <ulink
url="http://en.wikipedia.org/wiki/Brooks_Law"
>en.wikipedia.org/wiki/Brooks_Law</ulink>, and
<ulink url="http://en.wikipedia.org/wiki/Fred_Brooks"
>en.wikipedia.org/wiki/Fred_Brooks</ulink>.</para></footnote>,
which states that adding manpower to a late software project makes it
later. Fred Brooks observed that the complexity of communications in
a project
increases as the <emphasis>square</emphasis> of the number of
participants. When only a few people are involved, everyone can easily
talk to everyone else, but when hundreds of people are involved, it is
no longer possible for each person to remain constantly aware of what
everyone else is doing. If good free software project management is
about making everyone feel like they're all working together in the
same room, the obvious question is: what happens when everyone in a
crowded room tries to talk at once?</para>
<para>This problem is not new. In non-metaphorical crowded rooms, the
solution is <firstterm>parliamentary procedure</firstterm>: formal
guidelines for how to have real-time discussions in large groups, how
to make sure important dissents are not lost in floods of "me-too"
comments, how to form subcommittees, how to recognize and record when
decisions
are made, etc. An important part of parliamentary procedure is
specifying how the group interacts with its information management
system. Some remarks are made "for the record", others are not. The
record itself is subject to direct manipulation, and is understood to
be not a literal transcript of what occurred, but a representation of
what the group is willing to <emphasis>agree</emphasis> occurred. The
record is not monolithic, but takes different forms for different
purposes. It comprises the minutes of individual meetings, the
complete collection of all minutes of all meetings, summaries, agendas
and their annotations, committee reports, reports from correspondents
not present, lists of action items, etc.</para>
<para>Because the Internet is not really a room, we don't have to
worry about replicating those parts of parliamentary procedure that
keep some people quiet while others are speaking. But when it comes
to information management techniques, well-run open source projects
are parliamentary procedure on steroids. Since almost all
communication in open source projects happens in writing, elaborate
systems have evolved for routing and labeling data appropriately, for
minimizing repetitions so as to avoid spurious divergences, for
storing and retrieving data, for correcting bad or obsolete
information, and for associating disparate bits of information with
each other as new connections are observed. Active participants in
open source projects internalize many of these techniques, and will
often perform complex manual tasks to ensure that information is
routed correctly. But the whole endeavor ultimately depends on
sophisticated software support. As much as possible, the
communications media themselves should do the routing, labeling, and
recording, and should make the information available to humans in the
most convenient way possible. In practice, of course, humans will
still need to intervene at many points in the process, and it's
important that the software make such interventions convenient too.
But in general, if the humans take care to label and route information
accurately on its first entry into the system, then the software
should be configured to make as much use of that metadata as
possible.</para>
<para>The advice in this chapter is intensely practical, based on
experiences with specific software and usage patterns. But the point
is not just to teach a particular collection of techniques. It is
also to demonstrate, by means of many small examples, the overall
attitude that will best encourage good information management in your
project. This attitude will involve a combination of technical skills
and people skills. The technical skills are essential because
information management software always requires configuration, plus a
certain amount of ongoing maintenance and tweaking as new needs arise
(for example, see the discussion of how to handle project growth in
<xref linkend="bug-filtering"/><phrase output="printed"> later in
this chapter</phrase>). The people skills are necessary
because the human community also requires maintenance: it's not always
immediately obvious how to use these tools to full advantage, and in
some cases projects have conflicting conventions (for example, see the
discussion of setting <systemitem>Reply-to</systemitem> headers on
outgoing mailing list posts, in <xref linkend="message-forums"/>).
Everyone involved with the project will need to be encouraged, at the
right times and in the right ways, to do their part to keep the
project's information well organized. The more involved the
contributor, the more complex and specialized the techniques she can
be expected to learn.</para>
<para>Information management has no cut-and-dried solution. There are
too many variables. You may finally get everything configured just
the way you want it, and have most of the community participating, but
then project growth will make some of those practices unscalable. Or
project growth may stabilize, and the developer and user communities
settle into a comfortable relationship with the technical
infrastructure, but then someone will come along and invent a whole
new information management service, and pretty soon newcomers will be
asking why your project doesn't use it—for example, this
happened to a lot of free software projects that predate the invention
of the wiki (see <ulink url="http://en.wikipedia.org/wiki/Wiki"
>en.wikipedia.org/wiki/Wiki</ulink>), and more recently has been
happening to projects whose workflows were developed before the rise
of GitHub PRs (see <xref linkend="pull-requests"/>) as the canonical
way to package proposed contributions. Many infrastructure questions
are matters of judgement, involving tradeoffs between the convenience
of those producing information and the convenience of those consuming
it, or between the time required to configure information management
software and the benefit it brings to the project.</para>
<para>Beware of the temptation to over-automate, that is, to automate
things that really require human attention. Technical infrastructure
is important, but what makes a free software project work is
care—and intelligent expression of that care—by the humans
involved. The technical infrastructure is mainly about giving humans
easy ways to apply care.</para>
</simplesect>
<sect1 id="tools-needed">
<title>What a Project Needs</title>
<para>Most open source projects offer at least a minimum, standard set
of tools for managing information:</para>
<variablelist>
<varlistentry><term>Web site</term>
<listitem>
<para>Primarily a centralized, one-way conduit of
information from the project out to the public. The web
site may also serve as an administrative interface for
other project tools.</para>
</listitem>
</varlistentry>
<varlistentry><term>Mailing lists / Message forums</term>
<listitem>
<para>Usually the most active communications forum in the
project, and the "medium of record."</para>
</listitem>
</varlistentry>
<varlistentry><term>Version control</term>
<listitem>
<para>Enables developers to manage code changes conveniently,
including reverting and "change porting". Enables
everyone to watch what's happening to the code.</para>
</listitem>
</varlistentry>
<varlistentry><term>Bug tracking</term>
<listitem>
<para>Enables developers to keep track of what they're working
on, coordinate with each other, and plan releases. Enables
everyone to query the status of bugs and record
information (e.g., reproduction recipes) about particular
bugs. Can be used for tracking not only bugs, but also
tasks, releases, new features, etc.</para>
</listitem>
</varlistentry>
<varlistentry><term>Real-time chat</term>
<listitem>
<para>A place for quick, lightweight discussions and
question/answer exchanges. Not always archived
completely.</para>
</listitem>
</varlistentry>
<!-- TODO: Add blogs/planets to this list? At least mention them
later in the chapter. -->
<!-- TODO: What about Q&A software like OSQA and other things
similar to Stack Exchange? Worth mentioning. See:
http://projects.opensource.org/cgi-bin/mailman/private/infrastructure/2014-January/thread.html#1586
(Thread "Q&A-style software for eventual qa.opensource.org site."
on OSI infrastructure@ list.)
-->
</variablelist>
<para>Each tool in this set addresses a distinct need, but their functions
are also interrelated, and the tools must be made to work together.
Below we will examine how they can do so, and more importantly, how to
get people to use them.</para>
<para>You may be able to avoid a lot of the headache of choosing and
configuring many of these tools by using a <firstterm>canned
hosting</firstterm> site: an online service that offers prepackaged,
templatized web services with some or all of the collaboration tools
needed to run a free software project. See
<xref linkend="canned-hosting"/><phrase output="printed"> later
in this chapter</phrase> for a discussion of the advantages and
disadvantages of canned hosting.</para>
</sect1>
<sect1 id="web-site">
<title>Web Site</title>
<para><emphasis>possv2 24 March 2013: If you're reading this note, then
you've encountered this chapter while it's undergoing substantial
revision; see <ulink url="http://producingoss.com/v2.html"
>producingoss.com/v2.html</ulink> for details.</emphasis></para>
<para>For our purposes, <emphasis>the web site</emphasis> means web
pages devoted to helping people participate in the project as
developers, documenters, etc. Note that this is different from the
main user-facing web site. In many projects, users have different
needs and often (statistically speaking) a different mentality from
the developers. The kinds of web pages most helpful to users are not
necessarily the same as those helpful for
developers — don't try to make a "one size fits all"
web site just to save some writing and maintenance effort: you'll end
up with a site that is not quite right for either audience.</para>
<para>The two types of sites should cross-link, of course, and in
particular it's important that the user-oriented site have, tucked a
way in a corner somewhere, a clear link to the developers' site, since
most new developers will start out at the user-facing pages and look
for a path from there to the developers' area.</para>
<para>An example may make this clearer. As of this writing in
November 2013, the office suite LibreOffice has its main user-oriented
web site at <ulink url="https://libreoffice.org/"
>libreoffice.org</ulink>, as you'd expect. If you were a user wanting
to download and install LibreOffice, you'd start there, go straight to
the "Download" link, and so on. But if you were a developer looking
to (say) fix a bug in LibreOffice, you might
<emphasis>start</emphasis> at <ulink url="https://libreoffice.org/"
>libreoffice.org</ulink>, but you'd be looking for a link that says
something like "Developers", or "Development", or "Get
Involved" — in other words, you'd be looking for the
gateway to the development area.</para>
<para>In the case of LibreOffice, as with some other large projects,
they actually have a couple of different gateways. There's one link
that says <ulink url="https://www.libreoffice.org/get-involved/"
>"Get Involved"</ulink>, and another that says <ulink
url="https://www.libreoffice.org/developers/" >"Developers"</ulink>.
The "Get Involved" page is aimed at the broadest possible range of
potential contributors: developers, yes, but also documenters,
quality-assurance testers, marketing volunteers, web infrastructure
volunteers, financial or in-kind donors, interface designers, support
forum volunteers, etc. This frees up the "Developers" page to target
the rather narrower audience of programmers who want to get involved
in improving the LibreOffice code. The set of links and short
descriptions provided on both pages is admirably clear and concise:
you can tell immediately from looking whether you're in the right
place for what you want do, and if so what the next thing to click on
is. The "Development" page gives some information about where to find
the code, how to contact the other developers, how to file bugs, and
things like that, but most importantly it points to what most seasoned
open source contributors would instantly recognize as the
<emphasis>real</emphasis> gateway to actively-maintained development
information: the development wiki at <ulink
url="http://wiki.documentfoundation.org/Development"
>wiki.documentfoundation.org/Development</ulink>.</para>
<para>This division into two contributor-facing gateways, one for all
kinds of contributions and another for coders specifically, is
probably right for a large, multi-faceted project like LibreOffice.
You'll have to use your judgement as to whether that kind of
subdivision is appropriate for your project; at least at the
beginning, it probably isn't. It's better to start with one unified
contributor gateway, aimed at all the types of contributors you
expect, and if that page ever gets large enough or complex enough to
feel unwieldy — listen carefully for complaints about
it, since you and other long-time participants will be naturally
desensitized to weaknesses in introductory
pages! — then you can divide it up however seems
best.</para>
<para>From a technical point of view there is not much to say about
setting up the project web site. Configuring a web server and writing
web pages are fairly simple tasks, and most of the important things to
say about layout and arrangement were covered in the previous chapter.
The web site's main function is to present a clear and welcoming
overview of the project, and to bind together the other tools (the
version control system, bug tracker, etc.). If you don't have the
expertise to set up a web server yourself, it's usually not hard to
find someone who does and is willing to help out. Nonetheless, to
save time and effort, people often prefer to use one of the canned
hosting sites.</para>
<sect2 id="canned-hosting">
<title>Canned Hosting</title>
<para>A <firstterm>canned hosting</firstterm> site is an online
service that offers some or all of the online collaboration tools
needed to run a free software project. At a minimal, a canned hosting
site offers public version control repositories and bug tracking; most
also offer wiki space, many offer mailing list hosting too, and some
offer continuous integration testing and other services.</para>
<!-- possv2 todo: link to 'fund-servers' in Chapter 5, re the mention
of continuous integration above? Should one be firstterm? -->
<para>There are two main advantages to using a canned site. The first
is server capacity and bandwidth: their servers are beefy boxes
sitting on really fat pipes. No matter how successful your project
gets, you're not going to run out of disk space or swamp the network
connection. The second advantage is simplicity. They have already
chosen a bug tracker, a version control system, perhaps discussion
forum software, and everything else you need to run a project.
They've configured the tools, arranged single-sign-on authentication
where appropriate, are taking care of backups for all the data stored
in the tools, etc. You don't need to make many decisions. All you
have to do is fill in a registration form, press a button, and
suddenly you've got a project development web site.</para>
<para>These are pretty significant benefits. The disadvantage, of
course, is that you must accept <emphasis>their</emphasis> choices and
configurations, even if something different would be better for your
project. Usually canned sites are adjustable within certain narrow
parameters, but you will never get the fine-grained control you would
have if you set up the site yourself and had full administrative
access to the server.</para>
<para>A perfect example of this is the handling of generated files.
Certain project web pages may be generated files—for example,
there are systems for keeping FAQ data in an easy-to-edit master
format, from which HTML, PDF, and other presentation formats can be
generated. As explained in
<xref linkend="version-everything"/><phrase output="printed">
earlier in this chapter</phrase>,
you wouldn't want to version the generated formats, only the master
file. But when your web site is hosted on someone else's server, it
may be difficult to set up a custom hook to regenerate the online
HTML version of the FAQ whenever the master file is changed.</para>
<para>If you choose a canned site, leave open the option of switching
to a different site later, by using a custom domain name as the
project's development home address. You can forward that URL to the
canned site, or have a fully customized development home page at the
main URL and link to the canned site for specific functionality. Just
try to arrange things such that if you later decide to use a different
hosting solution, the project's main address doesn't need to
change.</para>
<para>And if you're not sure whether to use canned hosting, then you
should probably use canned hosting. These sites have integrated their
services in myriad ways (just one example: if a commit mentions a bug
ticket number using a certain format, then people browsing that commit
later will find that it automatically links to that ticket), ways that
would be laborious for you to reproduce, especially if it's your first
time running an open source project. The universe of possible
configurations of collaboration tools is vast and complex, but the
same set of choices has faced everyone running an open source project
and there are some settled solutions now. Each of the canned hosting
sites implements a reasonable subset of that solution space, and
unless you have reason to believe you can do better, your project will
probably run best just using one of those sites.</para>
<sect3 id="canned-hosting-choosing">
<title>Choosing a canned hosting site</title>
<para><emphasis>possv2 todo 26 September 2014: If you're reading this
note, then you've encountered this section while it's undergoing
revision; see <ulink url="http://producingoss.com/v2.html"
>producingoss.com/v2.html</ulink> for details. The specific todo item
here is: update this to talk more about <ulink
url="https://about.gitlab.com/" >GitLab.com</ulink> (and similarly
well-integrated and easy-to-use services that are themselves open
source). I'm not sure that the recommendation toward GitHub below
should be as strong as it is. GitHub is still dominant, but that is
not the important question; the important question is the degree to
which choosing GitHub is in itself a factor in your project's
success — that is, would some developers be slower to
contribute if one is hosted somewhere other than GitHub? I'm not sure
it makes that much of a difference anymore. All the good forge sites
are looking basically alike now. And GitLab is open source, whereas
GitHub is not.</emphasis></para>
<para>There are now so many sites providing free-of-charge canned
hosting for projects released under open source licenses that there is
not space here to review the field.</para>
<para>So I'll make this easy: choose <ulink url="http://github.com/"
>GitHub</ulink>. It's by far the most popular and appears set to stay
that way, or even grow in dominance, for some years to come. It has a
good set of features and integrations. Many developers are already
familiar with GitHub and have an account there. It has an <ulink
url="http://develop.github.com/" >API</ulink> for interacting
programmatically with project resources, and while it does not
currently offer mailing lists, there are plenty of other places you
can host those, such as <ulink url="http://groups.google.com/" >Google
Groups</ulink>.</para>
<para>If you're not convinced by GitHub (for example because your
project uses, say, Mercurial instead of Git), but you aren't sure
where to host, take a look at Wikipedia's thorough <ulink
url="http://en.wikipedia.org/wiki/Comparison_of_open_source_software_hosting_facilities"
>comparison of open source software hosting facilities</ulink>; it's
the first place to look for up-to-date, comprehensive information on
open source project hosting options. Currently the two most popular
other hosting sites are <ulink url="http://code.google.com/hosting/"
>Google Code Hosting</ulink>, <ulink url="http://sourceforge.net/"
>SourceForge</ulink>, but consult the Wikipedia page before making a
decision.</para>
</sect3>
<sect3 id="hosting-on-freedom">
<title>Hosting on fully open source infrastructure</title>
<para>Although all the canned hosting sites use plenty of free
software in their stack, most of them also wrote some proprietary
code to glue it all together. In these cases the hosting environment
itself is not fully open source, and thus cannot be easily reproduced
by others. For example, while Git itself is free software, GitHub is
a hosted service running partly with proprietary
software — if you leave GitHub, you can't take a copy
of their infrastructure with you, at least not all of it.</para>
<para>Some projects prefer a canned hosting site that runs an entirely
free software infrastructure and that could, in theory, be reproduced
independently were that ever to become necessary. Fortunately, there
are such sites, the most well-known being <ulink
url="http://gitlab.com/" >GitLab</ulink>, <ulink
url="http://gitorious.org/" >Gitorious</ulink>, and <ulink
url="http://savannah.gnu.org/" >GNU Savannah</ulink> (as of this
writing in 2014). Furthermore, any service that offers hosting
of the <ulink url="http://redmine.org/" >Redmine</ulink> or <ulink
url="http://trac.edgewall.org" >Trac</ulink> code collaboration
platforms effectively offers fully freedom-preserving project hosting,
because those platforms include most of the features needed to run an
open source project; some companies offer that kind of commercial
platform hosting with a zero-cost or very cheap rate for open source
projects.</para>
<para>Should you host your project on fully open source
infrastructure? While it would be ideal to have access to all the
code that runs the site, my opinion is that the crucial thing is to
have a way to export project data, and to be able to interact with the
data in automatable ways. A site that meets these criteria can never
truly lock you in, and will even be extensible via its programmatic
interface. While there is some value in
having all the code that runs a hosting site available under open
source terms, in practice the demands of actually deploying that code
in a production environment are prohibitive for most projects anyway.
These sites need multiple servers, customized networks, and full-time
staffs to keep them running; merely having the code would not be
sufficient to duplicate or "fork" the service anyway. The main thing
is just to make sure your data isn't trapped.</para>
<para>Of course, all the above applies only to the servers of the
hosting site. Your project itself should never require participants
to run proprietary collaboration software on their own machines.</para>
</sect3>
<sect3 id="anonymity">
<title>Anonymity and involvement</title>
<para>A problem that is not strictly limited to the canned sites, but
is most often found there, is the over-requirement of user
registration to participate in various aspects of the project. The
proper degree of requirement is a bit of a judgement call. User
registration helps prevent spam, for one thing, and even if every
commit gets reviewed you still probably don't want anonymous strangers
pushing changes into your repository, for example.</para>
<para>But sometimes user registration ends up being required for tasks
that ought to be permitted to unregistered visitors, especially the
ability to file tickets in the bug tracker, and to comment on existing
tickets. By requiring a logged-in username for such actions, the
project raises the involvement bar for what should be quick,
convenient tasks. It also changes the demographics of who files bugs,
since those who take the trouble to set up a user account at the
project site are hardly a random sample even from among users who are
willing to file bugs (who in turn are already a biased subset of all
the project's users). Of course, one wants to be able to contact
someone who's entered data into the ticket tracker, but having a field
where she can enter her email address (if she wants to) is sufficient.
If a new user spots a bug and wants to report it, she'll only be
annoyed at having to fill out an account creation form before she can
enter the bug into the tracker. She may simply decide not to file the
bug at all.</para>
<para>If you have control over which actions can be done anonymously,
make sure that at least <emphasis>all</emphasis> read-only actions are
permitted to non-logged-in visitors, and if possible that data entry
portals, such as the bug tracker, that tend to bring information from
users to developers, can also be used anonymously, although of course
anti-spam techniques, such as captchas, may still be necessary.</para>
</sect3>
</sect2>
</sect1>
<sect1 id="message-forums">
<!-- For link compatibility with the old section ID. -->
<anchor id="mailing-lists" />
<title>Mailing Lists / Message Forums</title>
<para>Discussion forums in which participants post and respond to
messages are the bread and butter of project communications. For a
long time these were mainly email-based discussion lists, but the
distinction between Web-based forums and mailing lists is, thankfully,
slowly disappearing. Services like <ulink
url="https://groups.google.com/" >Google Groups</ulink> (which is not
itself open source) and <ulink url="http://Gmane.org/"
>Gmane.org</ulink> (which is) have now established that
cross-accessibility of message forums as mailing lists and vice versa
is the minimum bar to meet, and modern discussion management systems
like GroupServer and Sympa reflect this.</para>
<para>Because of this nearly-completed unification between email lists
and web-based forums<footnote><para>Which was a long time
coming — see <ulink
url="http://www.rants.org/2008/03/06/thread_theory/"
>rants.org/2008/03/06/thread_theory</ulink> for more. And no, I'm not
too dignified to refer to my own blog post.</para></footnote>, I will
use the terms <firstterm>message forum</firstterm> and
<firstterm>mailing list</firstterm> more or less interchangeably.
They refer to any kind of message-based forum where posts are linked
together in threads (topics), people can subscribe, archives of past
messages can be browsed, and the forum can be interacted with via
email or via a web browser.</para>
<para>If a user is exposed to any channel besides a project's web
pages, it is most likely to be one of the project's message forums.
But before she experiences the forum itself, she will experience the
process of finding the right forums. Your project should
have a prominently-placed description of all the available public
forums, to give newcomers guidance in deciding which ones to browse or
post to first. A typical such description might say something like
this:</para>
<screen>
The mailing lists are the main day-to-day communication channels for
the Scanley community. You don't have to be subscribed to post to a
list, but if it's your first time posting (whether you're subscribed
or not), your message may be held in a moderation queue until a
human moderator has a chance to confirm that the message is not spam.
We're sorry for this delay; blame the spammers who make it necessary.
Scanley has the following lists:
<emphasis role="bold"><literal>users {_AT_} scanley.org</literal></emphasis>:
Discussion about using Scanley or programming with the Scanley
API, suggestions of possible improvements, etc. You can browse the
users@ archives at <emphasis role="bold"><<<link to archive>>></emphasis> or subscribe here:
<emphasis role="bold"><<<link to subscribe>>></emphasis>.
<emphasis role="bold"><literal>dev {_AT_} scanley.org</literal></emphasis>:
Discussion about developing Scanley. Maintainers and contributors
are subscribed to this list. You can browse the dev@ archives at
<emphasis role="bold"><<<link to archive>>></emphasis> or subscribe here: <emphasis role="bold"><<<link to subscribe>>></emphasis>.
(Sometimes threads cross over between users@ and dev@, and
Scanley's developers will often participate in discussions on both
lists. In general if you're unsure where a question or post
should go, start it out on <literal>users@</literal>. If it should be a
development discussion, someone will suggest moving it over to
<literal>dev@</literal>.)
<emphasis role="bold"><literal>announcements {_AT_} scanley.org</literal></emphasis>:
This is a low-traffic, subscribe-only list. The Scanley
developers post announcements of new releases and occasional other
news items of interest to the entire Scanley community here, but
followup discussion takes place on users@ or dev@.
<emphasis role="bold"><<<link to subscribe>>></emphasis>.
<emphasis role="bold"><literal>notifications {_AT_} scanley.org</literal></emphasis>:
All code commit messages, bug tracker tickets, automated
build/integration failures, etc, are sent to this list. Most
developers should subscribe: <emphasis role="bold"><<<link to subscribe>>></emphasis>.
There is also a non-public list you may need to send to, although
only developers are subscribed:
<emphasis role="bold"><literal>security {_AT_} scanley.org</literal></emphasis>:
Where the Scanley project receives confidential reports of
security vulnerabilities. Of course, the report will be made
public eventually, but only after a fix is released; see our
security procedures page for more [...]
</screen>
<sect2 id="message-forum-choosing">
<title>Choosing the Right Forum Management Software</title>
<para>It's worth investing some time in choosing the right mailing
list management system for your project. Modern list management tools
offer at least the following features:</para>
<variablelist>
<varlistentry><term>Both email- and web-based access</term>
<listitem>
<para>Users should be able to subscribe to the forums by email,
and read them on the web (where they are organized into
conversations or "threads", just as they would be in a
mailreader).</para>
</listitem>
</varlistentry>
<varlistentry><term>Moderation features</term>
<listitem>
<para>To "moderate" is to check posts, especially first-time
posts, to make sure they are not spam before they go out
to the entire list. Moderation necessarily involves
human administrators, but software can do a great deal to
make it easier on the moderators. There is more said
about moderation in <xref linkend="spam-prevention"/>
later in this chapter.</para>
</listitem>
</varlistentry>
<varlistentry><term>Rich administrative interface</term>
<listitem>
<para>There are many things administrators need to do besides
spam moderation — for example, removing
obsolete addresses, a task that can become urgent when a
recipient's address starts sending "I am no longer at this
address" bounces back to the list in response to every
list post (though some systems can even detect this and
unsubscribe the person automatically). If your forum
software doesn't have decent administrative capabilities,
you will quickly realize it, and should consider switching
to software that does.</para>
</listitem>
</varlistentry>
<varlistentry><term>Header manipulation</term>
<listitem>
<para>Some people have sophisticated filtering and replying
rules set up in their mail readers, and rely on the forum
adding or manipulating certain standard headers. See
<xref linkend="header-management"/> later in this chapter
for more on this.</para>
</listitem>
</varlistentry>
<varlistentry><term>Archiving</term>
<listitem>
<para>All posts to the managed lists are stored and made
available on the web (see <xref
linkend="using-archives"/><phrase output="printed"> in
<xref linkend="communications"/></phrase> for more on the
importance of public archives). Usually the archiver is a
native part of the message forum system; occasionally, it
is a separate tool that needs to be integrated.</para>
</listitem>
</varlistentry>
</variablelist>
<para>The point of the above list is really just to show that forum
management is a complex problem that has already been given a lot of
thought, and to some degree been solved. You don't need to become an
expert, but you will have to learn at least a little bit about
it, and you should expect list management to occupy your attention
from time to time in the course of running any free software project.
Below we'll examine a few of the most common issues.</para>
<sect3 id="spam-prevention">
<title>Spam Prevention</title>
<para>Between when this sentence is written and when it is published,
the Internet-wide spam problem will probably double in
severity—or at least it will feel that way. There was a time,
not so long ago, when one could run a mailing list without taking any
spam-prevention measures at all. The occasional stray post would
still show up, but infrequently enough to be only a low-level
annoyance. That era is gone forever. Today, a mailing list that
takes no spam prevention measures will quickly be submerged in junk
emails, to the point of unusability. Spam prevention is
mandatory.</para>
<para>We divide spam prevention into two categories: preventing spam
posts from appearing on your mailing lists, and preventing your
mailing list from being a source of new email addresses for spammers'
harvesters. The former is more important to your project, so we
examine it first.</para>
<sect4 id="spam-filtering">
<title>Filtering posts</title>
<para>There are three basic techniques for preventing spam posts, and
most mailing list software offers all three. They are best used in
tandem:</para>
<orderedlist>
<listitem><para><emphasis role="bold">Only auto-allow postings from
list subscribers.</emphasis></para>
<para>This is effective as far as it goes, and also
involves very little administrative overhead, since it's
usually just a matter of changing a setting in the mailing
list software's configuration. But note that posts which
aren't automatically approved must not be simply
discarded. Instead, they should go into a moderation
queue, for two reasons. First, you want to allow
non-subscribers to post: a person with a question or
suggestion should not need to subscribe to a mailing list
just to ask a question there. Second, even
subscribers may sometimes post from an address other than
the one by which they're subscribed. Email addresses are
not a reliable method of identifying people, and shouldn't
be treated as such.</para>
</listitem>
<listitem><para><emphasis role="bold">Filter posts through
spam-detection software.</emphasis></para>
<para>If the mailing list software makes it possible (most
do), you can have posts filtered by spam-filtering
software. Automatic spam-filtering is not perfect, and
never will be, since there is a never-ending arms race
between spammers and filter writers. However, it can
greatly reduce the amount of spam that makes it through to the
moderation queue, and since the longer that queue is the
more time humans must spend examining it, any amount of
automated filtering is beneficial.</para>
<para>There is not space here for detailed instructions
on setting up spam filters. You will have to consult
your mailing list software's documentation for that (see
<xref
linkend="mailing-list-software"/><phrase
output="printed"> later in this chapter</phrase>). List
software often comes with some built-in spam prevention
features, but you may want to add some third-party
filters. I've had good experiences with SpamAssassin
(<ulink url="http://spamassassin.apache.org/"
>spamassassin.apache.org</ulink>) and SpamProbe
(<ulink url="http://spamprobe.sourceforge.net/"
>spamprobe.sourceforge.net</ulink>), but this
is not a comment on the many other open source spam
filters out there, some of which are apparently also quite
good. I just happen to have used those two myself and
been satisfied with them.</para>
</listitem>
<listitem><para><emphasis role="bold">Moderation.</emphasis></para>
<para>For mails that aren't automatically allowed by
virtue of being from a list subscriber, and which make it
through the spam filtering software, if any, the last stage
is <firstterm>moderation</firstterm>: the mail is routed
to a special holding area, where a human examines it and
confirms or rejects it.</para>
<para>Confirming a post usually takes one of two forms:
you can accept the sender's post just this once, or you
can tell the system to allow this and all future posts
from the same sender. You almost always want to do the
latter, in order to reduce the future moderation
burden — after all, someone who has made a
valid post to a forum is unlikely to suddenly turn into a
spammer later.</para>
<para>Rejecting is done by either marking the item to be
discarded, or by explicitly telling the system the message
was spam so the system can improve its ability to
recognize future spams. Sometimes
you also have the option to automatically discard future
mails from the same sender without them ever being held in
the moderation queue, but there is rarely any point doing
this, since spammers don't send from the same address
twice anyway.</para>
<para>Oddly, most message-forum systems have not yet given
the moderation queue administrative interface the
attention it deserves, considering how common the task is,
so moderation often still requires more clicks and UI
gestures than it should. I hope this situation will
improve in the future. In the meantime, perhaps knowing
you're not alone in your frustration will temper your
disappointment somewhat.</para>
</listitem>
</orderedlist>
<para>Be sure to use moderation <emphasis>only</emphasis> for
filtering out spams, and perhaps for clearly off-topic messages such
as when someone accidentally posts to the wrong mailing list.
Although the moderation system may give you a way to respond directly
to the sender, you should never use that method to answer questions
that really belong on the mailing list itself, even if you know the
answer off the top of your head. To do so would deprive the project's
community of an accurate picture of what sorts of questions people are
asking, and deprive people of a chance to answer questions themselves
and/or see answers from others. Mailing list moderation is strictly
about keeping the list free of spam and of wildly off-topic emails,
nothing more.</para>
</sect4>
<sect4 id="address-hiding">
<title>Address hiding in archives</title>
<para>To prevent your mailing lists from being a source of addresses
for spammers, a common technique is for the archiving software to
obscure people's email addresses, for example by replacing</para>
<blockquote>
<para><literal>jrandom@somedomain.com</literal></para>
</blockquote>
<para>with</para>
<blockquote>
<para><literal>jrandom_AT_somedomain.com</literal></para>
</blockquote>
<para>or</para>
<blockquote>
<para><literal>jrandomNOSPAM@somedomain.com</literal></para>
</blockquote>
<para>or some similarly obvious (to a human) encoding. Since spam
address harvesters often work by crawling through web
pages—including your mailing list's online archives—and
looking for sequences containing "@", encoding the addresses is a way
of making people's email addresses invisible or useless to spammers.
This does nothing to prevent spam from being sent to the mailing list
itself, of course, but it does avoid increasing the amount of spam
sent directly to list users' personal addresses.</para>
<para>Address hiding can be controversial. Some people like it a lot,
and will be surprised if your archives don't do it automatically.
Other people think it's too much of an inconvenience (because humans
also have to translate the addresses back before using them).
Sometimes people assert that it's ineffective, because a harvester
could in theory compensate for any consistent encoding pattern.
However, note that there is empirical evidence that address hiding
<emphasis>is</emphasis> effective; see <ulink
url="http://www.cdt.org/speech/spam/030319spamreport.shtml"
>cdt.org/speech/spam/030319spamreport.shtml</ulink>.</para>
<para>Ideally, the list management software would leave the choice up
to each individual subscriber, either through a special yes/no header
or a setting in that subscriber's list account preferences. However,
I don't know of any software which offers per-subscriber or per-post
choice in the matter, so for now the list manager must make a decision
for everyone (assuming the archiver offers the feature at all, which
is not always the case). For what it's worth, I lean toward turning
address hiding on. Some people are very careful to avoid posting
their email addresses on web pages or anywhere else a spam harvester
might see it, and they would be disappointed to have all that care
thrown away by a mailing list archive; meanwhile, the inconvenience
address hiding imposes on archive users is very slight, since it's
trivial to transform an obscured address back to a valid one if you
need to reach the person. But keep in mind that, in the end, it's
still an arms race: by the time you read this, harvesters might well
have evolved to the point where they can recognize most common forms
of hiding, and we'll have to think of something else.</para>
</sect4>
</sect3>
<sect3 id="header-management">
<title>Identification and Header Management</title>
<para>When interacting with the forum by email, subscribers often want
to put mails from the list into a project-specific folder, separate
from their other mail. Their mail reading software can do this
automatically by examining the mail's <firstterm>headers</firstterm>.
The headers are the fields at the top of the mail that indicate the
sender, recipient, subject, date, and various other things about the
message. Certain headers are well known and are effectively
mandatory:</para>
<screen>
From: ...
To: ...
Subject: ...
Date: ...
</screen>
<para>Others are optional, though still quite standard. For example,
emails are not strictly required to have the</para>
<screen>
Reply-to: sender@email.address.here
</screen>
<para>header, but most do, because it gives recipients a foolproof way
to reach the author (it is especially useful when the author had to
send from an address other than the one to which replies should be
directed).</para>
<para>Some mail reading software offers an easy-to-use interface for
filing mails based on patterns in the Subject header. This leads
people to request that the mailing list add an automatic prefix to all
Subjects, so they can set their readers to look for that prefix and
automatically file the mails in the right folder. The idea is that
the original author would write:</para>
<screen>
Subject: Making the 2.5 release.
</screen>
<para>but the mail would show up on the list looking like this:</para>
<screen>
Subject: [Scanley Discuss] Making the 2.5 release.
</screen>
<para>Although most list management software offers the option to do
this, you may decide against turning the option on. The problem
it solves can often be solved in less obtrusive ways (see below), and
there is a cost to eating space in the Subject field. Experienced
mailing list users typically scan the Subjects of the day's incoming
list mail to decide what to read and/or respond to. Prepending the
list's name to the Subject can push the right side of the Subject off
the screen, rendering it invisible. This obscures information that
people depend on to decide what mails to open, thus reducing the
overall functionality of the mailing list for everyone.</para>
<para>Instead of munging the Subject header, your project could take
advantage of the other standard headers, starting with the To header,
which should say the mailing list's address:</para>
<screen>
To: <discuss@lists.example.org>
</screen>
<para>Any mail reader that can filter on Subject should be able to filter on
To just as easily.</para>
<para>There are a few other optional-but-standard headers expected for
mailing lists; they are sometimes not displayed by most mailreader
software, but they are present nonetheless. Filtering on them is
even more reliable than using the "To" or "Cc" headers, and since these
headers are added to each post by the mailing list management software
itself, some users may be counting on their presence:</para>
<screen>
list-help: <mailto:discuss-help@lists.example.org>
list-unsubscribe: <mailto:discuss-unsubscribe@lists.example.org>
list-post: <mailto:discuss@lists.example.org>
Delivered-To: mailing list discuss@lists.example.org
Mailing-List: contact discuss-help@lists.example.org; run by ezmlm
</screen>
<para>For the most part, they are self-explanatory. See <ulink
url="http://www.nisto.com/listspec/list-manager-intro.html"
>nisto.com/listspec/list-manager-intro.html</ulink> for more
explanation, or if you need the really detailed, formal specification,
see <ulink url="http://www.faqs.org/rfcs/rfc2369.html"
>faqs.org/rfcs/rfc2369.html</ulink>.
</para>
<para>Having said all that, these days I find that most subscribers
just request that the Subject header include a list-identifying
prefix. That's increasingly how people are accustomed to filtering
email: Subject-based filtering is what many of the major online email
services (like Gmail) offer users by default, and those services tend
not to make it easy to see the presence of less-commonly used headers
like the ones I mentioned above — thus making it hard
for people to figure out that they would even have the option of
filtering on those other headers.</para>
<para>Therefore, reluctantly, I recommend using a Subject prefix (keep
it as short as you can) if that's what your community wants. But if
your project highly technical and most of its participants are
comfortable using the other headers, then that option is always there
as a more space-efficient alternative.</para>
<para>It also used to be the case that if you have a mailing list
named "foo", then you also have administrative addresses "foo-help"
and "foo-unsubscribe" available. In addition to these, it was
traditional to have "foo-subscribe" for joining, and "foo-owner",
for reaching the list administrators. Increasingly, however,
subscribers manage their list membership via Web-based interfaces, so
even if the list management software you use sets up these
administrative addresses, they may go largely unused.</para>
<para>Some mailing list software offers an option to append
unsubscription instructions to the bottom of every post. If that
option is available, turn it on. It causes only a couple of extra
lines per message, in a harmless location, and it can save you a lot
of time, by cutting down on the number of people who mail you—or
worse, mail the list!—asking how to unsubscribe.</para>
</sect3>
<sect3 id="reply-to">
<title>The Great Reply-to Debate</title>
<para>Earlier, in <xref linkend="avoid-private-discussions"/>, I stressed the
importance of making sure discussions stay in public forums, and
talked about how active measures are sometimes needed to prevent
conversations from trailing off into private email threads;
furthermore, this chapter is all about setting up project
communications software to do as much of the work for people as possible.
Therefore, if the mailing list management software offers a way to
automatically cause discussions to stay on the list, you would think
turning on that feature would be the obvious choice.</para>
<para>Well, not quite. There is such a feature, but it has some
pretty severe disadvantages. The question of whether or not to use it
is one of the hottest debates in mailing list
management—admittedly, not a controversy that's likely to make
the evening news in your city, but it can flare up from time to time
in free software projects. Below, I will describe the feature, give
the major arguments on both sides, and make the best recommendation I
can.</para>
<para>The feature itself is very simple: the mailing list software
can, if you wish, automatically set the Reply-to header on every post
to redirect replies to the mailing list. That is, no matter what the
original sender puts in the Reply-to header (or even if they don't
include one at all), by the time the list subscribers see the post,
the header will contain the list address:</para>
<screen>
Reply-to: discuss@lists.example.org
</screen>
<para>On its face, this seems like a good thing. Because virtually
all mail reading software pays attention to the Reply-to header, now
when anyone responds to a post, their response will be automatically
addressed to the entire list, not just to the sender of the message
being responded to. Of course, the responder can still manually
change where the message goes, but the important thing is that
<emphasis>by default</emphasis> replies are directed to the list.
It's a perfect example of using technology to encourage
collaboration.</para>
<para>Unfortunately, there are some disadvantages. The first is known
as the <firstterm>Can't Find My Way Back Home</firstterm> problem:
sometimes the original sender will put their "real" email address in
the Reply-to field, because for one reason or another they send email
from a different address than where they receive it. People who
always read and send from the same location don't have this problem,
and may be surprised that it even exists. But for those who have
unusual email configurations, or who cannot control how the From
address on their mails looks (perhaps because they send from work and
do not have any influence over the IT department), using Reply-to may
be the only way they have to ensure that responses reach them. When
such a person posts to a mailing list that he's not subscribed to, his
setting of Reply-to becomes essential information. If the list
software overwrites it<footnote><para>In theory, the list software
could <emphasis>add</emphasis> the lists's address to whatever
Reply-to destination were already present, if any, instead of
overwriting. In practice, for reasons I don't know, most list
software overwrites instead of appending.</para></footnote>, he may
never see the responses to his post.</para>
<para>The second disadvantage has to do with expectations, and in my
opinion is the most powerful argument against Reply-to munging. Most
experienced mail users are accustomed to two basic methods of
replying: <firstterm>reply-to-all</firstterm> and
<firstterm>reply-to-author</firstterm>. All modern mail reading
software has separate keys for these two actions. Users know that to
reply to everyone (that is, including the list), they should choose
reply-to-all, and to reply privately to the author, they should choose
reply-to-author. Although you want to encourage people to reply to
the list whenever possible, there are certainly circumstances where a
private reply is the responder's prerogative—for example, they
may want to say something confidential to the author of the original
message, something that would be inappropriate on the public
list.</para>
<para>Now consider what happens when the list has overridden the
original sender's Reply-to. The responder hits the reply-to-author
key, expecting to send a private message back to the original author.
Because that's the expected behavior, he may not bother to look
carefully at the recipient address in the new message. He composes
his private, confidential message, one which perhaps says embarrassing
things about someone on the list, and hits the send key.
Unexpectedly, a few minutes later his message appears <emphasis>on the
mailing list!</emphasis> True, in theory he should have looked
carefully at the recipient field, and should not have assumed anything
about the Reply-to header. But authors almost always set Reply-to to
their own personal address (or rather, their mail software sets it for
them), and many longtime email users have come to expect that. In
fact, when a person deliberately sets Reply-to to some other address,
such as the list, she usually makes a point of mentioning this in the
body of her message, so people won't be surprised at what happens when
they reply.</para>
<para>Because of the possibly severe consequences of this unexpected
behavior, my own preference is to configure list management software
to never touch the Reply-to header. This is one instance where using
technology to encourage collaboration has, it seems to me, potentially
dangerous side-effects. However, there are also some powerful
arguments on the other side of this debate. Whichever way you choose,
you will occasionally get people posting to your list asking why you
didn't choose the other way. Since this is not something you ever
want as the main topic of discussion on your list, it might be good to
have a canned response ready, of the sort that's more likely to stop
discussion than encourage it. Make sure you do
<emphasis>not</emphasis> insist that your decision, whichever it is,
is obviously the only right and sensible one (even if you think that's
the case). Instead, point out that this is a very old debate, there
are good arguments on both sides, no choice is going to satisfy
all users, and therefore you just made the best decision you
could. Politely ask that the subject not be revisited unless someone
has something genuinely new to say, then stay out of the thread and
hope it dies a natural death.</para>
<para>Someone may suggest a vote to choose one way or the other. You
can do that if you want, but I personally do not feel that counting
heads is a satisfactory solution in this case. The penalty for
someone who is surprised by the behavior is so huge (accidentally
sending a private mail to a public list), and the inconvenience for
everyone else is fairly slight (occasionally having to remind someone
to respond to the whole list instead of just to you), that it's not
clear that the majority, even though they are the majority, should be
able to put the minority at such risk.</para>
<para>I have not addressed all aspects of this issue here, just the
ones that seemed of overriding importance. For a full discussion, see
these two canonical documents, which are the ones people always cite
when they're having this debate:
<itemizedlist>
<listitem>
<para><emphasis role="bold">Leave Reply-to alone</emphasis>,
<emphasis>by Chip Rosenthal</emphasis></para>
<para><ulink
url="http://www.unicom.com/pw/reply-to-harmful.html"
>unicom.com/pw/reply-to-harmful.html</ulink></para>
</listitem>
<listitem>
<para><emphasis role="bold">Set Reply-to to list</emphasis>,
<emphasis>by Simon Hill</emphasis></para>
<para><ulink
url="http://www.metasystema.net/essays/reply-to.mhtml"
>metasystema.net/essays/reply-to.mhtml</ulink></para>
</listitem>
</itemizedlist>
</para>
<para>Despite the mild preference indicated above, I do not feel there
is a "right" answer to this question, and happily participate in many
lists that <emphasis>do</emphasis> set Reply-to. The most important
thing you can do is settle on one way or the other early, and try not
to get entangled in debates about it after that. When the debate
re-arises every few years, as it inevitably will, you can point people
to the archived discussion from last time.</para>
<sect4 id="reply-fantasies">
<title>Two fantasies</title>
<para>Someday, someone will get the bright idea to implement a
<firstterm>reply-to-list</firstterm> key in a mail reader. It would
use some of the custom list headers mentioned earlier to figure out
the address of the mailing list, and then address the reply directly
to the list only, leaving off any other recipient addresses, since
most are probably subscribed to the list anyway. Eventually, other
mail readers will pick up the feature, and this whole debate will go
away. (Actually, the <ulink url="http://www.mutt.org/" >Mutt</ulink>
mail reader does offer this feature.<footnote><para>Shortly after this
book appeared, <ulink url="http://www.michaelbernstein.com/"
>Michael Bernstein</ulink> wrote me to say: "There are other email
clients that implement a reply-to-list function besides Mutt. For
example, Evolution has this function as a keyboard shortcut, but not a
button (Ctrl+L)."</para></footnote>)</para>
<para>An even better solution would be for Reply-to munging to be a
per-subscriber preference. Those who want the list to set Reply-to
munged (either on others' posts or on their own posts) could ask for
that, and those who don't would ask for Reply-to to be left alone.
However, I don't know of any list management software that offers this
on a per-subscriber basis. For now, we seem to be stuck with a global
setting.<footnote><para>Since I wrote that, I've learned that there is
at least one list management system that offers this
feature: <ulink url="http://siesta.unixbeard.net/">Siesta</ulink>.
See also this article about it:
<ulink url="http://www.perl.com/pub/a/2004/02/05/siesta.html"
>perl.com/pub/a/2004/02/05/siesta.html</ulink></para></footnote></para>
</sect4>
</sect3>
<sect3 id="archiving">
<title>Archiving</title>
<para>The technical details of setting up mailing list archiving are
specific to the software that's running the list, and are beyond the
scope of this book. If you have to choose or configure an archiver,
consider these qualities:</para>
<variablelist>
<varlistentry><term>Prompt updating</term>
<listitem>
<para>People will often want to refer to an archived message
that was posted recently. If possible, the archiver
should archive each post instantaneously, so that by the
time a post appears on the mailing list, it's already
present in the archives. If that option isn't available,
then at least try to set the archiver to update itself
every hour or so. (By default, some archivers run their
update processes once per night, but in practice that's
far too much lag time for an active mailing list.)</para>
</listitem>
</varlistentry>
<varlistentry><term>Referential stability</term>
<listitem>
<para>Once a message is archived at a particular URL, it should
remain accessible at that exact same URL forever, or as
close to forever as possible. Even if the archives are
rebuilt, restored from backup, or otherwise fixed, any
URLs that have already been made publicly available
should remain the same. Stable references make it
possible for Internet search engines to index the
archives, which is a major boon to users looking for
answers. Stable references are also important because
mailing list posts and threads are often linked to from
the bug tracker (see
<xref
linkend="bug-tracker"/><phrase output="printed">
later in this chapter</phrase>) or
from other project documents.</para>
<para>Ideally, mailing list software would include a message's
archive URL, or at least the message-specific portion of
the URL, in a header when it distributes the message to
recipients. That way people who have a copy of the
message would be able to know its archive location
without having to actually visit the archives, which would
be helpful because any operation that involves one's web
browser is automatically time-consuming. Whether any
mailing list software actually offers this feature, I don't
know; unfortunately, the ones I have used do not.
However, it's something to look for (or, if you write
mailing list software, it's a feature to consider
implementing, please).</para>
</listitem>
</varlistentry>
<varlistentry><term>Thread support</term>
<listitem>
<para>It should be possible to go from any individual message to
the <firstterm>thread</firstterm> (group of related
messages) that the original message is part of. Each
thread should have its own URL too, separate from the URLs
of the individual messages in the thread.</para>
</listitem>
</varlistentry>
<varlistentry><term>Searchability</term>
<listitem>
<para>An archiver that doesn't support searching—on the
bodies of messages, as well as on authors and
subjects—is close to useless. Note that some archivers
support searching by simply farming the work out to an
external search engine such as <ulink
url="http://www.google.com/" >Google</ulink>. This is
acceptable, but direct search support is usually more
fine-tuned, because it allows the searcher to specify that
the match must appear in a subject line versus the body,
for example.</para>
</listitem>
</varlistentry>
</variablelist>
<para>The above is just a technical checklist to help you evaluate and
set up an archiver. Getting people to
actually <emphasis>use</emphasis> the archiver to the project's
advantage is discussed in later chapters, in particular
<xref linkend="using-archives"/>.</para>
</sect3>
<sect3 id="message-forum-software">
<!-- For link compatibility with the old section ID. -->
<anchor id="mailing-list-software" />
<title>Mailing List / Message Forum Software</title>
<para>Here are some tools for running message forums. If the site
where you're hosting your project already has a default setup, then
you can just use that and avoid having to choose. But if you need to
install one yourself, below are some possibilities. (Of course, there
are probably other tools out there that I just didn't happen to find,
so don't take this as a complete list).</para>
<itemizedlist>
<listitem>
<para><emphasis role="bold">Google Groups</emphasis> — <ulink url="http://groups.google.com/" >groups.google.com</ulink></para>
<para>Listing Google Groups first was a tough call. The service is
not itself open source, and a few of its administrative
functions can be a bit hard to use. However, its advantages
are substantial: your group's archives are always online and
searchable; you don't have to worry about scalability,
backups, or other run-time infrastructure issues; the
moderation and spam-prevention features are pretty good (with
the latter constantly being improved, which is important in
the neverending spam arms race); and Google Groups are easily
accessible via both email and web, in ways that are likely to
be already familiar to many participants. These are strong
advantages. If you just want to get your project started,
and don't want to spend too much time thinking about what
message forum software or service to use, Google Groups
is a good default choice.</para>
</listitem>
<listitem>
<para><emphasis role="bold">GroupServer</emphasis> — <ulink
url="http://www.groupserver.org/"/></para>
<para>Has built-in archiver and integrated Web-based interface.
GroupServer is a bit of work to set up, but once you have it
up and running it offers users a good experience.
You may able to find free or low-cost hosted GroupServer
hosting for your project's forums, for example from <ulink
url="https://OnlineGroups.net/" >OnlineGroups.net</ulink>.</para>
</listitem>
<listitem>
<para><emphasis role="bold">Sympa</emphasis> — <ulink
url="http://www.sympa.org/" >sympa.org</ulink></para>
<para>Developed and maintained by a consortium of French
universities, and designed for a given instance to handle
both very large lists (> 700000 members, they claim) and a
large number of lists. Sympa can work with a variety of
dependencies; for example, you can run it with sendmail,
postfix, qmail or exim as the underlying message transfer
agent. It has built-in Web-based archiving.</para>
</listitem>
<listitem>
<para><emphasis role="bold">Mailman</emphasis> — <ulink
url="http://www.list.org/" >list.org</ulink></para>
<para>For many years, Mailman was the standard for open source
project mailing lists. It comes with a built-in archiver,
Pipermail, and hooks for plugging in external archivers.
Unfortunately, Mailman is showing its age now, and while
it is very reliable in terms of message delivery and other
under-the-hood functionality, its administrative
interfaces — especially for spam moderation
and subscription moderation — are frustrating
for those accustomed to the modern Web. As of this writing
in late 2013, the long-awaited Mailman 3 was still in
development but was about to enter beta-testing; by the time
you read this, Mailman 3 may be released, and would be worth
a look. It is supposed to solve many of the problems of
Mailman 2, and may make Mailman a reasonable choice again.</para>
</listitem>
<listitem>
<para><emphasis role="bold">Dada</emphasis> — <ulink
url="http://dadamailproject.com/" >dadamailproject.com</ulink></para>
<para>I've not used Dada myself, but it is actively maintained and,
at least from outward appearances, quite spiffy. Note that
to use it for participatory lists, as opposed to announcement
lists, you apparently need to activate the plug-in "Dada
Bridge". Commercial Dada hosting and installation offerings
are available, or you can download the code and install it
yourself.</para>
</listitem>
</itemizedlist>
</sect3>
</sect2>
</sect1>
<sect1 id="vc">
<title>Version Control</title>
<para>A <firstterm>version control system</firstterm> (or
<firstterm>revision control system</firstterm>) is a combination of
technologies and practices for tracking and controlling changes to a
project's files, in particular to source code, documentation, and web
pages. If you have never used version control before, the first thing
you should do is go find someone who has, and get them to join your
project. These days, everyone will expect at least your project's
source code to be under version control, and probably will not take
the project seriously if it doesn't use version control with at least
minimal competence.</para>
<para>The reason version control is so universal is that it helps with
virtually every aspect of running a project: inter-developer
communications, release management, bug management, code stability and
experimental development efforts, and attribution and authorization of
changes by particular developers. The version control system provides
a central coordinating force among all of these areas. The core of
version control is <firstterm>change management</firstterm>:
identifying each discrete change made to the project's files,
annotating each change with metadata like the change's date and
author, and then replaying these facts to whoever asks, in whatever
way they ask. It is a communications mechanism where a change is the
basic unit of information.</para>
<para>This section does not discuss all aspects of using a version
control system. It's so all-encompassing that it must be addressed
topically throughout the book. Here, we will concentrate on choosing
and setting up a version control system in a way that will foster
cooperative development down the road.</para>
<sect2 id="vc-vocabulary">
<title>Version Control Vocabulary</title>
<para>This book cannot teach you how to use version control if you've
never used it before, but it would be impossible to discuss the
subject without a few key terms. These terms are useful independently
of any particular version control system: they are the basic nouns and
verbs of networked collaboration, and will be used generically
throughout the rest of this book. Even if there were no version
control systems in the world, the problem of change management would
remain, and these words give us a language for talking about that
problem concisely.</para>
<para>If you're comfortably experienced with version control already,
you can probably skip this section. If you're not sure, then read
through this section at least once. Certain version control terms
have gradually changed in meaning since the early 2000s, and you may
occasionally find people using them in incompatible ways in the same
conversation. Being able to detect that phenomenon early in a
discussion can often be helpful.</para>
<variablelist>
<varlistentry id="vc-vocabulary-commit">
<term><firstterm>commit</firstterm></term>
<listitem><para>To make a change to the project; more formally, to
store a change in the version control database in such a way that it
can be incorporated into future releases of the project. "Commit"
can be used as a verb or a noun. For example: "I just committed a
fix for the server crash bug people have been reporting on Mac OS X.
Jay, could you please review the commit and check that I'm not
misusing the allocator there?"</para></listitem>
</varlistentry>
<varlistentry id="vc-vocabulary-push">
<term><firstterm>push</firstterm></term>
<listitem><para>To publish a commit to a publicly online repository,
from which others can incorporate it into their copy of the
project's code. When one says one has pushed a commit, the
destination repository is usually implied. Often it is the
project's master repository, the one from which public releases are
made, but not always.</para>
<para>Note that in some version control systems (e.g., Subversion),
commits are automatically and unavoidably pushed up to a
predetermined central repository, while in others (e.g., Git,
Mercurial) the developer chooses when and where to push commits.
Because the former types privilege a particular central repository,
they are known as "centralized" version control systems, while the
latter are known as "decentralized". In general,
decentralized systems are the modern trend, especially for open
source projects, which benefit from the peer-to-peer relationship
between developers' repositories.</para></listitem>
</varlistentry>
<varlistentry id="vc-vocabulary-pull">
<!-- For link compatibility with the old varlistentry ID. -->
<anchor id="vc-vocabulary-update" />
<term><firstterm>pull</firstterm></term>
<listitem><para><emphasis>(or
"<firstterm>update</firstterm>")</emphasis></para>
<para>To pull others' changes (commits) into your local
copy of the project. When pulling changes from a project's mainline
development branch (see <xref linkend="vc-vocabulary-branch"/>),
people often say "update" instead of "pull", for example: "Hey, I
noticed the indexing code is always dropping the last byte. Is this
a new bug?" "Yes, but it was fixed last week—try updating and
it should go away."</para></listitem>
<!-- possv2 todo: link to 'pull-requests' from here? -->
</varlistentry>
<varlistentry id="vc-vocabulary-commit-message">
<!-- For link compatibility with the old varlistentry ID. -->
<anchor id="vc-vocabulary-log-message" />
<term><firstterm>commit message</firstterm> <emphasis>or</emphasis> <firstterm>log message</firstterm></term>
<listitem><para>A bit of commentary attached to each commit,
describing the nature and purpose of the commit (both terms are used
about equally often; I'll use them interchangeably in this book).
Log messages are among the most important documents in any project:
they are the bridge between the detailed, highly technical meaning
of each individual code changes and the more user-visible world of
bugfixes, features and project progress. Later in this section,
we'll look at ways to distribute them to the appropriate audiences;
also, <xref linkend="codifying-tradition"/><phrase
output="printed"> in <xref linkend="communications"/></phrase>
discusses ways to encourage contributors to write concise and useful
commit messages.</para></listitem>
</varlistentry>
<varlistentry id="vc-vocabulary-repository">
<term><firstterm>repository</firstterm></term> <listitem><para>A
database in which changes are stored and from which they are
published. In centralized version control systems, there is a
single, master repository, which stores all changes to the project,
and each developer works with a kind of latest summary on her own
machine. In decentralized systems, each developer has her own
repository, changes can be swapped back and forth between
repositories arbitrarily, and the question of which repository is
the "master" (that is, the one from which public releases are
rolled) is defined purely by social convention, instead of by a
combination of social convention and technical
enforcement.</para></listitem>
</varlistentry>
<varlistentry id="vc-vocabulary-clone">
<term><firstterm>clone</firstterm> <emphasis>(see also
<xref linkend="vc-vocabulary-checkout">"checkout"</xref>)</emphasis></term>
<listitem><para>To obtain one's own development repository by making
a copy of the project's central repository.</para></listitem>
</varlistentry>
<varlistentry id="vc-vocabulary-checkout">
<term><firstterm>checkout</firstterm></term>
<listitem><para>When used in discussion, "checkout" usually means
something like "clone", except that centralized systems don't really
clone the full repository, they just obtain a <xref
linkend="vc-vocabulary-working-copy">working copy</xref>. When
decentralized systems use the word "checkout", they also mean the
process of obtaining working files from a repository, but since the
repository is local in that case, the user experience is quite
different because the network is not involved.</para>
<para>In the centralized sense, a checkout produces a directory tree
called a "working copy" (see below), from which changes may be
sent back to the original repository.</para></listitem>
</varlistentry>
<varlistentry id="vc-vocabulary-working-copy">
<anchor id="vc-vocabulary-working-files" />
<term><firstterm>working copy</firstterm> <emphasis>or</emphasis> <firstterm>working files</firstterm></term>
<listitem><para>A developer's private directory tree containing the
project's source code files, and possibly its web pages or other
documents, in a form that allows the developer to edit them. A
working copy also contains some version control metadata saying what
repository it comes from, what branch it represents, and a few other
things. Typically, each developer has her own working copy, from
which she edits, tests, commits, pulls, pushes,
etc.</para>
<para>In decentralized systems, working copies and repositories are
usually colocated anyway, so the term "working copy" is less often
used. Developers instead tend to say "my clone" or "my copy" or
sometimes "my fork".</para></listitem>
</varlistentry>
<varlistentry id="vc-vocabulary-revision">
<term><firstterm>revision</firstterm>,
<firstterm>change</firstterm>,
<firstterm>changeset</firstterm>,
or (again) <emphasis>commit</emphasis></term>
<listitem><para>A "revision" is a precisely specified incarnation of
the project at a point in time, or of a particular file or directory
in the project. These days, most systems also use "revision",
"change", "changeset", or "commit" to refer to a set of changes
committed together as one conceptual unit, if multiple files were
involved, though colloquially most people would refer to changeset
12's effect on file F as "revision 12 of F".</para>
<para>These terms occasionally have distinct technical meanings in
different version control systems, but the general idea is always
the same: they give a way to speak precisely about exact points in
time in the history of a file or a set of files (say, immediately
before and after a bug is fixed). For example: "Oh yes, she fixed
that in revision 10" or "She fixed that in commit fa458b1fac".</para>
<para>When one talks about a file or collection of files without
specifying a particular revision, it is generally assumed that one
means the most recent revision(s) available.</para></listitem>
</varlistentry>
<sidebar id="version-vs-revision">
<title>"Version" Versus "Revision"</title>
<para>The word <firstterm>version</firstterm> is sometimes used as a
synonym for "revision", but I will not use it that way in this
book, because it is too easily confused with "version" in the sense
of a version of a piece of software—that is, the release or
edition number, as in "Version 1.0". However, since the phrase
"version control" is already standard, I will continue to use it as
a synonym for "revision control" and "change control". Sorry. One
of open source's most endearing characteristics is that it has two
words for everything, and one word for every two things.</para>
</sidebar>
<varlistentry id="vc-vocabulary-diff">
<term><firstterm>diff</firstterm></term>
<listitem><para>A textual representation of a change. A diff shows
which lines were changed and how, plus a few lines of surrounding
context on either side. A developer who is already familiar with
some code can usually read a diff against that code and understand
what the change did, and often even spot bugs.</para></listitem>
</varlistentry>
<varlistentry id="vc-vocabulary-tag">
<term><firstterm>tag</firstterm> <emphasis>or</emphasis> <firstterm>snapshot</firstterm></term>
<listitem><para>A label for a particular state of the project at a
point in time. Tags are generally used to mark interesting
snapshots of the project. For example, a tag is usually made for
each public release, so that one can obtain, directly from the
version control system, the exact set of files/revisions comprising
that release. Tag names are often things like
<literal>Release_1_0</literal>, <literal>Delivery_20130630</literal>,
etc.</para></listitem>
</varlistentry>
<varlistentry id="vc-vocabulary-branch">
<term><firstterm>branch</firstterm></term>
<listitem><para>A copy of the project, under version control but
isolated so that changes made to the branch don't affect other
branches of the project, and vice versa, except when changes are
deliberately "merged" from one branch to another (see below).
Branches are also known as "lines of development". Even when a
project has no explicit branches, development is still considered
to be happening on the "main branch", also known as the "main line"
or "<firstterm>trunk</firstterm>" or
"<firstterm>master</firstterm>".</para>
<para>Branches offer a way to keep different lines of development
from interfering with each other. For example, a branch can be used
for experimental development that would be too destabilizing for the
main trunk. Or conversely, a branch can be used as a place to
stabilize a new release. During the release process, regular
development would continue uninterrupted in the main branch of the
repository; meanwhile, on the release branch, no changes are allowed
except those approved by the release managers. This way, making a
release needn't interfere with ongoing development work. See <xref
linkend="branches"/><phrase output="printed"> later in this
chapter</phrase> for a more detailed discussion of
branching.</para></listitem>
</varlistentry>
<varlistentry id="vc-vocabulary-merge">
<anchor id="vc-vocabulary-port" />
<term><firstterm>merge</firstterm> <emphasis>or</emphasis> <firstterm>port</firstterm></term>
<listitem><para>To move a change from one branch to another. This
includes merging from the main trunk to some other branch, or vice
versa. In fact, those are the most common kinds of merges; it is
less common to port a change between two non-trunk branches. See
<xref linkend="vc-singularity"/> for more on change porting.</para>
<para>"Merge" has a second, related meaning: it is what some version
control systems do when they see that two people have changed the
same file but in non-overlapping ways. Since the two changes do not
interfere with each other, when one of the people updates their copy
of the file (already containing their own changes), the other
person's changes will be automatically merged in. This is very
common, especially on projects where multiple people are hacking on
the same code. When two different changes <emphasis>do</emphasis>
overlap, the result is a "conflict"; see below.</para>
</listitem>
</varlistentry>
<varlistentry id="vc-vocabulary-conflict">
<term><firstterm>conflict</firstterm></term>
<listitem><para>What happens when two people try to make different
changes to the same place in the code. All version control systems
automatically detect conflicts, and notify at least one of the
humans involved that their changes conflict with someone else's. It
is then up to that human to <firstterm>resolve</firstterm> the
conflict, and to communicate that resolution to the version control
system.</para></listitem>
</varlistentry>
<varlistentry id="vc-vocabulary-lock">
<term><firstterm>lock</firstterm></term>
<listitem><para>A way to declare an exclusive intent to change a
particular file or directory. For example, "I can't commit any
changes to the web pages right now. It seems Alfred has them all
locked while he fixes their background images." Not all version
control systems even offer the ability to lock, and of those that
do, not all require the locking feature to be used. This is because
parallel, simultaneous development is the norm, and locking people
out of files is (usually) contrary to this ideal.</para>
<para>Version control systems that require locking to make commits
are said to use the <firstterm>lock-modify-unlock</firstterm> model.
Those that do not are said to use the
<firstterm>copy-modify-merge</firstterm> model. An excellent
in-depth explanation and comparison of the two models may be found
at <ulink
url="http://svnbook.red-bean.com/nightly/en/svn.basic.version-control-basics.html#svn.basic.vsn-models"
>svnbook.red-bean.com/nightly/en/svn.basic.version-control-basics.html#svn.basic.vsn-models</ulink>. In
general, the copy-modify-merge model is better for open source
development, and all the version control systems discussed in this
book support that model.</para></listitem>
</varlistentry>
</variablelist>
</sect2>
<sect2 id="vc-choosing">
<title>Choosing a Version Control System</title>
<para>If you don't already have a strong opinion about which version
control system your project should use, then choose Git (<ulink
url="http://git-scm.com/" >git-scm.com</ulink>), and host your
project's repositories at <ulink url="http://github.com/"
>GitHub.com</ulink>, which offers unlimited free hosting for open
source projects.</para>
<para>Git is by now the <foreignphrase>de facto</foreignphrase>
standard in the open source world, as is hosting one's repositories at
GitHub. Because so many developers are already comfortable with that
combination, choosing it sends the signal that your project is ready
for participants. But Git-at-GitHub is not the only viable
combination. Two other reasonable choices of version control system
are <ulink url="http://mercurial.selenic.com/" >Mercurial</ulink> and
<ulink url="http://subversion.apache.org/" >Subversion</ulink>.
Mercurial and Git are both decentralized systems, whereas Subversion
is centralized. All three are offered at many different free hosting
services; some services even support more than one of them (though
GitHub only supports Git, as its name suggests). While some projects
host their repositories on their own servers, most just put their
repositories on one of the free hosting services, as described in
<xref linkend="canned-hosting"/>.</para>
<para>There isn't space here for an in-depth exploration of why you
might choose something other than Git. If you have a reason to do so,
then you already know what that reason is. If you don't, then just
use Git (and probably on GitHub). If you find yourself using
something other than Git, Mercurial, or Subversion, ask yourself
why — because whatever that other version control
system is, most other developers won't be familiar with it, and it
likely has a smaller and less stable community of support around it
than the big three do.</para>
</sect2>
<sect2 id="vc-using">
<title>Using the Version Control System</title>
<para>The recommendations in this section are not targeted toward a
particular version control system, and should be implementable in any
of them. Consult your specific system's documentation for
details.</para>
<sect3 id="version-everything">
<title>Version everything</title>
<para>Keep not only your project's source code under version control,
but also its web pages, documentation, FAQ, design notes, and anything
else that people might want to edit. Keep them right with the
source code, in the same repository tree. Any piece of information
worth writing down is worth versioning—that is, any piece of
information that could change. Things that don't change should be
archived, not versioned. For example, an email, once posted, does not
change; therefore, versioning it wouldn't make sense (unless it becomes
part of some larger, evolving document).</para>
<para>The reason to version everything together in one place is so
that people only have to learn one mechanism for submitting changes.
Often a contributor will start out making edits to the web pages or
documentation, and move to small code contributions later, for
example. When the project uses the same system for all kinds of
submissions, people only have to learn the ropes once. Versioning
everything together also means that new features can be committed
together with their documentation updates, that branching the code
will branch the documentation too, etc.</para>
<para>Don't keep <firstterm>generated files</firstterm> under version
control. They are not truly editable data, since they are produced
programmatically from other files. For example, some build systems
create a file named <filename>configure</filename> based on a template
in <filename>configure.in</filename>. To make a change to the
<filename>configure</filename>, one would edit
<filename>configure.in</filename> and then regenerate; thus, only the
template <filename>configure.in</filename> is an "editable file."
Just version the templates—if you version the generated files as
well, people will inevitably forget to regenerate them when they commit a
change to a template, and the resulting inconsistencies will cause no
end of confusion.</para>
<para>There are technical exceptions to the rule that all editable
data should be kept in the same version control system as the code.
For example, a project's bug tracker and its wiki hold plenty of
editable data, but usually do not store that data in the main version
control system<footnote><para>There are development environments that
integrate everything into one unified version control world; see <xref
linkend="vc-veracity"/> for an example.</para></footnote>. However,
they should still have versioning systems of their own, e.g., the
comment history in a bug ticket, and the ability to browse past
revisions and view differences between them in a wiki.</para>
</sect3>
<sect3 id="vc-browsing">
<title>Browsability</title>
<para>The project's repository should be browsable on the Web. This
means not only the ability to see the latest revisions of the
project's files, but to go back in time and look at earlier revisions,
view the differences between revisions, read log messages for selected
changes, etc.</para>
<para>Browsability is important because it is a lightweight portal to
project data. If the repository cannot be viewed through a web
browser, then someone wanting to inspect a particular file (say, to
see if a certain bugfix had made it into the code) would first have to
install version control client software locally, which could turn
their simple query from a two-minute task into a half-hour or longer
task.</para>
<para>Browsability also implies canonical URLs for viewing a particular
change (i.e., a commit), and for viewing the latest revision at any given
time without specifying its commit identifier. This can be very
useful in technical discussions or when
pointing people to documentation. For example, instead of saying "For
bug management guidelines, see the community-guide/index.html file
in your working copy," one can say "For bug management guidelines,
see
<emphasis>http://subversion.apache.org/docs/community-guide/</emphasis>,"
giving a URL that always points to the latest revision of the
<filename>community-guides/index.html</filename> file. The URL is
better because it is completely unambiguous, and avoids the question
of whether the addressee has an up-to-date working copy.</para>
<para>Some version control systems come with built-in
repository-browsing mechanisms, and in any case most hosting sites
offer a good web interface. But if you need to install a third-party
tool for repository browsing, there are many out there. Three that
support Git are <firstterm>GitLab</firstterm> (<ulink
url="http://gitlab.org/" >gitlab.org</ulink>),
<firstterm>GitWeb</firstterm> (<ulink
url="https://git.wiki.kernel.org/index.php/Gitweb"
>git.wiki.kernel.org/index.php/Gitweb</ulink>), and
<firstterm>GitList</firstterm> (<ulink url="http://gitlist.org/"
>gitlist.org</ulink>). For Subversion, there is
<firstterm>ViewVC</firstterm> (<ulink url="http://viewvc.org/"
>viewvc.org</ulink>). A web search will turn up plenty of others
besides these.</para>
</sect3>
<sect3 id="branches">
<title>Use branches to avoid bottlenecks</title>
<para>Non-expert version control users are sometimes a bit afraid of
branching and merging. If you are among those people, resolve right
now to conquer any fears you may have and take the time to learn how
to do branching and merging. They are not difficult operations, once
you get used to them, and they become increasingly important as a
project acquires more developers.</para>
<para>Branches are valuable because they turn a scarce
resource—working room in the project's code—into an
abundant one. Normally, all developers work together in the same
sandbox, constructing the same castle. When someone wants to add a
new drawbridge, but can't convince everyone else that it would be an
improvement, branching makes it possible for her to make a copy of the
castle, take it off to an isolated corner, and try out the new
drawbridge design. If the effort succeeds, she can invite the
other developers to examine the result (in GitHub-speak, this
invitation is known as a "pull request" — see <xref
linkend="pull-requests"/>). If everyone agrees that the
result is good, she or someone else can tell the version control
system to move ("merge") the drawbridge from the branch version of the
castle over to the main version, sometimes called the
<firstterm>master branch</firstterm>.</para>
<para>It's easy to see how this ability helps collaborative
development. People need the freedom to try new things without
feeling like they're interfering with others' work. Equally
importantly, there are times when code needs to be isolated from the
usual development churn, in order to get a bug fixed or a release
stabilized (see <xref linkend="stabilizing-a-release"/> and
<xref linkend="release-lines"/><phrase output="printed"> in
<xref linkend="development-cycle"/></phrase>) without worrying
about tracking a moving target. At the same time, people need to be
able to review and comment on experimental work, whether it's
happening in the master branch or somewhere else. Treating branches
as first-class, publishable objects makes all this possible.</para>
<para>Use branches liberally, and encourage others to use them. But
also make sure that a given branch is only active for as long as
needed. Every active branch is a slight drain on the community's
attention. Even those who are not working in a branch still maintain
a peripheral awareness of what's going on in it. Such awareness is
desirable, of course, and commit notices should be sent out for branch
commits just as for any other commit. But branches should not become
a mechanism for dividing the development community. With rare
exceptions, the eventual goal of most branches should be to merge
their changes back into the main line and disappear.</para>
</sect3>
<sect3 id="vc-singularity">
<title>Singularity of information</title>
<para>Merging has an important corollary: never commit the same change
twice. That is, a given change should enter the version control
system exactly once. The revision (or set of revisions) in which the
change entered is its unique identifier from then on. If it needs to
be applied to branches other than the one on which it entered, then it
should be merged from its original entry point to those other
destinations—as opposed to committing a textually identical
change, which would have the same effect in the code, but would make
accurate bookkeeping and release management much harder.</para>
<para>The practical effects of this advice differ from one version
control system to another. In some systems, merges are special
events, fundamentally distinct from commits, and carry their own
metadata with them. In others, the results of merges are committed
the same way other changes are committed, so the primary means of
distinguishing a "merge commit" from a "new change commit" is in the
log message. In a merge's log message, don't repeat the log message
of the original change. Instead, just indicate that this is a merge,
and give the identifying revision of the original change, with at most
a one-sentence summary of its effect. If someone wants to see the
full log message, she should consult the original revision.</para>
<para>One reason it's important to avoid repeating the log message is
that, in some systems, log messages are sometimes edited after they've
been committed. If a change's log message were repeated at each merge
destination, then even if someone edited the original message, she'd
still leave all the repeats uncorrected—which would only cause
confusion down the road. Another reason is that non-duplication makes
it easier to be sure when one has tracked down the original source of
a change. When you're looking at a complete log message that doesn't
refer to a some other merge source, you can know that it must be the
original change, and handle it accordingly.</para>
<para>The same principle applies to reverting a change. If a change
is withdrawn from the code, then the log message for the reversion
should merely state that some specific revision(s) is being reverted,
<emphasis>not</emphasis> describe the actual code change that results
from the reversion, since the semantics of the change can be derived
by reading the original log message and change. Of course, the
reversion's log message should also state the reason why the change is
being reverted, but it should not duplicate anything from the original
change's log message. If possible, go back and edit the original
change's log message to point out that it was reverted.</para>
<para>All of the above implies that you should use a consistent syntax
for referring to changes. This is helpful not only in log messages,
but in emails, the bug tracker, and elsewhere. In Git and Mercurial,
the syntax is usually "commit bb2377" (where the commit hash code on
the right is long enough to be unique in the relevant context); in
Subversion, revision numbers are linearly incremented integers and the
standard syntax for, say, revision 1729 is "r1729". In other systems,
there is usually a standard syntax for expressing the changeset name.
Whatever the appropriate syntax is for your system, encourage people
to use it when referring to changes. Consistent expression of change
names makes project bookkeeping much easier (as we will see in <xref
linkend="communications"/> and <xref linkend="development-cycle"/>),
and since a lot of the bookkeeping may be done by volunteers, it
needs to be as easy as possible.</para>
<para>See also
<xref
linkend="releases-and-daily-development"/><phrase
output="printed"> in
<xref linkend="development-cycle"/></phrase>.</para>
</sect3>
<sect3 id="vc-authz">
<title>Authorization</title>
<para>Many version control systems offer a feature whereby certain
people can be allowed or disallowed from committing in specific
sub-areas of the master repository. Following the principle that when
handed a hammer, people start looking around for nails, many projects use
this feature with abandon, carefully granting people access to just
those areas where they have been approved to commit, and making sure
they can't commit anywhere else. (See
<xref linkend="committers"/><phrase output="printed"> in
<xref linkend="managing-volunteers"/></phrase> for how projects
decide who can put changes where.)</para>
<para>Exercising such tight control is usually unnecessary, and may
even be harmful. Some projects simply use an honor system: when a
person is granted commit access, even for a sub-area of the project,
what they actually receive is the ability to commit anywhere in the
master repository. They're just asked to keep their commits in their
area. Remember that there is little real risk here: the repository
provides an audit trail, and in an active project, all commits are
reviewed anyway. If someone commits where they're not supposed to,
others will notice it and say something. If a change needs to be
undone, that's simple enough—everything's under version control
anyway, so just revert.</para>
<para>There are several advantages to this more relaxed approach.
First, as developers expand into other areas (which they usually will
if they stay with the project), there is no administrative overhead to
granting them wider privileges. Once the decision is made, the person
can just start committing in the new area right away.</para>
<para>Second, expansion can be done in a more fine-grained manner.
Generally, a committer in area X who wants to expand to area Y will
start posting patches against Y and asking for review. If someone who
already has commit access to area Y sees such a patch and approves of
it, she can just tell the submitter to commit the change directly
(mentioning the reviewer/approver's name in the log message, of
course). That way, the commit will come from the person who actually
wrote the change, which is preferable from both an information
management standpoint and from a crediting standpoint.</para>
<para>Last, and perhaps most important, using the honor system
encourages an atmosphere of trust and mutual respect. Giving someone
commit access to a subdomain is a statement about their technical
preparedness—it says: "We see you have expertise to make commits
in a certain domain, so go for it." But imposing strict authorization
controls says: "Not only are we asserting a limit on your expertise,
we're also a bit suspicious about
your <emphasis>intentions</emphasis>." That's not the sort of
statement you want to make if you can avoid it. Bringing someone into
the project as a committer is an opportunity to initiate them into a
circle of mutual trust. A good way to do that is to give them more
power than they're supposed to use, then inform them that it's up to
them to stay within the stated limits.</para>
<para>The Subversion project has operated on this honor system way or
well over a decade, with more than 40 full committers and many more
partial committers as of this writing. The only distinction the
system actually enforces is
between committers and non-committers; further subdivisions are
maintained solely by human judgement. Yet the project never had a
serious problem with someone deliberately committing outside their
domain. Once or twice there's been an innocent misunderstanding about
the extent of someone's commit privileges, but it's always been
resolved quickly and amiably.</para>
<para>Obviously, in situations where self-policing is impractical, you
must rely on hard authorization controls. But such situations are
rare. Even when there are millions of lines of code and hundreds or
thousands of developers, a commit to any given code module should
still be reviewed by those who work on that module, and they can
recognize if someone committed there who wasn't supposed to. If
regular commit review <emphasis>isn't</emphasis> happening, then the
project has bigger problems to deal with than the authorization system
anyway.</para>
<para>In summary, don't spend too much time fiddling with the version
control authorization system, unless you have a specific reason to. It
usually won't bring much tangible benefit, and there are advantages to
relying on human controls instead.</para>
<para>None of this should be taken to mean that the restrictions
themselves are unimportant, of course. It would be bad for a project
to encourage people to commit in areas where they're not qualified.
Furthermore, in many projects, full (unrestricted) commit access has a
special corollary status: it implies voting rights on project-wide
questions. This political aspect of commit access is discussed more
in <xref linkend="electorate"/><phrase output="printed"> in
<xref linkend="social-infrastructure"/></phrase>.</para>
</sect3>
</sect2>
<sect2 id="receiving-changes">
<title>Receiving and reviewing contributions</title>
<para><emphasis>15 March 2015: If you're reading this note, then
you've encountered this section while it's in the process of being
written as part of the overall update of this book (see <ulink
url="http://producingoss.com/v2.html"
>producingoss.com/v2.html</ulink>).</emphasis></para>
<para>poss2 todo: there are three main things to cover here: pull
requests (GitHub-style), Gerrit and similar tools, and commit emails.
Intro paragraph should give an overview and describe how they interact, then
a short section on each. The section for commit emails is already
done as it was just moved here from its old home as a subsection of
the "Using the Version Control System" section. Discuss how
human-centered commit review can be linked with automated buildbots
that may or may not be a hard gateway to the central repository.</para>
<!-- http://programmers.stackexchange.com/questions/173262/gerrit-code-review-or-githubs-fork-and-pull-model is worth looking at -->
<sect3 id="pull-requests">
<title>Pull requests</title>
<!-- http://julien.danjou.info/blog/2013/rant-about-github-pull-request-workflow-implementation is an interesting read for this -->
<!-- In the now-defunct Gitorious, and perhaps elsewhere
(Phabricator? GitLab?), these are called by the IMHO more
intuitive name "merge requests". Make sure to mention that
too. -->
</sect3>
<sect3 id="commit-review-systems">
<title>Review systems</title>
<!-- See http://en.wikipedia.org/wiki/List_of_tools_for_code_review ,
as Gerrit isn't the only thing out there, though it's probably the
most popular. I guess Review Board is the other. -->
</sect3>
<sect3 id="commit-emails">
<title>Commit emails</title>
<para>Every commit to the repository should generate an email showing
who made the change, when they made it, what files and directories
changed, and how they changed. The email should go to a special
mailing list devoted to commit emails, separate from the mailing lists
to which humans post. Developers and other interested parties should
be encouraged to subscribe to the commits list, as it is the most
effective way to keep up with what's happening in the project at the
code level. Aside from the obvious technical benefits of peer review
(see <xref linkend="code-review"/>), commit emails help create a
sense of community, because they establish a shared environment in
which people can react to events (commits) that they know are visible
to others as well.</para>
<para>The specifics of setting up commit emails will vary depending on
your version control system, but usually there's a script or other
packaged facility for doing it. If you're having trouble finding it,
try looking for documentation on <firstterm>hooks</firstterm> (or
sometimes <firstterm>triggers</firstterm>) specifically a
<firstterm>post-commit hook</firstterm> hook. Post-commit hooks are a
general means of launching automated tasks in response to commits.
The hook is triggered when a given commit finalizes, is fed all the
information about that commit, and is then free to use that
information to do anything—for example, to send out an
email.</para>
<para>With pre-packaged commit email systems, you may want to
modify some of the default behaviors:</para>
<orderedlist>
<listitem>
<para>Some commit mailers don't include the actual diffs in the
email, but instead provide a URL to view the change on the web using
the repository browsing system. While it's good to provide the URL,
so the change can be referred to later, it is also important that
the commit email include
the diffs themselves. Reading email is already part of people's
routine, so if the content of the change is visible right there in
the commit email, developers will review the commit on the spot,
without leaving their mail reader. If they have to click on a URL to
review the change, most won't do it, because that requires a new
action instead of a continuation of what they were already doing.
Furthermore, if the reviewer wants to ask something about the
change, it's vastly easier to hit reply-with-text and simply
annotate the quoted diff than it is to visit a web page and
laboriously cut-and-paste parts of the diff from web browser to
email client.</para>
<para>(Of course, if the diff is huge, such as when a large body of
new code has been added to the repository, then it makes sense to
omit the diff and offer only the URL. Most commit mailers can do
this kind of size-limiting automatically. If yours can't, then it's
still better to include diffs, and live with the occasional huge
email, than to leave the diffs off entirely. Convenient reviewing
and commenting is a cornerstone of cooperative development, and much
too important to do without.)</para>
</listitem>
<listitem><para>The commit emails should set their Reply-to header
to the regular development list, not the commit email list. That
is, when someone reviews a commit and writes a response, their
response should be automatically directed toward the human
development list, where technical issues are normally discussed.
There are a few reasons for this. First, you want to keep all
technical discussion on one list, because that's where people expect
it to happen, and because that way there's only one archive to
search. Second, there might be interested parties not subscribed to
the commit email list. Third, the commit email list advertises
itself as a service for watching commits, not for watching commits
<emphasis>and</emphasis> having occasional technical discussions.
Those who subscribed to the commit email list did not sign up for
anything but commit emails; sending them other material via that
list would violate an implicit contract.</para>
<para>Note that this advice to set Reply-to does not contradict the
recommendations in
<xref linkend="reply-to"/><phrase output="printed"> earlier in
this chapter</phrase>. It's
always okay for the <emphasis>sender</emphasis> of a message to set
Reply-to. In this case, the sender is the version control system
itself, and it sets Reply-to in order to indicate that the
appropriate place for replies is the development mailing list, not
the commit list.</para>
</listitem>
</orderedlist>
</sect3>
</sect2>
</sect1>
<sect1 id="bug-tracker">
<title>Bug Tracker</title>
<para>Bug tracking is a broad topic; various aspects of it are
discussed throughout this book. Here I'll concentrate mainly on the
features your project should look for in a bug tracker, and how to use
them. But to get to those, we have to start with a policy question:
exactly what kind of information should be kept in a bug
tracker?</para>
<para>The term <firstterm>bug tracker</firstterm> is misleading. Bug
tracking systems are used to track not only bug reports, but new
feature requests, one-time tasks, unsolicited patches—really
anything that has distinct beginning and end states, with optional
transition states in between, and that accrues information over its
lifetime. For this reason, bug trackers are also called
<firstterm>issue trackers</firstterm>, <firstterm>ticket
trackers</firstterm>, <firstterm>defect trackers</firstterm>,
<firstterm>artifact trackers</firstterm>, <firstterm>request
trackers</firstterm>, etc.</para>
<para>In this book, I'll generally use the word
<firstterm>ticket</firstterm> to refer the items in the tracker's
database, because that distinguishes between the behavior that the
user encountered or proposed — that is, the bug or
feature itself — and the tracker's ongoing
<emphasis>record</emphasis> of that discovery, diagnosis, discussion,
and eventual resolution. But note that many projects use the word
<emphasis>bug</emphasis> or <emphasis>issue</emphasis> to refer to
both the ticket itself and to the underlying behavior or goal that the
ticket is tracking. (In fact, those usages are probably more common than
"ticket"; it's just that in this book we need to be able to make that
distinction explicitly in a way that projects themselves usually
don't.)</para>
<para>The classic ticket life cycle looks like this:
<orderedlist>
<listitem><para>Someone files the ticket. They provide a summary, an
initial description (including a reproduction recipe, if
applicable; see
<xref
linkend="users-to-volunteers"/><phrase
output="printed"> in
<xref linkend="managing-volunteers"/></phrase> for
how to encourage good bug reports), and whatever other
information the tracker asks for. The person who files
the ticket may be totally unknown to the project—bug
reports and feature requests are as likely to come from
the user community as from the developers.</para>
<para>Once filed, the ticket is in what's called an
<firstterm>open</firstterm> state. Because no action has
been taken yet, some trackers also label it as
<firstterm>unverified</firstterm> and/or
<firstterm>unstarted</firstterm>. It is not assigned to
anyone; or, in some systems, it is assigned to a fake
user to represent the lack of real assignation. At this
point, it is in a holding area: the ticket has been
recorded, but not yet integrated into the project's
consciousness.</para>
</listitem>
<listitem><para>Others read the ticket, add comments to it, and
perhaps ask the original filer for clarification on some
points.</para>
</listitem>
<listitem><para>The bug gets <firstterm>reproduced</firstterm>.
This may be the most important moment in its
life cycle. Although the bug is not actually fixed yet,
the fact that someone besides the original filer was able
to make it happen proves that it is genuine, and, no less
importantly, confirms to the original filer that they've
contributed to the project by reporting a real bug.
<emphasis>(This step and some of the others don't apply to
feature proposals, task tickets, etc, of course. But most
filings are for genuine bugs, so we'll focus on that
here.)</emphasis></para>
</listitem>
<listitem><para>The bug gets <firstterm>diagnosed</firstterm>: its
cause is identified, and if possible, the effort required
to fix it is estimated. Make sure these things get
recorded in the ticket; if the person who diagnosed the
bug suddenly has to step away from it for a
while, someone else should be able to pick up where she
left off.</para>
<para>In this stage, or sometimes in the previous one,
a developer may "take ownership" of the ticket and
<firstterm>assign</firstterm> it to herself (<xref
linkend="delegation-assignment"/><phrase
output="printed"> in
<xref linkend="managing-volunteers"/></phrase>
examines the assignment process in more detail). The ticket's
<firstterm>priority</firstterm> may also be set at this
stage. For example, if it is so important that it should
delay the next release, that fact needs to be identified
early, and the tracker should have some way of noting
it.</para>
</listitem>
<listitem><para>The ticket gets scheduled for resolution.
Scheduling doesn't necessarily mean naming a date by which
it will be fixed. Sometimes it just means deciding which
future release (not necessarily the next one) the bug
should be fixed by, or deciding that it need not block any
particular release. Scheduling may also be dispensed
with, if the bug is quick to fix.</para>
</listitem>
<listitem><para>The bug gets fixed (or the task completed, or
the patch applied, or whatever). The change or set of
changes that fixed it should be discoverable from
the ticket. After this, the ticket is
<firstterm>closed</firstterm> and/or marked as
<firstterm>resolved</firstterm>.</para>
</listitem>
</orderedlist>
</para>
<para>There are some common variations on this life cycle. Sometimes
a ticket is closed very soon after being filed, because it turns out
not to be a bug at all, but rather a misunderstanding on the part of
the user. As a project acquires more users, more and more such
invalid tickets will come in, and developers will close them with
increasingly short-tempered responses. Try to guard against the
latter tendency. It does no one any good, as the individual user in
each case is not responsible for all the previous invalid tickets; the
statistical trend is visible only from the developers' point of view,
not the user's. (In
<xref linkend="bug-filtering"/><phrase output="printed"> later
in this chapter,</phrase> we'll look at
techniques for reducing the number of invalid tickets.) Also, if
different users are experiencing the same misunderstanding over and
over, it might mean that aspect of the software needs to be
redesigned. This sort of pattern is easiest to notice when there is
an issue manager monitoring the bug database; see
<xref linkend="issue-manager"/><phrase output="printed"> in
<xref linkend="managing-volunteers"/></phrase>.</para>
<para>Another common life event for the ticket to be closed
as a <firstterm>duplicate</firstterm> soon after Step 1. A duplicate
is when someone reports something that's already known to the project.
Duplicates are not confined to open tickets: it's possible for a bug to
come back after having been fixed (this is known as a
<firstterm>regression</firstterm>), in which case a reasonable course
is to reopen the original ticket and close any new reports as
duplicates of the original one. The bug tracking system should keep
track of this relationship bidirectionally, so that reproduction
information in the duplicates is available to the original ticket, and
vice versa.</para>
<para>A third variation is for the developers to close the ticket,
thinking they have fixed it, only to have the original reporter reject
the fix and reopen it. This is usually because the developers simply
don't have access to the environment necessary to reproduce the bug,
or because they didn't test the fix using the exact same reproduction
recipe as the reporter.</para>
<para>Aside from these variations, there may be other small details of
the life cycle that vary depending on the tracking software. But the
basic shape is the same, and while the life cycle itself is not
specific to open source software, it has implications for how open
source projects use their bug trackers.</para>
<para>The tracker is as much a public face of the project as the
mailing lists or web pages. Anyone may file a ticket, anyone may look
at a ticket, and anyone may browse the list of currently open tickets.
It follows that you never know how many people are waiting to see
progress on a given ticket. While the size and skill of the
development community constrains the rate at which tickets can be
resolved, the project should at least try to acknowledge each ticket
the moment it appears. Even if the ticket lingers for a while, a
response encourages the reporter to stay involved, because she feels
that a human has registered what she has done (remember that filing a
ticket usually involves more effort than, say, posting an email).
Furthermore, once a ticket is seen by a developer, it enters the
project's consciousness, in the sense that the developer can be on the
lookout for other instances of the ticket, can talk about it with
other developers, etc.</para>
<para>This centrality to the life of the project implies a few things
about trackers' technical features:
<itemizedlist>
<listitem>
<para>The tracker should be connected to email, such that
every change to a ticket, including its initial filing, causes a
notification mail to go out to some set of appropriate
recipients. See <xref linkend="bug-tracker-email-interaction"/>
later in this chapter for more on this.</para>
</listitem>
<listitem>
<para>The form for filing tickets should have a place to record
the reporter's email address or other contact information, so she
can be contacted for more details. But if possible, it should not
<emphasis>require</emphasis> the reporter's email address or real
identity, as some people prefer to report anonymously. See <xref
linkend="anonymity"/><phrase output="printed"> later in this
chapter</phrase> for more on the importance of anonymity.</para>
</listitem>
<listitem>
<para>The tracker should have APIs. I cannot stress the
importance of this enough. If there is no way to interact with
the tracker programmatically, then in the long run there is no way
to interact with it scalably. APIs provide a route to customizing
the behavior of the tracker by, in effect, expanding it to include
third-party software. Instead of being just the specific ticket
tracking software running on a server somewhere, it's that
software <emphasis>plus</emphasis> whatever custom behaviors your
project implements elsewhere and plugs in to the tracker via the
APIs.</para>
<para>Also, if your project uses a proprietary ticket tracker,
as is becoming more common now that so many projects host their
code on proprietary-but-free-of-charge hosting sites and just use
the site's built-in tracker, APIs provide a way to avoid being
locked in to that hosting platform. You can, in theory, take the
ticket history with you if you choose to go somewhere else (you
may never exercise this option, but think of it as
insurance — and some projects have actually done
it).</para>
<para>Currently, the ticket trackers of the big three hosting
sites (GitHub, Google Code Hosting, and SourceForge) all have
APIs, fortunately. Of them, only SourceForge is itself open
source, running a platform called
<firstterm>Allura</firstterm><footnote><para>Oddly, SourceForge's
API was also the hardest to find documentation for, though it
helps once you know the platform's name is "Allura". For
reference, their API documentation is here: <ulink
url="http://sourceforge.net/p/forge/documentation/Allura%20API/"
>sourceforge.net/p/forge/documentation/Allura%20API</ulink
></para></footnote>.</para>
</listitem>
</itemizedlist>
</para>
<sect2 id="bug-tracker-email-interaction">
<!-- For link compatibility with old section ID. -->
<anchor id="bug-tracker-mailing-list-interaction" />
<title>Interaction with Email</title>
<para>Most trackers now have at least decent email integration
features: at a minimum, the ability to create new tickets by email,
the ability to "subscribe" to a ticket to receive
emails about activity on that ticket, and the ability to add new
comments to a ticket by email. Some trackers even allow one to
manipulate ticket state (e.g., change the status field, the assignee,
etc) by email, and for people who use the tracker a lot, such as an
<xref linkend="issue-manager" >issue manager</xref>, that can make a
huge difference in their ability to stay on top of tracker activity
and keep things organized.</para>
<para>The tracker email feature that is likely to be used by everyone,
though, is simply the ability to read a ticket's activity by email and
respond by email. This is a valuable time-saver for many people in
the project, since it makes it easy to integrate bug traffic into
one's daily email flow. But don't let this integration give
anyone the illusion that the total collection of bug tickets and their
email traffic is the equivalent of the development mailing list. It's
not, and <xref linkend="choose-the-forum"/><phrase output="printed">
in <xref linkend="communications"/></phrase> discusses why this is
important and how to manage the difference.</para>
</sect2>
<sect2 id="bug-filtering">
<title>Pre-Filtering the Bug Tracker</title>
<para>Most ticket databases eventually suffer from the same problem: a
crushing load of duplicate or invalid tickets filed by well-meaning but
inexperienced or ill-informed users. The first step in combatting
this trend is usually to put a prominent notice on the front page of
the bug tracker, explaining how to tell if a bug is really a bug, how
to search to see if it's already been reported, and finally, how to
effectively report it if one still thinks it's a new bug.</para>
<para>This will reduce the noise level for a while, but as the number
of users increases, the problem will eventually come back. No
individual user can be blamed for it. Each one is just trying to
contribute to the project's well-being, and even if their first bug
report isn't helpful, you still want to encourage them to stay
involved and file better tickets in the future. In the meantime,
though, the project needs to keep the ticket database as free of junk
as possible.</para>
<para>The two things that will do the most to prevent this problem
are: making sure there are people watching the bug tracker who have
enough knowledge to close tickets as invalid or duplicates the moment
they come in, and requiring (or strongly encouraging) users to confirm
their bugs <emphasis>with other people</emphasis> before filing them
in the tracker.</para>
<para>The first technique seems to be used universally. Even projects
with huge ticket databases (say, the Debian bug tracker at
<ulink url="http://bugs.debian.org/" >bugs.debian.org</ulink>, which
contained 739,542 tickets as of this writing) still arrange things so that
<emphasis>someone</emphasis> sees each ticket that comes in. It may be
a different person depending on the category of the ticket. For
example, the Debian project is a collection of software packages, so
Debian automatically routes each ticket to the appropriate package
maintainers. Of course, users can sometimes misidentify a ticket's
category, with the result that the ticket is sent to the wrong person
initially, who may then have to reroute it. However, the important
thing is that the burden is still shared—whether the user
guesses right or wrong when filing, ticket watching is still
distributed more or less evenly among the developers, so each ticket is
able to receive a timely response.</para>
<para>The second technique is less widespread, probably because it's
harder to automate. The essential idea is that every new ticket gets
"buddied" into the database. When a user thinks he's found a problem,
he is asked to describe it on one of the mailing lists, or in an IRC
channel, and get confirmation from someone that it is indeed a bug.
Bringing in that second pair of eyes early can prevent a lot of
spurious reports. Sometimes the second party is able to identify that
the behavior is not a bug, or is fixed in recent releases. Or she may
be familiar with the symptoms from a previous ticket, and can prevent a
duplicate filing by pointing the user to the older ticket. Often it's
enough just to ask the user "Did you search the bug tracker to see if
it's already been reported?" Many people simply don't think of that,
yet are happy to do the search once they know someone's
<emphasis>expecting</emphasis> them to.</para>
<para>The buddy system can really keep the ticket database clean, but
it has some disadvantages too. Many people will file solo anyway,
either through not seeing, or through disregarding, the instructions
to find a buddy for new tickets. Thus it is still necessary for
volunteers to watch the ticket database. Furthermore, because most new
reporters don't understand how difficult the task of maintaining the
ticket database is, it's not fair to chide them too harshly for
ignoring the guidelines. Thus the volunteers must be vigilant, and
yet exercise restraint in how they bounce unbuddied tickets back to
their reporters. The goal is to train each reporter to use the
buddying system in the future, so that there is an ever-growing pool
of people who understand the ticket-filtering system. On seeing an
unbuddied ticket, the ideal steps are:</para>
<orderedlist>
<listitem>
<para>Immediately respond to the ticket, politely thanking the user
for filing, but pointing them to the buddying guidelines
(which should, of course, be prominently posted on the web
site).</para>
</listitem>
<listitem>
<para>If the ticket is clearly valid and not a duplicate, approve it
anyway, and start it down the normal life cycle. After all,
the reporter's now been informed about buddying, so there's
no point closing a valid ticket and wasting the work done so
far.</para>
</listitem>
<listitem>
<para>Otherwise, if the ticket is not clearly valid, close it, but
ask the reporter to reopen it if they get confirmation from
a buddy. When they do, they should put a reference to the
confirmation thread (e.g., a URL into the mailing list
archives).</para>
</listitem>
</orderedlist>
<para>Remember that although this system will improve the signal/noise
ratio in the ticket database over time, it will never completely stop
the misfilings. The only way to prevent misfilings entirely is to
close off the bug tracker to everyone but developers—a cure that
is almost always worse than the disease. It's better to accept that
cleaning out invalid tickets will always be part of the project's
routine maintenance, and to try to get as many people as possible to
help.</para>
<para>See also
<xref linkend="issue-manager"/><phrase output="printed"> in
<xref linkend="managing-volunteers"/></phrase>.</para>
</sect2>
</sect1>
<sect1 id="irc">
<title>IRC / Real-Time Chat Systems</title>
<para>Many projects offer real-time chat rooms using
<firstterm>Internet Relay Chat</firstterm>
(<firstterm>IRC</firstterm>), forums where users and developers can
ask each other questions and get instant responses. IRC has been
around for a long time, and its primarily text-based interface and
command language can look old-fashioned — but don't be
fooled: the number of people using IRC continues to
grow<footnote><para>See <ulink url="http://freenode.net/history.shtml"
>freenode.net/history.shtml</ulink> for example.</para></footnote>,
and it is a key communications forum for many open source projects.
It's generally the only place where developers can meet in a shared
space for real-time conversation on a regular basis.</para>
<para>If you've never used IRC before, don't be daunted. It's not
hard; although there isn't space in this book for an IRC primer,
<ulink url="http://irchelp.org/" >irchelp.org</ulink> is a good guide
to IRC usage and administration, and in particular see the tutorial at
<ulink url="http://www.irchelp.org/irchelp/irctutorial.html"
>irchelp.org/irchelp/irctutorial.html</ulink>. While in theory your
project <emphasis>could</emphasis> run its own IRC servers, it is
generally not worth the hassle. Instead, just do what everyone else
does: host your project's IRC channels<footnote><para>An IRC
<firstterm>channel</firstterm> is a single "chat
room" — a shared space in which people can "talk" to
each other using text. A given IRC server usually hosts many
different channels. When a user connects to the server, she chooses
which of those channels to join, or her client software remembers and
auto-joins them for her. To speak to a particular person in an IRC
channel, it is standard to address them by their username
(<firstterm>nickname</firstterm> or <firstterm>nick</firstterm>), so
they can pick out your inquiry from the other conversation in the
room; see <ulink
url="http://www.rants.org/2013/01/09/the-irc-curmudgeon/"
>rants.org/2013/01/09/the-irc-curmudgeon</ulink> for more on this
practice.</para></footnote> at Freenode (<ulink
url="http://freenode.net/" >freenode.net</ulink>). Freenode gives you
the control you need to administer your project's IRC channels, while
sparing you the not-insignificant trouble of maintaining an IRC server
yourself.</para>
<para>The first thing to do is choose a channel name. The most
obvious choice is the name of your project—if that's available
at Freenode, then use it. If not, try to choose something as close to
your project's name, and as easy to remember, as possible. Advertise
the channel's availabity from your project's web site, so a visitor
with a quick question will see it right away.<footnote><para>In fact,
you can even offer an IRC chat portal right on your web site. See
<ulink url="https://webchat.freenode.net/"
>webchat.freenode.net</ulink> — from the dropdown menu
in the upper left corner, choose "Add webchat to your site" and follow
the instructions.</para></footnote>. If your project's channel gets
too noisy, you can divide into multiple channels, for example one for
installation problems, another for usage questions, another for
development chat, etc (<xref linkend="growth"/><phrase
output="printed"> in <xref linkend="communications"/></phrase>
discusses when and how to divide into multiple channels). But when
your project is young, there should only be one channel, with everyone
talking together. Later, as the user-to-developer ratio increases,
separate channels may become necessary.</para>
<para>How will people know all the available channels, let alone which
channel to talk in? And when they talk, how will they know what the
local conventions are?</para>
<para>The answer is to tell them by setting the <firstterm>channel
topic</firstterm>.<footnote><para>To set a channel topic, use the
<literal>/topic</literal> command. All commands in IRC start with
"<literal>/</literal>".</para></footnote> The channel topic is a brief
message each user sees when they first enter the channel. It gives
quick guidance to newcomers, and pointers to further information. For
example:</para>
<screen>
The Apache (TM) Subversion (R) version control system
(http://subversion.apache.org/) | Don't ask to ask; just ask your
question! | Read the book: http://www.svnbook.org/ | No one here? Try
http://subversion.apache.org/mailing-lists |
http://subversion.apache.org/faq | Subversion 1.8.8 and 1.7.16 released
</screen>
<para>That's terse, but it tells newcomers what they need to know. It
says exactly what the channel is for, gives the project home page (in
case someone wanders into the channel without having first been to the
project web site), gives a pointer to some documentation, and gives
recent release news.</para>
<sidebar id="paste-sites">
<title>Paste Sites</title>
<para>An IRC channel is a shared space: everyone can see what everyone
else is saying. Normally, this is a good thing, as it allows people
to jump into a conversation when they think they have something to
contribute, and allows spectators to learn by watching. But it
becomes problematic when someone has to provide a large quantity of
information at once, such as a large error message or a transcript
from a debugging session, because pasting too many lines of output
into the room will disrupt other conversations.</para>
<para>The solution is to use one of the
<firstterm>pastebin</firstterm> or <firstterm>pastebot</firstterm>
sites. When requesting a large amount of data from someone, ask them
not to paste it into the channel, but instead to go to (for example)
<ulink url="http://pastebin.ca/" >pastebin.ca</ulink>, paste their
data into the form there, and tell the resulting new URL to the IRC
channel. Anyone can then visit the URL and view the data.</para>
<para>There are many free paste sites available, far too many for a
comprehensive list. Three that I seen used a lot are GitHub Gists
(<ulink url="https://gist.github.com/" >gist.github.com</ulink>),
<ulink url="http://paste.lisp.org/" >paste.lisp.org</ulink> and <ulink
url="http://pastebin.ca/" >pastebin.ca</ulink>. But there are many
other fine ones, and it's okay if different people in your IRC channel
choose to use different paste sites.</para>
</sidebar>
<sect2 id="irc-bots">
<!-- For link compatibility with the old section ID. -->
<anchor id="bots" />
<title>IRC Bots</title>
<para>Many technically-oriented IRC channels have a non-human member,
a so-called <firstterm>bot</firstterm>, that is capable of storing and
regurgitating information in response to specific commands.
Typically, the bot is addressed just like any other member of the
channel, that is, the commands are delivered by "speaking to" the bot.
For example:</para>
<screen>
<kfogel> wayita: learn diff-cmd = http://subversion.apache.org/faq.html#diff-cmd
<wayita> Thanks!
</screen>
<para>That told the bot, who is logged into the channel as wayita, to
remember a certain URL as the answer to the query "diff-cmd" (wayita
responded, confirming with a "Thanks!"). Now we can address wayita,
asking the bot to tell another user about diff-cmd:</para>
<screen>
<kfogel> wayita: tell jrandom about diff-cmd
<wayita> jrandom: http://subversion.apache.org/faq.html#diff-cmd
</screen>
<para>The same thing can be accomplished via a convenient shorthand:</para>
<screen>
<kfogel> !a jrandom diff-cmd
<wayita> jrandom: http://subversion.apache.org/faq.html#diff-cmd
</screen>
<para>The exact command set and behaviors differ from bot to bot
(unfortunately, the diversity of IRC bot command languages seems to be
rivaled only by the diversity of wiki syntaxes). The above example
happens to be with <literal>wayita</literal> (<ulink
url="http://repos.borg.ch/svn/wayita/trunk/"
>repos.borg.ch/svn/wayita/trunk</ulink>), of which there is usually an
instance running in <literal>#svn</literal> at Freenode, but there are
many other IRC bots available. Note that no special server privileges
are required to run a bot. A bot is just like any other user joining
a channel.</para>
<para>If your channel tends to get the same questions over and over,
I highly recommend setting up a bot. Only a small percentage of
channel users will acquire the expertise needed to manipulate the bot,
but those users will answer a disproportionately high percentage of
questions, because the bot enables them to respond so much more
efficiently.</para>
<sect3 id="irc-commit-notifications">
<!-- For link compatibility with the old section ID. -->
<anchor id="cia" />
<title>Commit Notifications in IRC</title>
<para>You can also configure a bot to watch your project's version
control repository and broadcast commit activity to the relevant IRC
channels. Though of somewhat less technical utility than commit
emails, since observers might or might not be around when a commit
notice pops up in IRC, this technique is of immense
<emphasis>social</emphasis> utility. People get the sense of being
part of something alive and active, and feel that they can see
progress being made right before their eyes. And because the
notifications appear in a shared space, people in the chat room will
often react in real time, reviewing the commit and commenting on it on
the spot. The technical details of setting this up are beyond the
scope of this book, but it's usually worth the effort. This service
used to be provided in an easy-to-use way by the much-missed <ulink
url="http://cia.vc/" >cia.vc</ulink>, which shut down in 2011, but
several replacements are available: Notifico (<ulink
url="http://n.tkte.ch/" >n.tkte.ch</ulink>), Irker (<ulink
url="http://www.catb.org/esr/irker/" >catb.org/esr/irker</ulink>), and
KGB (<ulink url="http://kgb.alioth.debian.org/"
>kgb.alioth.debian.org</ulink>).</para>
</sect3>
</sect2>
<sect2 id="irc-archiving">
<title>Archiving IRC</title>
<para>Although it is possible to publicly archive everything that
happens in an IRC channel, it's not necessarily expected. IRC
conversations are nominally public, but many people think of them as
informal and ephemeral conversations. Users may be careless with
grammar, and often express opinions (for example, about other software
or other programmers) that they wouldn't want preserved forever in a
searchable online archive. Of course, there will sometimes be
<emphasis>excerpts</emphasis> that get quoted elsewhere, and that's
fine. But indiscriminate public logging may make some users uneasy.
If you do archive everything, make sure you state so clearly in the
channel topic, and give a URL to the archive.</para>
</sect2>
</sect1>
<sect1 id="rss">
<title>RSS Feeds</title>
<para><firstterm>RSS</firstterm> (Really Simple Syndication) is a
mechanism for distributing meta-data-rich news summaries to
"subscribers", that is, people who have indicated an interest in
receiving those summaries. A given RSS source is usually called
a <firstterm>feed</firstterm>, and the user's subscription interface
is called a <firstterm>feed reader</firstterm> or <firstterm>feed
aggregator</firstterm>. <ulink url="http://www.rssbandit.org/">RSS
Bandit</ulink> and the eponymous
<ulink url="http://www.feedreader.com/">Feedreader</ulink> are two
open source RSS readers, for example.</para>
<para>There is not space here for a detailed technical explanation of
RSS<footnote><para>See
<ulink url="http://www.xml.com/pub/a/2002/12/18/dive-into-xml.html"
>xml.com/pub/a/2002/12/18/dive-into-xml.html</ulink>
for that.</para></footnote>, but you should be aware of two main
things. First, the feed reading software is chosen by the subscriber
and is <emphasis>the same</emphasis> for all the feeds that subscriber
monitors — in fact, this is the major selling point of
RSS: that the subscriber chooses one interface to use for all their
feeds, so each feed can concentrate just on delivering content.
Second, RSS is now ubiquitous, so much so that most people who use it
don't even know they're using it. To the world at large, RSS looks
like a little button on a web page, with a label saying "Subscribe to
this site" or "News feed". You click on the button, and from then on,
your feed reader (which may well be an applet embedded in your home
page) automatically updates whenever there's news from the
site.</para>
<para>This means that your open source project should probably offer
an RSS feed (note that many of the canned hosting
sites — see
<xref linkend="canned-hosting"/> — offer it right out
of the box). Be careful not to post so many news items each day that
subscribers can't separate the wheat from the chaff. If there are too
many news events, people will just ignore the feed, or even
unsubscribe in exasperation. Ideally, a project would offer separate
feeds, one for big announcements, another following (say) events in
the ticket tracker, another for each mailing list, etc. In practice,
this is hard to do well: it can result in interface confusion both for
visitors to the project's web site and for the administrators. But at
a minimum, the project should offer one RSS feed on the front page,
for sending out major announcements such as releases and security
alerts.<footnote><para>Credit where credit is due: this section wasn't
in the first published edition of the book, but Brian Aker's blog
entry
<ulink url="http://krow.livejournal.com/564980.html">"Release Criteria,
Open Source, Thoughts On..."</ulink> reminded me of the usefulness of
RSS feeds for open source projects.</para></footnote></para>
<!-- TODO Rex Karz recommends http://lzone.de/liferea/ as a mature
feedreader; is using it as a replacement for Google Reader.
Not sure if we want to recommend feed readers though. -->
</sect1>
<sect1 id="wikis">
<title>Wikis</title>
<para>When open source software project wikis go bad, they usually go
bad for the same reasons: lack of consistent organization and editing,
leading to a mess of outdated and redundant pages, and lack of clarity
on who the target audience is for a given page or section.</para>
<para>A well-run wiki can be a wonderful thing for users, however, and
is worth some effort to maintain. Try to have a clear page
organization strategy and even a pleasing visual layout, so that
visitors (i.e., potential editors) will instinctively know how to fit
their contributions in. Make sure the intended audience is clear at
all times to all editors. Most importantly, document these standards
in the wiki itself and point people to them, so editors have somewhere
to go for guidance. Too often, wiki administrators fall victim to the
fantasy that because hordes of visitors are individually adding high
quality content to the site, the sum of all these contributions must
therefore also be of high quality. That's not how collaborative
editing works. Each individual page or paragraph may be good when
considered by itself, but it will not be good if embedded in a
disorganized or confusing whole.</para>
<para>In general, wikis will amplify any failings that are present
from early on, since contributors tend to imitate whatever patterns
they see in front of them. So don't just set up the wiki and hope
everything falls into place. You must also prime it with well-written
content, so people have a template to follow.</para>
<para>The shining example of a well-run wiki is Wikipedia, of course,
and in some ways it makes a poor example because it gets so much more
editorial attention than any other wiki in the world. Still, if you
examine Wikipedia closely, you'll see that its administrators laid a
<emphasis>very</emphasis> thorough foundation for cooperation. There
is extensive documentation on how to write new entries, how to
maintain an appropriate point of view, what sorts of edits to make,
what edits to avoid, a dispute resolution process for contested edits
(involving several stages, including eventual arbitration), and so
forth. They also have authorization controls, so that if a page is
the target of repeated inappropriate edits, they can lock it down
until the problem is resolved. In other words, they didn't just throw
some templates onto a web site and hope for the best. Wikipedia works
because its founders give careful thought to getting thousands of
strangers to tailor their writing to a common vision. While you may
not need the same level of preparedness to run a wiki for a free
software project, the spirit is worth emulating.</para>
<sect2 id="wiki-spam">
<title>Wikis and Spam</title>
<para>Never allow open, anonymous editing on your wiki. The days when
that was possible are <emphasis>long</emphasis> gone now; today, any
open wiki other than Wikipedia will be covered completely with spam in
approximately 3 milliseconds. (Wikipedia is an exception because it
has an exceptionally large number of readers willing to clean up spam
quickly, and because it has a well-funded organization behind it
devoted to resisting spam using various large-scale monitoring
techniques not practically available to smaller projects.)</para>
<para>All edits in your project's wiki must come from registered
users; if your wiki software doesn't already enforce this by default,
then configure it to enforce that. Even then you may need to keep
watch for spam edits from users who registered under false pretences
for the purpose of spamming.</para>
</sect2>
<sect2 id="wiki-choosing">
<title>Choosing a Wiki</title>
<para>If your project is on GitHub or some other free hosting site,
it's usually best to use the built-in wiki feature that most such
sites offer. That way your wiki will be automatically integrated with
your repository or other project permissions, and you can rely on the
site's user account system instead of having a separate registration
system for the wiki.</para>
<para>If you are setting up your own wiki, then you're free to choose
which one, and fortunately there are plenty of good free software wiki
implementations available. I've had good experience with DokuWiki
(<ulink url="https://www.dokuwiki.org/dokuwiki"
>dokuwiki.org/dokuwiki</ulink>), but there are many others. There is
a wonderful tool called the Wiki Choice Wizard at <ulink
url="http://www.wikimatrix.org/" >wikimatrix.org</ulink> that allows
you to specify the features you care about (an open source license can
be one of them) and then view a chart comparing all the wiki software
that meets those criteria. Another good resource is Wikipedia's own
list of wikis: <ulink
url="http://en.wikipedia.org/wiki/List_of_wiki_software"
>en.wikipedia.org/wiki/List_of_wiki_software</ulink>.</para>
<para>I do not recommend using MediaWiki (<ulink
url="https://www.mediawiki.org" >mediawiki.org</ulink>) as the wiki
software for most projects. MediaWiki is the software on which
Wikipedia itself runs, and while it is very good at that, its
administrative facilities are tuned to the needs of a site unlike any
other wiki on the Net — and actually not so well-tuned
to the needs of smaller editing communities. Many projects are
tempted to choose MediaWiki because they think it will be easier for
users who already know its editing syntax from having edited at
Wikipedia, but this turns out to be an almost non-existent advantage
for several reasons. First, wikis in general, including Wikipedia,
are tending toward rich-text in-browser editing anyway, so that no one
really needs to learn the underlying wiki syntax unless they aim to be
a power user. Second, many other wikis offer a MediaWiki-syntax
plugin, so you can have that syntax anyway if you really want it.
Third, for those who will use a plaintext syntax instead of rich-text
editing, it's better to use a standardized generic markup format like
Markdown (<ulink url="http://daringfireball.net/projects/markdown/"
>daringfireball.net/projects/markdown</ulink>), which is available in
many wikis either natively or via a plugin, than to use a wiki syntax
of any flavor. If you support Markdown, then people can edit in your
wiki using the same markup syntax they already know from GitHub and
other popular tools.</para>
</sect2>
</sect1>
<sect1 id="q-and-a-forums">
<title>Q&A Forums</title>
<para>In the past few years, online question-and-answer forums (or
<firstterm>Q&A forums</firstterm>) have gone from being an
afterthought offered by the occasional project to an increasingly
expected and normal component of user-facing services. A high-quality
Q&A forum is like a FAQ with nearly real-time
updates — indeed, if your Q&A forum is
sufficiently healthy, it often makes sense to either use it directly
as your project's FAQ, or have the FAQ consist mostly of pointers to
the forum's most popular items.</para>
<para>A project can certainly host its own forums, and many do, using
free software such as <ulink url="http://askbot.com" >Askbot</ulink>,
<ulink url="http://osqa.net" >OSQA</ulink>, <ulink
url="http://shapado.com/" >Shapado</ulink>, or <ulink
url="http://www.coordino.com/" >Coordino</ulink>. However, there are
also some third-party services that aggregate questions and answers,
the best-known of which, <ulink url="http://stackoverflow.com/"
>stackoverflow.com</ulink>, frequently has its answers coming up first
in generic search engine results for popular questions.</para>
<para>While Stack Overflow hosts Q&A about many things, not just
about open source projects, it seems to have found the right
combination of cultural guidelines and upvoting/downvoting features to
enable its contributors to quickly narrow in on good answers for
questions about open source software in particular. (The questions
and answers on Stack Overflow are freely licensed, although the code
that runs the site itself is not open source.) On the other hand,
projects that host their own Q&A forums are lately doing pretty
well in search engine results too. It may be that the current
dominance of Stack Overflow, as of this writing in 2014, is partly
just an accident of timing, and that the real lesson is that
Q&A-style forums are an important addition to the free software
project communications toolbox — one that scales
better with user base than many other tools do.</para>
<para>There is no definite answer to the question of whether or when
you should set up dedicated Q&A forums for your project. It
depends on available resources, on the type of project, the
demographics of the user community, etc. But do keep an eye out for
Stack Overflow results, or other third-party results, coming up in
generic question-style searches about your project. Their presence may
indicate that it's time to consider setting up a dedicated Q&A
forum. Whether you do or not, the project can still learn a lot from
looking at what people are asking on Stack Overflow, and at the
responses.</para>
</sect1>
<sect1 id="social-networking">
<title>Social Networking Services</title>
<para><emphasis>24 March 2013: If you're reading this note, then
you've encountered this section while it's undergoing substantial
revision; see <ulink url="http://producingoss.com/v2.html"
>producingoss.com/v2.html</ulink> for details.</emphasis></para>
<para>poss2 todo: subsections for Twitter, Facebook, any others.
Twitter is useful; Facebook appears not to be so relevant to open
source projects but check this with people who use it more. Identi.ca
(if will persist). Others? Eventbrite (mention from
"meeting-in-person" section), what else? Acknowledge that many of
these services are not open source; times have changed, the train has
left the barn or the horse has left the station or whatever. One good
example: LibreOffice's "@AskLibreOffice" tweet stream at <ulink
url="https://twitter.com/AskLibreOffice"
>twitter.com/AskLibreOffice</ulink>. See also <ulink
url="http://ask.libreoffice.org/en/questions/"
>ask.libreoffice.org</ulink>
</para>
</sect1>
</chapter>
<!--
local variables:
sgml-parent-document: ("book.xml" "chapter")
end:
--> |
The Song Editor displays the structure of your song.
http://tangram.dnsalias.net/lmms-imgs/lmms-0.3.1/songeditor-simple.png
Down the left-hand side of the window are listed the instrument and beat/bassline tracks available; on the right of these is listed the activity of each track at each bar in the song. For beat lines this is simply a block showing that the beat/bassline is active; Instruments will have a small display of the notes in a piano roll. Double-clicking on this small note display will bring up the Piano Roll editor for that instrument at that point in time.
= Tracks =
== The anatomy of a track ==
Each track has a section on the left hand side that shows the track tools and settings. The right hand side displays the segments of audio that the track will play over time. The right hand side scrolls left and right to show you a window of time from the song; the whole song editor scrolls up and down to show you the various tracks.
Each track's activity is divided into '''segments'''. For instrument tracks, these display a miniature piano roll; for beat-bassline tracks it simply displayed a filled (shaded) coloured bar for the length of the beat or bassline; for sample tracks it displays a miniature wave display of the sample.
== Adding new tracks ==
You can add new instrument track to the song editor by dragging them from the Side Bar. The instrument's [[Plugins|plugin]] will be displayed, allowing you to make any changes you need to the sound of the instrument. You can dispel this plugin display by using its close button or by clicking on the instrument name button in the song editor.
To add a new beat or bassline track, click the '''add beat/bassline''' button (http://tangram.dnsalias.net/lmms-imgs/lmms-0.3.1/songeditor-button-new-bassline.png) to add a new bassline. Alternatively, you can open the [[Beat Bassline Editor|Beat + Bassline Editor]] and click the '''add beat/bassline''' button (same symbol) to the right of the bassline selector. You can then right-click on the name of the beat/bassline in the song editor in order to rename it to something more identifiable.
To add a new sample track, click the '''add sample-track''' button (http://tangram.dnsalias.net/lmms-imgs/lmms-0.3.1/songeditor-button-new-sampletrack.png) to add a new sample track.
Note that there is no button allowing you to add a new instrument track. This is because you would have to select a plugin for the instrument before the track was created, and this is far easier to do by tradding the correct plugin or preset from the [[Side Bar]].
== Working with existing tracks ==
=== Moving tracks ===
You can drag instruments and beat/bassline tracks up and down in order to organise them by dragging the 'grip' - the stippled handle on the left-hand side of the instrument line (http://tangram.dnsalias.net/lmms-imgs/lmms-0.3.1/songeditor-track-settings-grabbar.png). You can also easily make a copy of an entire track by holding down ''Ctrl'' while dragging the grip.
The button next to the stippled handle is a drop-down menu for the track controls, allowing you to clone or remove the track.
=== Resizing tracks ===
By holding down the '''shift''' key and dragging in a track, you can resize the height of a track. This can be very useful for sample tracks when you need to see more precision in the sample.
=== Scrolling around ===
The scroll bars at the right and bottom of the window allow you to move the segment view around. You can also hold down '''shift''' and use the mouse wheel to scroll horizontally.
=== Zooming in and out ===
The zoom control (http://tangram.dnsalias.net/lmms-imgs/lmms-0.3.1/songeditor-toolbar-zoom-100.png) allows you to choose a magnification control for the segment area. Larger magnifications will show detail more clearly, and smaller magnifications will allow you to see more of the playback. You can also hold down '''ctrl''' and use the mose wheel to control the zoom setting.
== Working with Segments ==
Despite their different content, the ways of working with segments are mostly similar. Most of the work with segments is done using the edit tool (http://tangram.dnsalias.net/lmms-imgs/lmms-0.3.1/songeditor-toolbar-edit.png).
=== The Edit Tool ===
To '''create a new segment''', simply left-click on the track activity inside the bar in which you want the segment to start. For instrument and sample tracks, this creates a blank area to put notes or samples in. For beat and bassline tracks, this creates one bar filled with the bassline as programmed.
To '''move a segment''', simply drag it around by clicking and holding anywhere inside the segment. Normally this will lock to the start of the bar, but you can free drag (with a 1/64th resolution) the segment by pressing the ''control'' key down ''once you have started dragging''.
To '''copy a segment''', simply hold the ''control'' key down ''before you click'' and then drag the segment to its copies' new location. You can also right-click on the segment, choose ''copy'' from the context menu, click to create a new sample where you want the copy to go, right click and choose ''paste'' from the menu. You can't copy segments of one type to tracks of another type, however. To copy more than once, the control key has to be released and re-pressed before the next drag operation.
To '''delete a segment''', click on it using the middle mouse button or right-click on it and choose 'delete' from the context menu.
Double-clicking on a segment aims to '''edit the segment's contents'''. If you double-click on an instrument track segment, the [[Piano Roll Editor]] window will open and the notes in that segment will be displayed for editing. If you double-click on a sample track segment, a file open dialog will display allowing you to choose a new sample for that segment. If you double-click on a beat or bassline segment, the [[Beat Bassline Editor|Beat + Bassline Editor]] window will open and that beat or bassline will be displayed.
=== The Move Tool ===
The '''Move''' tool (http://tangram.dnsalias.net/lmms-imgs/lmms-0.3.1/songeditor-toolbar-move.png) allows you to select a rectangular region of the segments in the tracks and move them as a group.
In addition, you can use '''Shift-Insert''' and '''Shift-Delete''' to move all the segments in the song forward or backward one bar at a time. Effectively, Shift-Insert inserts a new bar at the start of the piece and Shift-Delete removes a bar. Segments that are already at the first bar will not be deleted but other later segments will still move up.
= The Song Editor toolbar =
The Song Editor window has a toolbar that allows you to control playback of the song, add new tracks, choose edit tools, customise the method of playback, and control the view of the song.
== Playback Buttons ==
* The '''Play''' button (http://tangram.dnsalias.net/lmms-imgs/lmms-0.3.1/songeditor-toolbar-play.png) starts playback at the current cursor point.
* The '''Stop''' button (http://tangram.dnsalias.net/lmms-imgs/lmms-0.3.1/songeditor-toolbar-stop.png) stops playback if it has been started and moves the cursor depending on what mode you have chosen in the play control tool (see below).
* While the song is playing, you can use the '''Pause''' button (http://tangram.dnsalias.net/lmms-imgs/lmms-0.3.1/songeditor-toolbar-pause.png) to halt playback without moving the cursor.
== Add Track Buttons ==
* The '''Add Bassline Track''' button (http://tangram.dnsalias.net/lmms-imgs/lmms-0.3.1/songeditor-toolbar-add-bassline.png) allows you to add a new beat / bassline track.
* The '''Add Sample Track''' button (http://tangram.dnsalias.net/lmms-imgs/lmms-0.3.1/songeditor-toolbar-add-sampletrack.png) allows you to add a new sample track, and not to add a new penguin as you may have suspected. Penguins can only be added to LMMS in audio form.
== Editing Tools ==
* The '''Edit''' tool (http://tangram.dnsalias.net/lmms-imgs/lmms-0.3.1/songeditor-toolbar-edit.png) is the main tool used in the Song Editor. You use it to create segments in tracks ([[Song Editor#The Edit Tool|see above]]).
* The '''Move''' tool (http://tangram.dnsalias.net/lmms-imgs/lmms-0.3.1/songeditor-toolbar-move.png) allows you to select regions of segments and move them around as one group ([[Song Editor#The Move Tool|see above]]).
== Playback Controls ==
* The '''Autoscroll''' button (http://tangram.dnsalias.net/lmms-imgs/lmms-0.3.1/songeditor-toolbar-playcontrol-autoscroll-yes.png) is normally turned on. During playback, the view in the song editor will automatically move to include the current playback point. If it moves off the right hand edge of the window, the window will be repositioned so it is at the left hand edge. If the autoscroll button is turned off (http://tangram.dnsalias.net/lmms-imgs/lmms-0.3.1/songeditor-toolbar-playcontrol-autoscroll-no.png), then the window position will not follow the playback point during playback.
* The '''Loop''' button (http://tangram.dnsalias.net/lmms-imgs/lmms-0.3.1/songeditor-toolbar-playcontrol-loop-no.png) is normally turned off. When turned on (http://tangram.dnsalias.net/lmms-imgs/lmms-0.3.1/songeditor-toolbar-playcontrol-loop-yes.png), the loop points are turned on and playback will loop continuously between the start and end loop points. This can be useful when testing a particular section of your piece, but it only exists as a playback mode, not as a way to repeat a section a certain number of times.
* The '''Return''' button controls the way the playback position moves after you halt playback using the stop button (see above). It has three modes:
** '''To Start''' (http://tangram.dnsalias.net/lmms-imgs/lmms-0.3.1/songeditor-toolbar-playcontrol-return-tostart.png) - by default, the playback position will return to the start of the song.
** '''To Before''' (http://tangram.dnsalias.net/lmms-imgs/lmms-0.3.1/songeditor-toolbar-playcontrol-return-tobefore.png) - when in this mode, the playback position will return to the position that it previously started from. This will usually be where you last placed the playback position.
** '''Continue''' (http://tangram.dnsalias.net/lmms-imgs/lmms-0.3.1/songeditor-toolbar-playcontrol-return-cont.png) - in this mode, the playback position will not be moved and playback will commence from where it is stopped.
== Zoom Controls ==
* The final control is the '''Zoom''' control (http://tangram.dnsalias.net/lmms-imgs/lmms-0.3.1/songeditor-toolbar-zoom-100.png). Setting this allows you to control how much detail is shown in the view of the track segments. The larger this is, the more detail you see; the smaller it is, the more of the song you see in the view. You can also hold down '''ctrl''' and use the mouse wheel to zoom in and out.
= The Track Settings bar =
To the left of the track's activity is a set of buttons and controls that allow you to work with the track as a whole.
The grey stippled area immediately at the left of the track (http://tangram.dnsalias.net/lmms-imgs/lmms-0.3.1/songeditor-track-settings-grabbar.png) is the '''grab bar'''. This allows you to grab the track and drag it up and down in the order of tracks. This is very useful since new tracks are, by default, created at the bottom of the track list and you may be adding a track that is logically connected with tracks near the top.
Next appears the '''track tools menu''' icon (http://tangram.dnsalias.net/lmms-imgs/lmms-0.3.1/songeditor-track-settings-tools.png). This displays a drop-down menu with two options: '''clone track''' and '''remove track'''. Cloning a track makes an exact copy of the track and its contents and pastes them at the bottom of the track list. Hopefully it won't be necessary to explain what removing a track does. :-)
After this is the '''mute control''' (http://tangram.dnsalias.net/lmms-imgs/lmms-0.3.1/songeditor-track-settings-mute.png). This allows you to turn off the sound of this track temporarily. This is useful, for example, when you want to hear the sound of an accompanying instrument without the lead instrument. Right clicking on the track gives you the option to [[Working with Automation|automate]] the muting process on the track, although this is strongly discouraged in preference to automating the volume control. Once the automation menu is displayed, right-clicking ''again'' on the control (which will require you to move your mouse slightly to the left) will toggle all the track mute buttons - in other words, all tracks 'on' will be turned 'off' and vice versa.
The rest of the track settings displays the '''sound source''' information. This varies between instrument tracks, sample tracks and beat/bassline tracks.
For instrument tracks you get a volume control (http://tangram.dnsalias.net/lmms-imgs/lmms-0.3.1/songeditor-track-settings-volume.png) (also automatable), a drop-down menu to select the track's midi inputs and outputs (http://tangram.dnsalias.net/lmms-imgs/lmms-0.3.1/songeditor-track-settings-midi.png), and the button that displays the instrument's plugin (http://tangram.dnsalias.net/lmms-imgs/lmms-0.3.1/songeditor-track-settings-plugin.png).
For sample tracks you get a volume control (likewise also automatable), a button which allows you to set up [[LADSPA|effects]] on the samples in the track, and the name of the sample track (which can be edited by right-clicking on it).
For beat / bassline tracks, you get an graphic displaying the content of the pattern (clicking on this gives you a file open dialog open to a directory of icons to allow you to choose an icon which reflects the content of the track) and the pattern's name
(likewise editable with a right-click).
At the far right of the sound source there is an '''activity bar''' ((http://tangram.dnsalias.net/lmms-imgs/lmms-0.3.1/songeditor-track-settings-activity-off.png) which lights up when the instrument is actually playing.
= The Track Context menu =
The track context menu appears when you right-click on a segment of a track's activity. The options presented depend on which type of track it is.
== Instrument Tracks ==
The instrument track context menu looks like this:
<!--{\begin{center}}-->
http://tangram.dnsalias.net/lmms-imgs/lmms-0.3.1/songeditor-contextmenu-instrument.png
<!--{\end{center}}-->
This gives you the most options of all the song editor context menus.
'''Open in piano-roll''' opens the clicked-on segment in the [[Piano Roll Editor]] (strangely enough).
'''Delete''' deletes the clicked-on segment.
'''Cut''' removes the clicked-on segment and puts it in the clipboard.
'''Copy''' takes a copy of the clicked-on segment and puts it in the clipboard.
'''Paste''' pastes the contents of the clipboard into this segment, overwriting its previous contents.
'''Mute/Unmute''' allows you to turn sound off or on for this track while editing it. This does not affect the set volume of the track, but acts like the 'mute' button on a mixing desk.
'''Clear all notes''' allows you to erase the contents of the clicked-on segment without deleting the segment itself.
Normally the name of the instrument is given to the segment. This is copied and pasted with the contents of the segment, so you can see the original source of this segment. '''Reset name''' allows you to reset that name to the name of the instrument plugin of the track, and '''Change name''' allows you to edit it manually.
'''Freeze''' allows you to [[Definitions#F|freeze]] the sound of this track by creating a pre-rendered sample of the track alone. This then cuts down on the workload of rendering this track, which may be useful on lower-powered systems or tracks with complex effects and melodies. You can edit the track's contents while the track is frozen, but the edits do not take effect until it is thawed or refrozen.
'''Add steps''' and '''Remove Steps''' allow you to add or remove a number steps (equal to a 16th note) selected from a submenu to the end of a pattern. This is similar to the same option in the [[Beat Bassline Editor|Beat + Bassline Editor]] but seems to have little purpose here.
== Sample Tracks ==
The sample track context menu looks like this:
<!--{\begin{center}}-->
http://tangram.dnsalias.net/lmms-imgs/lmms-0.3.1/songeditor-contextmenu-sample.png
<!--{\end{center}}-->
The actions of each option are essentially the same as those for the instrument track above.
== Bassline Tracks ==
The bassline track context menu looks like this:
<!--{\begin{center}}-->
http://tangram.dnsalias.net/lmms-imgs/lmms-0.3.1/songeditor-contextmenu-bassline.png
<!--{\end{center}}-->
The actions of each option are essentially the same as those for the instrument track above. The only addition is:
'''Change color''' allows you to change the colour of the bassline track. This allows you to coordinate the function or content of the tracks by their colour, allowing you to quickly work out which bassline in a complex rhythm section you are dealing with.
= Navigation =
Howto: [[Putting the song together]]
{| style="border: 1px solid black;"
|-
| Prev: [[Plugins]]
| Up: [[0.3:Manual]]
| Next: [[Piano Roll Editor]]
|}
[[Category:Reference]]
[[Category:0.3-Manual]] |
import axios from 'axios';
// Animal-specific behavior patterns
const ANIMAL_PATTERNS = {
elk: {
elevation: {
optimal: [6000, 10000],
weight: 0.6
},
cover: {
optimal: 0.7,
weight: 0.7
},
waterDistance: {
optimal: 500, // meters
weight: 0.8
},
temperature: {
optimal: [45, 65],
weight: 0.7
}
},
mule_deer: {
elevation: {
optimal: [4000, 8000],
weight: 0.5
},
cover: {
optimal: 0.5,
weight: 0.8
},
waterDistance: {
optimal: 800, // meters
weight: 0.7
},
temperature: {
optimal: [40, 70],
weight: 0.6
}
},
turkey: {
elevation: {
optimal: [2000, 6000],
weight: 0.4
},
cover: {
optimal: 0.6,
weight: 0.9
},
waterDistance: {
optimal: 400, // meters
weight: 0.6
},
temperature: {
optimal: [50, 75],
weight: 0.5
}
}
};
// Time of day preferences by species
const TIME_WEIGHTS = {
elk: {
DAWN: 1.0,
MORNING: 0.8,
MIDDAY: 0.3,
AFTERNOON: 0.5,
DUSK: 1.0,
NIGHT: 0.4
},
mule_deer: {
DAWN: 1.0,
MORNING: 0.7,
MIDDAY: 0.2,
AFTERNOON: 0.4,
DUSK: 1.0,
NIGHT: 0.6
},
turkey: {
DAWN: 1.0,
MORNING: 0.9,
MIDDAY: 0.5,
AFTERNOON: 0.4,
DUSK: 0.8,
NIGHT: 0.0 // Turkeys roost at night
}
};
// Weather condition impacts by species
const WEATHER_IMPACTS = {
elk: {
WIND_TOLERANCE: 15, // mph
RAIN_TOLERANCE: 0.3, // inches
PRESSURE_SENSITIVITY: 0.4
},
mule_deer: {
WIND_TOLERANCE: 12,
RAIN_TOLERANCE: 0.2,
PRESSURE_SENSITIVITY: 0.5
},
turkey: {
WIND_TOLERANCE: 8,
RAIN_TOLERANCE: 0.1,
PRESSURE_SENSITIVITY: 0.6
}
};
// Seasonal patterns by species
const SEASONAL_PATTERNS = {
elk: {
SPRING: {
elevation: [5000, 8000],
foodSources: ['grass', 'forbs', 'shrubs'],
breeding: false,
migration: 'upward',
migrationFactor: 0.8
},
SUMMER: {
elevation: [7000, 10000],
foodSources: ['grass', 'forbs', 'leaves'],
breeding: false,
migration: 'stable',
migrationFactor: 0.3
},
FALL: {
elevation: [6000, 9000],
foodSources: ['grass', 'shrubs', 'bark'],
breeding: true,
migration: 'downward',
migrationFactor: 0.9
},
WINTER: {
elevation: [4000, 7000],
foodSources: ['bark', 'twigs', 'dried grass'],
breeding: false,
migration: 'stable',
migrationFactor: 0.4
}
},
mule_deer: {
SPRING: {
elevation: [4000, 7000],
foodSources: ['grass', 'forbs', 'new growth'],
breeding: false,
migration: 'upward',
migrationFactor: 0.7
},
SUMMER: {
elevation: [6000, 8000],
foodSources: ['leaves', 'forbs', 'fruits'],
breeding: false,
migration: 'stable',
migrationFactor: 0.3
},
FALL: {
elevation: [5000, 7000],
foodSources: ['shrubs', 'acorns', 'remaining fruits'],
breeding: true,
migration: 'downward',
migrationFactor: 0.8
},
WINTER: {
elevation: [3000, 6000],
foodSources: ['twigs', 'bark', 'evergreen leaves'],
breeding: false,
migration: 'stable',
migrationFactor: 0.4
}
},
turkey: {
SPRING: {
elevation: [2000, 5000],
foodSources: ['insects', 'seeds', 'new growth'],
breeding: true,
migration: 'upward',
migrationFactor: 0.5
},
SUMMER: {
elevation: [2500, 6000],
foodSources: ['insects', 'berries', 'seeds'],
breeding: false,
migration: 'stable',
migrationFactor: 0.2
},
FALL: {
elevation: [2000, 5000],
foodSources: ['acorns', 'nuts', 'berries'],
breeding: false,
migration: 'downward',
migrationFactor: 0.6
},
WINTER: {
elevation: [1500, 4000],
foodSources: ['nuts', 'dried berries', 'buds'],
breeding: false,
migration: 'stable',
migrationFactor: 0.3
}
}
};
// Food source ratings by type
const FOOD_SOURCE_RATINGS = {
grass: { spring: 0.9, summer: 0.8, fall: 0.6, winter: 0.3 },
forbs: { spring: 0.9, summer: 0.7, fall: 0.4, winter: 0.1 },
shrubs: { spring: 0.6, summer: 0.7, fall: 0.8, winter: 0.5 },
bark: { spring: 0.3, summer: 0.2, fall: 0.4, winter: 0.7 },
leaves: { spring: 0.8, summer: 0.9, fall: 0.5, winter: 0.1 },
acorns: { spring: 0.1, summer: 0.1, fall: 0.9, winter: 0.6 },
insects: { spring: 0.8, summer: 0.9, fall: 0.6, winter: 0.1 },
berries: { spring: 0.2, summer: 0.9, fall: 0.7, winter: 0.3 },
nuts: { spring: 0.2, summer: 0.1, fall: 0.9, winter: 0.7 },
seeds: { spring: 0.7, summer: 0.8, fall: 0.9, winter: 0.5 }
};
class PredictionService {
constructor() {
this.weatherApi = axios.create({
baseURL: 'https://api.openweathermap.org/data/2.5',
params: {
appid: process.env.REACT_APP_OPENWEATHER_API_KEY
}
});
}
// Get current weather conditions for a location
async getWeatherConditions(lat, lon) {
try {
const response = await this.weatherApi.get('/weather', {
params: {
lat,
lon,
units: 'imperial'
}
});
return {
temperature: response.data.main.temp,
windSpeed: response.data.wind.speed,
precipitation: response.data.rain ? response.data.rain['1h'] || 0 : 0,
pressure: response.data.main.pressure * 0.02953 // Convert hPa to inHg
};
} catch (error) {
console.error('Error fetching weather data:', error);
return null;
}
}
// Get time of day factor for specific species
getTimeOfDayFactor(hour, species) {
const timeWeights = TIME_WEIGHTS[species];
if (hour >= 5 && hour < 7) return timeWeights.DAWN;
if (hour >= 7 && hour < 10) return timeWeights.MORNING;
if (hour >= 10 && hour < 14) return timeWeights.MIDDAY;
if (hour >= 14 && hour < 17) return timeWeights.AFTERNOON;
if (hour >= 17 && hour < 19) return timeWeights.DUSK;
return timeWeights.NIGHT;
}
// Calculate weather score for specific species
calculateWeatherScore(conditions, species) {
if (!conditions) return 0;
const impacts = WEATHER_IMPACTS[species];
let score = 0;
let weights = 0;
// Temperature factor
const pattern = ANIMAL_PATTERNS[species];
const tempFactor = this.calculateRangeFactor(
conditions.temperature,
pattern.temperature.optimal[0],
pattern.temperature.optimal[1]
);
score += tempFactor * pattern.temperature.weight;
weights += pattern.temperature.weight;
// Wind speed factor
const windFactor = this.calculateRangeFactor(
conditions.windSpeed,
0,
impacts.WIND_TOLERANCE
);
score += windFactor * 0.6;
weights += 0.6;
// Precipitation factor
const precipFactor = this.calculateRangeFactor(
conditions.precipitation,
0,
impacts.RAIN_TOLERANCE
);
score += precipFactor * 0.5;
weights += 0.5;
// Pressure factor
const pressureFactor = this.calculateRangeFactor(
conditions.pressure,
29.8,
30.2
);
score += pressureFactor * impacts.PRESSURE_SENSITIVITY;
weights += impacts.PRESSURE_SENSITIVITY;
return score / weights;
}
// Calculate terrain score for specific species
calculateTerrainScore(location, terrainData, species) {
const pattern = ANIMAL_PATTERNS[species];
let score = 0;
let weights = 0;
// Water source proximity
if (terrainData.waterSources) {
const waterFactor = this.calculateProximityScore(
location,
terrainData.waterSources,
pattern.waterDistance.optimal
);
score += waterFactor * pattern.waterDistance.weight;
weights += pattern.waterDistance.weight;
}
// Elevation suitability
if (terrainData.elevation) {
const elevationFactor = this.calculateRangeFactor(
terrainData.elevation,
pattern.elevation.optimal[0],
pattern.elevation.optimal[1]
);
score += elevationFactor * pattern.elevation.weight;
weights += pattern.elevation.weight;
}
// Cover density
if (terrainData.coverDensity) {
const coverFactor = this.calculateRangeFactor(
terrainData.coverDensity,
pattern.cover.optimal * 0.8,
pattern.cover.optimal * 1.2
);
score += coverFactor * pattern.cover.weight;
weights += pattern.cover.weight;
}
return score / weights;
}
// Calculate how close a value is to the optimal range
calculateRangeFactor(value, min, max) {
if (value >= min && value <= max) return 1;
const midpoint = (min + max) / 2;
const range = max - min;
const distance = Math.abs(value - midpoint);
return Math.max(0, 1 - (distance / range));
}
// Calculate score based on proximity to points of interest
calculateProximityScore(location, points, optimalDistance) {
const distances = points.map(point =>
this.calculateDistance(location, point)
);
const minDistance = Math.min(...distances);
return Math.max(0, 1 - (minDistance / optimalDistance));
}
// Calculate distance between two points in meters
calculateDistance(point1, point2) {
const R = 6371e3; // Earth's radius in meters
const φ1 = point1.lat * Math.PI / 180;
const φ2 = point2.lat * Math.PI / 180;
const Δφ = (point2.lat - point1.lat) * Math.PI / 180;
const Δλ = (point2.lon - point1.lon) * Math.PI / 180;
const a = Math.sin(Δφ/2) * Math.sin(Δφ/2) +
Math.cos(φ1) * Math.cos(φ2) *
Math.sin(Δλ/2) * Math.sin(Δλ/2);
const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
return R * c;
}
// Calculate historical factor based on past sightings
calculateHistoricalFactor(location, historicalData) {
if (!historicalData || historicalData.length === 0) return 0;
const recentSightings = historicalData.filter(sighting => {
const sightingDate = new Date(sighting.timestamp);
const now = new Date();
const daysDiff = (now - sightingDate) / (1000 * 60 * 60 * 24);
return daysDiff <= 30; // Consider sightings from the last 30 days
});
if (recentSightings.length === 0) return 0;
const proximityScores = recentSightings.map(sighting => {
const distance = this.calculateDistance(location, {
lat: sighting.lat,
lon: sighting.lon
});
const daysAgo = (new Date() - new Date(sighting.timestamp)) / (1000 * 60 * 60 * 24);
const timeDecay = Math.exp(-daysAgo / 30); // Exponential decay over 30 days
return Math.max(0, 1 - (distance / 1000)) * timeDecay;
});
return Math.max(...proximityScores);
}
// Get current season
getSeason(date) {
const month = date.getMonth();
if (month >= 2 && month <= 4) return 'SPRING';
if (month >= 5 && month <= 7) return 'SUMMER';
if (month >= 8 && month <= 10) return 'FALL';
return 'WINTER';
}
// Calculate seasonal adjustment
calculateSeasonalFactor(location, species, date) {
const season = this.getSeason(date);
const pattern = SEASONAL_PATTERNS[species][season];
let score = 0;
let weights = 0;
// Elevation adjustment for season
const elevationFactor = this.calculateRangeFactor(
location.elevation,
pattern.elevation[0],
pattern.elevation[1]
);
score += elevationFactor * 0.4;
weights += 0.4;
// Migration pattern impact
if (pattern.migration !== 'stable') {
score += pattern.migrationFactor * 0.3;
weights += 0.3;
}
// Breeding season impact
if (pattern.breeding) {
score += 0.8 * 0.3;
weights += 0.3;
}
return score / weights;
}
// Calculate food availability score
calculateFoodScore(foodSources, species, date) {
const season = this.getSeason(date).toLowerCase();
const pattern = SEASONAL_PATTERNS[species][season.toUpperCase()];
let totalScore = 0;
for (const source of foodSources) {
if (pattern.foodSources.includes(source.type)) {
const rating = FOOD_SOURCE_RATINGS[source.type][season];
const distance = this.calculateDistance(source.location, source);
const proximityFactor = Math.max(0, 1 - (distance / 1000));
totalScore += rating * proximityFactor;
}
}
return Math.min(1, totalScore / pattern.foodSources.length);
}
// Generate predictions for all species
async generatePredictions(bounds, terrainData, historicalData = []) {
const predictions = [];
const now = new Date();
const hour = now.getHours();
const centerLat = (bounds.north + bounds.south) / 2;
const centerLon = (bounds.east + bounds.west) / 2;
const weather = await this.getWeatherConditions(centerLat, centerLon);
const species = ['elk', 'mule_deer', 'turkey'];
const gridSize = 10;
const latStep = (bounds.north - bounds.south) / gridSize;
const lonStep = (bounds.east - bounds.west) / gridSize;
for (const animalType of species) {
const weatherScore = this.calculateWeatherScore(weather, animalType);
const timeScore = this.getTimeOfDayFactor(hour, animalType);
for (let i = 0; i < gridSize; i++) {
for (let j = 0; j < gridSize; j++) {
const lat = bounds.south + (i * latStep);
const lon = bounds.west + (j * lonStep);
const location = { lat, lon, elevation: terrainData.elevation };
const terrainScore = this.calculateTerrainScore(
location,
terrainData,
animalType
);
const seasonalFactor = this.calculateSeasonalFactor(
location,
animalType,
now
);
const foodScore = this.calculateFoodScore(
terrainData.foodSources || [],
animalType,
now
);
const historicalFactor = this.calculateHistoricalFactor(
location,
historicalData.filter(h => h.type === animalType)
);
const probability = (
weatherScore * 0.2 +
timeScore * 0.15 +
terrainScore * 0.2 +
seasonalFactor * 0.2 +
foodScore * 0.15 +
historicalFactor * 0.1
);
const threshold = animalType === 'turkey' ? 0.7 : 0.6;
if (probability > threshold) {
predictions.push({
lat,
lon,
probability,
type: animalType,
factors: {
weather: weatherScore,
time: timeScore,
terrain: terrainScore,
seasonal: seasonalFactor,
food: foodScore,
historical: historicalFactor
},
season: this.getSeason(now),
breeding: SEASONAL_PATTERNS[animalType][this.getSeason(now)].breeding,
migration: SEASONAL_PATTERNS[animalType][this.getSeason(now)].migration,
preferredFood: SEASONAL_PATTERNS[animalType][this.getSeason(now)].foodSources
});
}
}
}
}
return predictions.sort((a, b) => b.probability - a.probability);
}
}
export default new PredictionService(); |
package pl.globallogic.lessons;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.List;
public class TestAutomation02 {
private boolean isSearchResultItemTitles(WebDriver driver, String validQuery) {
List<WebElement> itemTitles = driver.findElements(By.cssSelector("h3.v2-listing-card__title"));
List<String> tokenizedQuery = List.of(validQuery.toLowerCase().split(" "));
for (WebElement title : itemTitles) {
List<String> tokenizedTitle = List.of(title.getText().toLowerCase().split(" "));
if (!tokenizedTitle.containsAll(tokenizedQuery)) {
return false;
}
}
return true;
}
public static void main(String[] args) {
// Set the path to your ChromeDriver executable
System.setProperty("webdriver.chrome.driver", "/path/to/chromedriver");
// Create a new instance of the ChromeDriver
WebDriver driver = new ChromeDriver();
// Replace with the URL you want to navigate to
driver.get("https://www.example.com");
TestAutomation02 automation = new TestAutomation02();
// Replace with the desired search query
String searchQuery = "your search query";
boolean result = automation.isSearchResultItemTitles(driver, searchQuery);
System.out.println("Search result validation: " + result);
// Close the browser
driver.quit();
}
} |
package com.example.springsecurity.config;
import com.example.springsecurity.filter.JwtAuthenticationTokenFilter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import javax.annotation.Resource;
/**
* @author wxz
* @date 21:13 2023/2/16
*/
@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Resource
private JwtAuthenticationTokenFilter jwtAuthenticationTokenFilter;
@Resource
private AuthenticationEntryPoint authenticationEntryPoint;
@Resource
private AccessDeniedHandler accessDeniedHandler;
/**
* 创建BCryptPasswordEncoder注入容器
*
* @return org.springframework.security.crypto.password.PasswordEncoder
* @author wxz
* @date 21:15 2023/2/16
*/
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
/**
* @return org.springframework.security.authentication.AuthenticationManager
* @author wxz
* @date 12:00 2023/2/17
*/
@Bean
@Override
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
/**
* @param http 请求
* @author wxz
* @date 12:12 2023/2/17
*/
@Override
protected void configure(HttpSecurity http) throws Exception {
http
// 关闭csrf
.csrf().disable()
// 不通过Session获取SecurityContext
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and().authorizeRequests()
// 对于接口 允许匿名访问
.antMatchers("/user/login").anonymous()
// 除上面外的接口都需要权限验证
.anyRequest().authenticated();
// 添加过滤器
http.addFilterBefore(jwtAuthenticationTokenFilter, UsernamePasswordAuthenticationFilter.class);
// 异常处理器
http.exceptionHandling()
.authenticationEntryPoint(authenticationEntryPoint)
.and()
.exceptionHandling()
.accessDeniedHandler(accessDeniedHandler);
// 允许跨域
http.cors();
}
} |
# Given a string s and an integer k, return the maximum number of vowel letters in any substring of s with length k.
# Vowel letters in English are 'a', 'e', 'i', 'o', and 'u'.
# Example 1:
# Input: s = "abciiidef", k = 3
# Output: 3
# Explanation: The substring "iii" contains 3 vowel letters.
# Example 2:
# Input: s = "aeiou", k = 2
# Output: 2
# Explanation: Any substring of length 2 contains 2 vowels.
# Example 3:
# Input: s = "leetcode", k = 3
# Output: 2
# Explanation: "lee", "eet" and "ode" contain 2 vowels.
# Constraints:
# 1 <= s.length <= 105
# s consists of lowercase English letters.
# 1 <= k <= s.length
class Solution:
def maxVowels(self, s: str, k: int) -> int:
# Set of vowels for quick lookup
v = {'a', 'e', 'i', 'o', 'u'}
# Count vowels in the first window of size k
c = 0
for i in range(k):
if s[i] in v:
c += 1
# Track the current maximum
m = c
# Slide the window through the rest of the string
for i in range(k, len(s)):
# Remove the leftmost character if it is a vowel
if s[i - k] in v:
c -= 1
# Add the new rightmost character if it is a vowel
if s[i] in v:
c += 1
# Update the maximum count
if c > m:
m = c
# If we've hit the upper bound (k), return immediately
if m == k:
return k
return m |
package me.moomoo.anarchyexploitfixes.modules.combat;
import com.cryptomorin.xseries.XMaterial;
import me.moomoo.anarchyexploitfixes.AnarchyExploitFixes;
import me.moomoo.anarchyexploitfixes.config.Config;
import me.moomoo.anarchyexploitfixes.modules.AEFModule;
import me.moomoo.anarchyexploitfixes.utils.MaterialUtil;
import org.bukkit.GameMode;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.block.Block;
import org.bukkit.block.BlockFace;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.block.BlockPlaceEvent;
import org.bukkit.event.player.PlayerMoveEvent;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class Burrow implements AEFModule, Listener {
private final Set<Material> SLAB_LIKE;
private final Material AIR, SAND, GRAVEL, DIRT, ENCHANTING_TABLE, ENDER_CHEST, BEACON;
private final double damageWhenMovingInBurrow;
private final boolean shouldTeleportUp, preventIfBlockAboveBurrow, breakAnvilInsteadOfTP, allowSlabs;
public Burrow() {
shouldEnable();
// All slabs and slab-like blocks
this.SLAB_LIKE = new HashSet<>();
this.SLAB_LIKE.addAll(Arrays.stream(XMaterial.values())
.filter(xMaterial -> xMaterial.isSupported() && xMaterial.name().endsWith("_SLAB"))
.map(XMaterial::parseMaterial)
.collect(Collectors.toSet()));
Stream.of(XMaterial.SCULK_SENSOR, XMaterial.SCULK_SHRIEKER, XMaterial.CALIBRATED_SCULK_SENSOR)
.filter(XMaterial::isSupported).map(XMaterial::parseMaterial).forEach(SLAB_LIKE::add);
// Other cached parsed material
this.AIR = XMaterial.AIR.parseMaterial();
this.SAND = XMaterial.SAND.parseMaterial();
this.GRAVEL = XMaterial.GRAVEL.parseMaterial();
this.ENCHANTING_TABLE = XMaterial.ENCHANTING_TABLE.parseMaterial();
this.ENDER_CHEST = XMaterial.ENDER_CHEST.parseMaterial();
this.BEACON = XMaterial.BEACON.parseMaterial();
this.DIRT = XMaterial.DIRT.parseMaterial();
Config config = AnarchyExploitFixes.getConfiguration();
this.damageWhenMovingInBurrow = config.getDouble(configPath() + ".damage-when-moving",1.0,
"1.0 = Half a heart of damage every time you move.");
this.shouldTeleportUp = config.getBoolean(configPath() + ".teleport-above-block", true);
this.preventIfBlockAboveBurrow = config.getBoolean(configPath() + ".prevent-if-block-above-burrow", false,
"Prevent burrow even if there is a block above the block they are burrowing in.\n" +
"Please note this may allow creating an \"elevator\", as players will keep teleporting up until they hit air.");
this.breakAnvilInsteadOfTP = config.getBoolean(configPath() + ".break-anvil-instead-of-teleport", true);
boolean slabsAreAllowed = config.getBoolean(configPath() + ".allow-slabs-in-burrow", true,
"Disabled by default in 1.12, needs to be enabled to prevent a bug where players are teleported\n" +
"above a slab when the slab is under water, only happens in newer versions.");
this.allowSlabs = AnarchyExploitFixes.getMCVersion() > 12 && slabsAreAllowed;
}
@Override
public String configPath() {
return "combat.prevent-burrow";
}
@Override
public void enable() {
AnarchyExploitFixes plugin = AnarchyExploitFixes.getInstance();
plugin.getServer().getPluginManager().registerEvents(this, plugin);
}
@Override
public boolean shouldEnable() {
return AnarchyExploitFixes.getConfiguration().getBoolean(configPath() + ".enable", false);
}
private void teleportUpAndCenter(Player player, Location from) {
player.teleport(from.clone().add(0.5, 1, 0.5));
}
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
private void onSelfPlace(BlockPlaceEvent event) {
final Location blockLoc = event.getBlock().getLocation();
Location legsLoc = event.getPlayer().getLocation().toBlockLocation();
if (legsLoc.equals(blockLoc) || legsLoc.add(0, 1, 0).equals(blockLoc)) {
event.setCancelled(true);
}
}
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
private void onPlayerMove(PlayerMoveEvent event) {
Player player = event.getPlayer();
if (!player.getGameMode().equals(GameMode.SURVIVAL)) return;
if (player.isInsideVehicle() || player.isGliding()) return;
final Location playerLocation = player.getLocation();
final Block burrowBlock = playerLocation.getBlock();
final Material burrowMaterial = burrowBlock.getType();
if (
burrowMaterial.equals(AIR)
|| burrowMaterial.equals(DIRT) // Fixes false positives when trampling farmland
|| burrowMaterial.equals(SAND)
|| burrowMaterial.equals(GRAVEL)
|| MaterialUtil.SHULKER_BOXES.contains(burrowMaterial)
) return;
if (preventIfBlockAboveBurrow || burrowBlock.getRelative(BlockFace.UP).getType().equals(AIR)) {
// Occluding Blocks
if (burrowMaterial.isOccluding() && !MaterialUtil.SINK_IN_BLOCKS.contains(burrowMaterial)) {
if (!allowSlabs || !SLAB_LIKE.contains(burrowMaterial)) {
player.damage(damageWhenMovingInBurrow);
if (shouldTeleportUp) teleportUpAndCenter(player, burrowBlock.getLocation());
}
return;
}
// Ender chests and blocks that are slightly lower in height
if (burrowMaterial.equals(ENDER_CHEST) || MaterialUtil.SINK_IN_BLOCKS.contains(burrowMaterial)) {
if (playerLocation.getY() - playerLocation.getBlockY() < 0.875) {
player.damage(damageWhenMovingInBurrow);
if (shouldTeleportUp) teleportUpAndCenter(player, burrowBlock.getLocation());
}
return;
}
// Enchantment Tables
if (burrowMaterial.equals(ENCHANTING_TABLE)) {
if (playerLocation.getY() - playerLocation.getBlockY() < 0.75) {
player.damage(damageWhenMovingInBurrow);
if (shouldTeleportUp) teleportUpAndCenter(player, burrowBlock.getLocation());
}
return;
}
// Anvils
if (MaterialUtil.ANVILS.contains(burrowMaterial)) {
player.damage(damageWhenMovingInBurrow);
if (breakAnvilInsteadOfTP) {
burrowBlock.breakNaturally();
} else {
if (shouldTeleportUp) teleportUpAndCenter(player, burrowBlock.getLocation());
}
return;
}
// Beacons and Indestructibles
if (burrowMaterial.equals(BEACON) || MaterialUtil.SOLID_INDESTRUCTIBLES.contains(burrowMaterial)) {
player.damage(damageWhenMovingInBurrow);
if (shouldTeleportUp) teleportUpAndCenter(player, burrowBlock.getLocation());
}
}
}
} |
package com.flashcardapp.gui;
import com.flashcardapp.FlashcardApp;
import com.flashcardapp.util.ConfigHandler;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.scene.control.Alert;
import javafx.scene.control.ButtonType;
import javafx.scene.control.ChoiceBox;
/**
* Controller for handling settings-related interactions in the FlashcardApp.
*/
public class SettingsSceneController {
@FXML
private ChoiceBox<String> themeChoiceBox;
/**
* Initializes the settings scene with the current theme choice.
*/
@FXML
public void initialize() {
themeChoiceBox.getItems().addAll("light", "dark");
String currentTheme = ConfigHandler.getInstance().getOption("theme", String.class);
themeChoiceBox.setValue(currentTheme);
}
/**
* Handles navigation back to the main scene.
*/
@FXML
public void handleBack(ActionEvent actionEvent) {
FlashcardApp.getInstance().setFXMLScene("MainScene");
}
/**
* Handles the theme change operation.
*/
@FXML
public void handleThemeChange(ActionEvent actionEvent) {
String selectedTheme = themeChoiceBox.getValue().toLowerCase();
FlashcardApp.getInstance().setTheme(selectedTheme);
ConfigHandler.getInstance().saveOption("theme", selectedTheme);
}
/**
* Displays an informational dialog about the application.
*/
@FXML
public void handleAbout(ActionEvent actionEvent) {
Alert alert = createAboutAlert();
alert.showAndWait();
}
/**
* Handles data reset with confirmation.
*/
@FXML
public void handleResetData(ActionEvent actionEvent) {
if (confirmAction("Reset Data", "Are you sure you want to reset all data?",
"This will delete all decks and flashcards. This action cannot be undone.")) {
FlashcardApp.getInstance().resetData();
ConfigHandler.getInstance().saveOption("theme", "light"); // Resets theme to default
}
}
/**
* Creates an alert dialog for the 'About' section with app details.
* @return Configured Alert.
*/
private Alert createAboutAlert() {
Alert alert = new Alert(Alert.AlertType.INFORMATION);
alert.initOwner(FlashcardApp.getInstance().getPrimaryStage());
// update style
alert.getDialogPane().getStylesheets().add(getClass().getResource("/com/flashcardapp/gui/" + FlashcardApp.getInstance().getTheme()).toExternalForm());
alert.setTitle("About Flashcard Study Helper");
alert.setHeaderText("Flashcard Study Helper");
alert.setContentText("This application is a simple flashcard study helper that allows you to " +
"create, edit, and study flashcards.\n\nVersion: 1.0\n" +
"Authors: Carson Kelley, Andrew Abdelaty, Brayden Kielb, Spencer Morse, " +
"and Vic Westmoreland\nLicense: MIT License\n\n" +
"Icon by Freepik from www.flaticon.com\nhttps://www.flaticon.com/authors/freepik\n\n" +
"Created as a final project for CPS 240 at Central Michigan University.");
return alert;
}
/**
* Displays a confirmation dialog and returns the result.
* @param title Title of the dialog.
* @param header Header text for the dialog.
* @param content Detailed content/message of the dialog.
* @return true if the user confirmed, false otherwise.
*/
private boolean confirmAction(String title, String header, String content) {
Alert alert = new Alert(Alert.AlertType.CONFIRMATION);
alert.setTitle(title);
alert.setHeaderText(header);
alert.setContentText(content);
return alert.showAndWait().filter(response -> response == ButtonType.OK).isPresent();
}
} |
/*
* CDDL HEADER START
*
* The contents of this file are subject to the terms of the
* Common Development and Distribution License (the "License").
* You may not use this file except in compliance with the License.
*
* You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
* or http://www.opensolaris.org/os/licensing.
* See the License for the specific language governing permissions
* and limitations under the License.
*
* When distributing Covered Code, include this CDDL HEADER in each
* file and include the License file at usr/src/OPENSOLARIS.LICENSE.
* If applicable, add the following below this CDDL HEADER, with the
* fields enclosed by brackets "[]" replaced with your own identifying
* information: Portions Copyright [yyyy] [name of copyright owner]
*
* CDDL HEADER END
*/
/*
* Copyright 2007 Sun Microsystems, Inc. All rights reserved.
* Use is subject to license terms.
*/
#ifndef _DS_IMPL_H
#define _DS_IMPL_H
#pragma ident "%Z%%M% %I% %E% SMI"
#ifdef __cplusplus
extern "C" {
#endif
/*
* The Domain Services Protocol
*
* The DS protocol is divided into two parts. The first is fixed and
* must remain exactly the same for *all* versions of the DS protocol.
* The only messages supported by the fixed portion of the protocol are
* to negotiate a version to use for the rest of the protocol.
*/
/*
* Domain Services Header
*/
typedef struct ds_hdr {
uint32_t msg_type; /* message type */
uint32_t payload_len; /* payload length */
} ds_hdr_t;
#define DS_HDR_SZ (sizeof (ds_hdr_t))
/*
* DS Fixed Message Types
*/
#define DS_INIT_REQ 0x0 /* initiate DS connection */
#define DS_INIT_ACK 0x1 /* initiation acknowledgment */
#define DS_INIT_NACK 0x2 /* initiation negative acknowledgment */
/*
* DS Fixed Initialization Messages
*/
typedef struct ds_init_req {
uint16_t major_vers; /* requested major version */
uint16_t minor_vers; /* requested minor version */
} ds_init_req_t;
typedef struct ds_init_ack {
uint16_t minor_vers; /* highest supported minor version */
} ds_init_ack_t;
typedef struct ds_init_nack {
uint16_t major_vers; /* alternate supported major version */
} ds_init_nack_t;
/*
* DS Message Types for Version 1.0
*/
#define DS_REG_REQ 0x3 /* register a service */
#define DS_REG_ACK 0x4 /* register acknowledgment */
#define DS_REG_NACK 0x5 /* register failed */
#define DS_UNREG 0x6 /* unregister a service */
#define DS_UNREG_ACK 0x7 /* unregister acknowledgment */
#define DS_UNREG_NACK 0x8 /* unregister failed */
#define DS_DATA 0x9 /* data message */
#define DS_NACK 0xa /* data error */
/* result codes */
#define DS_OK 0x0 /* success */
#define DS_REG_VER_NACK 0x1 /* unsupported major version */
#define DS_REG_DUP 0x2 /* duplicate registration attempted */
#define DS_INV_HDL 0x3 /* service handle not valid */
#define DS_TYPE_UNKNOWN 0x4 /* unknown message type received */
/*
* Service Register Messages
*/
typedef struct ds_reg_req {
uint64_t svc_handle; /* service handle to register */
uint16_t major_vers; /* requested major version */
uint16_t minor_vers; /* requested minor version */
char svc_id[1]; /* service identifier string */
} ds_reg_req_t;
typedef struct ds_reg_ack {
uint64_t svc_handle; /* service handle sent in register */
uint16_t minor_vers; /* highest supported minor version */
} ds_reg_ack_t;
typedef struct ds_reg_nack {
uint64_t svc_handle; /* service handle sent in register */
uint64_t result; /* reason for the failure */
uint16_t major_vers; /* alternate supported major version */
} ds_reg_nack_t;
/*
* Service Unregister Messages
*/
typedef struct ds_unreg_req {
uint64_t svc_handle; /* service handle to unregister */
} ds_unreg_req_t;
typedef struct ds_unreg_ack {
uint64_t svc_handle; /* service handle sent in unregister */
} ds_unreg_ack_t;
typedef struct ds_unreg_nack {
uint64_t svc_handle; /* service handle sent in unregister */
} ds_unreg_nack_t;
/*
* Data Transfer Messages
*/
typedef struct ds_data_handle {
uint64_t svc_handle; /* service handle for data */
} ds_data_handle_t;
typedef struct ds_data_nack {
uint64_t svc_handle; /* service handle sent in data msg */
uint64_t result; /* reason for failure */
} ds_data_nack_t;
/*
* Message Processing Utilities
*/
#define DS_MSG_TYPE_VALID(type) ((type) <= DS_NACK)
#define DS_MSG_LEN(ds_type) (sizeof (ds_hdr_t) + sizeof (ds_type))
/*
* Domain Service Port
*
* A DS port is a logical representation of an LDC dedicated to
* communication between DS endpoints. The ds_port_t maintains state
* associated with a connection to a remote endpoint. This includes
* the state of the port, the LDC state, the current version of the
* DS protocol in use on the port, and other port properties.
*
* Locking: The port is protected by a single mutex. It must be held
* while the port structure is being accessed and also when data is
* being read or written using the port
*/
typedef enum {
DS_PORT_FREE, /* port structure not in use */
DS_PORT_INIT, /* port structure created */
DS_PORT_LDC_INIT, /* ldc successfully initialized */
DS_PORT_INIT_REQ, /* initialization handshake sent */
DS_PORT_READY /* init handshake completed */
} ds_port_state_t;
typedef struct ds_ldc {
uint64_t id; /* LDC id */
ldc_handle_t hdl; /* LDC handle */
ldc_status_t state; /* current LDC state */
} ds_ldc_t;
typedef struct ds_port {
kmutex_t lock; /* port lock */
uint64_t id; /* port id from MD */
ds_port_state_t state; /* state of the port */
ds_ver_t ver; /* DS protocol version in use */
uint32_t ver_idx; /* index of version during handshake */
ds_ldc_t ldc; /* LDC for this port */
} ds_port_t;
/*
* A DS portset is a bitmap that represents a collection of DS
* ports. Each bit represent a particular port id. The current
* implementation constrains the maximum number of ports to 64.
*/
typedef uint64_t ds_portset_t;
#define DS_MAX_PORTS ((sizeof (ds_portset_t)) * 8)
#define DS_MAX_PORT_ID (DS_MAX_PORTS - 1)
#define DS_PORT_SET(port) (1UL << (port))
#define DS_PORT_IN_SET(set, port) ((set) & DS_PORT_SET(port))
#define DS_PORTSET_ADD(set, port) ((void)((set) |= DS_PORT_SET(port)))
#define DS_PORTSET_DEL(set, port) ((void)((set) &= ~DS_PORT_SET(port)))
#define DS_PORTSET_ISNULL(set) ((set) == 0)
#define DS_PORTSET_DUP(set1, set2) ((void)((set1) = (set2)))
/*
* LDC Information
*/
#define DS_STREAM_MTU 4096
/*
* Machine Description Constants
*/
#define DS_MD_ROOT_NAME "domain-services"
#define DS_MD_PORT_NAME "domain-services-port"
#define DS_MD_CHAN_NAME "channel-endpoint"
/*
* DS Services
*
* A DS Service is a mapping between a DS capability and a client
* of the DS framework that provides that capability. It includes
* information on the state of the service, the currently negotiated
* version of the capability specific protocol, the port that is
* currently in use by the capability, etc.
*/
typedef enum {
DS_SVC_INVAL, /* svc structure uninitialized */
DS_SVC_FREE, /* svc structure not in use */
DS_SVC_INACTIVE, /* svc not registered */
DS_SVC_REG_PENDING, /* register message sent */
DS_SVC_ACTIVE /* register message acknowledged */
} ds_svc_state_t;
typedef struct ds_svc {
ds_capability_t cap; /* capability information */
ds_clnt_ops_t ops; /* client ops vector */
ds_svc_hdl_t hdl; /* handle assigned by DS */
ds_svc_state_t state; /* current service state */
ds_ver_t ver; /* svc protocol version in use */
uint_t ver_idx; /* index into client version array */
ds_port_t *port; /* port for this service */
ds_portset_t avail; /* ports available to this service */
} ds_svc_t;
#define DS_SVC_ISFREE(svc) ((svc == NULL) || (svc->state == DS_SVC_FREE))
/*
* A service handle is a 64 bit value with two pieces of information
* encoded in it. The upper 32 bits is the index into the table of
* a particular service structure. The lower 32 bits is a counter
* that is incremented each time a service structure is reused.
*/
#define DS_IDX_SHIFT 32
#define DS_COUNT_MASK 0xfffffffful
#define DS_ALLOC_HDL(_idx, _count) (((uint64_t)_idx << DS_IDX_SHIFT) | \
((uint64_t)(_count + 1) & \
DS_COUNT_MASK))
#define DS_HDL2IDX(hdl) (hdl >> DS_IDX_SHIFT)
#define DS_HDL2COUNT(hdl) (hdl & DS_COUNT_MASK)
/*
* DS Message Logging
*
* The DS framework logs all incoming and outgoing messages to a
* ring buffer. This provides the ability to reconstruct a trace
* of DS activity for use in debugging. In addition to the message
* data, each log entry contains a timestamp and the destination
* of the message. The destination is based on the port number the
* message passed through (port number + 1). The sign of the dest
* field distinguishes incoming messages from outgoing messages.
* Incoming messages have a negative destination field.
*/
typedef struct ds_log_entry {
struct ds_log_entry *next; /* next in log or free list */
struct ds_log_entry *prev; /* previous in log */
time_t timestamp; /* time message added to log */
size_t datasz; /* size of the data */
void *data; /* the data itself */
int32_t dest; /* message destination */
} ds_log_entry_t;
#define DS_LOG_IN(pid) (-(pid + 1))
#define DS_LOG_OUT(pid) (pid + 1)
/*
* DS Log Limits:
*
* The size of the log is controlled by two limits. The first is
* a soft limit that is configurable by the user (via the global
* variable ds_log_sz). When this limit is exceeded, each new
* message that is added to the log replaces the oldest message.
*
* The second is a hard limit that is calculated based on the soft
* limit (DS_LOG_LIMIT). It is defined to be ~3% above the soft limit.
* Once this limit is exceeded, a thread is scheduled to delete old
* messages until the size of the log is below the soft limit.
*/
#define DS_LOG_DEFAULT_SZ (4 * 1024 * 1024) /* 4 MB */
#define DS_LOG_LIMIT (ds_log_sz + (ds_log_sz >> 5))
#define DS_LOG_ENTRY_SZ(ep) (sizeof (ds_log_entry_t) + (ep)->datasz)
/*
* DS Log Memory Usage:
*
* The log free list is initialized from a pre-allocated pool of entry
* structures (the global ds_log_entry_pool). The number of entries
* in the pool (DS_LOG_NPOOL) is the number of entries that would
* take up half the default size of the log.
*
* As messages are added to the log, entry structures are pulled from
* the free list. If the free list is empty, memory is allocated for
* the entry. When entries are removed from the log, they are placed
* on the free list. Allocated memory is only deallocated when the
* entire log is destroyed.
*/
#define DS_LOG_NPOOL ((DS_LOG_DEFAULT_SZ >> 1) / \
sizeof (ds_log_entry_t))
#define DS_LOG_POOL_END (ds_log_entry_pool + DS_LOG_NPOOL)
#define DS_IS_POOL_ENTRY(ep) (((ep) >= ds_log_entry_pool) && \
((ep) <= &(ds_log_entry_pool[DS_LOG_NPOOL])))
#ifdef __cplusplus
}
#endif
#endif /* _DS_IMPL_H */ |
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
font-family: 'Roboto', sans-serif; /* Mudei para Roboto como fonte principal */
background-color: #f4f4f4;
color: #333;
text-align: center;
}
/* Estilo para o header */
header {
display: flex;
justify-content: space-between; /* Título à esquerda e menu à direita */
align-items: center; /* Centraliza verticalmente */
background-color: black;
padding: 20px;
color: #E75480;
box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
}
header h1{
color: #eead2d;
}
h1 {
font-size: 24px;
margin: 0;
padding: 0;
}
h4 {
color: #eead2d;
}
ul {
list-style: none; /* Remove as bolinhas do menu */
margin: 0;
padding: 0;
}
ul li {
display: inline-block;
margin-left: 20px; /* Espaçamento entre os itens do menu */
}
ul li a {
text-decoration: none;
color: #E75480;
font-size: 18px;
font-weight: 500;
transition: color 0.3s;
}
ul li a:hover {
color: #fff; /* Muda a cor ao passar o mouse */
}
/* Estilo da imagem */
img {
max-width: 250px; /* A imagem não pode exceder a largura do seu contêiner */
height: auto; /* Mantém a proporção da imagem */
margin: 20px 0; /* Espaçamento acima e abaixo da imagem */
}
/* Estilo geral do conteúdo */
#usuario {
margin: 20px 0;
font-size: 18px;
}
/* Estilo para o saldo */
#saldoContainer {
margin: 20px 0;
}
#saldo {
font-size: 20px;
font-weight: bold;
}
/* Estilo do formulário de transferência */
form {
margin: 20px auto;
padding: 20px;
background: #fff;
border-radius: 8px;
box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
width: 80%;
max-width: 400px; /* Limita a largura do formulário */
}
label {
display: block;
margin-bottom: 5px;
}
input[type="number"],
select {
border-radius: 5px;
border: 1px solid #ccc;
padding: 10px;
width: calc(100% - 22px); /* Ajusta para a borda e preenchimento */
margin-bottom: 15px;
}
input[type="number"]:focus,
select:focus {
border-color: #007BFF;
box-shadow: 0 0 5px rgba(0, 123, 255, 0.5);
outline: none;
}
/* Estilo para botões */
button {
padding: 10px 20px;
background-color: #28a745;
border: none;
border-radius: 5px;
color: white;
cursor: pointer;
font-size: 18px;
transition: background-color 0.3s;
}
button:hover {
background-color: #218838; /* Muda a cor do botão ao passar o mouse */
}
/* Estilo da tabela */
table {
width: 100%; /* Tabela ocupa 100% do contêiner */
margin: 20px 0;
border-collapse: collapse; /* Remove espaços entre as células */
background-color: #fff;
}
th, td {
padding: 10px; /* Espaçamento interno das células */
text-align: left;
border-bottom: 1px solid #ddd; /* Linha separadora entre as células */
}
th {
background-color: #28a745; /* Fundo verde para o cabeçalho da tabela */
color: white;
}
tr:hover {
background-color: #f5f5f5; /* Destaque ao passar o mouse sobre as linhas */
}
/* Estilo para mensagens de erro e sucesso */
.error {
color: red;
}
.success {
color: green;
font-weight: 500;
padding: 10px 0;
}
#notificacoes {
position: relative;
cursor: pointer;
}
#notificacoesPresentes {
display: none;
background-color: #f9f9f9;
border: 1px solid #ddd;
padding: 10px;
position: absolute;
top: 40px;
right: 0;
width: 300px;
box-shadow: 0 2px 5px rgba(0, 0, 0, 0.3);
z-index: 1000;
}
#notificacoesPresentes ul {
list-style-type: none;
padding: 0;
}
#notificacoesPresentes ul li {
background-color: #ffeeba;
margin-bottom: 5px;
padding: 10px;
border-radius: 5px;
display: flex;
align-items: center;
}
#notificacoesPresentes ul li img {
width: 50px;
height: 50px;
margin-right: 10px;
}
#limparNotificacoes {
margin-top: 10px;
padding: 5px 10px;
background-color: #ff6f61;
color: white;
border: none;
border-radius: 5px;
cursor: pointer;
}
#limparNotificacoes:hover {
background-color: #ff4c3a;
}
#notificacoes.active {
color: orange; /* Muda a cor do sino */
animation: glow 1s infinite; /* Efeito de brilho */
}
@keyframes glow {
0% { text-shadow: 0 0 8px orange; }
50% { text-shadow: 0 0 20px orange; }
100% { text-shadow: 0 0 5px orange; }
}
/* Responsivo */
@media (max-width: 768px) {
header {
flex-direction: column; /* Alinha em coluna em telas menores */
justify-content: center; /* Centraliza os itens */
align-items: center; /* Centraliza os itens verticalmente */
gap: 10px; /* Espaço entre o título e o menu */
}
img {
max-width: 80%; /* Aumenta a largura máxima da imagem em dispositivos móveis */
}
form {
width: 90%; /* Aumenta a largura do formulário em dispositivos móveis */
}
h1 {
font-size: 20px; /* Reduz o tamanho da fonte do título em telas menores */
}
ul li {
display: block; /* Coloca o menu em coluna para caber em telas menores */
margin: 10px 0; /* Adiciona espaçamento entre os itens */
}
ul li a {
font-size: 16px; /* Reduz o tamanho da fonte do menu */
}
} |
import Foundation
import UIKit
final class CustomHeaderView: UIView {
private lazy var stackView: UIStackView = {
let sv = UIStackView()
sv.translatesAutoresizingMaskIntoConstraints = false
sv.axis = .vertical
sv.spacing = 10
sv.distribution = .fill
return sv
}()
var finalPrediction = ""
var probabilityAndResult: (Int, String, PredictionResultType) = (0, "", .LESS_THAN_30_MINUTES) { didSet { didUpdateProbabilityAndResult() } }
private lazy var warningLabel: UILabel = {
let l = UILabel()
l.translatesAutoresizingMaskIntoConstraints = false
l.font = UIFont.systemFont(ofSize: 14, weight: .semibold)
l.textColor = .secondaryLabel
l.text = initialText
l.numberOfLines = 0
l.setContentHuggingPriority(.defaultHigh, for: .vertical)
return l
}()
private lazy var clickHereButton: UIButton = {
let b = UIButton()
b.translatesAutoresizingMaskIntoConstraints = false
b.setTitleColor(.blue, for: .normal)
b.setTitle("Click here to find alternatives →", for: .normal)
b.titleLabel?.font = .systemFont(ofSize: 15, weight: .bold)
b.titleLabel?.textAlignment = .left
b.addTarget(self, action: #selector(didClickSearchAlternatives), for: .touchUpInside)
return b
}()
var initialText = "No delay prediction available for this flight."
var onTapClickHere: ((Int) -> Void)? = nil
override init(frame: CGRect) {
super.init(frame: frame)
setUpLayout()
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func resetText() {
warningLabel.text = initialText
}
private func setUpLayout() {
addSubview(stackView)
stackView.addArrangedSubview(warningLabel)
stackView.addArrangedSubview(clickHereButton)
clickHereButton.isHidden = true
setUpConstraints()
}
private func setUpConstraints() {
NSLayoutConstraint.activate([
stackView.topAnchor.constraint(equalTo: topAnchor),
stackView.leadingAnchor.constraint(equalTo: leadingAnchor, constant: 30),
trailingAnchor.constraint(equalTo: stackView.trailingAnchor, constant: 30),
bottomAnchor.constraint(equalTo: stackView.bottomAnchor)
])
}
private func didUpdateProbabilityAndResult() {
let index = probabilityAndResult.0
let probability = probabilityAndResult.1.integerValue
let result = probabilityAndResult.2
DispatchQueue.main.async {
let newLine = self.finalPrediction == "" ? "" : "\n"
var prediction = "\(newLine)Flight no. \(index) has \(probability)% chance of being \(result.description)"
switch (probability, result) {
case (_, .LESS_THAN_30_MINUTES):
prediction = "\(newLine)Flight no. \(index) is usually on time"
self.warningLabel.textColor = .systemGreen
self.clickHereButton.isHidden = true
case ((0...29), .BETWEEN_30_AND_60_MINUTES):
self.warningLabel.textColor = .systemOrange
self.clickHereButton.isHidden = self.onTapClickHere == nil
default:
self.warningLabel.textColor = .systemRed
self.clickHereButton.isHidden = self.onTapClickHere == nil
}
self.finalPrediction.append(prediction)
self.warningLabel.text = self.finalPrediction
}
}
@objc private func didClickSearchAlternatives() {
self.onTapClickHere?(self.tag-100)
}
} |
import streamlit as st
import joblib
import pandas as pd
teams = ['Rajasthan Royals ',
'Royal Challengers Bangalore',
'Sunrisers Hyderabad',
'Delhi Capitals',
'Chennai Super Kings',
'Gujarat Titans',
'Lucknow Super Giants',
'Kolkata Knight Riders',
'Punjab Kings',
'Mumbai Indians']
logos = {'Mumbai Indians': "MI.png",
'Rajasthan Royals': "RR.png",
'Royal Challengers Bangalore': "RCB.png",
'Sunrisers Hyderabad': "SRH.png",
'Delhi Capitals': "DC.png",
'Chennai Super Kings': "CSK.png",
'Gujarat Titans': "GT.png",
'Lucknow Super Giants': "LSG.png",
'Kolkata Knight Riders': "KKR.png",
'Punjab Kings': "PBKS.png",
}
def set_bg_hack_url():
st.markdown(
f"""
<style>
.stApp {{
color: white;
text-align:center;
padding: 1rem;
}}
</style>
""",
unsafe_allow_html=True
)
set_bg_hack_url()
cities = ['Ahmedabad', 'Kolkata', 'Mumbai', 'Navi Mumbai', 'Pune', 'Dubai',
'Sharjah', 'Abu Dhabi', 'Delhi', 'Chennai', 'Hyderabad',
'Visakhapatnam', 'Chandigarh', 'Bengaluru', 'Jaipur', 'Indore',
'Bangalore', 'Raipur', 'Ranchi', 'Cuttack', 'Dharamsala', 'Nagpur',
'Johannesburg', 'Centurion', 'Durban', 'Bloemfontein',
'Port Elizabeth', 'Kimberley', 'East London', 'Cape Town']
pipe = joblib.load('pipe.joblib')
st.title("IPL Winner Predictor")
default_batting_team = 'Mumbai Indians'
default_bowling_team = 'Chennai Super Kings'
default_city = 'Mumbai'
default_target_score = 180
default_current_score = 100 # Change this to your desired default current score
default_overs_completed = 10 # Change this to your desired default overs completed
default_wickets = 3 # Change this to your desired default wickets
# ... (rest of your code)
col1, col2 = st.columns(2)
# Team selection
with col1:
batting_team = st.selectbox(
"Batting Team", teams, index=teams.index(default_batting_team), key="batting"
)
with col2:
bowling_team = st.selectbox(
"Bowling Team", teams, index=teams.index(default_bowling_team), key="bowling"
)
col3, col4 = st.columns(2)
with col3:
city = st.selectbox("Host City", cities, index=cities.index(default_city))
with col4:
target_score = st.slider("Target Score", 0, 300, default_target_score)
# Sliders for current score, overs, and wickets
col5, col6, col7 = st.columns(3)
with col5:
current_score = st.slider("Current Score", 0, 300, default_current_score)
with col6:
overs_completed = st.slider("Overs Completed", 0, 20, default_overs_completed)
with col7:
wickets = st.slider("Wickets Out", 0, 10, default_wickets)
if st.button("Predict Probability"):
runs_left = target_score - current_score
balls_left = 120 - (overs_completed*6)
wickets_left = 10 - wickets
current_run_rate = current_score/overs_completed
required_run_rate = (runs_left*6)/balls_left
input_df = pd.DataFrame({'BattingTeam': [batting_team],
'BowlingTeam': [bowling_team],
'City': [city],
'runs_left': [runs_left],
'balls_left': [balls_left],
'wickets_left': [wickets_left],
'current_run_rate': [current_run_rate],
'required_run_rate': [required_run_rate],
'target': [target_score]})
result = pipe.predict_proba(input_df)
loss = result[0][0]
win = result[0][1]
col6, col7 = st.columns(2)
with col6:
st.image(logos[batting_team], caption=None, width=250,
clamp=False, channels="RGB", output_format="auto")
st.subheader(batting_team + ': ' + str(round(win * 100)) + '%')
with col7:
st.image(logos[bowling_team], caption=None, width=250,
clamp=False, channels="RGB", output_format="auto")
st.subheader(bowling_team + ': ' + str(round(loss * 100)) + '%')
pass |
"use client";
import { useState, useRef } from "react";
import { Select } from "antd";
import { spaceListig } from "@/service/storageService";
import { useDispatch, useSelector } from "react-redux";
import { setListStorage } from "@/app/globalRedux/Feature/ListStorage";
const formInputStyle =
"w-full px-2 py-2 mt-0 border rounded-md focus:outline-none focus:bg-white";
const formLabelStyle = "block text-[#1B1C57] text-sm font-normal mt-4 ";
const formSelectStyle =
"w-full px-2 py-2 mt-0 border rounded-md focus:outline-none focus:bg-white";
const options = [
{
label: "Fire Extinguisher",
value: "FireExtinguisher",
},
{
label: "Smoke Free",
value: "SmokeFree",
},
{
label: "Security Camera",
value: "SecurityCamera",
},
{
label: "Locked Area",
value: "LockedArea",
},
{
label: "Guarded Society",
value: "GuardedSociety",
},
{
label: "Moisture Free",
value: "MoistureFree",
},
{
label: "Pest Control",
value: "PestControl",
},
{
label: "Separate Access",
value: "SeparateAccess",
},
{
label: "Smoke Detector",
value: "SmokeDetector",
},
];
const SpaceDetails = ({
setPropertyId,
setCurrentItem,
userId,
setBankDetails,
}) => {
const [multipleError, setMultipleError] = useState({});
const [data, setData] = useState({});
const [error, setError] = useState();
const dispatch = useDispatch();
const {
listStorage: { value: reduxData },
} = useSelector((state) => state);
const formRef = useRef(null);
const onChange = (e) => {
setError();
setMultipleError({});
const { name, value } = e.target;
setData({ ...data, [name]: value });
dispatch(setListStorage({ ...data, ...reduxData, [name]: value }));
};
const onsubmitHandler = async (event) => {
event.preventDefault();
const allKeys = Object.keys(reduxData);
const formData = new FormData();
allKeys.forEach((item) => {
if (item === "stage1.Amenities") {
reduxData[item]?.length && formData.append(item, reduxData[item]);
} else {
formData.append(item, reduxData[item]);
}
});
const parameter = `?ApplicationUserId=${userId}&stage=1`;
const response = await spaceListig(formData, parameter);
if (response.success) {
setPropertyId(response.success.data.propertyId);
dispatch(
setListStorage({
...reduxData,
["propertyId"]: response.success.data.propertyId,
})
);
setBankDetails(response.success?.customerBankAccount);
setCurrentItem("spaceAddress");
} else {
setMultipleError(response?.error?.text);
const firstErrorKey = Object.keys(response?.error?.text)[0];
const firstErrorElement = formRef.current.querySelector(
`[data-error=${firstErrorKey}]`
);
if (firstErrorElement) {
firstErrorElement.scrollIntoView({
behavior: "smooth",
block: "center",
});
}
}
};
return (
<>
<form ref={formRef} onSubmit={onsubmitHandler}>
<div class="tab-pane mx-2 z-2 " role="tabpanel" id="step1">
<h4 class="text-[16px] md:text-[20px] font-semibold text-[#1B1C57] mb-2 ">
Space Details
</h4>
<div className="flex-col items-center justify-between my-2">
<label htmlFor="storageType" className={formLabelStyle}>
Property Type <span className="text-red-500">*</span>
</label>
<select
id="storageType"
className={formSelectStyle}
name="stage1.PropertyType"
onChange={onChange}
defaultValue={reduxData["stage1.PropertyType"]}
required=""
data-error="PropertyType"
>
<option value="" disabled selected>
Select
</option>
<option value="Residential">Residential</option>
<option value="Commercial">Commercial</option>
</select>
{multipleError?.PropertyType && (
<p className="text-sm text-red-500">
{multipleError.PropertyType}
</p>
)}
</div>
<div className="flex-col items-center justify-between my-2">
<label htmlFor="storageType" className={formLabelStyle}>
Storage Type <span className="text-red-500">*</span>
</label>
<select
id="propertyType"
className={formSelectStyle}
name="stage1.StorageType"
onChange={onChange}
defaultValue={reduxData["stage1.StorageType"]}
data-error="StorageType"
>
<option className="text-gray-500" value="" disabled selected>
Select
</option>
<option value="Independent">Independent</option>
<option value="Shared">Shared</option>
</select>
{multipleError?.StorageType && (
<p className="text-sm text-red-500">
{multipleError.StorageType}
</p>
)}
</div>
<div className="flex-col items-center justify-between my-2">
<label htmlFor="storagePurpose" className={formLabelStyle}>
What would you like to store?
<span className="text-red-500">*</span>
</label>
<select
id="storagePurpose"
className={formSelectStyle}
name="stage1.Category"
onChange={onChange}
defaultValue={reduxData["stage1.Category"]}
data-error="Category"
>
<option className="text-gray-500" value="" disabled selected>
Select
</option>
<option value="HouseholdItems">Household Item</option>
<option value="BusinessItems">Business Item</option>
<option value="Both">Both</option>
{/* <option value="None">None</option> */}
{/* <option value="Others">Others</option> */}
</select>
{multipleError?.Category && (
<p className="text-sm text-red-500">{multipleError?.Category}</p>
)}
</div>
{/* Space Description */}
<div className="group-select mb-6 ">
<label htmlFor="spaceDescription" className={formLabelStyle}>
What best describes your space?
<span className="text-red-500">*</span>
</label>
<select
id="spaceDescription"
className={formSelectStyle}
name="stage1.propertySpace"
onChange={onChange}
defaultValue={reduxData["stage1.propertySpace"]}
data-error="propertySpace"
>
<option className="text-gray-500" value="" disabled selected>
Select
</option>
<option value={"IsIndoor"}>Indoor</option>
<option value={"IsCovered"}>Covered</option>
{/* <option value={"IsUnCovered"}>UnCovered</option> */}
</select>
{multipleError?.propertySpace && (
<p className="text-sm text-red-500">
{multipleError?.propertySpace}
</p>
)}
</div>
{/* Amenities */}
<div className="group-select mb-6">
<label htmlFor="amenities" className={formLabelStyle}>
Amenities of your space <span className="text-red-500">*</span>
</label>
<Select
mode="multiple"
className="w-full mt-0 multipleSelect"
placeholder="Select Amenities"
name="stage1.Amenities"
defaultValue={reduxData["stage1.Amenities"]}
data-error="Amenities"
onChange={(value) => {
setMultipleError();
setData({ ...data, "stage1.Amenities": [...value] });
dispatch(
setListStorage({
...data,
...reduxData,
"stage1.Amenities": [...value],
})
);
}}
options={options}
/>
{/* {multipleError?.errors["stage1.Amenities"] && (
<p className="text-sm text-red-500">
{multipleError?.errors["stage1.Amenities"][0] }
</p>
)} */}
{multipleError?.Amenities && (
<p className="text-sm text-red-500">{multipleError?.Amenities}</p>
)}
</div>
{/* Access Frequency */}
<div className="group-select mb-6">
<label htmlFor="accessFrequency" className={formLabelStyle}>
How frequently can renters access their items?
<span className="text-red-500">*</span>
</label>
<select
id="accessFrequency"
className={formSelectStyle}
name="stage1.TenantVisitFrequency"
defaultValue={reduxData["stage1.TenantVisitFrequency"]}
onChange={onChange}
data-error="TenantVisitFrequency"
>
<option className="text-gray-500" value="" disabled selected>
Select
</option>
<option value="Daily">Daily</option>
<option value="Onceaweek">Once a week</option>
<option value="Monthly">Monthly</option>
<option value="askBeforeCome">Ask Before Come</option>
</select>
{multipleError?.TenantVisitFrequency && (
<p className="text-sm text-red-500">
{multipleError?.TenantVisitFrequency}
</p>
)}
</div>
{/* Preferred Time */}
<div className="group-select mb-6">
<label htmlFor="preferredTime" className={formLabelStyle}>
Which time suits best for you?
<span className="text-red-500">*</span>
</label>
<select
id="preferredTime"
className={formSelectStyle}
name="stage1.TenantVisitTiming"
onChange={onChange}
defaultValue={reduxData["stage1.TenantVisitTiming"]}
data-error="TenantVisitTiming"
>
<option className="text-gray-500" value="" disabled selected>
Select
</option>
<option value="StandardTiming">
Standard Timing (9 AM to 6 PM)
</option>
<option value="EveningTiming">
Evening Timing (6 PM to 9 PM)
</option>
<option value="AnyTiming">Any Timing (24 X 7)</option>
</select>
{multipleError?.TenantVisitTiming && (
<p className="text-sm text-red-500">
{multipleError?.TenantVisitTiming}
</p>
)}
</div>
<div className="group-select mb-6">
<label htmlFor="preferredTime" className={formLabelStyle}>
Floor <span className="text-red-500">*</span>
</label>
<input
type="Number"
className={formInputStyle}
name="stage1.Floor"
placeholder="Enter Floor"
required=""
min="0"
max="100"
value={reduxData["stage1.Floor"]}
onChange={onChange}
data-error="Floor"
/>
{multipleError?.Floor && (
<p className="text-sm text-red-500">{multipleError?.Floor}</p>
)}
</div>
<div className="group-select mb-6">
<label htmlFor="preferredTime" className={formLabelStyle}>
Is Lift Available? <span className="text-red-500">*</span>
</label>
<select
id="preferredTime"
className={formSelectStyle}
name="stage1.IsLiftAvailable"
onChange={onChange}
defaultValue={reduxData["stage1.IsLiftAvailable"]}
data-error="IsLiftAvailable"
>
<option className="text-gray-500" value="" disabled selected>
Select
</option>
<option value={false}>No</option>
<option value={true}>Yes</option>
</select>
{multipleError?.IsLiftAvailable && (
<p className="text-sm text-red-500">
{multipleError?.IsLiftAvailable}
</p>
)}
</div>
<h4 className="text-[16px] md:text-[20px] font-semibold text-[#1B1C57] mb-2 mt-4">
Space Dimensions
</h4>
<div class="row">
<div class="col-6">
<fieldset class="name-wrap">
<label className={formLabelStyle}>
Length (ft) <span class="text-danger">*</span>
</label>
<input
type="number"
className={formInputStyle}
name="stage1.LengthInFeet"
placeholder="Enter Length "
required=""
onChange={onChange}
value={reduxData["stage1.LengthInFeet"]}
data-error="LengthInFeet"
/>
{multipleError?.LengthInFeet && (
<p className="text-sm text-red-500">
{multipleError?.LengthInFeet}
</p>
)}
</fieldset>
</div>
<div class="col-6">
<fieldset class="name-wrap">
<label className={formLabelStyle}>
Width (ft) <span class="text-danger">*</span>
</label>
<input
type="number"
className={formInputStyle}
name="stage1.WidthInFeet"
placeholder="Enter Width"
required=""
onChange={onChange}
value={reduxData["stage1.WidthInFeet"]}
/>
{multipleError?.WidthInFeet && (
<p className="text-sm text-red-500">
{multipleError?.WidthInFeet}
</p>
)}
</fieldset>
</div>
<div class="col-6">
<fieldset class="name-wrap">
<label className={formLabelStyle}>
Height (ft)
{/* <span class="text-danger">*</span> */}
</label>
<input
type="number"
className={formInputStyle}
name="stage1.HeightInFeet"
placeholder="Enter Height "
required=""
value={reduxData["stage1.HeightInFeet"]}
onChange={onChange}
/>
{multipleError?.HeightInFeet && (
<p className="text-sm text-red-500">
{multipleError?.HeightInFeet}
</p>
)}
</fieldset>
</div>
</div>
<h4 class="text-[16px] md:text-[20px] font-semibold text-[#1B1C57] mb-2 mt-4">
Space Entrance Dimensions
</h4>
<div class="row">
<div class="col-6">
<fieldset class="name-wrap">
<label className={formLabelStyle}>
Width (ft)
{/* <span class="text-danger">*</span> */}
</label>
<input
type="number"
className={formInputStyle}
name="stage1.EntranceWidthInFeet"
placeholder="Enter Width "
required=""
value={reduxData["stage1.EntranceWidthInFeet"]}
onChange={onChange}
data-error="EntranceWidthInFeet"
/>
{/* {multipleError?.WidthInFeet && (
<p className="text-sm text-red-500">
{multipleError?.WidthInFeet}
</p>
)} */}
</fieldset>
</div>
<div class="col-6">
<fieldset class="name-wrap">
<label className={formLabelStyle}>
Height (ft)
{/* <span class="text-danger">*</span> */}
</label>
<input
type="number"
className={formInputStyle}
name="stage1.EntranceHeightInFeet"
placeholder="Enter Height"
required=""
value={reduxData["stage1.EntranceHeightInFeet"]}
onChange={onChange}
data-error="EntranceHeightInFeet"
/>
{multipleError?.EntranceHeightInFeet && (
<p className="text-sm text-red-500">
{multipleError?.EntranceHeightInFeet}
</p>
)}
</fieldset>
</div>
</div>
<div class="wizard-footer my-5 w-[100%]">
<ul class="d-flex justify-content-between w-full gap-2">
<li className="w-1/2">
{/* <button
type="button"
class=" w-full default-btn prev-step btn btn-outline-primary p-2"
>
Cancel
</button> */}
</li>
<li className="w-1/2">
<button
type="submit"
class=" w-full default-btn next-step btn !bg-blue-500 btn-full p-2 text-white"
>
Next
</button>
</li>
</ul>
{error?.text && (
<p className="text-sm text-red-500">{error?.text}</p>
)}
</div>
</div>
</form>
</>
);
};
export default SpaceDetails; |
<?php if (!defined('BASEPATH')) exit('No direct script access allowed');
/**
* Pagination Class
*
* @package CodeIgniter
* @link http://codeigniter.com/user_guide/libraries/pagination.html
*
* Modified by CodexWorld.com
* @Ajax pagination functionality has added with this library.
* @It will helps to integrate Ajax pagination with loading image in CodeIgniter application.
* @TutorialLink http://www.codexworld.com/ajax-pagination-in-codeigniter-framework/
*/
class Ajax_pagination{
var $base_url = ''; // The page we are linking to
var $total_rows = ''; // Total number of items (database results)
var $per_page = 10; // Max number of items you want shown per page
var $num_links = 2; // Number of "digit" links to show before/after the currently viewed page
var $cur_page = 0; // The current page being viewed
var $first_link = 'First';
var $next_link = '»';
var $prev_link = '«';
var $last_link = 'Last';
var $uri_segment = 3;
var $full_tag_open = '<div class="pagination">';
var $full_tag_close = '</div>';
var $first_tag_open = '';
var $first_tag_close = ' ';
var $last_tag_open = ' ';
var $last_tag_close = '';
var $cur_tag_open = ' <b>';
var $cur_tag_close = '</b>';
var $next_tag_open = ' ';
var $next_tag_close = ' ';
var $prev_tag_open = ' ';
var $prev_tag_close = '';
var $num_tag_open = ' ';
var $num_tag_close = '';
var $target = '';
var $anchor_class = '';
var $show_count = true;
var $link_func = 'getData';
var $loading = '.loading';
/**
* Constructor
* @access public
* @param array initialization parameters
*/
function CI_Pagination($params = array()){
if (count($params) > 0){
$this->initialize($params);
}
log_message('debug', "Pagination Class Initialized");
}
/**
* Initialize Preferences
* @access public
* @param array initialization parameters
* @return void
*/
function initialize($params = array()){
if (count($params) > 0){
foreach ($params as $key => $val){
if (isset($this->$key)){
$this->$key = $val;
}
}
}
// Apply class tag using anchor_class variable, if set.
if ($this->anchor_class != ''){
$this->anchor_class = 'class="' . $this->anchor_class . '" ';
}
}
/**
* Generate the pagination links
* @access public
* @return string
*/
function create_links(){
// If our item count or per-page total is zero there is no need to continue.
if ($this->total_rows == 0 OR $this->per_page == 0){
return '';
}
// Calculate the total number of pages
$num_pages = ceil($this->total_rows / $this->per_page);
// Is there only one page? Hm... nothing more to do here then.
if ($num_pages == 1){
$info = 'Showing : ' . $this->total_rows;
return $info;
}
// Determine the current page number.
$CI =& get_instance();
if ($CI->uri->segment($this->uri_segment) != 0){
$this->cur_page = $CI->uri->segment($this->uri_segment);
// Prep the current page - no funny business!
$this->cur_page = (int) $this->cur_page;
}
$this->num_links = (int)$this->num_links;
if ($this->num_links < 1){
show_error('Your number of links must be a positive number.');
}
if ( ! is_numeric($this->cur_page)){
$this->cur_page = 0;
}
// Is the page number beyond the result range?
// If so we show the last page
if ($this->cur_page > $this->total_rows){
$this->cur_page = ($num_pages - 1) * $this->per_page;
}
$uri_page_number = $this->cur_page;
$this->cur_page = floor(($this->cur_page/$this->per_page) + 1);
// Calculate the start and end numbers. These determine
// which number to start and end the digit links with
$start = (($this->cur_page - $this->num_links) > 0) ? $this->cur_page - ($this->num_links - 1) : 1;
$end = (($this->cur_page + $this->num_links) < $num_pages) ? $this->cur_page + $this->num_links : $num_pages;
// Add a trailing slash to the base URL if needed
$this->base_url = rtrim($this->base_url, '/') .'/';
// And here we go...
$output = '';
// SHOWING LINKS
if ($this->show_count){
$curr_offset = $CI->uri->segment($this->uri_segment);
$info = 'Showing ' . ( $curr_offset + 1 ) . ' to ' ;
if( ( $curr_offset + $this->per_page ) < ( $this->total_rows -1 ) )
$info .= $curr_offset + $this->per_page;
else
$info .= $this->total_rows;
$info .= ' of ' . $this->total_rows . ' | ';
$output .= $info;
}
// Render the "First" link
if ($this->cur_page > $this->num_links){
$output .= $this->first_tag_open
. $this->getAJAXlink( '' , $this->first_link)
. $this->first_tag_close;
}
// Render the "previous" link
if ($this->cur_page != 1){
$i = $uri_page_number - $this->per_page;
if ($i == 0) $i = '';
$output .= $this->prev_tag_open
. $this->getAJAXlink( $i, $this->prev_link )
. $this->prev_tag_close;
}
// Write the digit links
for ($loop = $start -1; $loop <= $end; $loop++){
$i = ($loop * $this->per_page) - $this->per_page;
if ($i >= 0){
if ($this->cur_page == $loop){
$output .= $this->cur_tag_open.$loop.$this->cur_tag_close; // Current page
}else{
$n = ($i == 0) ? '' : $i;
$output .= $this->num_tag_open
. $this->getAJAXlink( $n, $loop )
. $this->num_tag_close;
}
}
}
// Render the "next" link
if ($this->cur_page < $num_pages){
$output .= $this->next_tag_open
. $this->getAJAXlink( $this->cur_page * $this->per_page , $this->next_link )
. $this->next_tag_close;
}
// Render the "Last" link
if (($this->cur_page + $this->num_links) < $num_pages){
$i = (($num_pages * $this->per_page) - $this->per_page);
$output .= $this->last_tag_open . $this->getAJAXlink( $i, $this->last_link ) . $this->last_tag_close;
}
// Kill double slashes. Note: Sometimes we can end up with a double slash
// in the penultimate link so we'll kill all double slashes.
$output = preg_replace("#([^:])//+#", "\\1/", $output);
// Add the wrapper HTML if exists
$output = $this->full_tag_open.$output.$this->full_tag_close;
?>
<script>
function getData(page){
$.ajax({
method: "POST",
url: "<?php echo $this->base_url; ?>"+page,
data: { page: page },
beforeSend: function(){
$('<?php echo $this->loading; ?>').show();
},
success: function(data){
$('<?php echo $this->loading; ?>').hide();
$('<?php echo $this->target; ?>').html(data);
}
});
}
</script>
<?php
return $output;
}
function getAJAXlink($count, $text) {
$pageCount = $count?$count:0;
return '<a href="javascript:void(0);"' . $this->anchor_class . ' onclick="'.$this->link_func.'('.$pageCount.')">'. $text .'</a>';
}
}
// END Pagination Class |
---
title: Interactuar con flujos de trabajo mediante programación
description: Obtenga información sobre cómo administrar flujos de trabajo e interactuar mediante programación con flujos de trabajo mediante API y secuencias de comandos.
contentOwner: User
products: SG_EXPERIENCEMANAGER/6.4/SITES
topic-tags: extending-aem
content-type: reference
exl-id: da06850a-c4d5-44dd-b572-771e3b2a66c5
source-git-commit: c5b816d74c6f02f85476d16868844f39b4c47996
workflow-type: tm+mt
source-wordcount: '2051'
ht-degree: 1%
---
# Interactuar con flujos de trabajo mediante programación{#interacting-with-workflows-programmatically}
>[!CAUTION]
>
>AEM 6.4 ha llegado al final de la compatibilidad ampliada y esta documentación ya no se actualiza. Para obtener más información, consulte nuestra [períodos de asistencia técnica](https://helpx.adobe.com/es/support/programs/eol-matrix.html). Buscar las versiones compatibles [here](https://experienceleague.adobe.com/docs/).
When [personalización y ampliación de los flujos de trabajo](/help/sites-developing/workflows-customizing-extending.md) puede acceder a los objetos de flujo de trabajo:
* [Uso de la API Java del flujo de trabajo](#using-the-workflow-java-api)
* [Obtención de objetos de flujo de trabajo en scripts ECMA](#obtaining-workflow-objects-in-ecma-scripts)
* [Uso de la API de REST del flujo de trabajo](#using-the-workflow-rest-api)
## Uso de la API Java del flujo de trabajo {#using-the-workflow-java-api}
La API Java del flujo de trabajo consiste en la variable [`com.adobe.granite.workflow`](https://helpx.adobe.com/experience-manager/6-4/sites/developing/using/reference-materials/javadoc/com/adobe/granite/workflow/package-summary.html) y varios subpaquetes. El miembro más significativo de la API es `com.adobe.granite.workflow.WorkflowSession` Clase . La variable `WorkflowSession` proporciona acceso a los objetos de flujo de trabajo en tiempo de diseño y en tiempo de ejecución:
* modelos de flujo de trabajo
* elementos de trabajo
* instancias de flujo de trabajo
* datos de flujo de trabajo
* elementos de bandeja de entrada
La clase también proporciona varios métodos para intervenir en los ciclos de vida del flujo de trabajo.
En la tabla siguiente se proporcionan vínculos a la documentación de referencia de varios objetos Java clave que se deben utilizar al interactuar mediante programación con flujos de trabajo. Los siguientes ejemplos muestran cómo obtener y utilizar los objetos de clase en el código.
| Características | Objetos |
|---|---|
| Acceso a un flujo de trabajo | [`WorkflowSession`](https://helpx.adobe.com/experience-manager/6-4/sites/developing/using/reference-materials/javadoc/com/adobe/granite/workflow/WorkflowSession.html) |
| Ejecución y consulta de una instancia de flujo de trabajo | [`Workflow`](https://helpx.adobe.com/experience-manager/6-4/sites/developing/using/reference-materials/javadoc/com/adobe/granite/workflow/exec/Workflow.html)</br>[`WorkItem`](https://helpx.adobe.com/experience-manager/6-4/sites/developing/using/reference-materials/javadoc/com/adobe/granite/workflow/exec/WorkItem.html)</br>[`WorkflowData`](https://helpx.adobe.com/experience-manager/6-4/sites/developing/using/reference-materials/javadoc/com/adobe/granite/workflow/exec/WorkflowData.html) |
| Administración de un modelo de flujo de trabajo | [`WorkflowModel`](https://helpx.adobe.com/experience-manager/6-4/sites/developing/using/reference-materials/javadoc/com/adobe/granite/workflow/model/WorkflowModel.html)</br>[`WorkflowNode`](https://helpx.adobe.com/experience-manager/6-4/sites/developing/using/reference-materials/javadoc/com/adobe/granite/workflow/model/WorkflowNode.html)</br>[`WorkflowTransition`](https://helpx.adobe.com/experience-manager/6-4/sites/developing/using/reference-materials/javadoc/com/adobe/granite/workflow/model/WorkflowTransition.html) |
| Información de un nodo que se encuentra en el flujo de trabajo (o no) | [`WorkflowStatus`](https://helpx.adobe.com/experience-manager/6-4/sites/developing/using/reference-materials/javadoc/com/adobe/granite/workflow/status/WorkflowStatus.html) |
## Obtención de objetos de flujo de trabajo en scripts ECMA {#obtaining-workflow-objects-in-ecma-scripts}
Tal como se describe en [Localización de la secuencia de comandos](/help/sites-developing/the-basics.md#locating-the-script), AEM (a través de Apache Sling) proporciona un motor de secuencias de comandos ECMA que ejecuta secuencias de comandos ECMA del lado del servidor. La variable [`org.apache.sling.scripting.core.ScriptHelper`](https://sling.apache.org/apidocs/sling5/org/apache/sling/scripting/core/ScriptHelper.html) está disponible inmediatamente para las secuencias de comandos, ya que la `sling` variable.
La variable `ScriptHelper` proporciona acceso a la `SlingHttpServletRequest` que puede usar para obtener finalmente la variable `WorkflowSession` objeto; por ejemplo:
```
var wfsession = sling.getRequest().getResource().getResourceResolver().adaptTo(Packages.com.adobe.granite.workflow.WorkflowSession);
```
## Uso de la API de REST del flujo de trabajo {#using-the-workflow-rest-api}
La consola Flujo de trabajo utiliza en gran medida la API de REST; por lo tanto, esta página describe la API de REST para flujos de trabajo.
>[!NOTE]
>
>La herramienta de línea de comandos curl permite utilizar la API de REST de flujo de trabajo para acceder a los objetos de flujo de trabajo y administrar los ciclos de vida de las instancias. Los ejemplos de esta página muestran el uso de la API de REST a través de la herramienta de línea de comandos curl.
Las siguientes acciones son compatibles con la API de REST:
* iniciar o detener un servicio de flujo de trabajo
* crear, actualizar o eliminar modelos de flujo de trabajo
* [iniciar, suspender, reanudar o finalizar instancias de flujo de trabajo](/help/sites-administering/workflows.md#workflow-status-and-actions)
* completar o delegar elementos de trabajo
>[!NOTE]
>
>Al utilizar Firebug, una extensión de Firefox para el desarrollo web, es posible seguir el tráfico HTTP cuando se gestiona la consola. Por ejemplo, puede comprobar los parámetros y los valores enviados al servidor de AEM con un `POST` solicitud.
En esta página se da por hecho que AEM se ejecuta en localhost en el puerto `4502` y que el contexto de instalación es " `/`" (raíz). Si no es el caso de su instalación, las URI, a las que se aplican las solicitudes HTTP, deben adaptarse en consecuencia.
La renderización admitida para `GET` es la renderización JSON. Las direcciones URL de `GET` debe tener la variable `.json` , por ejemplo:
`http://localhost:4502/etc/workflow.json`
### Administración de instancias de flujo de trabajo {#managing-workflow-instances}
Los siguientes métodos de solicitud HTTP se aplican a:
`http://localhost:4502/etc/workflow/instances`
<table>
<tbody>
<tr>
<td>método de petición HTTP</td>
<td>Acciones</td>
</tr>
<tr>
<td><code>GET</code></td>
<td>Muestra las instancias de flujo de trabajo disponibles.</td>
</tr>
<tr>
<td><code>POST</code></td>
<td><p>Crea una nueva instancia de flujo de trabajo. Los parámetros son:<br /> - <code>model</code>: el ID (URI) del modelo de flujo de trabajo correspondiente<br /> - <code>payloadType</code>: que contiene el tipo de carga útil (por ejemplo <code>JCR_PATH</code> o URL).<br /> La carga útil se envía como parámetro <code>payload</code>. A <code>201</code> (<code>CREATED</code>) se devuelve con un encabezado de ubicación que contiene la dirección URL del nuevo recurso de instancia de flujo de trabajo.</p> </td>
</tr>
</tbody>
</table>
#### Administración de una instancia de flujo de trabajo por su estado {#managing-a-workflow-instance-by-its-state}
Los siguientes métodos de solicitud HTTP se aplican a:
`http://localhost:4502/etc/workflow/instances.{state}`
| método de petición HTTP | Acciones |
|---|---|
| `GET` | Muestra las instancias de flujo de trabajo disponibles y sus estados ( `RUNNING`, `SUSPENDED`, `ABORTED` o `COMPLETED`) |
#### Administración de una instancia de flujo de trabajo por su ID {#managing-a-workflow-instance-by-its-id}
Los siguientes métodos de solicitud HTTP se aplican a:
`http://localhost:4502/etc/workflow/instances/{id}`
<table>
<tbody>
<tr>
<td>método de petición HTTP</td>
<td>Acciones</td>
</tr>
<tr>
<td><code>GET</code></td>
<td>Obtiene los datos de instancias (definición y metadatos), incluido el vínculo al modelo de flujo de trabajo correspondiente.</td>
</tr>
<tr>
<td><code>POST</code></td>
<td>Cambia el estado de la instancia. El nuevo estado se envía como parámetro <code>state</code> y debe tener uno de los siguientes valores: <code>RUNNING</code>, <code>SUSPENDED</code>o <code>ABORTED</code>.<br /> Si el nuevo estado no está disponible (por ejemplo, al suspender una instancia terminada), se puede establecer un <code>409</code> (<code>CONFLICT</code>) se devuelve al cliente.</td>
</tr>
</tbody>
</table>
### Administración de modelos de flujo de trabajo {#managing-workflow-models}
Los siguientes métodos de solicitud HTTP se aplican a:
`http://localhost:4502/etc/workflow/models`
<table>
<tbody>
<tr>
<td>método de petición HTTP</td>
<td>Acciones</td>
</tr>
<tr>
<td><code>GET</code></td>
<td>Muestra los modelos de flujo de trabajo disponibles.</td>
</tr>
<tr>
<td><code>POST</code></td>
<td>Crea un nuevo modelo de flujo de trabajo. Si el parámetro <code>title</code> se envía, se crea un nuevo modelo con el título especificado. Adjuntar una definición de modelo JSON como parámetro <code>model</code> crea un nuevo modelo de flujo de trabajo según la definición proporcionada.<br /> A <code>201</code> Respuesta (<code>CREATED</code>) se devuelve con un encabezado de ubicación que contiene la dirección URL del nuevo recurso de modelo de flujo de trabajo.<br /> Lo mismo ocurre cuando se adjunta una definición de modelo como un parámetro de archivo denominado <code>modelfile</code>.<br /> En ambos casos, la variable <code>model</code> y <code>modelfile</code> parámetros, un parámetro adicional llamado <code>type</code> es necesario para definir el formato de serialización. Se pueden integrar nuevos formatos de serialización mediante la API OSGI. Se entrega un serializador JSON estándar con el motor de flujo de trabajo. Su tipo es JSON. Consulte a continuación un ejemplo del formato.</td>
</tr>
</tbody>
</table>
Ejemplo: en el explorador, una solicitud para `http://localhost:4502/etc/workflow/models.json` genera una respuesta json similar a la siguiente:
```
[
{"uri":"/var/workflow/models/activationmodel"}
,{"uri":"/var/workflow/models/dam/adddamsize"}
,{"uri":"/var/workflow/models/cloudconfigs/dtm-reactor/library-download"}
,{"uri":"/var/workflow/models/ac-newsletter-workflow-simple"}
,{"uri":"/var/workflow/models/dam/dam-create-language-copy"}
,{"uri":"/var/workflow/models/dam/dam-create-and-translate-language-copy"}
,{"uri":"/var/workflow/models/dam-indesign-proxy"}
,{"uri":"/var/workflow/models/dam-xmp-writeback"}
,{"uri":"/var/workflow/models/dam-parse-word-documents"}
,{"uri":"/var/workflow/models/dam/process_subasset"}
,{"uri":"/var/workflow/models/dam/dam_set_last_modified"}
,{"uri":"/var/workflow/models/dam/dam-autotag-assets"}
,{"uri":"/var/workflow/models/dam/update_asset"}
,{"uri":"/var/workflow/models/dam/update_asset_offloading"}
,{"uri":"/var/workflow/models/dam/dam-update-language-copy"}
,{"uri":"/var/workflow/models/dam/update_from_lightbox"}
,{"uri":"/var/workflow/models/cloudservices/DTM_bundle_download"}
,{"uri":"/var/workflow/models/dam/dam_download_asset"}
,{"uri":"/var/workflow/models/dam/dynamic-media-encode-video"}
,{"uri":"/var/workflow/models/dam/dynamic-media-video-thumbnail-replacement"}
,{"uri":"/var/workflow/models/dam/dynamic-media-video-user-uploaded-thumbnail"}
,{"uri":"/var/workflow/models/newsletter_bounce_check"}
,{"uri":"/var/workflow/models/projects/photo_shoot_submission"}
,{"uri":"/var/workflow/models/projects/product_photo_shoot"}
,{"uri":"/var/workflow/models/projects/approval_workflow"}
,{"uri":"/var/workflow/models/prototype-01"}
,{"uri":"/var/workflow/models/publish_example"}
,{"uri":"/var/workflow/models/publish_to_campaign"}
,{"uri":"/var/workflow/models/screens/publish_to_author_bin"}
,{"uri":"/var/workflow/models/s7dam/request_to_publish_to_youtube"}
,{"uri":"/var/workflow/models/projects/request_copy"}
,{"uri":"/var/workflow/models/projects/request_email"}
,{"uri":"/var/workflow/models/projects/request_landing_page"}
,{"uri":"/var/workflow/models/projects/request_launch"}
,{"uri":"/var/workflow/models/request_for_activation"}
,{"uri":"/var/workflow/models/request_for_deactivation"}
,{"uri":"/var/workflow/models/request_for_deletion"}
,{"uri":"/var/workflow/models/request_for_deletion_without_deactivation"}
,{"uri":"/var/workflow/models/request_to_complete_move_operation"}
,{"uri":"/var/workflow/models/reverse_replication"}
,{"uri":"/var/workflow/models/salesforce-com-export"}
,{"uri":"/var/workflow/models/scene7"}
,{"uri":"/var/workflow/models/scheduled_activation"}
,{"uri":"/var/workflow/models/scheduled_deactivation"}
,{"uri":"/var/workflow/models/screens/screens-update-asset"}
,{"uri":"/var/workflow/models/translation"}
,{"uri":"/var/workflow/models/s7dam/request_to_remove_from_youtube"}
,{"uri":"/var/workflow/models/wcm-translation/create_language_copy"}
,{"uri":"/var/workflow/models/wcm-translation/prepare_translation_project"}
,{"uri":"/var/workflow/models/wcm-translation/translate-i18n-dictionary"}
,{"uri":"/var/workflow/models/wcm-translation/sync_translation_job"}
,{"uri":"/var/workflow/models/wcm-translation/translate-language-copy"}
,{"uri":"/var/workflow/models/wcm-translation/update_language_copy"}
]
```
#### Administración de un modelo de flujo de trabajo específico {#managing-a-specific-workflow-model}
Los siguientes métodos de solicitud HTTP se aplican a:
`http://localhost:4502*{uri}*`
Donde `*{uri}*` es la ruta al nodo de modelo en el repositorio.
<table>
<tbody>
<tr>
<td>método de petición HTTP</td>
<td>Acciones</td>
</tr>
<tr>
<td><code>GET</code></td>
<td>Obtiene la variable <code>HEAD</code> versión del modelo (definición y metadatos).</td>
</tr>
<tr>
<td><code>PUT</code></td>
<td>Actualiza el <code>HEAD</code> versión del modelo (crea una nueva versión).<br /> La definición completa del modelo para la nueva versión del modelo debe agregarse como parámetro denominado <code>model</code>. Además, <code>type</code> se necesita como al crear nuevos modelos y debe tener el valor <code>JSON</code>.<br /> </td>
</tr>
<tr>
<td><code>POST</code></td>
<td>El mismo comportamiento que con el PUT. Necesario porque AEM widgets no son compatibles <code>PUT</code> operaciones.</td>
</tr>
<tr>
<td><code>DELETE</code></td>
<td>Elimina el modelo. Para resolver los problemas de firewall/proxy a <code>POST</code> que contiene un <code>X-HTTP-Method-Override</code> entrada de encabezado con valor <code>DELETE</code> también se aceptará como <code>DELETE</code> solicitud.</td>
</tr>
</tbody>
</table>
Ejemplo: en el explorador, una solicitud para `http://localhost:4502/var/workflow/models/publish_example.json` devuelve un valor `json` respuesta similar al siguiente código:
```shell
{
"id":"/var/workflow/models/publish_example",
"title":"Publish Example",
"version":"1.0",
"description":"This example shows a simple review and publish process.",
"metaData":
{
"multiResourceSupport":"true",
"tags":"wcm,publish"
},
"nodes":
[{
"id":"node0",
"type":"START",
"title":"Start",
"description":"The start node of the workflow.",
"metaData":
{
}
},
{
"id":"node1",
"type":"PARTICIPANT",
"title":"Validate Content",
"description":"Validate the modified content.",
"metaData":
{
"PARTICIPANT":"admin"
}
},
{
"id":"node2",
"type":"PROCESS",
"title":"Publish Content",
"description":"Publish the modified content.",
"metaData":
{
"PROCESS_AUTO_ADVANCE":"true",
"PROCESS":"com.day.cq.wcm.workflow.process.ActivatePageProcess"
}
},
{
"id":"node3",
"type":"END",
"title":"End",
"description":"The end node of the workflow.",
"metaData":
{
}
}],
"transitions":
[{
"from":"node0",
"to":"node1",
"metaData":
{
}
},
{
"from":"node1",
"to":"node2",
"metaData":
{
}
},
{
"from":"node2",
"to":"node3",
"metaData":
{
}
}
]}
```
#### Administración de un modelo de flujo de trabajo por su versión {#managing-a-workflow-model-by-its-version}
Los siguientes métodos de solicitud HTTP se aplican a:
`http://localhost:4502/etc/workflow/models/{id}.{version}`
| método de petición HTTP | Acciones |
|---|---|
| `GET` | Obtiene los datos del modelo en la versión dada (si existe). |
### Administración de bandejas de entrada (de usuario) {#managing-user-inboxes}
Los siguientes métodos de solicitud HTTP se aplican a:
`http://localhost:4502/bin/workflow/inbox`
<table>
<tbody>
<tr>
<td>método de petición HTTP</td>
<td>Acciones</td>
</tr>
<tr>
<td><code>GET</code></td>
<td>Enumera los elementos de trabajo que están en la bandeja de entrada del usuario, que se identifica mediante los encabezados de autenticación HTTP.</td>
</tr>
<tr>
<td><code>POST</code></td>
<td>Completa el elemento de trabajo cuyo URI se envía como parámetro <code>item</code> y avanza la instancia de flujo de trabajo correspondiente a los siguientes nodos, que se definen mediante el parámetro <code>route</code> o <code>backroute</code> en caso de retroceder un paso.<br /> Si el parámetro <code>delegatee</code> se envía, el elemento de trabajo identificado por el parámetro <code>item</code> se delega al participante especificado.</td>
</tr>
</tbody>
</table>
#### Administración de una bandeja de entrada (de usuario) mediante el ID de WorkItem {#managing-a-user-inbox-by-the-workitem-id}
Los siguientes métodos de solicitud HTTP se aplican a:
`http://localhost:4502/bin/workflow/inbox/{id}`
| método de petición HTTP | Acciones |
|---|---|
| `GET` | Obtiene los datos (definición y metadatos) de la bandeja de entrada. `WorkItem` identificado por su ID. |
## Ejemplos {#examples}
### Cómo obtener una lista de todos los flujos de trabajo en ejecución con sus ID {#how-to-get-a-list-of-all-running-workflows-with-their-ids}
Para obtener una lista de todos los flujos de trabajo en ejecución, haga una GET a:
`http://localhost:4502/etc/workflow/instances.RUNNING.json`
#### Cómo obtener una lista de todos los flujos de trabajo en ejecución con sus ID: REST mediante curl {#how-to-get-a-list-of-all-running-workflows-with-their-ids-rest-using-curl}
Ejemplo con curl:
```shell
curl -u admin:admin http://localhost:4502/etc/workflow/instances.RUNNING.json
```
La variable `uri` mostrado en los resultados se puede utilizar como instancia `id` en otros comandos; por ejemplo:
```shell
[
{"uri":"/etc/workflow/instances/server0/2017-03-08/request_for_activation_1"}
]
```
>[!NOTE]
>
>Esta `curl` puede utilizarse con cualquier [estado del flujo de trabajo](/help/sites-administering/workflows.md#workflow-status-and-actions) en lugar de `RUNNING`.
### Cómo cambiar el título del flujo de trabajo {#how-to-change-the-workflow-title}
Para cambiar el **Título del flujo de trabajo** se muestra en la **Instancias** de la consola de flujo de trabajo, envíe un `POST` comando:
* hasta: `http://localhost:4502/etc/workflow/instances/{id}`
* con los siguientes parámetros:
* `action`: su valor debe ser: `UPDATE`
* `workflowTitle`: el título del flujo de trabajo
#### Cambio del título del flujo de trabajo: REST con curl {#how-to-change-the-workflow-title-rest-using-curl}
Ejemplo con curl:
```shell
curl -u admin:admin -d "action=UPDATE&workflowTitle=myWorkflowTitle" http://localhost:4502/etc/workflow/instances/{id}
# for example
>[!CAUTION]
>
>AEM 6.4 has reached the end of extended support and this documentation is no longer updated. For further details, see our [technical support periods](https://helpx.adobe.com/support/programs/eol-matrix.html). Find the supported versions [here](https://experienceleague.adobe.com/docs/).
curl -u admin:admin -d "action=UPDATE&workflowTitle=myWorkflowTitle" http://localhost:4502/etc/workflow/instances/server0/2017-03-08/request_for_activation_1
```
### Lista de todos los modelos de flujo de trabajo {#how-to-list-all-workflow-models}
Para obtener una lista de todos los modelos de flujo de trabajo disponibles, haga una GET a:
`http://localhost:4502/etc/workflow/models.json`
#### Lista de todos los modelos de flujo de trabajo: REST con curl {#how-to-list-all-workflow-models-rest-using-curl}
Ejemplo con curl:
```shell
curl -u admin:admin http://localhost:4502/etc/workflow/models.json
```
>[!NOTE]
>
>Consulte también [Administración de modelos de flujo de trabajo](#managing-workflow-models).
### Obtención de un objeto WorkflowSession {#obtaining-a-workflowsession-object}
La variable `com.adobe.granite.workflow.WorkflowSession` es adaptable desde un `javax.jcr.Session` objeto o `org.apache.sling.api.resource.ResourceResolver` objeto.
#### Obtención de un objeto WorkflowSession: Java {#obtaining-a-workflowsession-object-java}
En una secuencia de comandos JSP (o código Java para una clase servlet), utilice el objeto de solicitud HTTP para obtener un `SlingHttpServletRequest` que proporciona acceso a un `ResourceResolver` objeto. Adaptar el `ResourceResolver` objeto a `WorkflowSession`.
```java
<%
%><%@include file="/libs/foundation/global.jsp"%><%
%><%@page session="false"
import="com.adobe.granite.workflow.WorkflowSession,
org.apache.sling.api.SlingHttpServletRequest"%><%
SlingHttpServletRequest slingReq = (SlingHttpServletRequest)request;
WorkflowSession wfSession = slingReq.getResourceResolver().adaptTo(WorkflowSession.class);
%>
```
#### Obtención de un objeto WorkflowSession: secuencia de comandos ECMA {#obtaining-a-workflowsession-object-ecma-script}
Utilice la variable `sling` para obtener la variable `SlingHttpServletRequest` objeto que utiliza para obtener un `ResourceResolver` objeto. Adaptar el `ResourceResolver` al `WorkflowSession` objeto.
```
var wfsession = sling.getRequest().getResource().getResourceResolver().adaptTo(Packages.com.adobe.granite.workflow.WorkflowSession);
```
### Creación, lectura o eliminación de modelos de flujo de trabajo {#creating-reading-or-deleting-workflow-models}
Los siguientes ejemplos muestran cómo acceder a los modelos de flujo de trabajo:
* El código para Java y el script ECMA utiliza la variable `WorkflowSession.createNewModel` método.
* El comando curl accede al modelo directamente usando su URL.
Los ejemplos utilizados:
1. Creación de un modelo (con el ID `/var/workflow/models/mymodel/jcr:content/model`).
1. Elimine el modelo.
>[!NOTE]
>
>Al eliminar el modelo, se establece la variable `deleted` propiedad del modelo `metaData` nodo secundario a `true`.
>
>La eliminación no elimina el nodo del modelo.
Al crear un modelo nuevo:
* El editor de modelos de flujo de trabajo requiere que los modelos utilicen una estructura de nodos específica a continuación `/var/workflow/models`. El nodo principal del modelo debe ser del tipo `cq:Page` tener un `jcr:content` con los siguientes valores de propiedad:
* `sling:resourceType`: `cq/workflow/components/pages/model`
* `cq:template`: `/libs/cq/workflow/templates/model`
Al crear un modelo, primero debe crear esto `cq:Page` nodo y utilice su `jcr:content` como nodo principal del nodo modelo.
* La variable `id` el argumento que algunos métodos requieren para identificar el modelo es la ruta absoluta del nodo de modelo en el repositorio:
`/var/workflow/models/<*model_name>*/jcr:content/model`
>[!NOTE]
>
>Consulte [Lista de todos los modelos de flujo de trabajo](#how-to-list-all-workflow-models).
#### Creación, lectura o eliminación de modelos de flujo de trabajo - Java {#creating-reading-or-deleting-workflow-models-java}
```java
<%@include file="/libs/foundation/global.jsp"%><%
%><%@page session="false" import="com.adobe.granite.workflow.WorkflowSession,
com.adobe.granite.workflow.model.WorkflowModel,
org.apache.sling.api.SlingHttpServletRequest"%><%
SlingHttpServletRequest slingReq = (SlingHttpServletRequest)request;
WorkflowSession wfSession = slingReq.getResourceResolver().adaptTo(WorkflowSession.class);
/* Create the parent page */
String modelRepo = new String("/var/workflow/models");
String modelTemplate = new String ("/libs/cq/workflow/templates/model");
String modelName = new String("mymodel");
Page modelParent = pageManager.create(modelRepo, modelName, modelTemplate, "My workflow model");
/* create the model */
String modelId = new String(modelParent.getPath()+"/jcr:content/model")
WorkflowModel model = wfSession.createNewModel("Made using Java",modelId);
/* delete the model */
wfSession.deleteModel(modelId);
%>
```
#### Creación, lectura o eliminación de modelos de flujo de trabajo: secuencia de comandos ECMA {#creating-reading-or-deleting-workflow-models-ecma-script}
```
var resolver = sling.getRequest().getResource().getResourceResolver();
var wfSession = resolver.adaptTo(Packages.com.adobe.granite.workflow.WorkflowSession);
var pageManager = resolver.adaptTo(Packages.com.day.cq.wcm.api.PageManager);
//create the parent page node
var workflowPage = pageManager.create("/var/workflow/models", "mymodel", "/libs/cq/workflow/templates/model", "Created via ECMA Script");
var modelId = workflowPage.getPath()+ "/jcr:content/model";
//create the model
var model = wfSession.createNewModel("My Model", modelId);
//delete the model
var model = wfSession.deleteModel(modelId);
```
#### Eliminación de un modelo de flujo de trabajo: REST con curl {#deleting-a-workflow-model-rest-using-curl}
```shell
# deleting the model by its id
>[!CAUTION]
>
>AEM 6.4 has reached the end of extended support and this documentation is no longer updated. For further details, see our [technical support periods](https://helpx.adobe.com/support/programs/eol-matrix.html). Find the supported versions [here](https://experienceleague.adobe.com/docs/).
curl -u admin:admin -X DELETE http://localhost:4502/etc/workflow/models/{id}
```
>[!NOTE]
>
>Debido al nivel de detalle requerido, el curl no se considera práctico para crear y/o leer un modelo.
### Filtrado de los flujos de trabajo del sistema al comprobar el estado del flujo de trabajo {#filtering-out-system-workflows-when-checking-workflow-status}
Puede usar la variable [API WorkflowStatus](https://helpx.adobe.com/experience-manager/6-4/sites/developing/using/reference-materials/javadoc/com/adobe/granite/workflow/status/WorkflowStatus.html) para recuperar información sobre el estado del flujo de trabajo de un nodo.
Varios métodos tienen el parámetro :
`excludeSystemWorkflows`
Este parámetro se puede establecer en `true` para indicar que los flujos de trabajo del sistema deben excluirse de los resultados relevantes.
You [puede actualizar la configuración de OSGi](/help/sites-deploying/configuring-osgi.md) **Carga útil de flujo de trabajo de Granite de AdobeMapCache** que especifica el flujo de trabajo `Models` para considerarse como flujos de trabajo del sistema. Los modelos de flujo de trabajo predeterminados (en tiempo de ejecución) son:
* `/var/workflow/models/scheduled_activation/jcr:content/model`
* `/var/workflow/models/scheduled_deactivation/jcr:content/model`
### Avance automático del paso del participante después de un tiempo de espera {#auto-advance-participant-step-after-a-timeout}
Si necesita avanzar automáticamente un **Participante** paso que no se haya completado en un tiempo predefinido, puede:
1. Implemente un detector de eventos OSGI para escuchar la creación y modificación de tareas.
1. Especifique un tiempo de espera (fecha límite) y, a continuación, cree un trabajo de sling programado para que se active en ese momento.
1. Escriba un controlador de trabajo al que se notifique cuando caduque el tiempo de espera y se déclencheur el trabajo.
Este controlador realizará la acción necesaria en la tarea si la tarea aún no se ha completado
>[!NOTE]
>
>Las medidas que se adopten deben definirse claramente para poder utilizar este enfoque.
### Interactuar con instancias de flujo de trabajo {#interacting-with-workflow-instances}
A continuación se proporcionan ejemplos básicos de cómo interactuar (de forma programática) con instancias de flujo de trabajo.
#### Interactuar con instancias de flujo de trabajo - Java {#interacting-with-workflow-instances-java}
```java
// starting a workflow
WorkflowModel model = wfSession.getModel(workflowId);
WorkflowData wfData = wfSession.newWorkflowData("JCR_PATH", repoPath);
wfSession.startWorkflow(model, wfData);
// querying and managing a workflow
Workflow[] workflows workflows = wfSession.getAllWorkflows();
Workflow workflow= wfSession.getWorkflow(id);
wfSession.suspendWorkflow(workflow);
wfSession.resumeWorkflow(workflow);
wfSession.terminateWorkflow(workflow);
```
#### Interactuar con instancias de flujo de trabajo: secuencia de comandos ECMA {#interacting-with-workflow-instances-ecma-script}
```
// starting a workflow
var model = wfSession.getModel(workflowId);
var wfData = wfSession.newWorkflowData("JCR_PATH", repoPath);
wfSession.startWorkflow(model, wfData);
// querying and managing a workflow
var workflows = wfSession.getWorkflows(“RUNNING“);
var workflow= wfSession.getWorkflow(id);
wfSession.suspendWorkflow(workflow);
wfSession.resumeWorkflow(workflow);
wfSession.terminateWorkflow(workflow);
```
#### Interactuar con instancias de flujo de trabajo: REST con curl {#interacting-with-workflow-instances-rest-using-curl}
* **Inicio de un flujo de trabajo**
```shell
# starting a workflow
curl -d "model={id}&payloadType={type}&payload={payload}" http://localhost:4502/etc/workflow/instances
# for example:
curl -u admin:admin -d "model=/var/workflow/models/request_for_activation&payloadType=JCR_PATH&payload=/content/we-retail/us/en/products" http://localhost:4502/etc/workflow/instances
```
* **Lista de instancias**
```shell
# listing the instances
curl -u admin:admin http://localhost:4502/etc/workflow/instances.json
```
Se enumerarán todas las instancias; por ejemplo:
```shell
[
{"uri":"/var/workflow/instances/server0/2018-02-26/prototype-01_1"}
,{"uri":"/var/workflow/instances/server0/2018-02-26/prototype-01_2"}
]
```
>[!NOTE]
>
>Consulte [Cómo obtener una lista de todos los flujos de trabajo en ejecución](#how-to-get-a-list-of-all-running-workflows-with-their-ids) con sus ID para enumerar instancias con un estado específico.
* **Suspender un flujo de trabajo**
```shell
# suspending a workflow
curl -d "state=SUSPENDED" http://localhost:4502/etc/workflow/instances/{id}
# for example:
curl -u admin:admin -d "state=SUSPENDED" http://localhost:4502/etc/workflow/instances/server0/2017-03-08/request_for_activation_1
```
* **Reanudación de un flujo de trabajo**
```shell
# resuming a workflow
curl -d "state=RUNNING" http://localhost:4502/etc/workflow/instances/{id}
# for example:
curl -u admin:admin -d "state=RUNNING" http://localhost:4502/etc/workflow/instances/server0/2017-03-08/request_for_activation_1
```
* **Finalización de una instancia de flujo de trabajo**
```shell
# terminating a workflow
curl -d "state=ABORTED" http://localhost:4502/etc/workflow/instances/{id}
# for example:
curl -u admin:admin -d "state=ABORTED" http://localhost:4502/etc/workflow/instances/server0/2017-03-08/request_for_activation_1
```
### Interactuar con elementos de trabajo {#interacting-with-work-items}
A continuación se proporcionan ejemplos básicos de cómo interactuar (mediante programación) con elementos de trabajo.
#### Interactuar con elementos de trabajo - Java {#interacting-with-work-items-java}
```java
// querying work items
WorkItem[] workItems = wfSession.getActiveWorkItems();
WorkItem workItem = wfSession.getWorkItem(id);
// getting routes
List<Route> routes = wfSession.getRoutes(workItem);
// delegating
Iterator<Participant> delegatees = wfSession.getDelegatees(workItem);
wfSession.delegateWorkItem(workItem, delegatees.get(0));
// completing or advancing to the next step
wfSession.complete(workItem, routes.get(0));
```
#### Interactuar con elementos de trabajo: secuencia de comandos ECMA {#interacting-with-work-items-ecma-script}
```
// querying work items
var workItems = wfSession.getActiveWorkItems();
var workItem = wfSession.getWorkItem(id);
// getting routes
var routes = wfSession.getRoutes(workItem);
// delegating
var delegatees = wfSession.getDelegatees(workItem);
wfSession.delegateWorkItem(workItem, delegatees.get(0));
// completing or advancing to the next step
wfSession.complete(workItem, routes.get(0));
```
#### Interactuar con elementos de trabajo: REST con curl {#interacting-with-work-items-rest-using-curl}
* **Listado de elementos de trabajo de la bandeja de entrada**
```shell
# listing the work items
curl -u admin:admin http://localhost:4502/bin/workflow/inbox
```
Se enumerarán los detalles de los elementos de trabajo que se encuentran actualmente en la Bandeja de entrada; por ejemplo:
```shell
[{
"uri_xss": "/var/workflow/instances/server0/2018-02-26/prototype-01_2/workItems/node2_var_workflow_instances_server0_2018-02-26_prototype-01_2",
"uri": "/var/workflow/instances/server0/2018-02-26/prototype-01_2/workItems/node2_var_workflow_instances_server0_2018-02-26_prototype-01_2",
"currentAssignee_xss": "workflow-administrators",
"currentAssignee": "workflow-administrators",
"startTime": 1519656289274,
"payloadType_xss": "JCR_PATH",
"payloadType": "JCR_PATH",
"payload_xss": "/content/we-retail/es/es",
"payload": "/content/we-retail/es/es",
"comment_xss": "Process resource is null",
"comment": "Process resource is null",
"type_xss": "WorkItem",
"type": "WorkItem"
},{
"uri_xss": "configuration/configure_analyticstargeting",
"uri": "configuration/configure_analyticstargeting",
"currentAssignee_xss": "administrators",
"currentAssignee": "administrators",
"type_xss": "Task",
"type": "Task"
},{
"uri_xss": "configuration/securitychecklist",
"uri": "configuration/securitychecklist",
"currentAssignee_xss": "administrators",
"currentAssignee": "administrators",
"type_xss": "Task",
"type": "Task"
},{
"uri_xss": "configuration/enable_collectionofanonymoususagedata",
"uri": "configuration/enable_collectionofanonymoususagedata",
"currentAssignee_xss": "administrators",
"currentAssignee": "administrators",
"type_xss": "Task",
"type": "Task"
},{
"uri_xss": "configuration/configuressl",
"uri": "configuration/configuressl",
"currentAssignee_xss": "administrators",
"currentAssignee": "administrators",
"type_xss": "Task",
"type": "Task"
}
```
* **Delegación de elementos de trabajo**
```xml
# delegating
curl -d "item={item}&delegatee={delegatee}" http://localhost:4502/bin/workflow/inbox
# for example:
curl -u admin:admin -d "item=/etc/workflow/instances/server0/2017-03-08/request_for_activation_1/workItems/node1_etc_workflow_instances_server0_2017-03-08_request_for_act_1&delegatee=administrators" http://localhost:4502/bin/workflow/inbox
```
>[!NOTE]
>
>La variable `delegatee` debe ser una opción válida para el paso del flujo de trabajo.
* **Finalización o avance de elementos de trabajo al paso siguiente**
```xml
# retrieve the list of routes; the results will be similar to {"results":1,"routes":[{"rid":"233123169","label":"End","label_xss":"End"}]}
http://localhost:4502/etc/workflow/instances/<path-to-the-workitem>.routes.json
# completing or advancing to the next step; use the appropriate route ID (rid value) from the above list
curl -d "item={item}&route={route}" http://localhost:4502/bin/workflow/inbox
# for example:
curl -u admin:admin -d "item=/etc/workflow/instances/server0/2017-03-08/request_for_activation_1/workItems/node1_etc_workflow_instances_server0_2017-03-08_request_for_activation_1&route=233123169" http://localhost:4502/bin/workflow/inbox
```
### Escucha de eventos de flujo de trabajo {#listening-for-workflow-events}
Utilice el marco de eventos OSGi para detectar eventos que [ `com.adobe.granite.workflow.event.WorkflowEvent`](https://helpx.adobe.com/experience-manager/6-4/sites/developing/using/reference-materials/javadoc/com/adobe/granite/workflow/event/WorkflowEvent.html) define la clase. Esta clase también proporciona varios métodos útiles para obtener información sobre el asunto del evento. Por ejemplo, la variable `getWorkItem` devuelve el valor `WorkItem` para el elemento de trabajo involucrado en el evento.
El siguiente código de ejemplo define un servicio que escucha los eventos de flujo de trabajo y realiza tareas según el tipo de evento.
```java
package com.adobe.example.workflow.listeners;
import org.apache.sling.event.jobs.JobProcessor;
import org.apache.sling.event.jobs.JobUtil;
import org.osgi.service.event.Event;
import org.osgi.service.event.EventHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.apache.felix.scr.annotations.Component;
import org.apache.felix.scr.annotations.Property;
import org.apache.felix.scr.annotations.Service;
import com.adobe.granite.workflow.event.WorkflowEvent;
import com.adobe.granite.workflow.exec.WorkItem;
/**
* The <code>WorkflowEventCatcher</code> class listens to workflow events.
*/
@Component(metatype=false, immediate=true)
@Service(value=org.osgi.service.event.EventHandler.class)
public class WorkflowEventCatcher implements EventHandler, JobProcessor {
@Property(value=com.adobe.granite.workflow.event.WorkflowEvent.EVENT_TOPIC)
static final String EVENT_TOPICS = "event.topics";
private static final Logger logger = LoggerFactory.getLogger(WorkflowEventCatcher.class);
public void handleEvent(Event event) {
JobUtil.processJob(event, this);
}
public boolean process(Event event) {
logger.info("Received event of topic: " + event.getTopic());
String topic = event.getTopic();
try {
if (topic.equals(WorkflowEvent.EVENT_TOPIC)) {
WorkflowEvent wfevent = (WorkflowEvent)event;
String eventType = wfevent.getEventType();
String instanceId = wfevent.getWorkflowInstanceId();
if (instanceId != null) {
//workflow instance events
if (eventType.equals(WorkflowEvent.WORKFLOW_STARTED_EVENT) ||
eventType.equals(WorkflowEvent.WORKFLOW_RESUMED_EVENT) ||
eventType.equals(WorkflowEvent.WORKFLOW_SUSPENDED_EVENT)) {
// your code comes here...
} else if (
eventType.equals(WorkflowEvent.WORKFLOW_ABORTED_EVENT) ||
eventType.equals(WorkflowEvent.WORKFLOW_COMPLETED_EVENT)) {
// your code comes here...
}
// workflow node event
if (eventType.equals(WorkflowEvent.NODE_TRANSITION_EVENT)) {
WorkItem currentItem = (WorkItem) event.getProperty(WorkflowEvent.WORK_ITEM);
// your code comes here...
}
}
}
} catch(Exception e){
logger.debug(e.getMessage());
e.printStackTrace();
}
return true;
}
}
``` |
/*
* 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 com.bennu.servicio;
import com.bennu.entidad.Categoria;
import com.bennu.entidad.SubCategoria;
import com.bennu.entidad.auxiliar.CategoriaSimple;
import com.bennu.entidad.auxiliar.SubCategoriaSimple;
import java.util.ArrayList;
import java.util.List;
import javax.ejb.EJB;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
/**
*
* @author administrador
*/
@Stateless
@Path("categoria")
public class CategoriaFacadeREST extends AbstractFacade<Categoria> {
@PersistenceContext(unitName = "AppAdminClasificatePU")
private EntityManager em;
@EJB
SubCategoriaFacadeREST subCategoriaREST;
public CategoriaFacadeREST() {
super(Categoria.class);
}
@POST
@Override
@Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
public void create(Categoria entity) {
super.create(entity);
}
@PUT
@Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
public void edit(Categoria entity) {
super.edit(entity);
}
@DELETE
@Path("{id}")
public void remove(@PathParam("id") Integer id) {
super.remove(super.find(id));
}
@GET
@Path("{id}")
@Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
public Categoria find(@PathParam("id") Integer id) {
return super.find(id);
}
@GET
@Override
@Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
public List<Categoria> findAll() {
return super.findAll();
}
@GET
@Path("{from}/{to}")
@Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
public List<Categoria> findRange(@PathParam("from") Integer from, @PathParam("to") Integer to) {
return super.findRange(new int[]{from, to});
}
@GET
@Path("simple")
@Produces({MediaType.APPLICATION_JSON})
public List<CategoriaSimple> getCategoriaSub() {
List<Categoria> categoriaLista = super.findAll();
List<CategoriaSimple> categoriaSimpleLista = new ArrayList<>();
categoriaLista.forEach(categoria -> {
List<SubCategoria> subCategoriaLista = subCategoriaREST.findSubCategoriaCategoria(categoria.getIdCategoria());
List<SubCategoriaSimple> subCategoriaSimpleLista = new ArrayList<>();
subCategoriaLista.forEach(subCategoria -> subCategoriaSimpleLista.add( new SubCategoriaSimple(subCategoria) ) );
categoriaSimpleLista.add( new CategoriaSimple(categoria, subCategoriaSimpleLista) );
});
return categoriaSimpleLista;
}
@GET
@Path("count")
@Produces(MediaType.TEXT_PLAIN)
public String countREST() {
return String.valueOf(super.count());
}
@Override
protected EntityManager getEntityManager() {
return em;
}
} |
package de.knuff0r.bsb.app;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
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.configuration.WebSecurityConfigurerAdapter;
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.util.matcher.AntPathRequestMatcher;
/**
* Created by sebastian on 29.11.15.
*/
@EnableWebSecurity
@Configuration
@Order(Ordered.LOWEST_PRECEDENCE - 8)
public class ApplicationSecurity extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
// .csrf()
// .disable()
.authorizeRequests()
.antMatchers("/css/*").permitAll()
.antMatchers("/register").permitAll()
.antMatchers("/activate/**").permitAll()
.antMatchers("/**/favicon.ico").permitAll()
.antMatchers("/webjars/**").permitAll()
//.antMatchers("/**").hasAuthority("USER")
.antMatchers("/admin/**").hasAuthority("ADMIN")
.anyRequest().fullyAuthenticated().and().formLogin()
.loginPage("/").failureUrl("/?loginFail").permitAll().and()
.logout().logoutRequestMatcher(new AntPathRequestMatcher("/logout")).logoutSuccessUrl("/");
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
@Bean
@Override
public AuthenticationManager authenticationManagerBean() throws Exception {
return authenticationManager();
}
@Override
@Bean
public UserDetailsService userDetailsService() {
return new JpaUserDetailsService();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService()).passwordEncoder(passwordEncoder());
}
} |
<?php
namespace App\Providers;
use App\Constants\GlobalConst;
use App\Constants\LanguageConst;
use Exception;
use App\Models\User;
use App\Models\Admin\Currency;
use App\Models\Admin\Language;
use App\Models\Admin\Extension;
use App\Models\UserSupportTicket;
use App\Models\Admin\BasicSettings;
use App\Models\Admin\GatewayAPi;
use App\Models\Admin\ModuleSetting;
use App\Models\Admin\SetupSeo;
use App\Models\VirtualCardApi;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\ServiceProvider;
use App\Providers\Admin\CurrencyProvider;
use App\Providers\Admin\BasicSettingsProvider;
class CustomServiceProvider extends ServiceProvider
{
/**
* Register services.
*
* @return void
*/
public function register()
{
$this->startingPoint();
}
/**
* Bootstrap services.
*
* @return void
*/
public function boot()
{
try{
$default_language = Language::where('status',GlobalConst::ACTIVE)->first();
$default_language_code = $default_language->code ?? LanguageConst::NOT_REMOVABLE;
$view_share = [];
$view_share['basic_settings'] = BasicSettings::first();
$view_share['default_currency'] = Currency::default();
$view_share['__languages'] = Language::get();
$view_share['all_user_count'] = User::count();
$view_share['email_verified_user_count'] = User::where('email_verified', 1)->count();
$view_share['kyc_verified_user_count'] = User::where('kyc_verified', 1)->count();
$view_share['default_currency'] = Currency::default();
$view_share['__extensions'] = Extension::get();
$view_share['pending_ticket_count'] = UserSupportTicket::pending()->get()->count();
$view_share['module'] = ModuleSetting::get();
$view_share['card_limit'] = VirtualCardApi::first()->card_limit;
$view_share['card_api'] = VirtualCardApi::first();
$view_share['default_language_code'] = $default_language_code;
$view_share['seo_data'] = SetupSeo::first();
$view_share['payLink'] = GatewayAPi::first();
view()->share($view_share);
$this->app->bind(BasicSettingsProvider::class, function () use ($view_share) {
return new BasicSettingsProvider($view_share['basic_settings']);
});
$this->app->bind(CurrencyProvider::class, function () use ($view_share) {
return new CurrencyProvider($view_share['default_currency']);
});
}catch(Exception $e) {
//
}
}
public function startingPoint() {
if(env('PURCHASE_CODE','') == null) {
Config::set('starting-point.status',true);
Config::set('starting-point.point','/project/install/welcome');
}
}
} |
package ru.practicum.shareit.item.repository;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
import org.springframework.boot.test.autoconfigure.orm.jpa.TestEntityManager;
import ru.practicum.shareit.item.model.Item;
import ru.practicum.shareit.request.model.ItemRequest;
import ru.practicum.shareit.user.model.User;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import static org.junit.jupiter.api.Assertions.assertEquals;
@DataJpaTest
class ItemRepositoryTest {
@Autowired
private TestEntityManager entityManager;
@Autowired
private ItemRepository itemRepository;
@Test
void findAllByOwnerId() {
User user = new User(null, "User", "email@email.com");
entityManager.persist(user);
Item item = new Item(null, "Example item", "Example item", true, user, null,
null, new ArrayList<>());
Item item2 = new Item(null, "Example item2", "Example item2", true, user, null,
null, new ArrayList<>());
entityManager.persist(item);
entityManager.persist(item2);
List<Item> items = itemRepository.findAllByOwnerIdOrderByIdAsc(user.getId());
assertEquals(2, items.size());
Item retrievedItem1 = items.get(0);
assertEquals("Example item", retrievedItem1.getName());
Item retrievedItem2 = items.get(1);
assertEquals("Example item2", retrievedItem2.getName());
}
@Test
void searchItemByNameOrDescription() {
User user = new User(null, "User", "email@email.com");
entityManager.persist(user);
Item item = new Item(null, "Example item", "Example item", true, user, null,
null, new ArrayList<>());
Item item2 = new Item(null, "Example item2", "Example item2", true, user, null,
null, new ArrayList<>());
entityManager.persist(item);
entityManager.persist(item2);
List<Item> items = itemRepository.searchItemByNameOrDescription("item");
assertEquals(2, items.size());
Item retrievedItem1 = items.get(0);
assertEquals("Example item", retrievedItem1.getName());
Item retrievedItem2 = items.get(1);
assertEquals("Example item2", retrievedItem2.getName());
}
@Test
void updateItemFields() {
User user = new User(null, "User", "email@email.com");
entityManager.persist(user);
ItemRequest itemRequest = new ItemRequest(1L, "Description", user, LocalDateTime.now(), null);
Item item = new Item(null, "Example item", "Example item", true, user, null,
null, new ArrayList<>());
entityManager.persist(item);
Item itemUpdateName = new Item(item.getId(), "Update item", "Example item", true, user, null,
null, new ArrayList<>());
Item itemUpdateDescription = new Item(item.getId(), "Example item", "Update item", true, user, null,
null, new ArrayList<>());
Item itemUpdateAvailable = new Item(item.getId(), "Example item", "Example item", false, user, null,
null, new ArrayList<>());
itemRepository.updateItemFields(itemUpdateName, user.getId(), item.getId());
Item retrievedItem = itemRepository.findById(item.getId()).get();
assertEquals("Update item", retrievedItem.getName());
itemRepository.updateItemFields(itemUpdateDescription, user.getId(), item.getId());
retrievedItem = itemRepository.findById(item.getId()).get();
assertEquals("Update item", retrievedItem.getDescription());
itemRepository.updateItemFields(itemUpdateAvailable, user.getId(), item.getId());
retrievedItem = itemRepository.findById(item.getId()).get();
assertEquals(false, retrievedItem.getAvailable());
}
} |
#!/usr/bin/env ruby
require 'yaml'
require 'shellwords'
# Extract the YAML frontmatter from the Markdown file
def extract_frontmatter(file)
frontmatter = ''
in_frontmatter = false
File.open(file, 'rb').each_line do |line|
# Encode line to UTF-8, replacing invalid and undefined characters
line = line.encode('UTF-8', 'binary', invalid: :replace, undef: :replace, replace: '')
if line.strip == '---'
in_frontmatter = !in_frontmatter
next if frontmatter.empty?
end
frontmatter += line if in_frontmatter
end
frontmatter
end
# Identify the Markdown file among the command line arguments
def find_markdown_file(args)
# This will hold the index positions of where options (-o, --output, etc.) appear
option_indices = args.each_index.select { |i| args[i].start_with?('-') && args[i] != '-' }
# Find the first argument that doesn't start with '-' and isn't immediately after an option
args.each_with_index do |arg, i|
if !arg.start_with?('-') && (i == 0 || (i > 0 && !args[i-1].start_with?('-')))
return arg
end
end
nil
end
def join_arguments_with_proper_quoting(args)
args.map do |arg|
# If an argument contains spaces, it needs to be quoted
if arg.include?(' ')
# Quote the argument if it contains spaces
"\"#{arg}\""
else
# Otherwise, return the argument as is
arg
end
end.join(' ')
end
# Usage in the run_pandoc function
def run_pandoc(markdown_file, args)
all_args = args + [markdown_file]
properly_quoted_command = join_arguments_with_proper_quoting(all_args)
# Construct the Pandoc command
command = "pandoc #{properly_quoted_command}"
puts "======== Running command: #{command} ========"
system(command)
end
markdown_file = find_markdown_file(ARGV)
if markdown_file.nil?
puts "No Markdown file specified."
exit 1
end
# Filter out the Markdown file from the list of arguments
additional_args = ARGV.reject { |arg| arg == markdown_file }
# Extract and parse the YAML frontmatter
frontmatter = extract_frontmatter(markdown_file)
parsed_yaml = YAML.load(frontmatter) || {}
frontmatter_args = parsed_yaml['pandoc_args'] || []
# Combine the command line arguments with those from the frontmatter
combined_args = additional_args + frontmatter_args
# Run Pandoc with the combined arguments
run_pandoc(markdown_file, combined_args) |
// Añadir producto
function addProduct(productData) {
fetch('/products', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(productData),
})
.then(response => response.json())
.then(data => {
console.log('Producto añadido:', data);
// Actualizar la vista de productos
loadProducts();
})
.catch((error) => {
console.error('Error al añadir producto:', error);
});
}
// Cargar y mostrar la lista de productos
function loadProducts() {
fetch('/products', {
method: 'GET',
})
.then(response => response.json())
.then(products => {
const productsTable = document.getElementById('productsTable');
// Limpiar tabla antes de cargar los nuevos productos
productsTable.innerHTML = '';
products.forEach(product => {
const row = productsTable.insertRow();
row.insertCell(0).textContent = product.name;
row.insertCell(1).textContent = product.description;
const editButton = document.createElement('button');
editButton.textContent = 'Editar';
editButton.onclick = () => loadProductForEdit(product.id);
row.insertCell(2).appendChild(editButton);
const deleteButton = document.createElement('button');
deleteButton.textContent = 'Eliminar';
deleteButton.onclick = () => deleteProduct(product.id);
row.insertCell(3).appendChild(deleteButton);
});
})
.catch((error) => {
console.error('Error al cargar productos:', error);
});
}
// Cargar producto para editar
function loadProductForEdit(productId) {
fetch(`/products/${productId}`, {
method: 'GET',
})
.then(response => response.json())
.then(product => {
document.getElementById('editName').value = product.name;
document.getElementById('editDescription').value = product.description;
document.getElementById('productId').value = product.id;
// Aquí también cambiarías a la vista o modal del formulario de edición si fuera necesario
})
.catch(error => {
console.error('Error al cargar el producto para editar:', error);
});
}
// Actualizar producto
function updateProduct(productId, updatedData) {
fetch(`/products/${productId}`, {
method: 'PUT',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(updatedData),
})
.then(response => response.json())
.then(data => {
console.log('Producto actualizado:', data);
// Actualizar la vista de productos
loadProducts();
})
.catch(error => {
console.error('Error al actualizar el producto:', error);
});
}
// Eliminar producto
function deleteProduct(productId) {
if (confirm('¿Estás seguro de eliminar este producto?')) {
fetch(`/products/${productId}`, {
method: 'DELETE',
})
.then(() => {
console.log('Producto eliminado');
// Actualizar la vista de productos
loadProducts();
})
.catch(error => {
console.error('Error al eliminar el producto:', error);
});
}
}
// Evento de formulario para añadir producto
document.getElementById('addProductForm').addEventListener('submit', function (e) {
e.preventDefault();
const name = document.getElementById('name').value;
const description = document.getElementById('description').value;
addProduct({ name, description });
this.reset(); // Resetea el formulario después de enviar
});
// Evento de formulario para editar producto
document.getElementById('editProductForm').addEventListener('submit', function (e) {
e.preventDefault();
const productId = document.getElementById('productId').value;
const name = document.getElementById('editName').value;
const description = document.getElementById('editDescription').value;
updateProduct(productId, { name, description });
});
// Cargar productos cuando la DOM esté lista
document.addEventListener('DOMContentLoaded', loadProducts); |
import React, { useState } from 'react';
import { Link } from 'react-router-dom';
import { validateEmail, validatePassword, validatePhoneNumber, validateTextField } from '../../../utils/validations';
import { Button, Card, CardContent, CardHeader, IconButton, Stack, TextField, Typography } from '@mui/material';
import { formatPhoneNumber, unformatPhoneNumber} from '../../../utils/formatPhone';
import ArrowBackIcon from '@mui/icons-material/ArrowBack';
const RegisterForm = ({ onSubmit }) => {
const [step, setStep] = useState(1);
const totalSteps = 2;
const [formData, setFormData] = useState({
email: '',
password: '',
confirmPassword: '',
name: '',
phone: ''
});
const [errors, setErrors] = useState({
email: '',
password: '',
confirmPassword: '',
name: '',
phone: ''
});
const handleChange = (e) => {
const { name, value } = e.target;
if (name === 'phone') {
const unformattedPhone = unformatPhoneNumber(value);
if (unformattedPhone.length <= 9) {
setFormData({
...formData,
phone: formatPhoneNumber(value)
});
}
} else {
setFormData({
...formData,
[name]: value
});
}
};
const validateStep = (step) => {
let newErrors = { ...errors };
switch (step) {
case 1:
newErrors.email = validateEmail(formData.email);
newErrors.password = validatePassword(formData.password);
newErrors.confirmPassword = formData.password === formData.confirmPassword ? '' : 'Hasła muszą się zgadzać';
break;
case 2:
newErrors.name = validateTextField(formData.name, 'Imię');
newErrors.phone = validatePhoneNumber(unformatPhoneNumber(formData.phone));
break;
default:
break;
}
setErrors(newErrors);
const hasErrors = Object.values(newErrors).some(error => error);
return !hasErrors;
};
const handleNextStep = (e) => {
e.preventDefault();
if (validateStep(step) && step < totalSteps) {
setStep(step + 1);
}
};
const handlePrevStep = (e) => {
if (step > 1) {
setStep(1);
setErrors({
email: '',
password: '',
confirmPassword: '',
name: '',
phone: ''
})
}
};
const handleSubmit = (e) => {
e.preventDefault();
if (validateStep(step)) {
const unformattedPhone = unformatPhoneNumber(formData.phone);
const dataToSubmit = {
...formData,
phone: unformattedPhone
};
const { confirmPassword, ...finalDataToSubmit } = dataToSubmit;
onSubmit(finalDataToSubmit);
}
};
return (
<Card sx={{ display: 'flex', flexDirection: 'column', minWidth: 360, borderRadius: 2, p: 1, position: 'relative' }} elevation={2}>
<CardHeader
title='Rejestracja'
sx={{
alignSelf: 'center',
color: 'text.secondary',
'& .MuiCardHeader-action': {
marginTop: 0,
marginRight: 0,
marginBottom: 0,
alignSelf: 'center'
}
}}
/>
{step > 1 && (
<IconButton aria-label='back' onClick={handlePrevStep} sx={{ position: 'absolute', right: 16, top: 16 }}>
<ArrowBackIcon />
</IconButton>
)}
<CardContent component='form' onSubmit={handleSubmit} noValidate>
{(step === 1) && (
<Stack spacing={3}>
<TextField
id='outlined-basic'
label='Email'
variant='outlined'
name='email'
value={formData.email}
onChange={handleChange}
error={errors.email.length > 0}
helperText={errors.email}
placeholder='user@example.com'
fullWidth
/>
<TextField
type='password'
id='outlined-basic'
label='Hasło'
variant='outlined'
name='password'
value={formData.password}
onChange={handleChange}
error={errors.password.length > 0}
helperText={errors.password}
fullWidth
/>
<TextField
type='password'
id='outlined-basic'
label='Potwierdź hasło'
variant='outlined'
name='confirmPassword'
value={formData.confirmPassword}
onChange={handleChange}
error={errors.confirmPassword.length > 0}
helperText={errors.confirmPassword}
fullWidth
/>
<Typography sx={{ alignSelf: 'center' }}>Masz już konto? <Link to='/login'>Zaloguj się</Link></Typography>
<Button variant='contained' type='button' onClick={handleNextStep} size='large'>Dalej</Button>
</Stack>
)}
{(step === 2) && (
<Stack spacing={3}>
<TextField
id='outlined-basic'
label='Imię'
variant='outlined'
name='name'
value={formData.name}
onChange={handleChange}
error={errors.name.length > 0}
helperText={errors.name}
fullWidth
/>
<TextField
id='outlined-basic'
label='Telefon'
variant='outlined'
name='phone'
value={formData.phone}
onChange={handleChange}
error={errors.phone.length > 0}
helperText={errors.phone}
placeholder='+48'
fullWidth
/>
<Typography sx={{ alignSelf: 'center' }}>Masz już konto? <Link to='/login'>Zaloguj się</Link></Typography>
<Button variant='contained' type='submit' size='large'>Zarejestruj się</Button>
</Stack>
)}
</CardContent>
</Card>
);
};
export default RegisterForm; |
abstract class Reader[+T] {
def first: T
def rest: Reader[T]
def atEnd: Boolean
}
trait Parsers {
type Elem
type Input = Reader[Elem]
sealed abstract class ParseResult[+T] {
val successful: Boolean
def map[U](f: T => U): ParseResult[U]
def flatMapWithNext[U](f: T => Input => ParseResult[U]): ParseResult[U]
}
sealed abstract class NoSuccess(val msg: String) extends ParseResult[Nothing] { // when we don't care about the difference between Failure and Error
val successful = false
def map[U](f: Nothing => U) = this
def flatMapWithNext[U](f: Nothing => Input => ParseResult[U]): ParseResult[U]
= this
}
case class Failure(override val msg: String) extends NoSuccess(msg)
case class Error(override val msg: String) extends NoSuccess(msg)
case class Success[+T](result: T, val next: Input) extends ParseResult[T] {
val successful = true
def map[U](f: T => U) = Success(f(result), next)
def flatMapWithNext[U](f: T => Input => ParseResult[U]): ParseResult[U] = f(result)(next) match {
case s @ Success(result, rest) => Success(result, rest)
case f: Failure => f
case e: Error => e
}
}
case class ~[+a, +b](_1: a, _2: b) {
override def toString = s"(${_1}~${_2})"
}
abstract class Parser[+T] extends (Input => ParseResult[T]) {
def apply(in: Input): ParseResult[T]
def ~ [U](q: => Parser[U]): Parser[~[T, U]] = { lazy val p = q
(for(a <- this; b <- p) yield new ~(a,b))
}
def flatMap[U](f: T => Parser[U]): Parser[U]
= Parser{ in => this(in).flatMapWithNext(f)}
def map[U](f: T => U): Parser[U] //= flatMap{x => success(f(x))}
= Parser{ in => this(in).map(f)}
def ^^ [U](f: T => U): Parser[U] = map(f)
}
def Parser[T](f: Input => ParseResult[T]): Parser[T]
= new Parser[T]{ def apply(in: Input) = f(in) }
def accept(e: Elem): Parser[Elem] = acceptIf(_ == e)("'"+e+"' expected but " + _ + " found")
def acceptIf(p: Elem => Boolean)(err: Elem => String): Parser[Elem] = Parser { in =>
if (in.atEnd) Failure("end of input")
else if (p(in.first)) Success(in.first, in.rest)
else Failure(err(in.first))
}
}
object grammars3 extends Parsers {
type Elem = String
val a: Parser[String] = accept("a")
val b: Parser[String] = accept("b")
val AnBnCn: Parser[List[String]] = {
repMany(a,b)
}
def repMany[T](p: => Parser[T], q: => Parser[T]): Parser[List[T]] =
p~repMany(p,q)~q ^^ {case x~xs~y => x::xs:::(y::Nil)}
} |
---
uid: web-forms/overview/data-access/masterdetail/master-detail-filtering-with-two-dropdownlists-cs
title: 2つの DropDownLists (C#) を使用したマスター/詳細フィルター処理Microsoft Docs
author: rick-anderson
description: このチュートリアルでは、マスター/詳細リレーションシップを展開して3番目のレイヤーを追加し、2つの DropDownList コントロールを使用して目的の親を選択します。
ms.author: riande
ms.date: 03/31/2010
ms.assetid: ac4b0d77-4816-4ded-afd0-88dab667aedd
msc.legacyurl: /web-forms/overview/data-access/masterdetail/master-detail-filtering-with-two-dropdownlists-cs
msc.type: authoredcontent
ms.openlocfilehash: e24b7f91d34fbce1676f7f28ebb7d23903157f7f
ms.sourcegitcommit: e7e91932a6e91a63e2e46417626f39d6b244a3ab
ms.translationtype: MT
ms.contentlocale: ja-JP
ms.lasthandoff: 03/06/2020
ms.locfileid: "78424288"
---
# <a name="masterdetail-filtering-with-two-dropdownlists-c"></a>2 つの DropDownList でマスター/詳細をフィルター処理する (C#)
[Scott Mitchell](https://twitter.com/ScottOnWriting)
[サンプルアプリのダウンロード](https://download.microsoft.com/download/4/6/3/463cf87c-4724-4cbc-b7b5-3f866f43ba50/ASPNET_Data_Tutorial_8_CS.exe)または[PDF のダウンロード](master-detail-filtering-with-two-dropdownlists-cs/_static/datatutorial08cs1.pdf)
> このチュートリアルでは、マスター/詳細リレーションシップを展開して3番目のレイヤーを追加します。2つの DropDownList コントロールを使用して、目的の親レコードと祖父母レコードを選択します。
## <a name="introduction"></a>はじめに
前の[チュートリアル](master-detail-filtering-with-a-dropdownlist-cs.md)では、カテゴリが設定された1つの DropDownList と、選択したカテゴリに属する製品を示す GridView を使用して、単純なマスター/詳細レポートを表示する方法を説明しました。 このレポートパターンは、一対多のリレーションシップを持つレコードを表示する場合に適しています。また、複数の一対多リレーションシップを含むシナリオで機能するように簡単に拡張できます。 たとえば、注文入力システムには、顧客、注文、および注文品目に対応するテーブルがあります。 特定の顧客には、注文ごとに複数の注文が含まれている場合があります。 このようなデータは、2つの DropDownLists と GridView を使用してユーザーに提示できます。 最初の DropDownList には、データベース内の顧客ごとに、2番目の内容が選択した顧客によって配置された注文であるというリストアイテムがあります。 GridView では、選択した順序で行項目が一覧表示されます。
Northwind データベースには、`Customers`、`Orders`、および `Order Details` の各テーブルに、正規の顧客/注文/注文の詳細情報が含まれていますが、これらのテーブルはアーキテクチャではキャプチャされません。 それでも、2つの依存する DropDownLists を使用して説明することはできます。 最初の DropDownList にカテゴリと、選択したカテゴリに属する2番目の製品が一覧表示されます。 次に、選択した製品の詳細が表示されます。
## <a name="step-1-creating-and-populating-the-categories-dropdownlist"></a>手順 1: カテゴリの作成と設定 DropDownList
最初の目標は、カテゴリを一覧表示する DropDownList を追加することです。 これらの手順の詳細については、前のチュートリアルで詳しく説明しましたが、ここでは完全を期すためにまとめました。
`Filtering` フォルダーの [`MasterDetailsDetails.aspx`] ページを開き、DropDownList をページに追加します。その `ID` プロパティを [`Categories`] に設定し、そのスマートタグの [データソースの構成] リンクをクリックします。 データソース構成ウィザードから、新しいデータソースの追加を選択します。
[DropDownList の新しいデータソースを追加 ](master-detail-filtering-with-two-dropdownlists-cs/_static/image1.png)
**図 1**: DropDownList の新しいデータソースを追加する ([クリックすると、フルサイズの画像が表示](master-detail-filtering-with-two-dropdownlists-cs/_static/image3.png)されます)
新しいデータソースは、当然、ObjectDataSource である必要があります。 この新しい ObjectDataSource `CategoriesDataSource` という名前を指定し、`CategoriesBLL` オブジェクトの `GetCategories()` メソッドを呼び出すようにします。
[カテゴリ Bll クラスの使用を選択 ](master-detail-filtering-with-two-dropdownlists-cs/_static/image4.png)
**図 2**: `CategoriesBLL` クラスの使用を選択する ([クリックしてフルサイズのイメージを表示する](master-detail-filtering-with-two-dropdownlists-cs/_static/image6.png))
[GetCategories () メソッドを使用するように ObjectDataSource を構成 ](master-detail-filtering-with-two-dropdownlists-cs/_static/image7.png)
**図 3**: `GetCategories()` メソッドを使用するように ObjectDataSource を構成する ([クリックしてフルサイズのイメージを表示する](master-detail-filtering-with-two-dropdownlists-cs/_static/image9.png))
ObjectDataSource を構成した後も、`Categories` DropDownList に表示するデータソースフィールドを指定し、リストアイテムの値として構成する必要があるデータソースフィールドを指定する必要があります。 `CategoryName` フィールドを表示として設定し、各リスト項目の値として `CategoryID` します。
[DropDownList で [区分項目] フィールドを表示し、値として CategoryID を使用する ](master-detail-filtering-with-two-dropdownlists-cs/_static/image10.png)
**図 4**: DropDownList に `CategoryName` フィールドが表示され、`CategoryID` を値として使用する ([クリックしてフルサイズの画像を表示する](master-detail-filtering-with-two-dropdownlists-cs/_static/image12.png))
この時点で、`Categories` テーブルのレコードが設定された DropDownList コントロール (`Categories`) があります。 ユーザーが DropDownList から新しいカテゴリを選択すると、手順 2. で作成しようとしている製品の DropDownList を更新するためにポストバックが発生します。 そのため、`categories` DropDownList のスマートタグから [AutoPostBack を有効にする] オプションをオンにします。
[カテゴリの DropDownList に対して AutoPostBack を有効に ](master-detail-filtering-with-two-dropdownlists-cs/_static/image13.png)
**図 5**: `Categories` DropDownList の AutoPostBack を有効[にする (クリックしてフルサイズのイメージを表示する](master-detail-filtering-with-two-dropdownlists-cs/_static/image15.png))
## <a name="step-2-displaying-the-selected-categorys-products-in-a-second-dropdownlist"></a>手順 2: 選択したカテゴリの製品を2番目の DropDownList に表示する
`Categories` DropDownList が完了したら、次の手順では、選択したカテゴリに属する製品の DropDownList を表示します。 これを行うには、`ProductsByCategory`という名前のページに別の DropDownList を追加します。 `Categories` DropDownList と同様に、`ProductsByCategoryDataSource`という名前の `ProductsByCategory` DropDownList の新しい ObjectDataSource を作成します。
[製品 Bycategory の DropDownList の新しいデータソースを追加 ](master-detail-filtering-with-two-dropdownlists-cs/_static/image16.png)
**図 6**: `ProductsByCategory` DropDownList の新しいデータソースを追加する ([クリックすると、フルサイズの画像が表示](master-detail-filtering-with-two-dropdownlists-cs/_static/image18.png)されます)
[新しい ObjectDataSource という名前の新しい ](master-detail-filtering-with-two-dropdownlists-cs/_static/image19.png)
**図 7**: `ProductsByCategoryDataSource` という名前の新しい ObjectDataSource を作成[する (クリックすると、フルサイズの画像が表示](master-detail-filtering-with-two-dropdownlists-cs/_static/image21.png)される)
`ProductsByCategory` DropDownList は選択されたカテゴリに属する製品のみを表示する必要があるため、ObjectDataSource は `ProductsBLL` オブジェクトから `GetProductsByCategoryID(categoryID)` メソッドを呼び出します。
[製品の Bll クラスの使用を選択 ](master-detail-filtering-with-two-dropdownlists-cs/_static/image22.png)
**図 8**: `ProductsBLL` クラスの使用を選択する ([クリックしてフルサイズのイメージを表示する](master-detail-filtering-with-two-dropdownlists-cs/_static/image24.png))
[Get$ Bycategoryid (categoryID) メソッドを使用するように ObjectDataSource を構成 ](master-detail-filtering-with-two-dropdownlists-cs/_static/image25.png)
**図 9**: `GetProductsByCategoryID(categoryID)` メソッドを使用するように ObjectDataSource を構成する ([クリックしてフルサイズのイメージを表示する](master-detail-filtering-with-two-dropdownlists-cs/_static/image27.png))
ウィザードの最後の手順では、 *`categoryID`* パラメーターの値を指定する必要があります。 このパラメーターを `Categories` DropDownList から選択した項目に割り当てます。
[カテゴリの DropDownList から categoryID パラメーター値をプル ](master-detail-filtering-with-two-dropdownlists-cs/_static/image28.png)
**図 10**: `Categories` DropDownList から *`categoryID`* パラメーターの値を取得[する (クリックしてフルサイズのイメージを表示する](master-detail-filtering-with-two-dropdownlists-cs/_static/image30.png))
ObjectDataSource が構成されていれば、DropDownList の項目の表示と値に使用されるデータソースフィールドを指定するだけです。 [`ProductName`] フィールドを表示し、[`ProductID`] フィールドを値として使用します。
[DropDownList の ListItems のテキストと値のプロパティに使用されるデータソースフィールドを指定 ](master-detail-filtering-with-two-dropdownlists-cs/_static/image31.png)
**図 11**: DropDownList の `ListItem` s ' `Text` と `Value` プロパティに使用されるデータソースフィールドを指定[する (クリックしてフルサイズの画像を表示する](master-detail-filtering-with-two-dropdownlists-cs/_static/image33.png))
ObjectDataSource と `ProductsByCategory` DropDownList が構成されている場合、ページには2つの DropDownLists が表示されます。1つ目はすべてのカテゴリを一覧表示し、2番目のリストは選択したカテゴリに属する製品を一覧表示します。 ユーザーが最初の DropDownList から新しいカテゴリを選択すると、ポストバックは議論され、2番目の DropDownList は再バインドされ、新しく選択されたカテゴリに属する製品が表示されます。 図12および13は、ブラウザーで表示したときに `MasterDetailsDetails.aspx` の動作を示しています。
[](master-detail-filtering-with-two-dropdownlists-cs/_static/image34.png)
**図 12**: 最初にページにアクセスしたときに飲み物のカテゴリが選択されている ([クリックすると、フルサイズの画像が表示](master-detail-filtering-with-two-dropdownlists-cs/_static/image36.png)されます)
[別のカテゴリを選択 ](master-detail-filtering-with-two-dropdownlists-cs/_static/image37.png)
**図 13**: 別のカテゴリを選択すると、新しいカテゴリの製品が表示されます ([クリックすると、フルサイズの画像が表示](master-detail-filtering-with-two-dropdownlists-cs/_static/image39.png)されます)
現在 `productsByCategory` DropDownList は、変更された場合、ポストバックを発生*させません*。 ただし、選択した製品の詳細を表示するために DetailsView を追加した後に、ポストバックが発生するようにします (手順 3)。 そのため、`productsByCategory` DropDownList のスマートタグから [AutoPostBack を有効にする] チェックボックスをオンにします。
[製品 Bycategory の DropDownList の AutoPostBack 機能を有効 ](master-detail-filtering-with-two-dropdownlists-cs/_static/image40.png)
**図 14**: `productsByCategory` DropDownList の AutoPostBack 機能を有効にする ([クリックしてフルサイズのイメージを表示する](master-detail-filtering-with-two-dropdownlists-cs/_static/image42.png))
## <a name="step-3-using-a-detailsview-to-display-details-for-the-selected-product"></a>手順 3: DetailsView を使用して選択した製品の詳細を表示する
最後の手順は、選択した製品の詳細を DetailsView で表示することです。 これを行うには、DetailsView をページに追加し、その `ID` プロパティを `ProductDetails`に設定して、新しい ObjectDataSource を作成します。 この ObjectDataSource を構成して、 *`productID`* パラメーターの値に対して `ProductsByCategory` DropDownList の選択された値を使用して、`ProductsBLL` クラスの `GetProductByProductID(productID)` メソッドからデータをプルします。
[製品の Bll クラスの使用を選択 ](master-detail-filtering-with-two-dropdownlists-cs/_static/image43.png)
**図 15**: `ProductsBLL` クラスの使用を選択する ([クリックしてフルサイズのイメージを表示する](master-detail-filtering-with-two-dropdownlists-cs/_static/image45.png))
[GetProductByProductID (productID) メソッドを使用するように ObjectDataSource を構成 ](master-detail-filtering-with-two-dropdownlists-cs/_static/image46.png)
**図 16**: `GetProductByProductID(productID)` メソッドを使用するように ObjectDataSource を構成する ([クリックしてフルサイズのイメージを表示する](master-detail-filtering-with-two-dropdownlists-cs/_static/image48.png))
[製品 Bycategory の DropDownList から productID パラメーター値をプル ](master-detail-filtering-with-two-dropdownlists-cs/_static/image49.png)
**図 17**: `ProductsByCategory` DropDownList から *`productID`* パラメーター値を取得する ([クリックすると、フルサイズの画像が表示](master-detail-filtering-with-two-dropdownlists-cs/_static/image51.png)されます)
DetailsView で使用可能なフィールドを表示するかどうかを選択できます。 `ProductID`、`SupplierID`、および `CategoryID` フィールドを削除し、残りのフィールドの並べ替えと書式設定を行いました。 さらに、DetailsView の `Height` と `Width` プロパティをクリアし、指定されたサイズに制限されるのではなく、データを最適に表示するために必要な幅まで DetailsView を拡張できるようにしました。 完全なマークアップが以下に表示されます。
[!code-aspx[Main](master-detail-filtering-with-two-dropdownlists-cs/samples/sample1.aspx)]
ブラウザーで `MasterDetailsDetails.aspx` のページを試してみましょう。 一見すると、すべてが必要に応じて動作しているように見えるかもしれませんが、微妙な問題があります。 新しいカテゴリを選択すると `ProductsByCategory` DropDownList は選択されたカテゴリの製品を含むように更新されますが、`ProductDetails` DetailsView は以前の製品情報を表示し続けます。 選択したカテゴリに対して別の製品を選択すると、DetailsView が更新されます。 さらに、十分にテストした場合は、新しいカテゴリ (`Categories` DropDownList からの飲み物の選択、Condiments、Confections など) を選択すると、他のすべてのカテゴリの選択によって `ProductDetails` の DetailsView が更新されることがわかります。
この問題をを具体化ために、特定の例を見てみましょう。 ページに初めてアクセスすると、飲み物カテゴリが選択され、関連する製品が `ProductsByCategory` DropDownList に読み込まれます。 Chai は選択された製品で、図18に示すように、`ProductDetails` の DetailsView にその詳細が表示されます。
[選択した製品の詳細が DetailsView に表示される ](master-detail-filtering-with-two-dropdownlists-cs/_static/image52.png)
**図 18**: 選択した製品の詳細が DetailsView に表示される ([クリックすると、フルサイズの画像が表示](master-detail-filtering-with-two-dropdownlists-cs/_static/image54.png)されます)
カテゴリの選択を飲み物から Condiments に変更すると、ポストバックが発生し、それに応じて `ProductsByCategory` DropDownList が更新されますが、DetailsView には、Chai の詳細が表示されます。
[以前に選択した製品の詳細が表示され ](master-detail-filtering-with-two-dropdownlists-cs/_static/image55.png)
**図 19**: 以前に選択された製品の詳細が表示される ([クリックすると、フルサイズの画像が表示](master-detail-filtering-with-two-dropdownlists-cs/_static/image57.png)されます)
一覧から新しい製品を選択すると、必要に応じて DetailsView が更新されます。 製品を変更した後で新しいカテゴリを選択しても、DetailsView は再更新されません。 ただし、新しいカテゴリを選択して新しい製品を選択するのではなく、DetailsView が更新されます。 ここでは、世界中で何が起こっているのでしょうか。
問題は、ページのライフサイクルのタイミングの問題です。 ページが要求されるたびに、レンダリングとしていくつかの手順を実行します。 これらの手順のいずれかで、ObjectDataSource コントロールは `SelectParameters` 値が変更されているかどうかを確認します。 その場合、ObjectDataSource にバインドされているデータ Web コントロールは、表示を更新する必要があることを認識しています。 たとえば、新しいカテゴリが選択されている場合、`ProductsByCategoryDataSource` ObjectDataSource はそのパラメーター値が変更されたことを検出し、`ProductsByCategory` DropDownList がそれ自体を再バインドして、選択されたカテゴリの製品を取得します。
この状況で発生する問題は、変更されたパラメーターの ObjectDataSources ソースチェックが、関連付けられたデータ Web コントロールの再バインドの*前に*発生することを示す、ページのライフサイクルのポイントです。 したがって、新しいカテゴリを選択すると `ProductsByCategoryDataSource` ObjectDataSource によって、パラメーターの値の変更が検出されます。 ただし、`ProductDetails` DetailsView で使用される ObjectDataSource は、`ProductsByCategory` DropDownList がまだ再バインドされていないため、このような変更はメモしていません。 その後、ライフサイクルの `ProductsByCategory` DropDownList を ObjectDataSource に再バインドし、新しく選択したカテゴリの製品を取得します。 `ProductsByCategory` DropDownList の値が変更されましたが、`ProductDetails` DetailsView の ObjectDataSource のパラメーター値のチェックが既に完了しています。そのため、DetailsView は前の結果を表示します。 この相互作用は、図20に示されています。
[ProductDetails DetailsView の ObjectDataSource が変更されたかどうかを確認した後に、Productbycategory の DropDownList 値の変更を ](master-detail-filtering-with-two-dropdownlists-cs/_static/image58.png)
**図 20**: `ProductDetails` DetailsView の ObjectDataSource の ObjectDataSource によって変更がチェックされた後の `ProductsByCategory` DropDownList 値の変更 ([クリックすると、フルサイズの画像が表示](master-detail-filtering-with-two-dropdownlists-cs/_static/image60.png)されます)
これを解決するには、`ProductsByCategory` DropDownList がバインドされた後に `ProductDetails` DetailsView を明示的に再バインドする必要があります。 これは、`ProductsByCategory` DropDownList の `DataBound` イベントが発生したときに `ProductDetails` DetailsView の `DataBind()` メソッドを呼び出すことによって実現できます。 次のイベントハンドラーコードを `MasterDetailsDetails.aspx` ページの分離コードクラスに追加します (イベントハンドラーを追加する方法の詳細については、「[ObjectDataSource のパラメーター値をプログラムで設定](../basic-reporting/programmatically-setting-the-objectdatasource-s-parameter-values-cs.md)する」を参照してください)。
[!code-csharp[Main](master-detail-filtering-with-two-dropdownlists-cs/samples/sample2.cs)]
`ProductDetails` DetailsView の `DataBind()` メソッドのこの明示的な呼び出しが追加されると、このチュートリアルは想定どおりに動作します。 図21は、この変更が以前の問題を解決した方法を示しています。
[Productbycategory の DropDownList のデータバインドイベントが発生したときに、ProductDetails の DetailsView が明示的に更新さ ](master-detail-filtering-with-two-dropdownlists-cs/_static/image61.png)
**図 21**: `ProductsByCategory` DropDownList の `DataBound` イベントが発生したときに `ProductDetails` DetailsView が明示的に更新される ([クリックしてフルサイズの画像を表示する](master-detail-filtering-with-two-dropdownlists-cs/_static/image63.png))
## <a name="summary"></a>まとめ
DropDownList はマスター/詳細レポートの理想的なユーザーインターフェイス要素として機能し、マスターレコードと詳細レコードの間に一対多のリレーションシップが存在します。 前のチュートリアルでは、1つの DropDownList を使用して、選択したカテゴリによって表示される製品をフィルター処理する方法を説明しました。 このチュートリアルでは、製品の GridView を DropDownList に置き換え、DetailsView を使用して選択した製品の詳細を表示しました。 このチュートリアルで説明する概念は、顧客、注文、注文品目など、複数の一対多リレーションシップを含むデータモデルに簡単に拡張できます。 一般に、一対多のリレーションシップでは、"one" エンティティごとに DropDownList をいつでも追加できます。
プログラミングを楽しんでください。
## <a name="about-the-author"></a>著者について
1998以来、 [Scott Mitchell](http://www.4guysfromrolla.com/ScottMitchell.shtml)は 7 asp/創設者 of [4GuysFromRolla.com](http://www.4guysfromrolla.com)の執筆者であり、Microsoft Web テクノロジを使用しています。 Scott は、独立したコンサルタント、トレーナー、およびライターとして機能します。 彼の最新の書籍は[ *、ASP.NET 2.0 を24時間以内に教え*](https://www.amazon.com/exec/obidos/ASIN/0672327384/4guysfromrollaco)ています。 mitchell@4GuysFromRolla.comでアクセスでき[ます。](mailto:mitchell@4GuysFromRolla.com) または彼のブログを参照してください。これは[http://ScottOnWriting.NET](http://ScottOnWriting.NET)にあります。
## <a name="special-thanks-to"></a>ありがとうございました。
このチュートリアルシリーズは、役に立つ多くのレビュー担当者によってレビューされました。 このチュートリアルのリードレビュー担当者は、Hilton Giesenow でした。 今後の MSDN 記事を確認することに興味がありますか? その場合は、mitchell@4GuysFromRolla.comの行を削除[します。](mailto:mitchell@4GuysFromRolla.com)
> [!div class="step-by-step"]
> [前へ](master-detail-filtering-with-a-dropdownlist-cs.md)
> [次へ](master-detail-filtering-across-two-pages-cs.md) |
import 'dart:convert';
import 'package:encrypt/encrypt.dart';
import '../models/http/http_setting.dart';
//MARK: RSA 加密
class RSAEncode {
static splitStr(String str) {
var begin = '-----BEGIN PUBLIC KEY-----\n';
var end = '\n-----END PUBLIC KEY-----';
int splitCount = str.length ~/ 64;
List<String> strList = [];
for (int i = 0; i < splitCount; i++) {
strList.add(str.substring(64 * i, 64 * (i + 1)));
}
if (str.length % 64 != 0) {
strList.add(str.substring(64 * splitCount));
}
return begin + strList.join('\n') + end;
}
static Future<String> encodeString(Map<String, String> content,
{String? key}) async {
String encoded = base64.encode(utf8.encode(jsonEncode(content)));
dynamic publicKey =
RSAKeyParser().parse(splitStr(key ?? HttpSetting.postKey));
final encrypt = Encrypter(RSA(publicKey: publicKey));
return encrypt.encrypt(encoded).base64;
}
static Future<String> encodeOnlyString(String content, {String? key}) async {
String encoded = base64.encode(utf8.encode(content));
dynamic publicKey =
RSAKeyParser().parse(splitStr(key ?? HttpSetting.postKey));
final encrypt = Encrypter(RSA(publicKey: publicKey));
return encrypt.encrypt(encoded).base64;
}
/// MARK: JSON 长参数分段加密
static Future<String> encodeLong(Map para) async {
// 设置加密对象
dynamic publicKey = RSAKeyParser().parse(splitStr(HttpSetting.postKey));
final encrypter = Encrypter(RSA(publicKey: publicKey));
// map转成json字符串
final jsonStr = base64.encode(utf8.encode(jsonEncode(para)));
// 原始json转成字节数组
List<int> sourceByts = utf8.encode(jsonStr);
// 数据长度
int inputLen = sourceByts.length;
// 加密最大长度
int maxLen = 117;
// 存放加密后的字节数组
List<int> totalByts = [];
// 分段加密 步长为117
for (var i = 0; i < inputLen; i += maxLen) {
// 还剩多少字节长度
int endLen = inputLen - i;
List<int> item;
if (endLen > maxLen) {
item = sourceByts.sublist(i, i + maxLen);
} else {
item = sourceByts.sublist(i, i + endLen);
}
// 加密后的对象转换成字节数组再存放到容器
totalByts.addAll(encrypter.encryptBytes(item).bytes);
}
// 加密后的字节数组转换成base64编码并返回
String en = base64.encode(totalByts);
return en;
}
static Future<String> decodeString(String content) async {
dynamic publicKey = RSAKeyParser().parse(splitStr(HttpSetting.postKey));
final encrypter = Encrypter(RSA(publicKey: publicKey));
return encrypter.decrypt(Encrypted.fromBase64(content));
}
} |
import React, { useState, useEffect } from 'react';
import { StyleSheet, Image } from 'react-native';
import { useAuth } from '../AuthContext';
import { MyTextInput, MyButton, MyContainer, MyText } from '../components';
import MyCheckbox from '../components/MyCheckbox';
import MyModal from '../components/MyModal';
import { termsText } from '../assets/terms_and_conditions';
export default function SignupScreen({ navigation, route }) {
const [email, setEmail] = useState(route?.params?.email || '');
const [password, setPassword] = useState(route?.params?.password || '');
const [passwordConfirm, setPasswordConfirm] = useState('');
const [error, setError] = useState('');
const [isTermsChecked, setTermsChecked] = useState(false);
const [termsModalVisible, setTermsModalVisible] = useState(false);
const { signUp } = useAuth();
useEffect(() => {
setError('');
}, [email, password]);
const handleSignUp = async () => {
try {
if (!email || !password || !passwordConfirm)
setError('Ingresá todos los campos');
else if (!isValidEmail())
setError('El correo electrónico no es válido');
else if (password != passwordConfirm)
setError('Las contraseñas no coinciden');
else if (!isTermsChecked)
setError('Debés aceptar los términos y condiciones');
else
await signUp({ email, password });
} catch (err) {
setError(err.message);
}
};
function isValidEmail() {
const emailRegex = /^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}$/i;
return emailRegex.test(email);
}
const onTermsValueChange = async () => {
if (isTermsChecked)
setTermsChecked(false);
else
setTermsModalVisible(true);
};
const onTermsCloseModal = async (accepted) => {
setTermsChecked(accepted);
setTermsModalVisible(false);
};
return (
<MyContainer>
<Image
source={require('../assets/tr.png')}
style={styles.image}
/>
<MyTextInput
placeholder="Correo electrónico"
value={email}
onChangeText={setEmail}
keyboardType="email-address"
/>
<MyTextInput
placeholder="Contraseña"
value={password}
onChangeText={setPassword}
secureTextEntry
/>
<MyTextInput
placeholder="Repetir contraseña"
value={passwordConfirm}
onChangeText={setPasswordConfirm}
secureTextEntry
/>
<MyCheckbox isChecked={isTermsChecked} onValueChange={onTermsValueChange} text="Acepto los términos y condiciones." />
<MyModal modalVisible={termsModalVisible} onCloseModal={onTermsCloseModal} title="Términos y condiciones" text={termsText}/>
<MyText size='sm' elemStyle={styles.errorText}>{error}</MyText>
<MyButton title="Crear usuario" onPress={handleSignUp} />
<MyButton
title="Ya estoy registrado"
onPress={() => navigation.navigate('SignIn', { email, password })}
secondaryButton
/>
</MyContainer>
);
}
const styles = StyleSheet.create({
image: {
alignSelf: 'center',
marginBottom: 30
},
errorText: {
color: 'red'
}
}); |
import { query } from "express";
import {MigrationInterface, QueryRunner, Table} from "typeorm";
export class createShelters1602615534414 implements MigrationInterface {
public async up(queryRunner: QueryRunner): Promise<void> {
await queryRunner.createTable(new Table({
name: 'shelters',
columns: [
{
name: 'id',
type: 'integer',
unsigned: true,
isPrimary: true,
isGenerated: true,
generationStrategy: 'increment'
},
{
name: 'name',
type: 'varchar',
},
{
name:'latitude',
type: 'decimal',
scale: 10,
precision: 2,
},
{
name: 'longitude',
type: 'decimal',
scale: 10,
precision: 2,
},
{
name: 'about',
type: 'text',
},
{
name: 'instructions',
type: 'text',
},
{
name: 'opening_hours',
type: 'varchar'
},
{
name: 'open_on_weekends',
type: 'boolean',
default: false,
},
],
}))
}
public async down(queryRunner: QueryRunner): Promise<void> {
await queryRunner.dropTable('shelters');
}
} |
import React, { useState } from 'react';
import axios from 'axios';
import Swal from 'sweetalert2';
const ParcoursEdit = ({ item, onSubmit }) => {
const [designparcours, setDesignparcours] = useState(item.designparcours);
const [description, setDescription] = useState(item.description);
const handleSubmit = (e) => {
e.preventDefault();
// Utilisez SweetAlert2 pour la confirmation
Swal.fire({
title: 'Êtes-vous sûr?',
text: 'Confirmez-vous la modification des informations de cette salle?',
icon: 'warning',
showCancelButton: true,
confirmButtonColor: '#32c637',
cancelButtonColor: '#ec1c24',
confirmButtonText: 'Oui, modifiez-la!',
cancelButtonText: 'Annuler'
}).then((result) => {
if (result.isConfirmed) {
// L'utilisateur a confirmé la modification
const updatedItem = { ...item, designparcours, description};
axios
.patch(`http://localhost:5000/parcour/${item.id_parcours}`, updatedItem)
.then(() => {
Swal.fire('Modifié!', 'Les informations de la salle ont été modifiées avec succès.', 'success');
onSubmit(updatedItem, true); // Informez le composant parent de la mise à jour
})
.catch(() => {
Swal.fire('Erreur!', 'La modification a échoué. Veuillez réessayer.', 'error');
});
}
});
};
return (
<>
<div>
{/* <h3>Ajouter un nouveau client</h3> */}
<form onSubmit={handleSubmit}>
<div className="mb-3">
<label htmlFor="exampleFormControlInput1" className="form-label">
Parcours
</label>
<input type="text" className="form-control" value={designparcours} onChange={(e) => setDesignparcours(e.target.value)} />
</div>
<div className="mb-3">
<label htmlFor="exampleFormControlInput1" className="form-label">
Description
</label>
<input type="text" className="form-control" value={description} onChange={(e) => setDescription(e.target.value)} />
</div>
<button className="btn btn-primary">Mettre à jour</button>
</form>
</div>
</>
);
};
export default ParcoursEdit; |
//
// ShellManager.swift
// iOSMcuManagerLibrary
//
// Created by Dinesh Harjani on 27/2/24.
//
import Foundation
import SwiftCBOR
// MARK: - ShellManager
/**
Enables remote execution of McuMgr Shell commands over BLE.
*/
public class ShellManager: McuManager {
// MARK: TAG
override class var TAG: McuMgrLogCategory { .shell }
// MARK: IDs
enum ShellID: UInt8 {
case exec = 0
}
// MARK: Init
public init(transporter: McuMgrTransport) {
super.init(group: McuMgrGroup.shell, transporter: transporter)
}
// MARK: API
public func execute(command: String, callback: @escaping McuMgrCallback<McuMgrExecResponse>) {
execute(command: command, arguments: [], callback: callback)
}
public func execute(command: String, arguments: [String],
callback: @escaping McuMgrCallback<McuMgrExecResponse>) {
let payload: [String: CBOR]
if arguments.isEmpty {
payload = ["argv": CBOR.array([CBOR.utf8String(command)])]
} else {
var allArguments = [command]
allArguments.append(contentsOf: arguments)
payload = ["argv": CBOR.array(allArguments.map({CBOR.utf8String($0)}))]
}
send(op: .write, commandId: ShellID.exec, payload: payload, callback: callback)
}
}
// MARK: - ShellManagerError
public enum ShellManagerError: UInt64, Error, LocalizedError {
case noError = 0
case unknown = 1
case commandTooLong = 2
case emptyCommand = 3
public var errorDescription: String? {
switch self {
case .noError:
return "Success"
case .unknown:
return "Unknown Error"
case .commandTooLong:
return "Given Command to run is too long"
case .emptyCommand:
return "No Command to run was provided"
}
}
} |
const express = require("express");
const router = express.Router();
const classController = require("../controllers/classController");
const cartController = require("../controllers/cartController");
const paymentController = require("../controllers/paymentController");
const userController = require("../controllers/userController");
const { generateToken, verifyJWT } = require("../middleware/jwtTOken");
const { verifyAdmin } = require("../middleware/verifyAdmin");
const { verifyInstructor } = require("../middleware/verifyInstructor");
//Routes For Class Operations
router.get("/classes", classController.getallCLasses);
router.get("/classes/:email", verifyJWT, classController.getinstructorMail);
router.post(
"/new-class",
verifyJWT,
verifyInstructor,
classController.postNewClass
);
router.get("/manage-classes", classController.manageClasses);
router.patch(
"/update-classStatus/:id",
verifyJWT,
verifyAdmin,
classController.updateClassStatus
);
router.get("/single-class/:id", classController.singleClassDetails);
router.get("/approved-classes", classController.approvedClasses);
router.put(
"/update-classdetails/:id",
verifyJWT,
verifyInstructor,
classController.updateClassDetails
);
//Routes For Cart Operations
router.post("/add-to-cart", verifyJWT, cartController.addToCart);
router.get("/get-cart-Item/:id", verifyJWT, cartController.getCartItemsbyId);
router.get("/get-cart-info/:email", verifyJWT, cartController.cartinfobyID);
router.delete(
"/delete-cart-item/:id",
verifyJWT,
cartController.deleteCartbyID
);
//Routes for Payment
router.post("/create-payment-intent", paymentController.createPaymentIntent);
router.post("/payment-info", verifyJWT, paymentController.postPaymentIntent);
router.get("/payment-history/:email", paymentController.getPaymentHistory);
router.get(
"/payment-history-length/:email",
paymentController.PaymentHistoryLength
);
//Routes for Enrollment
router.get("/popular-classes");
router.get("/popular-instructors");
//Routes for User
router.post("/user-signup", userController.postNewUser);
router.get("/get-all-user", userController.getAllUsers);
router.get("/get-user/:id", userController.getUsersByID);
router.post("/get-useremail/:email", verifyJWT, userController.getUsersByEmail);
router.put("/user-update", verifyJWT, verifyAdmin, userController.updateUser);
router.put(
"/deleteuser/:id",
verifyJWT,
verifyAdmin,
userController.deleteUser
);
router.post("/generate-token", generateToken);
module.exports = router; |
// Copyright 2018 Open Source Robotics Foundation, 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 "convert/utils.hpp"
#include "ros_gz_bridge/convert/builtin_interfaces.hpp"
#include "ros_gz_bridge/convert/std_msgs.hpp"
namespace ros_gz_bridge
{
template<>
void
convert_ros_to_gz(
const std_msgs::msg::Bool & ros_msg,
gz::msgs::Boolean & gz_msg)
{
gz_msg.set_data(ros_msg.data);
}
template<>
void
convert_gz_to_ros(
const gz::msgs::Boolean & gz_msg,
std_msgs::msg::Bool & ros_msg)
{
ros_msg.data = gz_msg.data();
}
template<>
void
convert_ros_to_gz(
const std_msgs::msg::ColorRGBA & ros_msg,
gz::msgs::Color & gz_msg)
{
gz_msg.set_r(ros_msg.r);
gz_msg.set_g(ros_msg.g);
gz_msg.set_b(ros_msg.b);
gz_msg.set_a(ros_msg.a);
}
template<>
void
convert_gz_to_ros(
const gz::msgs::Color & gz_msg,
std_msgs::msg::ColorRGBA & ros_msg)
{
ros_msg.r = gz_msg.r();
ros_msg.g = gz_msg.g();
ros_msg.b = gz_msg.b();
ros_msg.a = gz_msg.a();
}
template<>
void
convert_ros_to_gz(
const std_msgs::msg::Empty &,
gz::msgs::Empty &)
{
}
template<>
void
convert_gz_to_ros(
const gz::msgs::Empty &,
std_msgs::msg::Empty &)
{
}
template<>
void
convert_ros_to_gz(
const std_msgs::msg::UInt32 & ros_msg,
gz::msgs::UInt32 & gz_msg)
{
gz_msg.set_data(ros_msg.data);
}
template<>
void
convert_gz_to_ros(
const gz::msgs::UInt32 & gz_msg,
std_msgs::msg::UInt32 & ros_msg)
{
ros_msg.data = gz_msg.data();
}
template<>
void
convert_ros_to_gz(
const std_msgs::msg::Float32 & ros_msg,
gz::msgs::Float & gz_msg)
{
gz_msg.set_data(ros_msg.data);
}
template<>
void
convert_gz_to_ros(
const gz::msgs::Float & gz_msg,
std_msgs::msg::Float32 & ros_msg)
{
ros_msg.data = gz_msg.data();
}
template<>
void
convert_ros_to_gz(
const std_msgs::msg::Float64 & ros_msg,
gz::msgs::Double & gz_msg)
{
gz_msg.set_data(ros_msg.data);
}
template<>
void
convert_gz_to_ros(
const gz::msgs::Double & gz_msg,
std_msgs::msg::Float64 & ros_msg)
{
ros_msg.data = gz_msg.data();
}
template<>
void
convert_ros_to_gz(
const std_msgs::msg::Header & ros_msg,
gz::msgs::Header & gz_msg)
{
convert_ros_to_gz(ros_msg.stamp, *gz_msg.mutable_stamp());
auto newPair = gz_msg.add_data();
newPair->set_key("frame_id");
newPair->add_value(ros_msg.frame_id);
}
template<>
void
convert_ros_to_gz(
const std_msgs::msg::Int32 & ros_msg,
gz::msgs::Int32 & gz_msg)
{
gz_msg.set_data(ros_msg.data);
}
template<>
void
convert_gz_to_ros(
const gz::msgs::Int32 & gz_msg,
std_msgs::msg::Int32 & ros_msg)
{
ros_msg.data = gz_msg.data();
}
template<>
void
convert_gz_to_ros(
const gz::msgs::Header & gz_msg,
std_msgs::msg::Header & ros_msg)
{
convert_gz_to_ros(gz_msg.stamp(), ros_msg.stamp);
for (auto i = 0; i < gz_msg.data_size(); ++i) {
auto aPair = gz_msg.data(i);
if (aPair.key() == "frame_id" && aPair.value_size() > 0) {
ros_msg.frame_id = frame_id_gz_to_ros(aPair.value(0));
}
}
}
template<>
void
convert_ros_to_gz(
const std_msgs::msg::String & ros_msg,
gz::msgs::StringMsg & gz_msg)
{
gz_msg.set_data(ros_msg.data);
}
template<>
void
convert_gz_to_ros(
const gz::msgs::StringMsg & gz_msg,
std_msgs::msg::String & ros_msg)
{
ros_msg.data = gz_msg.data();
}
} // namespace ros_gz_bridge |
import { Component, EventEmitter, Input, OnInit, Output } from "@angular/core";
import { Router } from "@angular/router";
import { NgbModal } from "@ng-bootstrap/ng-bootstrap";
import { Observable, of } from "rxjs";
import { catchError } from "rxjs/operators";
import { UPDATE_CAR_PAGE_PATH } from "src/app/core/constants/page-constans";
import { BookingFeedbackModel } from "src/app/shared/models/booking-feedback/booking-feedback.model";
import { Car } from "src/app/shared/models/car/car.model";
import { BookingFeedbackService } from "src/app/shared/services/bookingFeedback.service";
import { CarService } from "src/app/shared/services/car.service";
import { LoginService } from "src/app/shared/services/login.service";
import { LoginModalComponent } from "../../auth/login-modal/login-modal.component";
import { BookCarComponent } from "../book-car/book-car.component";
@Component({
selector: 'app-car-card',
templateUrl: 'car-card.component.html',
styleUrls: ['car-card.component.css']
}) export class CarCardComponent implements OnInit {
public isFeedbackLoaded: boolean = false;
@Output() onError = new EventEmitter();
@Input() car!: Car;
@Input() public keyReceivingTime!: Date;
@Input() public keyHandOverTime!: Date;
public isFeedbackSpinner: boolean = true;
public isCollapsed = true;
public bookingFeedbacks$: Observable<BookingFeedbackModel[]> = new Observable();
public bookingFeedbacks: BookingFeedbackModel[] = [];
public averageFeedback$: Observable<number> = new Observable();
constructor
(
private carService: CarService,
private bookingFeedbackService: BookingFeedbackService,
private router: Router,
private modalService: NgbModal,
private loginService: LoginService
) { }
ngOnInit(): void {
this.averageFeedback$ = this.carService.getCarAverageFeedback(this.car.id).pipe(
catchError(error => {
return of(0);
})
);
}
public deleteCar(carId: string) {
this.carService.deleteCar(carId).subscribe(() => window.location.reload());
}
public updateCar(carId: string) {
this.router.navigate([UPDATE_CAR_PAGE_PATH, carId]);
}
public showRentCarWindow(car: Car): void {
if (!this.isLogin) {
this.modalService.open(LoginModalComponent)
.result.then(() => {
if (this.isLogin()) {
this.carService.lockCar(car.id).subscribe(data => {
this.openBookModel(car);
},
() => {
this.onError.emit();
});
}
});
}
else {
this.carService.lockCar(car.id).subscribe(data => {
this.openBookModel(car);
},
() => {
this.onError.emit();
});
}
}
private openBookModel(car: Car): void {
const modalRef = this.modalService.open(BookCarComponent);
modalRef.componentInstance.car = car;
modalRef.componentInstance.keyHandOverTime = this.keyHandOverTime;
modalRef.componentInstance.keyReceivingTime = this.keyReceivingTime;
}
public loadFeedbacks(): void {
if (!this.isFeedbackLoaded) {
this.bookingFeedbacks$ = this.bookingFeedbackService.getBookingFeedbacksByCarId(this.car.id);
this.bookingFeedbackService.getBookingFeedbacksByCarId(this.car.id)
.subscribe(data => {
this.bookingFeedbacks = data;
this.isFeedbackLoaded = true;
});
}
}
public isAdmin(): boolean {
return this.loginService.getRole() === 'Admin';
}
public isLogin(): boolean {
return this.loginService.isLogin();
}
} |
const express = require('express');
const Task = require('../models/task');
const protect = require('../middleware/auth');
const router = express.Router();
// Create a new task (Protected)
router.post('/', protect, async (req, res) => {
const { title, description, dueDate } = req.body;
const userId = req.user.userId;
try {
const newTask = new Task({
title,
description,
dueDate,
userId, // Associate the task with the authenticated user
});
await newTask.save();
res.status(201).json(newTask);
} catch (error) {
res.status(400).json({ message: 'Error creating task', error });
}
});
// Get all tasks for the authenticated user (Protected)
router.get('/', protect, async (req, res) => {
const userId = req.user.userId;
try {
const tasks = await Task.find({ userId }); // Fetch tasks only for the authenticated user
res.status(200).json(tasks);
} catch (error) {
res.status(500).json({ message: 'Error fetching tasks', error });
}
});
// Update a task by ID (Protected)
router.put('/:id', protect, async (req, res) => {
const { id } = req.params;
const { title, description, completed, dueDate } = req.body;
const userId = req.user.userId;
try {
const updatedTask = await Task.findOneAndUpdate(
{ _id: id, userId }, // Ensure the task belongs to the authenticated user
{ title, description, completed, dueDate },
{ new: true }
);
if (!updatedTask) {
return res.status(404).json({ message: 'Task not found' });
}
res.status(200).json(updatedTask);
} catch (error) {
res.status(400).json({ message: 'Error updating task', error });
}
});
// Mark a task as completed by ID (Protected)
router.patch('/:id/complete', protect, async (req, res) => {
const { id } = req.params; // Task ID from the URL
const userId = req.user.userId; // User ID from authentication
try {
const task = await Task.findOne({ _id: id, userId });
if (!task) {
return res.status(404).json({ message: 'Task not found' });
}
// Update the task to mark it as completed
task.completed = true;
task.updatedAt = new Date(); // Update the updatedAt field
const updatedTask = await task.save();
res.status(200).json(updatedTask); // Return the updated task
} catch (error) {
res.status(400).json({ message: 'Error marking task as completed', error });
}
});
// Delete a task by ID (Protected)
router.delete('/:id', protect, async (req, res) => {
const { id } = req.params;
const userId = req.user.userId;
console.log(req.user.email);
try {
const deletedTask = await Task.findOneAndDelete({ _id: id, userId });
if (!deletedTask) {
return res.status(404).json({ message: 'Task not found' });
}
res.status(200).json({ message: 'Task deleted successfully' });
} catch (error) {
res.status(400).json({ message: 'Error deleting task', error });
}
});
module.exports = router; |
"""
Aresh Tajvar, 2024
CS50 Python Final Project
Fed Weather
This program accesses the NOAA free and public-access API at https://api.weather.gov.
Prompts user for weather station per NOAA convention (ex: KSEA for Seattle, WA)
Return station name (ex: Seattle, Seattle-Tacoma International Airport)
Prompt user for desired weather detail (ex: temperature, barometricPressure)
Return selected weather detail (ex: Temperature: 13.7 degC)
Github repository:
https://github.com/AreTaj/fed-weather
Harvard CS50 Python Final Project:
https://cs50.harvard.edu/python/2022/project/
NOAA API Documentation:
https://www.weather.gov/documentation/services-web-api#/
NOAA Station Observations API:
https://api.weather.gov/stations/{station}/observations
"""
import re
import sys
import requests
def main():
station_input = input("Input a weather station: ")
station_code = validate_station(station_input) # If validated, station_input becomes station_code and is passed to station()
station(station_code)
properties_dict = api_and_parse(station_code) # station_code is passed to api_and_parse(), which results properties_dict
result, selection_data = get_weather(properties_dict) # properties_dict is passed to get_weather(), which results result and selection_data
format_and_print(result, selection_data) # result and selection_data are passed to format_and_print()
def validate_station(station_input):
example_stations = ["KBOS", "KNYC", "KOPF", "KHOU", "KABQ", "KSAN", "KLAX", "KSFO", "KPDX", "KSEA"]
while True:
if re.match("^[A-Z]{4}$", station_input): # Standard is four capital letters
station_check = requests.get(f"https://api.weather.gov/stations/{station_input}")
if station_check.status_code != 200 and station_check.status_code != 404: # Checks for API status; if not status_code = 200 (running), then kill
sys.exit(f"Error: received status code {station_check.status_code}")
elif station_check.status_code == 404: # 404 indicates station does not exist in NOAA database, reprompt
print(f'\nIncorrect station code "{station_input}" or station does not exist. Try one of these: {example_stations}')
station_input = input("Input a weather station: ")
continue
break
else: # If failed regex, reprompt
print(f'\nInvalid station code "{station_input}". Try one of these: {example_stations}')
station_input = input("Input a weather station: ")
continue
station_code = station_input # If and only if validation passed, station_input becomes station_code and is returned
return station_code
def station(station_code): # Gets station name from API, prints, returns station_name to facilitate testing
station_response = requests.get(f"https://api.weather.gov/stations/{station_code}")
station_data = station_response.json()
station_properties = station_data["properties"]
station_name = station_properties["name"]
print(station_name)
return station_name
def api_and_parse(station_code):
response = requests.get(f"https://api.weather.gov/stations/{station_code}/observations")
if response.status_code !=200: # Checks for API status; if not status_code = 200 (running), then kill
sys.exit(f"Error: received status code {response.status_code}")
else:
data = response.json() # dict
features_list = data["features"] # list
element_dict = features_list[0] # dict; always takes the first element because NWS has standardized format
properties_dict = element_dict.get("properties") # dict
return properties_dict # dict of all possible weather properties, passes to get_weather()
def get_weather(properties_dict):
valid_properties_list = ["elevation", "temperature", "dewpoint", "windDirection", "windSpeed", "barometricPressure", "seaLevelPressure", "visibility", "relativeHumidity", "windChill"]
selection = input(f"Valid options: {valid_properties_list}.\nInput weather property: ")
while True:
if selection in valid_properties_list:
selection_data = properties_dict.get(selection) # dict
result = "".join(' ' + i if i.isupper() else i for i in selection).capitalize() # Ex: barometricPressure --> Barometric pressure, temperature --> Temperature
break
else:
print(f'\nInvalid weather property "{selection}"')
selection = input(f"Valid options: {valid_properties_list}.\nInput weather property: ")
continue
return result, selection_data
def format_and_print(result, selection_data):
unit_code = str(selection_data.get("unitCode")) # Take unitCode and convert to str
units = unit_code.split(":")[1] # Split unit_code at ":", and only take whatever is to the right into units
value = str(selection_data.get("value")) # Take value and convert to str
print(result +": "+ value + " " + units)
if __name__ == "__main__":
main() |
package com.shop.ecommerce.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.shop.ecommerce.modele.Panier;
import com.shop.ecommerce.modele.Produit;
import com.shop.ecommerce.service.PanierService;
import com.shop.ecommerce.service.ProduitService;
import lombok.AllArgsConstructor;
@RestController
@RequestMapping("/panier")
@AllArgsConstructor
public class PanierController {
@Autowired
private final PanierService panierService;
@Autowired
private final ProduitService produitService;
@PostMapping("/add")
public String addToPanier(@RequestParam Long idProd) {
// Assuming you have a method to get the product details by ID
Produit product = produitService.getProductById(idProd);
// Now, you can add the product to the cart or handle it as needed
// For simplicity, let's assume you have a service method to add a product to the cart
panierService.addProductToCart(product);
// Redirect back to the product details page or any other page as needed
return "redirect:/produit/produit-details/" + idProd;
//return "redirect:/process-paiement?idProd=" + idProd;
}
@GetMapping("/count/{idUser}")
public int getPanierItemCount(@PathVariable Long idUser) {
return panierService.getPanierItemCount(idUser);
}
@PostMapping("/create")
public Panier create(@RequestBody Panier panier) {
return panierService.addToCart(panier);
}
@GetMapping("/read")
public List<Panier> read() {
return panierService.lire();
}
@PutMapping("/update/{idPanier}")
public Panier update(@PathVariable Long idPanier, @RequestBody Panier panier) {
return panierService.modifier(idPanier, panier);
}
@DeleteMapping("/delete/{idPanier}")
public String delete(@PathVariable Long idPanier) {
return panierService.supprimer(idPanier);
}
} |
import { AggregateRoot } from "../../../../shared/domain/model/aggregates/AggregateRoot";
import { Entity, PrimaryGeneratedColumn, Column } from "typeorm";
@Entity('users')
export class User extends AggregateRoot {
@PrimaryGeneratedColumn()
readonly id!: number;
@Column({ unique: true })
public username!: string;
@Column()
public password!: string;
constructor(username?: string, password?: string) {
super();
if (username && password) {
this.username = username;
this.password = password;
}
}
changePassword(newPassword: string): void {
if (newPassword.length < 8) {
throw new Error('Password must be at least 8 characters long');
}
this.password = newPassword;
}
} |
<template>
<div class="construction_progress_wrapper">
<div class="page_title_wrapper touch">
<h1 class="page_title">
{{ post.title }}
</h1>
</div>
<!--компонент выбора дома -->
<HouseFilter :houses="houses" :house-number="this.filter.houseNumber"/>
<div class="wrapper">
<Card :card="card"/>
</div>
<div v-if="isGallery">
<Gallery :reportsList="reportsList"/>
</div>
<div v-else>
<div class="photo_slider">
<div class="slider_wrapper photo_slider_wrapper">
<SlickSlider :slider="slider" />
</div>
</div>
</div>
<PageContent :content="post.content"></PageContent>
</div>
</template>
<script>
import SlickSlider from '~/components/SlickSlider'
import Card from '~/components/Card'
import PageContent from '~/components/PageContent'
import HouseFilter from '~/components/ProgressSlider/HouseFilter'
import Gallery from '~/components/ProgressSlider/Gallery'
import {createClient} from '~/plugins/contentful';
const client = createClient();
const touchBreakpoint = 1023;
const defaultHouseNumber = 0;
export default {
name: 'ConstructionProgress',
components: {
HouseFilter,
PageContent,
Card,
Gallery,
SlickSlider
},
head() {
return {
title: this.post.title,
}
},
data() {
return {
reports: [],
reportsList: [],
filter: {
houseNumber: null,
year: new Date().getFullYear(),
month: (new Date().getMonth() + 1).toString().padStart(2, '0')
},
width: null,
slider: {
type: 'slideConstructionProgress',
isFullWidthOnDesktop: 'false',
isTopSlider: 'false',
isShowText: 'true',
slidesToShow: '3',
autoplay: true,
slidesToScroll: 1,
draggable: true,
slides: this.reportsList,
}
}
},
computed: {
isGallery: function () {
if ((this.isTouch && this.reportsList.length === 1) || !this.isTouch && this.reportsList.length <= 3) {
return true
}
},
isTouch: function () {
return this.width <= touchBreakpoint;
}
},
asyncData: async function ({store, error}) {
try {
let index = 0, years = {}, housesApproved = [];
const content = await client.getEntries({
include: 2,
content_type: 'mainPage',
'fields.id': '1'
});
let post = content.items[0].fields;
const cardContent = await client.getEntries({
content_type: 'card',
'fields.id': '15'
});
let card = cardContent.items[0];
const housesAll = await client.getEntries({
content_type: 'house',
'fields.isReadyForSale': true
});
const yearsData = await client.getEntries({
content_type: 'yearReport',
select: 'fields.year'
});
const withReports = await client.getEntries({
content_type: 'yearReport',
'fields.reports[exists]': true,
select: 'fields.year'
});
let yearsWithReports = withReports.items.map(withReport => withReport.fields.year);
let yearsAll = yearsData.items
.map(year => year.fields.year)
.sort((a, b) => a - b);
//divide not empty from empty years for years filter
for (const key in yearsAll) {
if (yearsAll.hasOwnProperty(key)) {
let yearValue = yearsAll[key];
years[index] = {
year: yearValue,
isNotEmpty: yearsWithReports.includes(yearValue)
};
index++;
}
}
//:TODO refactor it - check for houses with reports
let housesData = await Promise.all(housesAll.items.map(house => {
return client.getEntries({
content_type: 'report',
select: 'fields.houseNumber',
'fields.houseNumber': house.fields.number,
});
}
));
let housesWithReportsArray = housesData.map(house => {
if (house.total > 0) {
return house.items[0].fields.houseNumber
}
});
for (let i = 0; i < housesWithReportsArray.length; i++) {
if (typeof housesWithReportsArray[i] !== 'undefined') {
housesApproved.push(housesWithReportsArray[i])
}
}
let houses = {};
housesAll.items.forEach(house => {
houses[house.fields.number] = {
id: house.fields.number,
// isReadyForSale: house.fields.isReadyForSale && housesApproved.includes(house.fields.number)
isReadyForSale: false
};
});
return {
post: post,
card: card,
houses: houses,
years: years,
}
} catch (e) {
error(e)
}
},
methods: {
async getReports(filter) {
let {year, month, houseNumber} = filter;
let dateRange = this.formatDate(year, month);
let reports = await client.getEntries({
content_type: 'report',
'fields.houseNumber': houseNumber,
'fields.date[gte]': dateRange.firstDay,
'fields.date[lte]': dateRange.lastDay,
order: '-sys.createdAt'
});
this.reports = reports;
this.reportsList = reports.items.map(report => report.fields.reportPhotoCollection).flat();
},
//get first and last days of month formatted to ISO
formatDate(year, month) {
month = this.monthFormat(month);
let firstDayOfMonthDate = new Date(year, month, 1);
firstDayOfMonthDate.setMonth(firstDayOfMonthDate.getMonth() - 1);
let firstDayOfMonthISO = firstDayOfMonthDate.toISOString();
let lastDayOfMonth = this.getLastDayOfMonth(year, month);
let lastDayOfMonthDate = new Date(year, month, lastDayOfMonth);
lastDayOfMonthDate.setMonth(lastDayOfMonthDate.getMonth() - 1);
let lastDayOfMonthISO = lastDayOfMonthDate.toISOString();
return {
firstDay: firstDayOfMonthISO,
lastDay: lastDayOfMonthISO
}
},
getLastDayOfMonth(year, month) {
let date = new Date(year, month + 1, 0);
return date.getDate();
},
monthFormat(month) {
if (month[0] === '0') {
month = month.slice(1);
}
return month
},
updateWidth() {
this.width = window.innerWidth;
},
},
mounted() {
//set init house number
let housesReadyForSale = [];
let houses = this.houses;
for (let house in houses) {
if (houses.hasOwnProperty(house)) {
if (houses[house]['isReadyForSale'] === true) {
housesReadyForSale.push((houses[house]['id']));
}
}
}
housesReadyForSale
.map(house => house.id)
.sort((a, b) => a - b);
if (housesReadyForSale.length > 0) {
this.filter.houseNumber = housesReadyForSale[0];
} else {
this.filter.houseNumber = defaultHouseNumber;
}
////
window.addEventListener('resize', this.updateWidth);
this.updateWidth();
this.getReports(this.filter);
this.$bus.$on('houseChanged', ({house}) => {
this.filter.houseNumber = house;
});
this.$bus.$on('yearChanged', ({year}) => {
this.filter.year = year;
});
this.$bus.$on('monthChanged', ({month}) => {
this.filter.month = month;
});
},
watch: {
filter: {
handler: function () {
this.getReports(this.filter);
},
deep: true,
}
}
}
</script>
<style lang="scss" scoped>
@import "../assets/scss/mixins&vars.scss";
.construction-progress-page {
@include touch {
.house_selector_wrapper{
display: none;
}
.page_title_wrapper{
display: none;
}
.month_slider_wrapper{
overflow: hidden;
}
.photo_slider_wrapper{
padding-bottom: 0;
}
.top-card {
margin-bottom: 20px;
}
}
@include tab{
padding-top: 48px;
.construction_progress_wrapper{
margin-top: 40px;
}
.photo_slider{
margin-bottom: 30px;
}
}
@include desktop {
.house_selector_wrapper {
margin-bottom: 30px;
}
.top-card {
margin-bottom: 30px;
}
.month_slider_wrapper {
margin-bottom: 30px;
box-shadow: 0 7px 20px rgba(37, 60, 77, 0.2);
}
}
}
</style> |
import React from 'react';
import { rosterObject } from '../../../assets/interfaces';
interface playerInfoProp {
playerInfo: playerObjectInfo;
currentPosition: string;
roster: rosterObject;
setRoster: React.Dispatch<React.SetStateAction<rosterObject>>;
setAddPlayerModal: React.Dispatch<React.SetStateAction<boolean>>;
}
interface playerObjectInfo {
best_position: string;
club_name: string;
full_name: string;
id: number;
image_link: string;
known_as: string;
national_team_image_link: string;
overall: number;
potential: number;
}
export default function SearchResultPlayerCard({
playerInfo,
roster,
setRoster,
currentPosition,
setAddPlayerModal,
}: playerInfoProp) {
const addPlayerInfo = (playerType: string) => {
let rosterCopy: rosterObject = roster;
let playerObj = {
name: playerInfo.known_as,
position: playerInfo.best_position,
ovr: playerInfo.overall,
player_id: playerInfo.id,
player_photo: playerInfo.image_link,
};
if (playerType === 'substitutes' || playerType === 'firstTeam') {
const rosterCopyKey = playerType as 'firstTeam' | 'substitutes';
rosterCopy[rosterCopyKey][currentPosition] = playerObj;
} else {
rosterCopy['reserves'].push(playerObj);
}
setRoster((rosterCopy) => ({ ...rosterCopy }));
};
const addToTeam = () => {
if (currentPosition.startsWith('s')) {
addPlayerInfo('substitutes');
console.log(roster['substitutes']);
} else if (currentPosition === 'reserve') {
addPlayerInfo('reserves');
console.log(roster['reserves']);
} else {
addPlayerInfo('firstTeam');
}
setAddPlayerModal(false);
};
return (
<div className="grid grid-cols-7 pb-8 items-center justify-items-center">
<img
id="playerPic"
src={playerInfo.image_link ? playerInfo.image_link : ''}
></img>
<h3 id="fullName">{playerInfo.known_as}</h3>
<h3 id="position">{playerInfo.best_position}</h3>
<h3 id="overall">{playerInfo.overall}</h3>
<h3 id="potential">{playerInfo.potential}</h3>
<img
id="nationFlag"
src={
playerInfo.national_team_image_link
? playerInfo.national_team_image_link
: ''
}
className="w-[30px] h-[20px] text-center mt-1"
></img>
<button
onClick={addToTeam}
className="rounded-full bg-green-400 inline-block h-8 w-8 text-white font-extrabold text-xl text-center"
>
<p className="mb-1 mt-1">+</p>
</button>
</div>
);
} |
package com.example.tmdbclone.di
import android.content.Context
import com.example.tmdbclone.data.remote.repository.UserRepositoryImpl
import com.example.tmdbclone.data.remote.repository.CelebritiesRepositoryImpl
import com.example.tmdbclone.data.remote.repository.CelebrityDetailsRepositoryImpl
import com.example.tmdbclone.data.remote.repository.MovieDetailRepositoryImpl
import com.example.tmdbclone.data.remote.repository.MoviesRepositoryImpl
import com.example.tmdbclone.data.remote.repository.SearchRepositoryImpl
import com.example.tmdbclone.data.remote.repository.TvShowsRepositoryImpl
import com.example.tmdbclone.data.remote.service.UserService
import com.example.tmdbclone.data.remote.service.CelebritiesService
import com.example.tmdbclone.data.remote.service.CelebrityDetailsService
import com.example.tmdbclone.data.remote.service.GenresService
import com.example.tmdbclone.data.remote.service.IsFavouriteService
import com.example.tmdbclone.data.remote.service.MovieDetailService
import com.example.tmdbclone.data.remote.service.MoviesService
import com.example.tmdbclone.data.remote.service.SearchService
import com.example.tmdbclone.data.remote.service.TvShowDetailsService
import com.example.tmdbclone.data.remote.service.TvShowsService
import com.example.tmdbclone.domain.SessionManager
import com.example.tmdbclone.domain.repository.UserRepository
import com.example.tmdbclone.domain.repository.CelebritiesRepository
import com.example.tmdbclone.domain.repository.CelebrityDetailsRepository
import com.example.tmdbclone.domain.repository.MovieDetailRepository
import com.example.tmdbclone.domain.repository.MoviesRepository
import com.example.tmdbclone.domain.repository.SearchRepository
import com.example.tmdbclone.domain.repository.TvShowsRepository
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.android.qualifiers.ApplicationContext
import dagger.hilt.components.SingletonComponent
import javax.inject.Singleton
@Module
@InstallIn(SingletonComponent::class)
object RepoModule {
@Provides
@Singleton
fun provideMoviesRepo(apiService: MoviesService, genresApi: GenresService): MoviesRepository {
return MoviesRepositoryImpl(apiService, genresApi)
}
@Provides
@Singleton
fun provideTvShowsRepo(apiService: TvShowsService): TvShowsRepository {
return TvShowsRepositoryImpl(apiService)
}
@Provides
@Singleton
fun provideCelebritiesRepo(apiService: CelebritiesService): CelebritiesRepository {
return CelebritiesRepositoryImpl(apiService)
}
@Provides
@Singleton
fun provideMovieDetailsRepo(
apiService: MovieDetailService,
tvShowDetailsService: TvShowDetailsService,
isFavouriteService: IsFavouriteService,
genresApi: GenresService
): MovieDetailRepository {
return MovieDetailRepositoryImpl(
apiService,
tvShowDetailsService,
isFavouriteService,
genresApi
)
}
@Provides
@Singleton
fun provideAuthRepo(
apiService: UserService,
sessionManager: SessionManager
): UserRepository =
UserRepositoryImpl(apiService, sessionManager)
@Provides
@Singleton
fun provideSearchRepo(apiService: SearchService): SearchRepository =
SearchRepositoryImpl(apiService)
@Provides
@Singleton
fun provideCelebrityDetailsRepo(apiService: CelebrityDetailsService): CelebrityDetailsRepository =
CelebrityDetailsRepositoryImpl(apiService)
} |
from manim import *
PYTHON_CODE = \
'''
def dijkstra(s):
distance[s] = 0
q = PriorityQueue(V)
q.put_nowait(s)
while q.qsize()!=0:
v = q.get_nowait()
visited[v] = True
for u in range(V):
if graph[v][u] == math.inf or visited[u]:
continue
else:
q.put_nowait(u)
if distance[u] > distance[v] + graph[v][u]:
distance[u] = distance[v] + graph[v][u]
'''
class Dijkstra(Scene):
def construct(self):
self.video_start()
self.menu()
self.intro()
self.dijkstra()
self.source_code()
self.reference()
self.video_end()
def video_start(self):
title = Text(
'Dijkstra\'s Algorithm',
gradient = [BLUE, GREEN]
).scale(1.5)
title.to_corner((ORIGIN + 4 * UP))
subtitle = Text('CS201 Discrete Mathematics: Final project')
subtitle.next_to(title, DOWN, buff=0.75)
author = Text(
'Liu Leqi'
).scale(0.75)
author.next_to(subtitle, DOWN, buff=1.5)
self.play(
Write(title)
)
self.play(
Write(subtitle),
Write(author)
)
self.wait()
self.play(
FadeOut(title),
FadeOut(subtitle),
FadeOut(author),
run_time=0.5
)
def menu(self):
topics = VGroup(
Text('Introduction to the problem'),
Text('Dijkstra\'s Algorithm'),
Text('Source code'),
Text('Reference')
)
for topic in topics:
dot = Dot(color=BLUE)
dot.next_to(topic, LEFT)
topic.add(dot)
topics.arrange(
DOWN, aligned_edge=LEFT, buff=LARGE_BUFF
).move_to(LEFT)
self.add(topics)
self.wait(2)
length_of_topics = len(topics)
for i in range(length_of_topics):
self.play(
FadeOut(topics[length_of_topics-i-1])
)
# for i in range(len(topics)):
# self.play(
# topics[i + 1:].set_fill, {"opacity": 0.25},
# topics[:i].set_fill, {"opacity": 0.25},
# topics[i].set_fill, {"opacity": 1}
# )
# self.wait(2)
vertices = ['a','b','c','d','e']
edges = [('b','c'),('a','b'),('d','e'),('d','b'),('d','c'),('c','e'),('a','d'),('e','a')]
def intro(self):
title = Title("Introduction to the problem").set_color(BLUE)
self.play(Create(title))
self.wait(2)
problem = Text(
'Given a directed graph with weight, \n find a shortest path from source vertex to any other vertex',
line_spacing=0.6
).scale(0.5).move_to((ORIGIN+UL*2))
self.play(Write(problem))
self.wait()
graph = Graph(
self.vertices, self.edges,
labels=True, edge_type=Arrow,
edge_config={
'stroke_width':3.5,
('b','c'):{'color':WHITE},
('a','b'):{'color':BLUE},
('d','e'):{'color':BLUE},
('d','b'):{'color':YELLOW},
('d','c'):{'color':YELLOW},
('c','e'):{'color':GREEN},
('a','d'):{'color':RED},
('e','a'):{'color':RED}
}
).move_to((ORIGIN+DOWN*1.5))
self.play(Create(graph))
question = Text(
'How can we do that?'
).scale(0.5).move_to((ORIGIN+DL*3))
self.play(
FadeOut(title),
problem.animate.to_corner(UL),
graph.animate.change_layout('circular'),
Write(question)
)
self.wait()
self.play(
FadeOut(question),
FadeOut(graph),
FadeOut(problem)
)
def dijkstra(self):
title = Title("Dijkstra\'s Algorithm").set_color(BLUE)
self.play(Create(title))
self.wait(2)
# describe the algorithm roughly
describe = Text(
'As the graph shown on the right, we use (color, weight): \n(WHITE, 1), (BLUE, 2), (YELLOW, 3), (GREEN, 4), (RED, 5)',
line_spacing=0.6
).scale(0.5).move_to((ORIGIN+UL*2))
self.play(Write(describe))
self.wait()
graph = Graph(
self.vertices, self.edges,
labels=True, edge_type=Arrow,
layout='circular',
edge_config={
'stroke_width':3,
('b','c'):{'color':WHITE},
('a','b'):{'color':BLUE},
('d','e'):{'color':BLUE},
('d','b'):{'color':YELLOW},
('d','c'):{'color':YELLOW},
('c','e'):{'color':GREEN},
('a','d'):{'color':RED},
('e','a'):{'color':RED}
}
).move_to((ORIGIN+RIGHT*4+DOWN))
d1 = Text(
'Dijkstra\'s algorithm is a kind of greedy algorithm.'
).scale(0.5).move_to((ORIGIN+UL*2))
d2 = Text(
'It starts from source vertex and vertex set S.'
).scale(0.5).move_to((ORIGIN+UL*2))
d3 = Text(
'Every iteration it extracts a vertex that has \na shortest path to the source.',
line_spacing=0.5
).scale(0.5).move_to((ORIGIN+UL*2))
d4 = Text(
'However, it needs the weights to be positive.'
).scale(0.5).move_to((ORIGIN+UL*2))
algorithm_describe = VGroup(d1,d2,d3,d4).arrange(
DOWN, aligned_edge=LEFT, buff=SMALL_BUFF
).move_to(LEFT*3)
self.play(
Create(graph),
Write(algorithm_describe),
run_time=2.5
)
self.wait(2)
# start the algorithm
weight_describe = Text(
'Source is vertex a. \n(WHITE, 1), (BLUE, 2), (YELLOW, 3), (GREEN, 4), (RED, 5)',
line_spacing=0.6
).scale(0.5).to_corner(UL)
t = [
['a','0','null'],
['b','infty','null'],
['c','infty','null'],
['d','infty','null'],
['e','infty','null']
]
table1 = Table(
table=t,
col_labels=[Text('vertex v'), Text('distance(v)'), Text('parent(v)')]
).scale(0.5).move_to((ORIGIN+RIGHT*4))
self.play(
FadeOut(title),
FadeOut(algorithm_describe),
Transform(describe, weight_describe),
graph.animate.move_to((ORIGIN+LEFT*4)),
table1.create()
)
self.wait(2)
# iteration 1
s11 = Text('Start from source vertex a').scale(0.5).move_to((ORIGIN+DOWN*3))
s12 = Text('Relax the out-going edges of a').scale(0.5).move_to((ORIGIN+DOWN*3))
t[1][1], t[3][1] = '2', '5'
t[1][2], t[3][2] = 'a', 'a'
table2 = Table(
table=t,
col_labels=[Text('vertex v'), Text('distance(v)'), Text('parent(v)')]
).scale(0.5).move_to((ORIGIN+RIGHT*4))
table2.add_highlighted_cell((2,1),color=GREEN)
self.play(
Write(s11),
table1.animate.add_highlighted_cell((2,1),color=GREEN)
)
self.wait(2)
self.play(
ReplacementTransform(s11,s12),
ReplacementTransform(table1, table2)
)
self.wait(2)
# iteration 2
s21 = Text('Turn to vertex b').scale(0.5).move_to((ORIGIN+DOWN*3))
s22 = Text('Relax the out-going edges of b').scale(0.5).move_to((ORIGIN+DOWN*3))
t[2][1], t[2][2] = '3', 'b'
table1 = Table(
table=t,
col_labels=[Text('vertex v'), Text('distance(v)'), Text('parent(v)')]
).scale(0.5).move_to((ORIGIN+RIGHT*4))
table1.add_highlighted_cell((2,1),color=GREEN)
table1.add_highlighted_cell((3,1),color=GREEN)
self.play(
ReplacementTransform(s12,s21),
table2.animate.add_highlighted_cell((3,1),color=GREEN)
)
self.wait(2)
self.play(
ReplacementTransform(s21,s22),
ReplacementTransform(table2, table1)
)
self.wait(2)
# iteration 3
s31 = Text('Turn to vertex c').scale(0.5).move_to((ORIGIN+DOWN*3))
s32 = Text('Relax the out-going edges of c').scale(0.5).move_to((ORIGIN+DOWN*3))
t[4][1], t[4][2] = '7', 'c'
table2 = Table(
table=t,
col_labels=[Text('vertex v'), Text('distance(v)'), Text('parent(v)')]
).scale(0.5).move_to((ORIGIN+RIGHT*4))
table2.add_highlighted_cell((2,1),color=GREEN)
table2.add_highlighted_cell((3,1),color=GREEN)
table2.add_highlighted_cell((4,1),color=GREEN)
self.play(
ReplacementTransform(s22,s31),
table1.animate.add_highlighted_cell((4,1),color=GREEN)
)
self.wait(2)
self.play(
ReplacementTransform(s31,s32),
ReplacementTransform(table1, table2)
)
self.wait(2)
# iteration 4
s41 = Text('Turn to vertex d').scale(0.5).move_to((ORIGIN+DOWN*3))
s42 = Text('Relax the out-going edges of d. Here no need to relax.').scale(0.5).move_to((ORIGIN+DOWN*3))
self.play(
ReplacementTransform(s32,s41),
table2.animate.add_highlighted_cell((5,1),color=GREEN)
)
self.wait(2)
self.play(
ReplacementTransform(s41,s42)
)
self.wait(2)
# iteration 5
s51 = Text('Turn to vertex e').scale(0.5).move_to((ORIGIN+DOWN*3))
s52 = Text('Relax the out-going edges of e. Here no need to relax.').scale(0.5).move_to((ORIGIN+DOWN*3))
self.play(
ReplacementTransform(s42,s51)
)
self.wait(2)
self.play(
ReplacementTransform(s51,s52)
)
self.wait(3)
self.clear()
def source_code(self):
title = Title("Source code").set_color(BLUE)
self.play(Create(title))
self.wait(2)
code_kwargs = {
"code" : PYTHON_CODE,
"tab_width" : 4,
"background" : "window",
"language" : "Python",
"font" : "Monospace",
"font_size" : 20,
"style" : "monokai"
}
code = Code(**code_kwargs)
code.move_to(ORIGIN)
self.draw_code_all_lines_at_a_time(code,run_time=3)
self.wait()
self.play(
FadeOut(title, shift=UP),
code.animate.to_edge(UP, buff=0).scale(0.8)
)
self.wait()
frame = Rectangle(
width=config["frame_width"]*0.8,
height=config["frame_height"]*0.4,
)
frame.next_to(code,DOWN)
FRAME_SCALE = 0.45
FRAME_CENTER = frame.get_center()
# ShowCreation -> Create
line = self.get_remark_rectangle(code, 1)
# def dijkstra(s):
line.save_state()
line.stretch(0.01,0) # set_width(0.01,0) 0 is x direction
# line.set_fill(opacity=0)
self.add(line)
self.play(Restore(line))
self.wait()
self.play(Create(frame))
graph = Graph(
self.vertices, self.edges,
labels=True, edge_type=Arrow,
layout='circular',
edge_config={
'stroke_width':3,
('b','c'):{'color':WHITE},
('a','b'):{'color':BLUE},
('d','e'):{'color':BLUE},
('d','b'):{'color':YELLOW},
('d','c'):{'color':YELLOW},
('c','e'):{'color':GREEN},
('a','d'):{'color':RED},
('e','a'):{'color':RED}
}
).scale(FRAME_SCALE).move_to((FRAME_CENTER+LEFT*3.5))
self.play(Create(graph))
self.wait(0.5)
matrix = Matrix(
[
[0,2,0,5,0],
[0,0,1,0,0],
[0,0,0,0,4],
[0,3,3,0,2],
[5,0,0,0,0]
]
).scale(FRAME_SCALE).move_to((FRAME_CENTER+LEFT*3.5))
entries = matrix.get_entries()
self.play(
FadeOut(graph),
FadeIn(matrix)
)
# distance[s] = 0
self.change_line(code, line, 2)
t = [
['a','b','c','d','e'],
['0','inf','inf','inf','inf']
]
table1 = Table(
table=t,
row_labels=[Text('vertex v'), Text('distance(v)')]
).scale(0.35).move_to((FRAME_CENTER+RIGHT*2.5+UP))
self.play(table1.create())
# q = PriorityQueue(V)
self.change_line(code, line, 3)
# q.put_nowait(s)
self.change_line(code, line, 4)
rectangle1 = Rectangle().scale(FRAME_SCALE*0.75).move_to(frame, aligned_edge=DOWN)
bg_rec1 = BackgroundRectangle(rectangle1, color=YELLOW, stroke_width=1)
rec_label1 = Text('a').scale(0.5).next_to(bg_rec1, ORIGIN)
queue_element1 = VGroup(bg_rec1, rec_label1)
self.play(FadeIn(queue_element1, shift=DOWN))
# while q.qsize()!=0:
self.change_line(code, line, 5)
# v = q.get_nowait()
self.change_line(code, line, 6)
circle = Circle().scale(0.2).next_to(queue_element1, RIGHT)
circ_label = Text('a').scale(0.5).next_to(circle, ORIGIN)
vertex_element = VGroup(circle, circ_label)
self.play(ReplacementTransform(queue_element1, vertex_element))
# visited[v] = True
self.change_line(code, line, 7)
# for u in range(V):
self.change_line(code, line, 8)
# if graph[v][u] == math.inf or visited[u]:
# continue
# else:
# q.put_nowait(u)
self.change_line(code, line, 9) # if graph[v][u] == math.inf or visited[u]:
self.play(matrix.animate.add(SurroundingRectangle(entries[0])))
self.change_line(code, line, 10) # continue
self.change_line(code, line, 8) # for u in range(V):
self.change_line(code, line, 9) # if graph[v][u] == math.inf or visited[u]:
self.play(matrix.animate.add(SurroundingRectangle(entries[1])))
self.change_line(code, line, 11) # else:
self.change_line(code, line, 12) # q.put_nowait(u)
rectangle1 = Rectangle().scale(FRAME_SCALE*0.75).move_to(frame, aligned_edge=DOWN)
bg_rec1 = BackgroundRectangle(rectangle1, color=YELLOW, stroke_width=1)
rec_label1 = Text('b').scale(0.5).next_to(bg_rec1, ORIGIN)
queue_element1 = VGroup(bg_rec1, rec_label1)
self.play(FadeIn(queue_element1, shift=DOWN))
# if distance[u] > distance[v] + graph[v][u]:
# distance[u] = distance[v] + graph[v][u]
self.change_line(code, line, 13)
self.change_line(code, line, 14)
t[1][1] = '2'
table2 = Table(
table=t,
row_labels=[Text('vertex v'), Text('distance(v)')]
).scale(0.35).move_to((FRAME_CENTER+RIGHT*2.5+UP))
self.play(ReplacementTransform(table1, table2))
# for u in range(V):
self.change_line(code, line, 8)
# if graph[v][u] == math.inf or visited[u]:
# continue
# else:
# q.put_nowait(u)
self.change_line(code, line, 9) # if graph[v][u] == math.inf or visited[u]:
self.play(matrix.animate.add(SurroundingRectangle(entries[2])))
self.change_line(code, line, 10) # continue
self.change_line(code, line, 8) # for u in range(V):
self.change_line(code, line, 9) # if graph[v][u] == math.inf or visited[u]:
self.play(matrix.animate.add(SurroundingRectangle(entries[3])))
self.change_line(code, line, 11) # else:
self.change_line(code, line, 12) # q.put_nowait(u)
rectangle2 = Rectangle().scale(FRAME_SCALE*0.75).next_to(rectangle1, UP, buff=0)
bg_rec2 = BackgroundRectangle(rectangle2, color=ORANGE, stroke_width=1)
rec_label2 = Text('d').scale(0.5).next_to(bg_rec2, ORIGIN)
queue_element2 = VGroup(bg_rec2, rec_label2)
self.play(FadeIn(queue_element2, shift=DOWN))
# if distance[u] > distance[v] + graph[v][u]:
# distance[u] = distance[v] + graph[v][u]
self.change_line(code, line, 13)
self.change_line(code, line, 14)
t[1][3] = '5'
table1 = Table(
table=t,
row_labels=[Text('vertex v'), Text('distance(v)')]
).scale(0.35).move_to((FRAME_CENTER+RIGHT*2.5+UP))
self.play(ReplacementTransform(table2, table1))
# for u in range(V):
self.change_line(code, line, 8)
self.play(matrix.animate.add(SurroundingRectangle(entries[4])))
self.play(FadeOut(vertex_element))
# while q.qsize()!=0:
self.change_line(code, line, 5)
notice = Text(
'For short, \nwe omit the \nremaining steps.',
line_spacing=0.6
).scale(0.5).to_corner(UL)
self.play(Write(notice))
for i in range(len(entries)):
if i <= 4:
continue
if i == 5:
self.play(FadeOut(vertex_element))
circle = Circle().scale(0.2).next_to(rectangle1, RIGHT)
circ_label = Text('b').scale(0.5).next_to(circle, ORIGIN)
vertex_element = VGroup(circle, circ_label)
self.play(
ReplacementTransform(queue_element1, vertex_element),
queue_element2.animate.move_to(frame, aligned_edge=DOWN)
)
if i == 10:
self.play(FadeOut(vertex_element))
circle = Circle().scale(0.2).next_to(rectangle1, RIGHT)
circ_label = Text('c').scale(0.5).next_to(circle, ORIGIN)
vertex_element = VGroup(circle, circ_label)
self.play(
ReplacementTransform(queue_element1, vertex_element)
)
if i == 15:
self.play(FadeOut(vertex_element))
circle = Circle().scale(0.2).next_to(rectangle1, RIGHT)
circ_label = Text('d').scale(0.5).next_to(circle, ORIGIN)
vertex_element = VGroup(circle, circ_label)
self.play(
ReplacementTransform(queue_element2, vertex_element),
queue_element1.animate.move_to(frame, aligned_edge=DOWN)
)
if i == 20:
self.play(FadeOut(vertex_element))
circle = Circle().scale(0.2).next_to(rectangle1, RIGHT)
circ_label = Text('e').scale(0.5).next_to(circle, ORIGIN)
vertex_element = VGroup(circle, circ_label)
self.play(
ReplacementTransform(queue_element1, vertex_element)
)
self.play(matrix.animate.add(SurroundingRectangle(entries[i])))
if i == 7:
rectangle1 = Rectangle().scale(FRAME_SCALE*0.75).next_to(queue_element2, UP, buff=0)
bg_rec1 = BackgroundRectangle(rectangle1, color=YELLOW, stroke_width=1)
rec_label1 = Text('c').scale(0.5).next_to(bg_rec1, ORIGIN)
queue_element1 = VGroup(bg_rec1, rec_label1)
self.play(FadeIn(queue_element1, shift=DOWN))
t[1][2] = '3'
table2 = Table(
table=t,
row_labels=[Text('vertex v'), Text('distance(v)')]
).scale(0.35).move_to((FRAME_CENTER+RIGHT*2.5+UP))
self.play(ReplacementTransform(table1, table2))
if i == 14:
rectangle1 = Rectangle().scale(FRAME_SCALE*0.75).next_to(queue_element2, UP, buff=0)
bg_rec1 = BackgroundRectangle(rectangle1, color=YELLOW, stroke_width=1)
rec_label1 = Text('e').scale(0.5).next_to(bg_rec1, ORIGIN)
queue_element1 = VGroup(bg_rec1, rec_label1)
self.play(FadeIn(queue_element1, shift=DOWN))
t[1][4] = '7'
table1 = Table(
table=t,
row_labels=[Text('vertex v'), Text('distance(v)')]
).scale(0.35).move_to((FRAME_CENTER+RIGHT*2.5+UP))
self.play(ReplacementTransform(table2, table1))
self.wait(2)
self.clear()
def reference(self):
title = Title("Reference").set_color(BLUE)
text = Text("[1] Introduction to Algorithms (Second Edition)").scale(0.8).next_to(title, DOWN, buff=0.7).to_corner(LEFT)
self.play(
Create(title),
Write(text)
)
self.wait(2)
self.play(
FadeOut(title),
FadeOut(text)
)
def video_end(self):
text = Text('Thanks for watching.')
self.play(
Write(text)
)
self.wait(2)
def draw_code_all_lines_at_a_time(self, code, **kwargs):
self.play(LaggedStart(*[
Write(code[i])
for i in range(code.__len__())
]),
**kwargs
)
def get_remark_rectangle(
self,
code,
line,
fill_opacity=0.4,
stroke_width=0,
fill_color=YELLOW,
**kwargs):
lines = VGroup(code[2],code[1])
w, h = getattr(lines, "width"), getattr(lines, "height")
frame = Rectangle(width=w,height=h)
code_line = code[1][line-1]
line_rectangle = Rectangle(
width=w,
height=getattr(code[1][line-1],"height")*1.5,
fill_opacity=fill_opacity,
stroke_width=stroke_width,
fill_color=fill_color,
**kwargs
)
line_rectangle.set_y(code_line.get_y())
line_rectangle.scale([1.1,1,1])
return line_rectangle
def change_line(self, code, rect, next_line, *args, **kwargs):
self.play(
Transform(
rect,
self.get_remark_rectangle(code, next_line),
),
*args,
**kwargs,
) |
use super::{file_command::FilePlaceholder, SlashCommand, SlashCommandOutput};
use anyhow::{anyhow, Result};
use assistant_slash_command::SlashCommandOutputSection;
use collections::HashMap;
use editor::Editor;
use gpui::{AppContext, Entity, Task, WeakView};
use language::LspAdapterDelegate;
use std::{fmt::Write, path::Path, sync::Arc};
use ui::{IntoElement, WindowContext};
use workspace::Workspace;
pub(crate) struct TabsSlashCommand;
impl SlashCommand for TabsSlashCommand {
fn name(&self) -> String {
"tabs".into()
}
fn description(&self) -> String {
"insert open tabs".into()
}
fn menu_text(&self) -> String {
"Insert Open Tabs".into()
}
fn requires_argument(&self) -> bool {
false
}
fn complete_argument(
&self,
_query: String,
_cancel: Arc<std::sync::atomic::AtomicBool>,
_workspace: Option<WeakView<Workspace>>,
_cx: &mut AppContext,
) -> Task<Result<Vec<String>>> {
Task::ready(Err(anyhow!("this command does not require argument")))
}
fn run(
self: Arc<Self>,
_argument: Option<&str>,
workspace: WeakView<Workspace>,
_delegate: Arc<dyn LspAdapterDelegate>,
cx: &mut WindowContext,
) -> Task<Result<SlashCommandOutput>> {
let open_buffers = workspace.update(cx, |workspace, cx| {
let mut timestamps_by_entity_id = HashMap::default();
let mut open_buffers = Vec::new();
for pane in workspace.panes() {
let pane = pane.read(cx);
for entry in pane.activation_history() {
timestamps_by_entity_id.insert(entry.entity_id, entry.timestamp);
}
}
for editor in workspace.items_of_type::<Editor>(cx) {
if let Some(buffer) = editor.read(cx).buffer().read(cx).as_singleton() {
if let Some(timestamp) = timestamps_by_entity_id.get(&editor.entity_id()) {
let snapshot = buffer.read(cx).snapshot();
let full_path = snapshot.resolve_file_path(cx, true);
open_buffers.push((full_path, snapshot, *timestamp));
}
}
}
open_buffers
});
match open_buffers {
Ok(mut open_buffers) => cx.background_executor().spawn(async move {
open_buffers.sort_by_key(|(_, _, timestamp)| *timestamp);
let mut sections = Vec::new();
let mut text = String::new();
for (full_path, buffer, _) in open_buffers {
let section_start_ix = text.len();
writeln!(
text,
"```{}\n",
full_path
.as_deref()
.unwrap_or(Path::new("untitled"))
.display()
)
.unwrap();
for chunk in buffer.as_rope().chunks() {
text.push_str(chunk);
}
if !text.ends_with('\n') {
text.push('\n');
}
writeln!(text, "```\n").unwrap();
let section_end_ix = text.len() - 1;
sections.push(SlashCommandOutputSection {
range: section_start_ix..section_end_ix,
render_placeholder: Arc::new(move |id, unfold, _| {
FilePlaceholder {
id,
path: full_path.clone(),
line_range: None,
unfold,
}
.into_any_element()
}),
});
}
Ok(SlashCommandOutput {
text,
sections,
run_commands_in_text: false,
})
}),
Err(error) => Task::ready(Err(error)),
}
}
} |
rm(list = ls())
library(tidyverse)
library(readxl)
library(kewr)
library(furrr)
# Research Qs this R script will answer:
# What percentage of oligolectic bees visit non-host plants (where visit == at least 5 visits)
# How often are oligolectic bees observed visiting non-host plants?
# load formatted MS data with list of specialist bees and their hosts
ms = read_csv('modeling_data/MS_data_simplified.csv') %>%
filter(diet_breadth != "Polylectic")
# load globi data
globi = read_csv("modeling_data/globi_names_updated.csv") %>%
filter(scientificName %in% ms$scientificName) %>%
mutate(plant_genus = ifelse(plant_genus == "Ipomaea","Ipomoea",plant_genus))
#load discrepancies data
discrepancies = read_csv('modeling_data/discrepancies_fowler_ms.csv')
only_ms_specialist = discrepancies %>% filter(`This ms` =='specialist' & Fowler =="not on list")
# update the family names of the globi data so it's consistent with how i named families for the ms data
get_fams = unique(globi$plant_genus) %>% future_map(function(sciname){
output = search_wcvp(sciname, filters=c("families", "accepted"),limit = 1)
output_df = tidy(output)
if(nrow(output_df) !=0){
return_df = data.frame(genus = sciname,family = output_df$family)
}
else{
output = search_wcvp(sciname, filters=c("families"),limit = 1)
df=tidy(output)
if(nrow(df) !=0){
new_output_df = df$synonymOf[[1]]
return_df = data.frame(genus = sciname,family = new_output_df$family)
}else{
return_df = data.frame(genus=sciname,family = NA)
}
}
}) %>% bind_rows
still_need_fams = get_fams %>% filter(is.na(family))
add_fam_info = data.frame(genus = c('Heliantheae'),
family = c('Asteraceae'))
get_fams_final = get_fams %>%
filter(!is.na(family)) %>% filter(genus %in% add_fam_info$genus==F) %>%
bind_rows(add_fam_info)
(bees_bigN = globi %>% group_by(scientificName) %>% summarize(n=sum(n)) %>% filter(n>20))
globi_u=globi %>%
left_join(get_fams_final %>%
rename(plant_genus = genus, wcvp_family=family)) %>%
filter(n>5 & scientificName %in% bees_bigN$scientificName) #let's exclude interactions less than or equal to five and bees with les than or equal to 20 records total
# for the globi data: categorize interaction partner as host or non-host
# loop through the bee speices in globi_u
# get their host plants
# if the interaciton partner is in the family or genus then categorize it as a host
a = globi_u %>% split(1:nrow(globi_u))
row = a[[1]]
empty_list = c()
globi_host = globi_u %>% split(1:nrow(globi_u)) %>% purrr::map_dfr(function(row){
host_plant_df = ms %>% filter(scientificName == row$scientificName[1])
if(unique(host_plant_df$rank =='genus')) visiting_host = row$plant_genus %in% host_plant_df$host
if(unique(host_plant_df$rank =='family')) visiting_host = row$wcvp_family %in% host_plant_df$host
return(row %>% mutate(host=visiting_host))
}) %>%
mutate(only_ms = scientificName %in% only_ms_specialist$scientificName)
check_these = which(ms %>% split(.$scientificName) %>% map_lgl(function(df) nrow(df)>1))
#what percentage of oligolects visit non-host plants?
nonhost_visits=globi_host %>% group_by(scientificName,only_ms) %>% summarize(visiting_nonhost = F %in% host)
mean(nonhost_visits$visiting_nonhost)
nonhost_visits %>% group_by(only_ms) %>% summarize(mean(visiting_nonhost))
#how [frequently] do they visit non-host plants
head(globi_host)
prop_nonhost=globi_host %>% group_by(scientificName,only_ms) %>%
summarize(prop_nonhost_visits=sum(n[!host])/sum(n),total_n=sum(n))
with(prop_nonhost,hist(prop_nonhost_visits))
with(prop_nonhost,plot(prop_nonhost_visits~total_n))
with(prop_nonhost,boxplot(prop_nonhost_visits~only_ms))
# format the box-plot graph:
# pdf('figures/compare_fowler_ms.pdf')
with(prop_nonhost %>% mutate(on_fowler = factor(!only_ms,levels = c(T,F))),
boxplot(prop_nonhost_visits~on_fowler, ylab = 'proportion of bees visiting non-hosts',
xlab = 'On Fowler list'))
# dev.off()
# is there a difference between bees on fowler list vs MS list?
only_ms_specialist$scientificName
## old:
# note: for fowler df, bees on this list are duplicated if they occur in multiple regions (eg both east and central america)
fowler <- read_csv("modeling_data/fowler_hostplants.csv")
globi <- read_csv('modeling_data/globi_names_updated.csv')
# we want to reformat the fowler data so that there's only one row for each bee species
# and so that the host plants are in a consistent format
fowler %>% filter(host_plant == "Pontederia L., Fabaceae?")
host_plants = unique(fowler$host_plant)
fam_hosts = host_plants[grepl(":",host_plants)]
sub(":.*","",fam_hosts)
which(sub(":.*","",fam_hosts)=="Lyonia Nutt., Vaccinium L.")
gen_hosts=host_plants[!grepl(":",host_plants)]
gen_hosts[grepl('aceae' , gen_hosts)]
fam_hosts[51]
head(fowler)
fowler %>% split(.$host_plant)
authorities = c() |
package com.soberg.netinfo.android.ui.screen.state
import androidx.compose.runtime.Immutable
import com.soberg.netinfo.android.ui.screen.state.NetworkInfoViewState.Ready.Lan.ConnectionType.NoConnection
@Immutable
sealed interface NetworkInfoViewState {
data object Loading : NetworkInfoViewState
data object NoConnectionsFound : NetworkInfoViewState
data class Ready(
val lan: Lan,
val wan: Wan,
) : NetworkInfoViewState {
@Immutable
sealed interface Lan {
val type: ConnectionType
data object Unknown : Lan {
override val type: ConnectionType = NoConnection
}
data class Connected(
val ipAddress: String,
override val type: ConnectionType,
) : Lan
enum class ConnectionType {
NoConnection,
Cellular,
Ethernet,
Wifi,
}
}
@Immutable
sealed interface Wan {
data object CannotConnect : Wan
data class Connected(
val ipAddress: String,
val locationText: String?,
) : Wan
}
}
} |
# NashvilleHousing-SQL-Data-Cleaning
## Overview
This project focuses on cleaning and preprocessing Nashville housing data sourced from Kaggle using SQL queries. The dataset contains information on property sales, prices, locations, and property characteristics. The objective is to clean the dataset to ensure accuracy and consistency for further analysis.
## Tasks
### 1. Standardize Date Format
- Identify date columns in the dataset.
- Use SQL queries to standardize the date format to ensure consistency across records.
### 2. Populate Property Address Data
- Identify records with missing property address data.
- Use available information (e.g., parcel number, location details) to populate missing property addresses where possible.
### 3. Break Out Address into Individual Columns
- Split the address field into separate columns for address, city, and state.
- Use SQL queries to extract and separate address components for improved analysis and visualization.
### 4. Change "Y" and "N" to "Yes" and "No" in "Sold as Vacant" Field
- Identify records where the "Sold as Vacant" field contains "Y" or "N".
- Use SQL queries to replace "Y" with "Yes" and "N" with "No" for clarity and consistency.
### 5. Remove Duplicates
- Identify duplicate records in the dataset based on unique identifiers.
- Use SQL queries to remove duplicate records while preserving essential data.
### 6. Delete Unused Columns
- Identify columns in the dataset that are not required for analysis.
- Use SQL queries to delete unused columns to streamline the dataset and improve efficiency.
## Usage
1. **Setup Database**: Ensure the Nashville housing dataset sourced from Kaggle is imported into your SQL database.
2. **Execute SQL Queries**: Run SQL queries provided for each cleaning task to clean and preprocess the data.
3. **Verify Results**: Review the cleaned dataset to ensure data quality and consistency.
## Contributing
Contributions to improve data cleaning processes or address specific issues in the dataset are welcome! Please fork the repository, make your changes, and submit a pull request.
## Data Source
The Nashville housing dataset is sourced from Kaggle. [NashvilleHousing Data Set](https://github.com/SiriSrinivas6/NashvilleHousing-SQL-Data-Cleaning/blob/fd52a057199bf41cc54358e6dda409292ef00dea/Nashville%20Housing%20Data%20for%20Data%20Cleaning.xlsx). |
import React, { useContext, useState } from 'react'
import ReactDOM from 'react-dom'
import CurrentConditions from './components/CurrentConditions'
import Forecasts from './components/Forecasts'
import Highlights from './components/Highlights'
import Navigation from './components/Navigation'
import { currentData } from './store/CurrentPosition'
import './sass/index.scss'
import Modal from './components/Modal'
export default function App() {
const ctx = useContext(currentData)
const [showNav, setShowNav] = useState(false)
function handleShowNav() {
setShowNav(prevVal => !prevVal)
}
document.body.style.overflowY = ctx.showModal ? 'hidden' : 'unset'
document.querySelector('html').style.overflowY = ctx.showModal
? 'hidden'
: 'unset'
return (
<main>
{showNav ? (
<Navigation handleShowNav={handleShowNav} showNav={showNav} />
) : (
<CurrentConditions
showNav={showNav}
handleShowNav={handleShowNav}
weatherCondition={ctx.weatherData.weatherInfo}
location={ctx.loc}
/>
)}
<section className="section--2">
<Forecasts />
<Highlights />
{ctx.showModal && (
<Modal eventlisteners={[null, ctx.reRender]} show={false}>
{ctx.errorMessage || 'Please enable location to use this app'}
</Modal>
)}
</section>
</main>
)
} |
// Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
// or more contributor license agreements. Licensed under the Elastic License;
// you may not use this file except in compliance with the Elastic License.
package management
import (
"context"
"errors"
"fmt"
"os"
"os/signal"
"sync"
"syscall"
"time"
"github.com/joeshaw/multierror"
"go.uber.org/zap/zapcore"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials/insecure"
gproto "google.golang.org/protobuf/proto"
"gopkg.in/yaml.v2"
"github.com/elastic/beats/v7/libbeat/cfgfile"
"github.com/elastic/beats/v7/libbeat/common"
"github.com/elastic/beats/v7/libbeat/common/reload"
"github.com/elastic/beats/v7/libbeat/features"
lbmanagement "github.com/elastic/beats/v7/libbeat/management"
"github.com/elastic/beats/v7/libbeat/management/status"
"github.com/elastic/beats/v7/libbeat/version"
"github.com/elastic/elastic-agent-client/v7/pkg/client"
"github.com/elastic/elastic-agent-client/v7/pkg/proto"
conf "github.com/elastic/elastic-agent-libs/config"
"github.com/elastic/elastic-agent-libs/logp"
)
// diagnosticHandler is a wrapper type that's a bit of a hack, the compiler won't let us send the raw unit struct,
// since there's a type disagreement with the `client.DiagnosticHook` argument, and due to licensing issues we can't import the agent client types into the reloader
type diagnosticHandler struct {
log *logp.Logger
client *agentUnit
}
func (handler diagnosticHandler) Register(name string, description string, filename string, contentType string, callback func() []byte) {
handler.log.Infof("registering callback with %s", name)
// paranoid checking
if handler.client != nil {
handler.client.RegisterDiagnosticHook(name, description, filename, contentType, callback)
} else {
handler.log.Warnf("client handler for diag callback %s is nil", name)
}
}
// unitKey is used to identify a unique unit in a map
// the `ID` of a unit in itself is not unique without its type, only `Type` + `ID` is unique
type unitKey struct {
Type client.UnitType
ID string
}
// BeatV2Manager is the main type for tracing V2-related config updates
type BeatV2Manager struct {
config *Config
registry *reload.Registry
client client.V2
logger *logp.Logger
// handles client errors
errCanceller context.CancelFunc
// track individual units given to us by the V2 API
mx sync.Mutex
units map[unitKey]*agentUnit
actions []client.Action
forceReload bool
// status is reported as a whole for every unit sent to this component
// hopefully this can be improved in the future to be separated per unit
status status.Status
message string
payload map[string]interface{}
// stop callback must be registered by libbeat, as with the V1 callback
stopFunc func()
stopOnOutputReload bool
stopOnEmptyUnits bool
stopMut sync.Mutex
beatStop sync.Once
// sync channel for shutting down the manager after we get a stop from
// either the agent or the beat
stopChan chan struct{}
isRunning bool
// set with the last applied output config
// allows tracking if the configuration actually changed and if the
// beat needs to restart if stopOnOutputReload is set
lastOutputCfg *proto.UnitExpectedConfig
// set with the last applied input configs
lastInputCfgs map[string]*proto.UnitExpectedConfig
// used for the debug callback to report as-running config
lastBeatOutputCfg *reload.ConfigWithMeta
lastBeatInputCfgs []*reload.ConfigWithMeta
lastBeatFeaturesCfg *conf.C
// changeDebounce is the debounce time for a configuration change
changeDebounce time.Duration
// forceReloadDebounce is the time the manager will wait before
// trying to reload the configuration after an input not finished error
// happens
forceReloadDebounce time.Duration
}
// Optionals
// WithStopOnEmptyUnits enables stopping the beat when agent sends no units.
func WithStopOnEmptyUnits(m *BeatV2Manager) {
m.stopOnEmptyUnits = true
}
// WithChangeDebounce sets the changeDeboung value
func WithChangeDebounce(d time.Duration) func(b *BeatV2Manager) {
return func(b *BeatV2Manager) {
b.changeDebounce = d
}
}
// WithForceReloadDebounce sets the forceReloadDebounce value
func WithForceReloadDebounce(d time.Duration) func(b *BeatV2Manager) {
return func(b *BeatV2Manager) {
b.forceReloadDebounce = d
}
}
// Init Functions
// Register the agent manager, so that calls to lbmanagement.NewManager will
// invoke NewV2AgentManager when linked with x-pack.
func init() {
lbmanagement.SetManagerFactory(NewV2AgentManager)
}
// NewV2AgentManager returns a remote config manager for the agent V2 protocol.
// This is registered as the manager factory in init() so that calls to
// lbmanagement.NewManager will be forwarded here.
func NewV2AgentManager(config *conf.C, registry *reload.Registry) (lbmanagement.Manager, error) {
logger := logp.NewLogger(lbmanagement.DebugK).Named("V2-manager")
c := DefaultConfig()
if config.Enabled() {
if err := config.Unpack(&c); err != nil {
return nil, fmt.Errorf("parsing fleet management settings: %w", err)
}
}
versionInfo := client.VersionInfo{
Name: "beat-v2-client",
BuildHash: version.Commit(),
Meta: map[string]string{
"commit": version.Commit(),
"build_time": version.BuildTime().String(),
},
}
var agentClient client.V2
var err error
if c.InsecureGRPCURLForTesting != "" && c.Enabled {
// Insecure for testing Elastic-Agent-Client initialisation
logger.Info("Using INSECURE GRPC connection, this should be only used for testing!")
agentClient = client.NewV2(c.InsecureGRPCURLForTesting,
"", // Insecure connection for test, no token needed
versionInfo,
client.WithGRPCDialOptions(grpc.WithTransportCredentials(insecure.NewCredentials())))
} else {
// Normal Elastic-Agent-Client initialisation
agentClient, _, err = client.NewV2FromReader(os.Stdin, versionInfo)
if err != nil {
return nil, fmt.Errorf("error reading control config from agent: %w", err)
}
}
// officially running under the elastic-agent; we set the publisher pipeline
// to inform it that we are running under elastic-agent (used to ensure "Publish event: "
// debug log messages are only outputted when running in trace mode
lbmanagement.SetUnderAgent(true)
return NewV2AgentManagerWithClient(c, registry, agentClient)
}
// NewV2AgentManagerWithClient actually creates the manager instance used by the rest of the beats.
func NewV2AgentManagerWithClient(config *Config, registry *reload.Registry, agentClient client.V2, opts ...func(*BeatV2Manager)) (lbmanagement.Manager, error) {
log := logp.NewLogger(lbmanagement.DebugK)
if config.RestartOnOutputChange {
log.Infof("Output reload is enabled, the beat will restart as needed on change of output config")
}
m := &BeatV2Manager{
stopOnOutputReload: config.RestartOnOutputChange,
config: config,
logger: log.Named("V2-manager"),
registry: registry,
units: make(map[unitKey]*agentUnit),
status: status.Running,
message: "Healthy",
stopChan: make(chan struct{}, 1),
changeDebounce: time.Second,
// forceReloadDebounce is greater than changeDebounce because it is only
// used when an input has not reached its finished state, this means some events
// still need to be acked by the acker, hence the longer we wait the more likely
// for the input to have reached its finished state.
forceReloadDebounce: time.Second * 10,
}
if config.Enabled {
m.client = agentClient
}
for _, o := range opts {
o(m)
}
return m, nil
}
// Beats central management interface implementation
func (cm *BeatV2Manager) AgentInfo() client.AgentInfo {
if cm.client.AgentInfo() == nil {
return client.AgentInfo{}
}
return *cm.client.AgentInfo()
}
// RegisterDiagnosticHook will register a diagnostic callback function when elastic-agent asks for a diagnostics dump
func (cm *BeatV2Manager) RegisterDiagnosticHook(name string, description string, filename string, contentType string, hook client.DiagnosticHook) {
cm.client.RegisterDiagnosticHook(name, description, filename, contentType, hook)
}
// UpdateStatus updates the manager with the current status for the beat.
func (cm *BeatV2Manager) UpdateStatus(status status.Status, msg string) {
cm.mx.Lock()
defer cm.mx.Unlock()
cm.status = status
cm.message = msg
cm.updateStatuses()
}
// Enabled returns true if config management is enabled.
func (cm *BeatV2Manager) Enabled() bool {
return cm.config.Enabled
}
// SetStopCallback sets the callback to run when the manager want to shut down the beats gracefully.
func (cm *BeatV2Manager) SetStopCallback(stopFunc func()) {
cm.stopMut.Lock()
defer cm.stopMut.Unlock()
cm.stopFunc = stopFunc
}
// Start the config manager.
func (cm *BeatV2Manager) Start() error {
if !cm.Enabled() {
return fmt.Errorf("V2 Manager is disabled")
}
if cm.errCanceller != nil {
cm.errCanceller()
cm.errCanceller = nil
}
ctx := context.Background()
err := cm.client.Start(ctx)
if err != nil {
return fmt.Errorf("error starting connection to client")
}
ctx, canceller := context.WithCancel(ctx)
cm.errCanceller = canceller
go cm.watchErrChan(ctx)
cm.client.RegisterDiagnosticHook(
"beat-rendered-config",
"the rendered config used by the beat",
"beat-rendered-config.yml",
"application/yaml",
cm.handleDebugYaml)
go cm.unitListen()
cm.isRunning = true
return nil
}
// Stop stops the current Manager and close the connection to Elastic Agent.
func (cm *BeatV2Manager) Stop() {
cm.stopChan <- struct{}{}
}
// CheckRawConfig is currently not implemented for V1.
func (cm *BeatV2Manager) CheckRawConfig(_ *conf.C) error {
// This does not do anything on V1 or V2, but here we are
return nil
}
// RegisterAction adds a V2 client action
func (cm *BeatV2Manager) RegisterAction(action client.Action) {
cm.mx.Lock()
defer cm.mx.Unlock()
cm.actions = append(cm.actions, action)
for _, unit := range cm.units {
// actions are only registered on input units (not a requirement by Agent but
// don't see a need in beats to support actions on an output at the moment)
if clientUnit := unit; clientUnit != nil && clientUnit.Type() == client.UnitTypeInput {
clientUnit.RegisterAction(action)
}
}
}
// UnregisterAction removes a V2 client action
func (cm *BeatV2Manager) UnregisterAction(action client.Action) {
cm.mx.Lock()
defer cm.mx.Unlock()
// remove the registered action
i := func() int {
for i, a := range cm.actions {
if a.Name() == action.Name() {
return i
}
}
return -1
}()
if i == -1 {
// not registered
return
}
cm.actions = append(cm.actions[:i], cm.actions[i+1:]...)
for _, unit := range cm.units {
// actions are only registered on input units (not a requirement by Agent but
// don't see a need in beats to support actions on an output at the moment)
if clientUnit := unit; clientUnit != nil && clientUnit.Type() == client.UnitTypeInput {
clientUnit.UnregisterAction(action)
}
}
}
// SetPayload sets the global payload for the V2 client
func (cm *BeatV2Manager) SetPayload(payload map[string]interface{}) {
cm.mx.Lock()
defer cm.mx.Unlock()
cm.payload = payload
cm.updateStatuses()
}
// updateStatuses updates the status for all units to match the status of the entire manager.
//
// This is done because beats at the moment cannot fully manage different status per unit, something
// that is new in the V2 control protocol but not supported in beats itself.
//
// Errors while starting/reloading inputs are already reported by unit, but
// the shutdown process is still not being handled by unit.
func (cm *BeatV2Manager) updateStatuses() {
message := cm.message
payload := cm.payload
for _, unit := range cm.units {
expected := unit.Expected()
if expected.State == client.UnitStateStopped {
// unit is expected to be stopping (don't adjust the state as the state is now managed by the
// `reload` method and will be marked stopped in that code path)
continue
}
err := unit.UpdateState(cm.status, message, payload)
if err != nil {
cm.logger.Errorf("Failed to update unit %s status: %s", unit.ID(), err)
}
}
}
// Unit manager
func (cm *BeatV2Manager) upsertUnit(unit *client.Unit) {
cm.mx.Lock()
defer cm.mx.Unlock()
aUnit, ok := cm.units[unitKey{unit.Type(), unit.ID()}]
if ok {
aUnit.update(unit)
} else {
unitLogger := cm.logger.Named(fmt.Sprintf("state-unit-%s", unit.ID()))
aUnit = newAgentUnit(unit, unitLogger)
cm.units[unitKey{unit.Type(), unit.ID()}] = aUnit
}
// update specific unit to starting
_ = aUnit.UpdateState(status.Starting, "Starting", nil)
// register the already registered actions (only on input units)
for _, action := range cm.actions {
aUnit.RegisterAction(action)
}
}
func (cm *BeatV2Manager) updateUnit(unit *client.Unit) {
// `unit` is already in `cm.units` no need to add it to the map again
// but the lock still needs to be held so reload can be triggered
cm.mx.Lock()
defer cm.mx.Unlock()
// no need to update cm.units because the elastic-agent-client and the beats share
// the pointer to each unit, so when the client updates a unit on its side, it
// is reflected here. As this deals with modifications, they're already present.
// Only the state needs to be updated.
aUnit, ok := cm.units[unitKey{unit.Type(), unit.ID()}]
if !ok {
cm.logger.Infof("BeatV2Manager.updateUnit Unit %s not found", unit.ID())
return
}
aUnit.update(unit)
expected := unit.Expected()
if expected.State == client.UnitStateStopped {
// expected to be stopped; needs to stop this unit
_ = aUnit.UpdateState(status.Stopping, "Stopping", nil)
} else {
// update specific unit to configuring
_ = aUnit.UpdateState(status.Configuring, "Configuring", nil)
}
}
func (cm *BeatV2Manager) softDeleteUnit(unit *client.Unit) {
cm.mx.Lock()
defer cm.mx.Unlock()
key := unitKey{unit.Type(), unit.ID()}
if aUnit, ok := cm.units[key]; ok {
aUnit.markAsDeleted()
}
}
// Private V2 implementation
func (cm *BeatV2Manager) watchErrChan(ctx context.Context) {
for {
select {
case <-ctx.Done():
return
case err := <-cm.client.Errors():
// Don't print the context canceled errors that happen normally during shutdown, restart, etc
if !errors.Is(context.Canceled, err) {
cm.logger.Errorf("elastic-agent-client error: %s", err)
}
}
}
}
func (cm *BeatV2Manager) unitListen() {
// register signal handler
sigc := make(chan os.Signal, 1)
signal.Notify(sigc, syscall.SIGINT, syscall.SIGTERM, syscall.SIGHUP)
// timer is used to provide debounce on unit changes
// this allows multiple changes to come in and only a single reload be performed
t := time.NewTimer(cm.changeDebounce)
t.Stop() // starts stopped, until a change occurs
cm.logger.Debug("Listening for agent unit changes")
for {
select {
// The stopChan channel comes from the Manager interface Stop() method
case <-cm.stopChan:
cm.stopBeat()
case sig := <-sigc:
// we can't duplicate the same logic used by stopChan here.
// A beat will also watch for sigint and shut down, if we call the stopFunc
// callback, either the V2 client or the beat will get a panic,
// as the stopFunc sent by the beats is usually unsafe.
switch sig {
case syscall.SIGINT, syscall.SIGTERM:
cm.logger.Debug("Received sigterm/sigint, stopping")
case syscall.SIGHUP:
cm.logger.Debug("Received sighup, stopping")
}
cm.isRunning = false
cm.UpdateStatus(status.Stopping, "Stopping")
return
case change := <-cm.client.UnitChanges():
cm.logger.Infof(
"BeatV2Manager.unitListen UnitChanged.ID(%s), UnitChanged.Type(%s), UnitChanged.Trigger(%d): %s/%s",
change.Unit.ID(),
change.Type, int64(change.Triggers), change.Type, change.Triggers)
switch change.Type {
// Within the context of how we send config to beats, I'm not sure if there is a difference between
// A unit add and a unit change, since either way we can't do much more than call the reloader
case client.UnitChangedAdded:
cm.upsertUnit(change.Unit)
// reset can be called here because `<-t.C` is handled in the same select
t.Reset(cm.changeDebounce)
case client.UnitChangedModified:
cm.updateUnit(change.Unit)
// reset can be called here because `<-t.C` is handled in the same select
t.Reset(cm.changeDebounce)
case client.UnitChangedRemoved:
// necessary to soft-delete here and follow up with the actual deletion of units
// in `<-t.C` to avoid deleting a unit that will be re-created before `<-t.C`
// expires where the respective runners will not reload; actual deleting here
// can cause a runner to lose ref to a unit
cm.softDeleteUnit(change.Unit)
}
case <-t.C:
// a copy of the units is used for reload to prevent the holding of the `cm.mx`.
// it could be possible that sending the configuration to reload could cause the `UpdateStatus`
// to be called on the manager causing it to try and grab the `cm.mx` lock, causing a deadlock.
cm.mx.Lock()
units := make(map[unitKey]*agentUnit, len(cm.units))
for k, u := range cm.units {
if u.softDeleted {
delete(cm.units, k)
continue
}
units[k] = u
}
cm.mx.Unlock()
if len(cm.units) == 0 && cm.stopOnEmptyUnits {
cm.stopBeat()
}
cm.reload(units)
if cm.forceReload {
// Restart the debounce timer so we try to reload the inputs.
t.Reset(cm.forceReloadDebounce)
}
}
}
}
func (cm *BeatV2Manager) stopBeat() {
if !cm.isRunning {
return
}
cm.logger.Debugf("Stopping beat")
cm.UpdateStatus(status.Stopping, "Stopping")
cm.isRunning = false
cm.stopMut.Lock()
defer cm.stopMut.Unlock()
if cm.stopFunc != nil {
// I'm not 100% sure the once here is needed,
// but various beats tend to handle this in a not-quite-safe way
cm.beatStop.Do(cm.stopFunc)
}
cm.client.Stop()
cm.UpdateStatus(status.Stopped, "Stopped")
if cm.errCanceller != nil {
cm.errCanceller()
cm.errCanceller = nil
}
}
func (cm *BeatV2Manager) reload(units map[unitKey]*agentUnit) {
lowestLevel := client.UnitLogLevelError
var outputUnit *agentUnit
var inputUnits []*agentUnit
var stoppingUnits []*agentUnit
healthyInputs := map[string]*agentUnit{}
unitErrors := map[string][]error{}
// as the very last action, set the state of the failed units
defer func() {
for _, unit := range units {
errs := unitErrors[unit.ID()]
if len(errs) != 0 {
_ = unit.UpdateState(status.Failed, errors.Join(errs...).Error(), nil)
}
}
}()
for _, unit := range units {
expected := unit.Expected()
if expected.LogLevel > lowestLevel {
// log level is still used from an expected stopped unit until
// the unit is completely removed (aka. fully stopped)
lowestLevel = expected.LogLevel
}
if expected.Features != nil {
// unit is expected to update its feature flags
featuresCfg, err := features.NewConfigFromProto(expected.Features)
if err != nil {
unitErrors[unit.ID()] = append(unitErrors[unit.ID()], err)
}
if err := features.UpdateFromConfig(featuresCfg); err != nil {
unitErrors[unit.ID()] = append(unitErrors[unit.ID()], err)
}
cm.lastBeatFeaturesCfg = featuresCfg
}
if expected.State == client.UnitStateStopped {
// unit is being stopped
//
// we keep the unit so after reload is performed
// these units can be marked as stopped
stoppingUnits = append(stoppingUnits, unit)
continue
} else if expected.State != client.UnitStateHealthy {
// only stopped or healthy are known (and expected) state
// for a unit
cm.logger.Errorf("unit %s has an unknown state %+v",
unit.ID(), expected.State)
}
if unit.Type() == client.UnitTypeOutput {
outputUnit = unit
} else if unit.Type() == client.UnitTypeInput {
inputUnits = append(inputUnits, unit)
healthyInputs[unit.ID()] = unit
} else {
cm.logger.Errorf("unit %s as an unknown type %+v", unit.ID(), unit.Type())
}
}
// set the new log level (if nothing has changed is a noop)
ll, trace := getZapcoreLevel(lowestLevel)
logp.SetLevel(ll)
lbmanagement.SetUnderAgentTrace(trace)
// reload the output configuration
restartBeat, err := cm.reloadOutput(outputUnit)
// The manager has already signalled the Beat to stop,
// there is nothing else to do. Trying to reload inputs
// will only lead to invalid state updates and possible
// race conditions.
if restartBeat {
return
}
if err != nil {
// Output creation failed, there is no point in going any further
// because there is no output to read events.
//
// Trying to start inputs will eventually lead them to deadlock
// waiting for the output. Log input will deadlock when starting,
// effectively blocking this manager.
cm.logger.Errorw("could not start output", "error", err)
msg := fmt.Sprintf("could not start output: %s", err)
if err := outputUnit.UpdateState(status.Failed, msg, nil); err != nil {
cm.logger.Errorw("setting output state", "error", err)
}
return
}
if err := outputUnit.UpdateState(status.Running, "Healthy", nil); err != nil {
cm.logger.Errorw("setting output state", "error", err)
}
// compute the input configuration
//
// in v2 only a single input type will be started per component, so we don't need to
// worry about getting multiple re-loaders (we just need the one for the type)
if err := cm.reloadInputs(inputUnits); err != nil {
merror := &multierror.MultiError{}
if errors.As(err, &merror) {
for _, err := range merror.Errors {
unitErr := cfgfile.UnitError{}
if errors.As(err, &unitErr) {
unitErrors[unitErr.UnitID] = append(unitErrors[unitErr.UnitID], unitErr.Err)
delete(healthyInputs, unitErr.UnitID)
}
}
}
}
// report the stopping units as stopped
for _, unit := range stoppingUnits {
_ = unit.UpdateState(status.Stopped, "Stopped", nil)
}
// now update the statuses of all units that contain only healthy
// inputs. If there isn't an error with the inputs, we set the unit as
// healthy because there is no way to know more information about its inputs.
for _, unit := range healthyInputs {
expected := unit.Expected()
if expected.State == client.UnitStateStopped {
// unit is expected to be stopping (don't adjust the state as the state is now managed by the
// `reload` method and will be marked stopped in that code path)
continue
}
err := unit.UpdateState(status.Running, "Healthy", nil)
if err != nil {
cm.logger.Errorf("Failed to update unit %s status: %s", unit.ID(), err)
}
}
}
// reloadOutput reload outputs, it returns a bool and an error.
// The bool, if set, indicates that the output reload requires an restart,
// in that case the error is always `nil`.
//
// In any other case, the bool is always false and the error will be non nil
// if any error has occurred.
func (cm *BeatV2Manager) reloadOutput(unit *agentUnit) (bool, error) {
// Assuming that the output reloadable isn't a list, see createBeater() in cmd/instance/beat.go
output := cm.registry.GetReloadableOutput()
if output == nil {
return false, fmt.Errorf("failed to find beat reloadable type 'output'")
}
if unit == nil {
// output is being stopped
err := output.Reload(nil)
if err != nil {
return false, fmt.Errorf("failed to reload output: %w", err)
}
cm.lastOutputCfg = nil
cm.lastBeatOutputCfg = nil
return false, nil
}
expected := unit.Expected()
if expected.Config == nil {
// should not happen; hard stop
return false, fmt.Errorf("output unit has no config")
}
if cm.lastOutputCfg != nil && gproto.Equal(cm.lastOutputCfg, expected.Config) {
// configuration for the output did not change; do nothing
cm.logger.Debug("Skipped reloading output; configuration didn't change")
return false, nil
}
cm.logger.Debugf("Got output unit config '%s'", expected.Config.GetId())
if cm.stopOnOutputReload && cm.lastOutputCfg != nil {
cm.logger.Info("beat is restarting because output changed")
_ = unit.UpdateState(status.Stopping, "Restarting", nil)
cm.Stop()
return true, nil
}
reloadConfig, err := groupByOutputs(expected.Config)
if err != nil {
return false, fmt.Errorf("failed to generate config for output: %w", err)
}
// Set those variables regardless of the outcome of output.Reload
// this ensures that if we're on a failed output state and a new
// output configuration is sent, the Beat will gracefully exit
cm.lastOutputCfg = expected.Config
cm.lastBeatOutputCfg = reloadConfig
err = output.Reload(reloadConfig)
if err != nil {
return false, fmt.Errorf("failed to reload output: %w", err)
}
return false, nil
}
func (cm *BeatV2Manager) reloadInputs(inputUnits []*agentUnit) error {
obj := cm.registry.GetInputList()
if obj == nil {
return fmt.Errorf("failed to find beat reloadable type 'input'")
}
inputCfgs := make(map[string]*proto.UnitExpectedConfig, len(inputUnits))
inputBeatCfgs := make([]*reload.ConfigWithMeta, 0, len(inputUnits))
agentInfo := cm.client.AgentInfo()
for _, unit := range inputUnits {
expected := unit.Expected()
if expected.Config == nil {
// should not happen; hard stop
return fmt.Errorf("input unit %s has no config", unit.ID())
}
inputCfg, err := generateBeatConfig(expected.Config, agentInfo)
if err != nil {
return fmt.Errorf("failed to generate configuration for unit %s: %w", unit.ID(), err)
}
// add diag callbacks for unit
// we want to add the diagnostic handler that's specific to the unit, and not the gobal diagnostic handler
for idx, in := range inputCfg {
in.DiagCallback = diagnosticHandler{client: unit, log: cm.logger.Named("diagnostic-manager")}
in.InputUnitID = unit.ID()
in.StatusReporter = unit.GetReporterForStreamByIndex(idx)
}
inputCfgs[unit.ID()] = expected.Config
inputBeatCfgs = append(inputBeatCfgs, inputCfg...)
}
if !didChange(cm.lastInputCfgs, inputCfgs) && !cm.forceReload {
cm.logger.Debug("Skipped reloading input units; configuration didn't change")
return nil
}
if cm.forceReload {
cm.logger.Info("Reloading Beats inputs because forceReload is true. " +
"Set log level to debug to get more information about which " +
"inputs are causing this.")
}
if err := obj.Reload(inputBeatCfgs); err != nil {
merror := &multierror.MultiError{}
realErrors := multierror.Errors{}
// At the moment this logic is tightly bound to the current RunnerList
// implementation from libbeat/cfgfile/list.go and Input.loadStates from
// filebeat/input/log/input.go.
// If they change the way they report errors, this will break.
// TODO (Tiago): update all layers to use the most recent features from
// the standard library errors package.
if errors.As(err, &merror) {
for _, err := range merror.Errors {
causeErr := errors.Unwrap(err)
// A Log input is only marked as finished when all events it
// produced are acked by the acker so when we see this error,
// we just retry until the new input can be started.
// This is the same logic used by the standalone configuration file
// reloader implemented on libbeat/cfgfile/reload.go
inputNotFinishedErr := &common.ErrInputNotFinished{}
if ok := errors.As(causeErr, &inputNotFinishedErr); ok {
cm.logger.Debugf("file '%s' is not finished, will retry starting the input soon", inputNotFinishedErr.File)
cm.forceReload = true
cm.logger.Debug("ForceReload set to TRUE")
continue
}
// This is an error that cannot be ignored, so we report it
realErrors = append(realErrors, err)
}
}
if len(realErrors) != 0 {
return fmt.Errorf("failed to reload inputs: %w", realErrors.Err())
}
} else {
// If there was no error reloading input and forceReload was
// true, then set it to false. This prevents unnecessary logging
// and makes it clear this was the moment when the input reload
// finally worked.
if cm.forceReload {
cm.forceReload = false
cm.logger.Debug("ForceReload set to FALSE")
}
}
cm.lastInputCfgs = inputCfgs
cm.lastBeatInputCfgs = inputBeatCfgs
return nil
}
// this function is registered as a debug hook
// it prints the last known configuration generated by the beat
func (cm *BeatV2Manager) handleDebugYaml() []byte {
// generate input
inputList := []map[string]interface{}{}
for _, module := range cm.lastBeatInputCfgs {
var inputMap map[string]interface{}
err := module.Config.Unpack(&inputMap)
if err != nil {
cm.logger.Errorf("error unpacking input config for debug callback: %s", err)
return nil
}
inputList = append(inputList, inputMap)
}
// generate output
outputCfg := map[string]interface{}{}
if cm.lastBeatOutputCfg != nil {
err := cm.lastBeatOutputCfg.Config.Unpack(&outputCfg)
if err != nil {
cm.logger.Errorf("error unpacking output config for debug callback: %s", err)
return nil
}
}
// generate features
var featuresCfg map[string]interface{}
if cm.lastBeatFeaturesCfg != nil {
if err := cm.lastBeatFeaturesCfg.Unpack(&featuresCfg); err != nil {
cm.logger.Errorf("error unpacking feature flags config for debug callback: %s", err)
return nil
}
}
// combine all of the above in a somewhat coherent way
// This isn't perfect, but generating a config that can actually be fed back into the beat
// would require
beatCfg := struct {
Inputs []map[string]interface{}
Outputs map[string]interface{}
Features map[string]interface{}
}{
Inputs: inputList,
Outputs: outputCfg,
Features: featuresCfg,
}
data, err := yaml.Marshal(beatCfg)
if err != nil {
cm.logger.Errorf("error generating YAML for input debug callback: %w", err)
return nil
}
return data
}
func getZapcoreLevel(ll client.UnitLogLevel) (zapcore.Level, bool) {
switch ll {
case client.UnitLogLevelError:
return zapcore.ErrorLevel, false
case client.UnitLogLevelWarn:
return zapcore.WarnLevel, false
case client.UnitLogLevelInfo:
return zapcore.InfoLevel, false
case client.UnitLogLevelDebug:
return zapcore.DebugLevel, false
case client.UnitLogLevelTrace:
// beats doesn't support trace
// but we do allow the "Publish event:" debug logs
// when trace mode is enabled
return zapcore.DebugLevel, true
}
// info level for fallback
return zapcore.InfoLevel, false
}
func didChange(previous map[string]*proto.UnitExpectedConfig, latest map[string]*proto.UnitExpectedConfig) bool {
if (previous == nil && latest != nil) || (previous != nil && latest == nil) {
return true
}
if len(previous) != len(latest) {
return true
}
for k, v := range latest {
p, ok := previous[k]
if !ok {
return true
}
if !gproto.Equal(p, v) {
return true
}
}
return false
} |
import React, { useState, useEffect } from "react";
import { Container, Row, Col } from "react-bootstrap";
import {
Box,
Flex,
Heading,
Image,
Skeleton,
Text,
IconButton,
Tooltip,
} from "@chakra-ui/react";
import { FaPlay, FaMinus } from "react-icons/fa";
const LikedSongs = () => {
const [likedSongs, setLikedSongs] = useState([]);
const [isLoading, setIsLoading] = useState(true);
useEffect(() => {
const fetchLikedSongs = async () => {
try {
const response = await fetch(
"https://tunesmusicapp.onrender.com/user",
{
credentials: "include",
}
);
const data = await response.json();
setLikedSongs(data.likedSongs || []);
} catch (err) {
console.error("Error fetching liked songs", err);
} finally {
setTimeout(() => {
setIsLoading(false);
}, 2000);
}
};
fetchLikedSongs();
}, []);
const handleDelete = async (index) => {
try {
const songToDelete = likedSongs[index];
const response = await fetch(
"https://tunesmusicapp.onrender.com/deleteLikedSong",
{
method: "DELETE",
headers: {
"Content-Type": "application/json",
},
credentials: "include",
body: JSON.stringify({
songId: songToDelete._id,
}),
}
);
if (response.ok) {
const updatedSongs = likedSongs.filter((_, i) => i !== index);
setLikedSongs(updatedSongs);
} else {
console.error("Failed to delete song");
}
} catch (error) {
console.error("Error deleting song:", error);
}
};
return (
<Container maxW="container.lg" mt={{ base: "8", md: "16" }}>
<Box mt={{ base: "16", md: "32" }} mr={{ md: "4rem" }}>
<Row className="mb-2 justify-content-center mr-[20px]">
<Col md={6}>
<Text
fontSize={{ base: "2xl", md: "5xl" }}
textColor="white"
fontWeight="bold"
>
Liked Songs
</Text>
</Col>
</Row>
</Box>
<Flex direction="column" align="center" mb={20}>
{isLoading ? (
<Skeleton height="4rem" width={{ base: "full", md: "55%" }} />
) : likedSongs.length > 0 ? (
likedSongs.map((song, index) => (
<Flex
key={index}
direction="row"
align="center"
justifyContent="flex-start"
mb={1}
width={{ base: "full", md: "55%" }}
>
<Flex
bgGradient="linear(to-r, black, gray.800)"
p={4}
borderLeft="2px"
borderBottom="1px"
borderColor="gray.700"
rounded="md"
shadow="md"
flex="1"
justifyContent="space-between"
align="center"
height="4rem"
>
<Flex align="center" gap={2}>
<Image
src="/AlbumLogo.png"
alt="Logo"
rounded="md"
boxSize="12"
mr={2}
/>
<Text fontSize="md" textColor="white" fontWeight="semibold">
{song.name}
</Text>
</Flex>
<Flex gap={4} align="center">
<Tooltip
hasArrow
label="Play"
placement="left"
ml={1}
openDelay={1200}
>
<IconButton
rounded="full"
aria-label="Play"
boxSize={10}
bg="#1DB954"
_hover={{ bg: "#1ED760", transform: "scale(1.1)" }}
icon={<FaPlay color="black" />}
onClick={() => window.open(song.link, "_blank")}
/>
</Tooltip>
<Tooltip
hasArrow
label="Remove Song"
placement="right"
ml={1}
openDelay={500}
>
<IconButton
aria-label="Delete"
rounded="full"
icon={<FaMinus color="gray" />}
color="red.500"
boxSize={6}
p={1}
onClick={() => handleDelete(index)}
/>
</Tooltip>
</Flex>
</Flex>
</Flex>
))
) : (
<Box mr={{ base: "13rem", md: "30rem" }}>
<Box
bg="gray.700"
p={2}
rounded="md"
maxW="8rem"
maxH="3rem"
alignItems="center"
>
<Text textColor="white">No Liked Songs</Text>
</Box>
</Box>
)}
</Flex>
</Container>
);
};
export default LikedSongs; |
#include <iostream>
#include <stdlib.h>
#include <conio.h>
using namespace std;
class ArbolABB;
/**CLASE NODO**/
class Nodo {
private:
int dato;
Nodo *izq;
Nodo *der;
public:
Nodo(int x);
void setDato(int x);
void setIzq(Nodo * p);
void setDer(Nodo * p);
int getDato();
Nodo * getIzq();
Nodo * getDer();
};
Nodo::Nodo(int x){
dato = x;
izq = NULL;
der = NULL;
}
void Nodo::setDato(int x){
dato = x;
}
void Nodo::setIzq(Nodo * p){
izq = p;
}
void Nodo::setDer(Nodo * p){
der = p;
}
int Nodo::getDato(){
return dato;
}
Nodo * Nodo::getIzq(){
return izq;
}
Nodo * Nodo::getDer(){
return der;
}
/***CLASE ARBOL BINARIO DE BUSQUEDA***/
class ArbolABB {
private:
Nodo *raiz;
public:
ArbolABB() ;
Nodo *apRaiz();
int esVacio(Nodo *r);
void insertar(int x, Nodo * p);
void InOrden(Nodo *p);
//void PreOrden(Nodo *nodo);
//void PostOrden(Nodo *nodo);
int profundidad (Nodo* p);
};
//*****CODIGOS DE METODOS******************************//
ArbolABB::ArbolABB(){ //Constructor
raiz = NULL;
}
Nodo * ArbolABB::apRaiz(){ //regresa el apuntador a la raiz
return raiz;
}
int ArbolABB::esVacio(Nodo *r) {
return r==NULL;
}
void ArbolABB::insertar(int x, Nodo *p){
if(p== NULL){
p = new Nodo(x);
raiz = p;
}
else if (x < p->getDato()){
if(p->getIzq() == NULL){
Nodo *n = new Nodo(x);
p->setIzq(n);
}
else
insertar(x , p->getIzq());
}
else if (x > p->getDato()){
if(p->getDer() == NULL){
Nodo *n = new Nodo(x);
p->setDer(n);
}
else
insertar(x, p->getDer());
}
else
cout<<"\n El dato ya existe.";
}
//**RECORRIDOS ************************************
void ArbolABB::InOrden(Nodo *p){
if(p->getIzq() != NULL){
InOrden(p->getIzq());
}
cout<<p->getDato()<<", ";
if(p->getDer() != NULL){
InOrden(p->getDer());
}
}
//*SABER LA PROFUNDIDAD DEL ARBOL *************************
int ArbolABB::profundidad(Nodo* p){
//p es la raiz
//si la raiz es nula
if (p == NULL)
{
return -1; //regresa -1
}
//si la raiz no tiene hijos, entonces:
if (p->getIzq() == NULL && p->getDer() == NULL)
{
return 0; //regresamos 0
}
// pasamos a los casos recursivos
int pIzq = profundidad(p->getIzq());
int pDer = profundidad(p->getDer());
//una vez que se hicieron los casos recursivos, vamos a comprar
//si el dato derecho (btnApagar) es mayor
if (pDer > pIzq)
{
return pDer +1;
} else{ //en caso contrario:
return pIzq +1;
}
}
int main(){
ArbolABB ar;
Nodo *r;
// Inserci�n de nodos en �rbol:
ar.insertar(5,NULL);
r = ar.apRaiz();
ar.insertar(12,r);
ar.insertar(4,r);
ar.insertar(7,r);
ar.insertar(3,r);
ar.insertar(6,r);
ar.insertar(9,r);
ar.insertar(8,r);
ar.insertar(11,r);
ar.insertar(14,r);
ar.insertar(13,r);
ar.insertar(16,r);
//Mostrar el arbol
cout << "\nInOrden: "; ar.InOrden(r);
//cout << "\nPreOrden: "; ar.PreOrden(ar.apRaiz());
//cout << "\nPostOrden: "; ar.PostOrden(ar.apRaiz());
cout << endl;
int prof = ar.profundidad(r);
cout<<"La profundidad del arbol es: "<<prof;
return 0;
} |
// call by value vs call by reference
package com.eomcs.basic.ex07;
public class Exam0300 {
static class Person {
// 새로운 종류의 메모리를 설계한다.
// => 새로운 데이터 타입을 정의한다.
// => 클래스를 정의한다.
String name; // null로 초기화
int age; // 0으로 초기화
boolean working; // false로 초기화
}
public static void main(String[] args) {
int a = 200;
m1(a); // call by value
System.out.println(a);
a = 300;
m1(a);
System.out.println(a);
int[] arr = new int[3]; // arr은 배열의 주소를 담은 변수
arr[0] = 100;
arr[1] = 200;
arr[2] = 300;
// new 명령으로 생성하는 변수는 Heap이라는 영역에 만들어진다.
// 위에서 생성한 배열은 이 영역에 생성된다.
m2(arr); // call by reference
System.out.println(arr[0]);
System.out.println(arr[1]);
System.out.println(arr[2]);
System.out.println("----------------");
Person p;
p = new Person();
System.out.printf("%s, %d, %b\n", p.name, p.age, p.working);
m3(p); // call by reference
System.out.printf("%s, %d, %b\n", p.name, p.age, p.working);
}
static void m1(int a) {
a = 100; // 로컬 변수
} // 메서드 호출이 끝나면 로컬변수는 지워진다.
static void m2(int[] arr) {
arr[0] *= 2;
arr[1] *= 3;
arr[2] *= 4;
}
static void m3(Person p) {
p.name = "홍길동";
p.age = 20;
p.working = true;
}
}
// 시험지:
// 1. 다음 계산을 수행하라.
// a 변수에 100을 넣어라.
// b 변수에 200을 넣어라.
// a와 b를 더해 그 결과를 출력하라. |
import React from "react";
import { useChatStore } from "../store/chatStore";
import { FaEllipsisV } from "react-icons/fa";
import { IoIosArrowBack } from "react-icons/io";
import { RiSendPlaneLine } from "react-icons/ri";
import MessageContainer from "./MessageContainer";
import { useConversationStore } from "../store/conversationStore";
import { useAuthStore } from "../store/authStore";
import { useSendMessage } from "../hooks/useSendMessage";
import toast from "react-hot-toast";
const ChatScreen = () => {
const [sentMessage, setSentMessage] = React.useState("");
const [displayMessage, setDisplayMessage] = React.useState("");
const { setMessageArray } = useChatStore();
const { isSent, sendMessage } = useSendMessage();
const { user } = useAuthStore();
const {
selectedConversation,
setSelectedConversation,
ChatWhichIsSelected,
setChat,
} = useConversationStore();
// console.log("selectedConversation", selectedConversation);
const sendMessageHandler = async (e) => {
if (e.key === "Enter") {
if (sentMessage.length <= 0) {
toast.error("Please enter a message");
return;
}
const recieverId =
selectedConversation?.participants.find((p) => p._id !== user._id)
._id || ChatWhichIsSelected._id;
sendMessage(recieverId, sentMessage);
setSentMessage("");
}
};
return (
<div
id="chat-inbox"
className={`lg:col-span-8 sm:col-span-7 bg-[#f7f7f7] w-full h-full ${
selectedConversation || ChatWhichIsSelected
? "col-span-12"
: "col-span-0"
} sm:py-4 sm:px-2 p-0`}
>
<div className="bg-white w-full h-full rounded-xl shadow-[1px_4px_10px_rgba(1,1,1,0.06)] relative">
{(selectedConversation || ChatWhichIsSelected) && (
<>
<div className="w-full bg-purple-500 p-2 sm:px-4 px-2 sm:rounded-t-xl flex items-center">
<IoIosArrowBack
size={20}
color="white"
className="sm:hidden block mr-2"
onClick={() => {
if (selectedConversation) {
setSelectedConversation(null);
setMessageArray([]);
} else {
setChat(null);
}
}}
/>
<img
src={
selectedConversation
? selectedConversation.participants.find(
(p) => p._id !== user._id
).profile_picture
: ChatWhichIsSelected?.profile_picture
}
alt="profile"
className="w-[50px] h-[50px] object-cover rounded-full"
/>
<div className="flex flex-col ml-2 justify-center flex-grow">
<div className="text-sm font-semibold text-white">
{selectedConversation
? selectedConversation.participants.find(
(p) => p._id !== user._id
).username
: ChatWhichIsSelected?.username}
</div>
<div className="flex items-center gap-1">
<div className="text-sm font-semibold text-white">Online</div>
<div className="bg-green-400 w-3 h-3 rounded-full"></div>
</div>
</div>
<div>
<FaEllipsisV size={20} color="white" />
</div>
</div>
<MessageContainer displayMessage={displayMessage} />
<div className="px-4 w-full flex justify-center bg-gray-400">
<div className="w-[90%] px-4 absolute md:bottom-2 lg:bottom-[30px] bottom-6 flex items-center border rounded-lg justify-center bg-white">
<input
type="text"
placeholder="send message"
className="w-full outline-none p-2 rounded-lg text-wrap text-ellipsis"
value={sentMessage}
onChange={(e) => setSentMessage(e.target.value)}
onKeyDownCapture={(e) => sendMessageHandler(e)}
/>
<RiSendPlaneLine size={20} color="purple" />
</div>
</div>
</>
)}
</div>
</div>
);
};
export default ChatScreen; |
/* eslint-disable react/react-in-jsx-scope */
import './App.css'
import { BrowserRouter, Routes, Route } from 'react-router-dom'
import { Page404 } from '../src/404/page/404.jsx'
import { Landing } from './LandingPage/pages/Landing.jsx'
import { MyCartReservationPage } from './MyCartReservation/Pages/MyCartReservationPage.jsx'
import { Navbar } from './components/Navbar.jsx'
import { LocationSelection } from './LocationSelection/pages/LocationSelection.jsx'
import { BookYourCourtProvider } from './context/BookYourCourtContext.jsx'
import { StartCountProvider } from './context/StartCountdownContext.jsx'
import { CourtReservationCalendar } from './OneTimeCourtReservation/Pages/court-reservation.jsx'
import { ConfirmationPage } from './ConfimationPage/pages/ConfirmationPage.jsx'
import { CheckOutConfirmation } from './MyCartReservation/Pages/CheckoutConfirmation.jsx'
import { CourtDateProvider } from './context/CourtsDateContext.jsx'
import { ModalCourtReservationProvider } from './context/ModalCourtReservationContext.jsx'
import { Login } from './auth/Login/pages/Login.jsx'
import { SignUp } from './auth/SignUp/pages/SignUp.jsx'
import { ForgotPw } from './auth/ForgotPassword/pages/ForgotPw.jsx'
import { ResetPw } from './auth/ResetPassword/pages/ResetPw.jsx'
function App () {
return (
<>
<ModalCourtReservationProvider>
<StartCountProvider>
<BookYourCourtProvider>
<CourtDateProvider>
<BrowserRouter>
<Navbar />
<Routes>
<Route path="/" element={<Landing />} />
<Route path="/reserve/:locationId" element={<CourtReservationCalendar />} />
<Route path="/MyCart" element={<MyCartReservationPage />} />
<Route path="/LocationSelection" element={<LocationSelection />} />
<Route path="/reserve" element={<CourtReservationCalendar />} />
<Route path='/confirmationPage' element={<ConfirmationPage />}/>
<Route path='/CheckOutConfirmation' element={<CheckOutConfirmation />}/>
<Route path='/login' element={<Login/>} />
<Route path='/signUp' element={<SignUp/>} />
<Route path='/forgotPassword' element={<ForgotPw />} />
<Route path='/resetPassword' element={<ResetPw />} />
<Route path="*" element={<Page404 />} />
</Routes>
</BrowserRouter>
</CourtDateProvider>
</BookYourCourtProvider>
</StartCountProvider>
</ModalCourtReservationProvider>
</>
)
}
export default App |
import { GraphQLError } from 'graphql';
import { User, NewUser } from "../graphql/User/types";
import { GenericResponse } from "../graphql/types";
import { UserTable } from "../mock/users";
import { Status } from './../graphql/types';
import { v4 as uuidv4 } from 'uuid';
export function getAllUsers(): GenericResponse<User[]> {
return {
status: Status.success,
data: UserTable
};
}
export function getUserById(userId: string): GenericResponse<User> {
const user: User | undefined = UserTable.find(user => user.userId = userId);
if (!user) {
throw new GraphQLError("Not Found");
}
return {
status: Status.success,
data: user
};
}
export function updateUser(updatedUser: User): GenericResponse<User> {
let user: User | undefined = UserTable.find(user => user.userId = updatedUser.userId);
if (!user) {
throw new GraphQLError("Not Found");
}
user = updatedUser;
return {
status: Status.success,
data: user
}
}
export function deleteUser(userId: string): GenericResponse<string> {
const index = UserTable.findIndex(user => user.userId === userId);
if (index === -1) {
throw new GraphQLError("Not Found");
}
UserTable.splice(index, 1);
return {
status: Status.success,
data: "successfully deleted"
}
}
export function addUser(newUser: NewUser): GenericResponse<User> {
const index = UserTable.findIndex(user => user.email === newUser.email);
console.log(index);
if (index !== -1) {
throw new GraphQLError("Already Exists");
}
const userId = uuidv4();
const addedUser = {
userId,
...newUser
}
UserTable.push(addedUser);
return {
status: Status.success,
data: addedUser
}
} |
// 给定一个候选人编号的集合 candidates 和一个目标数 target ,找出 candidates 中所有可以使数字和为 target 的组合。
// candidates 中的每个数字在每个组合中只能使用 一次 。
// 注意:解集不能包含重复的组合。
// 输入: candidates = [10,1,2,7,6,1,5], target = 8,
// 输出:
// [
// [1,1,6],
// [1,2,5],
// [1,7],
// [2,6]
// ]
// 输入: candidates = [2,5,2,1,2], target = 5,
// 输出:
// [
// [1,2,2],
// [5]
// ]
const combinationSum1 = function(candidates, target) {
candidates.sort((a, b) => a - b);
const res = [];
const dfs = (target, combine, idx) => {
if (target === 0) {
res.push(combine);
return;
}
if (idx === candidates.length) {
return;
}
// 初始化与当前元素不重复的后一个元素的索引
let notRepeatIdx = idx + 1;
// 相同的元素
while(candidates[notRepeatIdx] === candidates[idx]) {
notRepeatIdx++;
};
if (target - candidates[idx] >= 0) {
// 跳到不重复的元素继续递归
dfs(target, combine, notRepeatIdx);
// 选择当前值,继续递归下一个元素
dfs(target - candidates[idx], [...combine, candidates[idx]], idx + 1);
}
};
dfs(target, [], 0);
return res;
};
const combinationSum = function(candidates, target) {
candidates.sort((a, b) => a - b);
const res = [];
dfs(res, [], candidates, target, 0);
return res;
function dfs(res, combine, nums, target, idx) {
if (target === 0) {
return res.push([...combine]);
}
if (target < 0) {
return;
}
for (let i = idx; i < nums.length; i++) {
// 去重
if (i > idx && nums[i] === nums[i - 1]) {
continue;
}
combine.push(nums[i]);
dfs(res, combine, nums, target - nums[i], i + 1);
combine.pop();
}
}
};
console.log(combinationSum([2,3,6,7], 7));
console.log(combinationSum([10,1,2,7,6,1,5], 8));
console.log(combinationSum([2,5,2,1,2], 5)); |
import {
Box,
Button,
Flex,
HStack,
Heading,
Hide,
Input,
Modal,
ModalBody,
ModalContent,
ModalOverlay,
Table,
TableContainer,
Tbody,
Td,
Th,
Thead,
Tr,
VStack,
useDisclosure,
} from "@chakra-ui/react";
import PopupModal from "./PopupModal";
import { RiDeleteBin5Fill as DeleteIcon } from "react-icons/ri";
import { ModalType, Student } from "../utils/constants";
import { useEffect, useState } from "react";
import ImageName from "./ImageName";
import axios from "axios";
import ErrorLoading from "./ErrorLoading";
const BASE_URL = "https://yellowowlbackend-l2ap.onrender.com/api";
const Home = () => {
const { isOpen, onOpen, onClose } = useDisclosure();
const [students, setStudents] = useState<Student[]>([]);
const [searchInput, setSearchInput] = useState<string>("");
const [studentId, setStudentId] = useState<string>("");
const [loading , setLoading] = useState<boolean>(false);
const [error , setError] = useState<boolean>(false);
const [formData, setFormData] = useState<Student>({
name: "",
email: "",
phone: "",
enrollNo: "",
dateOfAdmission: "",
});
const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
const { name, value } = e.target;
setFormData((prev) => {
return { ...prev, [name]: value };
});
};
const handleSearchChange = (e: React.ChangeEvent<HTMLInputElement>) => {
setSearchInput(e.target.value);
};
useEffect(() => {
setLoading(true);
setError(false);
axios
.get(`${BASE_URL}/search?s=${searchInput}`)
.then(({ data }) => {
console.log(data.students);
setStudents(data.students);
setError(false);
setLoading(false);
})
.catch(() => {
setError(true);
setLoading(false);
});
}, [searchInput]);
const handleSubmit = (type: ModalType) => {
setLoading(true);
setError(false);
if (type === ModalType.Create) {
axios
.post(`${BASE_URL}/postStudent`, formData)
.then((res) => {
setStudents([...students, res.data.student]);
setFormData({
name: "",
email: "",
phone: "",
enrollNo: "",
dateOfAdmission: "",
});
setError(false);
setLoading(false);
})
.catch(() => {
setError(true);
setLoading(false);
});
} else {
axios
.patch(`${BASE_URL}/updateStudent/${formData._id}`, formData)
.then((res) => {
let updatedStudent = res.data.student;
let updatedStudents = students.map((e) =>
e._id === updatedStudent._id ? updatedStudent : e
);
setStudents(updatedStudents);
setFormData({
name: "",
email: "",
phone: "",
enrollNo: "",
dateOfAdmission: "",
});
setError(false);
setLoading(false);
})
.catch(() => {
setError(true);
setLoading(false);
});
}
};
const handleDelete = () => {
setLoading(true);
setError(false);
axios
.delete(`${BASE_URL}/deleteStudent/${studentId}`)
.then((res) => {
let deletedStudent = res.data.student;
let updatedStudents = students.filter((e) => e._id !== deletedStudent);
setStudents(updatedStudents);
setError(false)
setLoading(false)
})
.catch(() => {
setError(true)
setLoading(false)
});
};
useEffect(() => {
setLoading(true);
axios
.get(`${BASE_URL}/getStudent`)
.then(({ data }) => {
setStudents(data.students);
setLoading(false);
setError(false);
})
.catch(() => {
setError(true);
setLoading(false);
});
}, []);
return (
<Box bg={"#E5E7EB"} height={"90vh"}>
{loading && <ErrorLoading text = "Loading..."/>}
{error && <ErrorLoading text = "Something went wrong"/>}
<VStack h={"95vh"} p={5}>
<HStack
w={"100%"}
py={2}
borderRadius={"8px"}
px={5}
justify={"space-between"}
>
<Box>
<Heading as="h2" size="lg">
Students
</Heading>
</Box>
<Flex maxW={"70%"} gap={"10px"}>
<Input
type="text"
placeholder="Search..."
bgColor={"white"}
value={searchInput}
onChange={handleSearchChange}
/>
<PopupModal
type={ModalType.Create}
{...formData}
changeState={handleChange}
handleSubmit={handleSubmit}
setFormData={setFormData}
/>
</Flex>
</HStack>
<TableContainer
w={"100%"}
shadow={
"rgba(50, 50, 93, 0.25) 0px 8px 15px 2px, rgba(0, 0, 0, 0.3) 0px 3px 7px -3px;"
}
borderRadius={"8px"}
>
<Table className = "table" variant="simple">
<Thead bg={"#F9FAFB"} padding={"10px"} textAlign={"center"}>
<Tr>
<Th textAlign={"center"}>NAME</Th>
<Th textAlign={"center"}>EMAIL</Th>
<Hide below="md">
<Th textAlign={"center"}>PHONE</Th>
</Hide>
<Hide below="md">
<Th textAlign={"center"}>ENROLL NUMBER</Th>
</Hide>
<Hide below="md">
<Th textAlign={"center"}>DATE OF ADMISSION</Th>
</Hide>
<Th></Th>
</Tr>
</Thead>
<Tbody bg={"#FFFFFF"} m={"10px"}>
{students.length > 0 &&
students.map((student) => (
<Tr
p={"10px"}
style={{
padding: "10px",
}}
key={student._id}
>
<Td textAlign={"left"}>
<ImageName name={student.name} />
</Td>
<Td textAlign={"center"}>{student.email}</Td>
<Hide below="md">
<Td textAlign={"center"}>{student.phone}</Td>
</Hide>
<Hide below="md">
<Td textAlign={"center"}>{student.enrollNo}</Td>
</Hide>
<Hide below="md">
<Td textAlign={"center"}>{student.dateOfAdmission}</Td>
</Hide>
<Td textAlign={"center"}>
<Flex justifyContent={"start"} gap={"10px"}>
<Box onClick={() => setFormData(student)}>
<PopupModal
type={ModalType.Update}
{...formData}
changeState={handleChange}
setFormData={setFormData}
handleSubmit={handleSubmit}
/>
</Box>
<Box
onClick={() => {
setStudentId(String(student._id));
onOpen();
}}
_hover={{
background: "local",
border: "none",
}}
cursor={"pointer"}
>
<DeleteIcon color="red" />
</Box>
</Flex>
<DeleteModal
student={student}
handleDelete={handleDelete}
isOpen={isOpen}
onClose={onClose}
/>
</Td>
</Tr>
))}
</Tbody>
</Table>
</TableContainer>
</VStack>
</Box>
);
};
interface deleteModalProps {
student: Student;
handleDelete: any;
onClose: any;
isOpen: any;
}
const DeleteModal = ({ handleDelete, onClose, isOpen }: deleteModalProps) => {
return (
<Modal
isCentered
onClose={onClose}
isOpen={isOpen}
motionPreset="slideInBottom"
>
<Box padding={"210px"}>
<ModalOverlay bg={"#1313132c"} />
<ModalContent p={"2.5rem"}>
<ModalBody fontWeight={600} fontSize={"18px"}>
Are you sure to delete this Student ?
</ModalBody>
<Flex
justifyContent={"center"}
alignItems={"center"}
gap={"18px"}
p={"15px 0"}
>
<Button
colorScheme="green"
bg={"#22C55E"}
width={"65%"}
onClick={() => {
handleDelete();
onClose();
}}
>
Yes
</Button>
<Button
colorScheme="red"
bg={"#C55D22"}
width={"65%"}
onClick={onClose}
>
No
</Button>
</Flex>
</ModalContent>
</Box>
</Modal>
);
};
export default Home; |
<?php
declare(strict_types=1);
namespace Benedekb97\Sudoku\Solver;
use Benedekb97\Sudoku\Component\Cell;
use Benedekb97\Sudoku\Component\CellContainer;
use Benedekb97\Sudoku\Component\Game;
use Doctrine\Common\Collections\ArrayCollection;
class SinglePossibilitySolver
{
public function solve(Game $game): void
{
for ($number = 1; $number <= 9; $number++) {
$this->solveRows($game, $number);
$this->solveColumns($game, $number);
$this->solveBoxes($game, $number);
}
}
private function solveRows(Game $game, int $number): void
{
/** @var CellContainer $row */
foreach ($game->getRows() as $row) {
$foundInCells = new ArrayCollection();
/** @var Cell $cell */
foreach ($row->getCells() as $cell) {
if ($cell->hasPossibility($number)) {
$foundInCells->add($cell);
if ($foundInCells->count() > 1) {
break;
}
}
}
if ($foundInCells->count() === 1) {
$foundInCells->first()->setNumber($number);
}
}
}
private function solveColumns(Game $game, int $number): void
{
/** @var CellContainer $column */
foreach ($game->getColumns() as $column) {
$foundInCells = new ArrayCollection();
/** @var Cell $cell */
foreach ($column->getCells() as $cell) {
if ($cell->hasPossibility($number)) {
$foundInCells->add($cell);
if ($foundInCells->count() > 1) {
break;
}
}
}
if ($foundInCells->count() === 1) {
$foundInCells->first()->setNumber($number);
}
}
}
private function solveBoxes(Game $game, int $number): void
{
/** @var CellContainer $box */
foreach ($game->getBoxes() as $box) {
$foundInCells = new ArrayCollection();
/** @var Cell $cell */
foreach ($box->getCells() as $cell) {
if ($cell->hasPossibility($number)) {
$foundInCells->add($cell);
if ($foundInCells->count() > 1) {
break;
}
}
}
if ($foundInCells->count() === 1) {
$foundInCells->first()->setNumber($number);
}
}
}
} |
package com.hyesun.tenone;
import java.util.List;
import javax.inject.Inject;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import com.hyesun.tenone.domain.Goods;
import com.hyesun.tenone.domain.Paging;
import com.hyesun.tenone.domain.User;
import com.hyesun.tenone.service.AdminService;
@Controller
@RequestMapping("/admin")
public class AdminController {
private static final Logger logger = LoggerFactory.getLogger(UserController.class);
@Inject
AdminService adminService;
// 상품 등록 Get
@GetMapping("/write")
public String getGoodsWrite(HttpServletRequest req, Model model) throws Exception {
logger.info("get goods write");
HttpSession session = req.getSession();
User sellerInfo = (User)session.getAttribute("user");
String sellerId = (String)sellerInfo.getUser_id();
Goods sellerShop = adminService.sellerInfo(sellerId);
model.addAttribute("shopName", sellerShop.getShop_name());
return "admin/adminWrite";
}
// 상품 등록 Post
@PostMapping("/postWrite")
public String goodsWrite(Goods gd, HttpServletRequest req) throws Exception {
logger.info("post goods write");
HttpSession session = req.getSession();
User sellerInfo = (User)session.getAttribute("user");
String sellerId = (String)sellerInfo.getUser_id();
gd.setSellerId(sellerId);
adminService.write(gd);
System.out.println("아아아아ㅏ아!== :");
return "redirect:list";
}
// 상품 수정 Get
@GetMapping("/update/{goodsId}")
public String getGoodsUpate(@PathVariable Integer goodsId, HttpServletRequest req, Model model) throws Exception {
logger.info("get goods update");
System.out.println("asdasda=== " + goodsId);
HttpSession session = req.getSession();
User sellerInfo = (User)session.getAttribute("user");
String sellerId = (String)sellerInfo.getUser_id();
Goods goods = adminService.goodsView(goodsId, sellerId);
model.addAttribute("goods", goods);
return "admin/adminUpdate";
}
// 상품 수정 Post
@PostMapping("/update")
public String postGoodsUpate(Goods gd, HttpServletRequest req) throws Exception {
logger.info("post goods update");
HttpSession session = req.getSession();
User sellerInfo = (User)session.getAttribute("user");
String sellerId = (String)sellerInfo.getUser_id();
gd.setSellerId(sellerId);
adminService.goodsUpdate(gd);
return "redirect:list";
}
// 상품목록 (페이징)
@GetMapping("/list")
public String getListPaging(@RequestParam(value = "num",required = false, defaultValue = "1") int num, Model model, HttpServletRequest req,
@RequestParam(value = "searchType",required = false, defaultValue = "title") String searchType,
@RequestParam(value = "keyword",required = false, defaultValue = "") String keyword) throws Exception {
logger.info("get goods list");
HttpSession session = req.getSession();
User sellerInfo = (User)session.getAttribute("user");
String sellerId = (String)sellerInfo.getUser_id();
Goods sellerShop = adminService.sellerInfo(sellerId);
Paging page = new Paging();
page.setNum(num);
page.setCount(adminService.goodsCount(sellerId, searchType, keyword));
page.setSearchType(searchType);
page.setKeyword(keyword);
List<Goods> list = null;
list = adminService.getListPaging(sellerId, page.getDisplayPost(), page.getPostNum(), searchType, keyword);
model.addAttribute("list", list);
model.addAttribute("page", page);
model.addAttribute("select", num);
model.addAttribute("sellerShop", sellerShop.getShop_name());
return "admin/adminHome";
}
// 상품삭제
@GetMapping("/delete/{goodsId}")
public String goodsDelete(@PathVariable Integer goodsId, HttpServletRequest req) throws Exception {
logger.info("post goods delete");
HttpSession session = req.getSession();
User sellerInfo = (User)session.getAttribute("user");
String sellerId = (String)sellerInfo.getUser_id();
adminService.goodsDelete(goodsId, sellerId);
return "redirect:/admin/list";
}
// // 상품 조회
// @GetMapping("/view")
// public void getGoodsView(@RequestParam("n") Integer goodsId, HttpServletRequest req, Model model) throws Exception {
// logger.info("get goods view");
//
// HttpSession session = req.getSession();
// User sellerInfo = (User)session.getAttribute("user");
// String sellerId = (String)sellerInfo.getUser_id();
// Goods goods = adminService.goodsView(goodsId, sellerId);
// model.addAttribute("goods", goods);
// }
} |
"use client";
import React, { useState, useEffect, useRef } from "react";
import { fabric } from "fabric";
import { PixabayImage } from "@/types/pixabay_image";
import { HiXCircle, HiArrowUturnLeft, HiArrowUturnRight, HiArrowDownOnSquare, HiMiniTrash, HiArrowUpCircle, HiSquare3Stack3D } from 'react-icons/hi2';
import Image from 'next/image';
import Phones from '@/data/phones';
import { Phone } from "@/types/phone";
import { useHistory } from '@/utils/historyUtils';
import { Modal } from '@/components/modal';
import { useImageUtils } from '@/utils/imageUtils';
import { Action } from "@/types/action";
import { AiFillMobile, AiOutlineFontSize } from "react-icons/ai";
import { IoImageSharp } from "react-icons/io5";
import { useTextUtils } from "@/utils/textUtils";
import "../../public/fonts.css"
import { TextEditor } from "@/components/TextEditor";
import { BottomSheet } from "@/components/bottomsheet";
import "../../public/fonts.css"
import { Layers } from "@/components/Layers";
export default function Home() {
const canvasRef = useRef<HTMLCanvasElement>(null);
const fabricCanvasRef = useRef<fabric.Canvas | null>(null);
const [canvas, setCanvas] = useState<fabric.Canvas | undefined>();
const [isResetCanvas, setIsResetCanvas] = useState<number>(0);
const { addText } = useTextUtils();
const { setBackgroundFromImage, setBackgroundFromUpload, uploadImage, exportImage, addImage } = useImageUtils();
const [images, setImages] = useState<PixabayImage[]>([]);
const [selectedPhone, setSelectedPhone] = useState<Phone>(Phones[0]);
const [openPopup, setOpenPopup] = useState<Action>('');
const { saveCanvasState, undo, redo } = useHistory();
const [selectedImageTab, setSelectedImageTab] = useState<number>(0);
const [objects, setObjects] = useState<fabric.Object[]>([]);
const [selectedObject, setSelectedObject] = useState<fabric.Object | null>(null);
useEffect(() => {
if (canvasRef.current) {
const s = window.innerHeight * 0.8;
let height = 800;
if (height > s) {
height = s;
}
const width = height / selectedPhone.height * selectedPhone.width;
const c = new fabric.Canvas(canvasRef.current, {
height: height,
width: width
});
fabricCanvasRef.current = c;
// Custom Trash Button Control
const deleteControl = new fabric.Control({
x: 0.5,
y: -0.5,
offsetX: 10,
offsetY: -10,
cursorStyle: "pointer",
mouseUpHandler: (_, transform) => {
const target = transform.target;
c.remove(target); // Remove the object
c.requestRenderAll(); // Refresh the canvas
return true; // Return a boolean value
},
render: (ctx, left, top) => {
const img = new window.Image();
img.src = '/icons/trash.svg';
img.onload = () => {
ctx.drawImage(img, left - 12, top - 12, 24, 24);
};
},
});
// Add the Trash Button to all objects
fabric.Object.prototype.controls.deleteControl = deleteControl;
c.on('object:added', function (e) {
if (e.target) {
c.setActiveObject(e.target);
c.centerObject(e.target);
}
setObjects(c.getObjects());
});
// Handle selection events
c.on("selection:created", (e) => {
setSelectedObject(e.selected?.[0] || null);
});
c.on('selection:updated', (e) => {
setSelectedObject(e.selected?.[0] || null);
});
c.on("selection:cleared", () => {
setSelectedObject(null);
});
c.on('object:removed', () => {
setObjects(c.getObjects());
});
// c.on('object:selected', (e) => {
// const selectedObject = e.target;
// // Disable the automatic bringing to front by removing this line
// // selectedObject.bringToFront(); // Do not call this method
// // Optionally, you can force the selected object to stay where it is in the stack
// // selectedObject.moveTo(selectedObject.canvas._objects.length - 1); // Keeps it in the same layer position
// });
setObjects(c.getObjects());
setCanvas(c);
return () => {
c.dispose();
};
}
}, [isResetCanvas, selectedPhone]);
//TODO: Use the cloneProduct function cloneProduct("9692855959837");
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const cloneProduct = async (productId: string) => {
const response = await fetch('/api/shopify', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ originalProductId: productId }),
});
const data = await response.json();
console.log('Cloned Product:', data);
};
useEffect(() => {
const fetchImages = async () => {
try {
const response = await fetch('/api/images', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
searchQuery: 'iphone',
category: 'fashion',
per_page: 9,
image_type: 'photo',
}),
});
const data = await response.json();
if (data.hits) setImages(data.hits);
} catch (error) {
console.error('Error fetching images:', error);
}
};
fetchImages();
}, []);
return (
<div className="w-full h-full relative bg-gray-200">
<div className="relative h-screen">
<div className="ml-16 my-16 inline-block relative">
<div className="mobileFrame overflow-hidden">
<Image
className="object-contain"
style={{ position: "absolute", zIndex: 20, pointerEvents: 'none' }}
width={fabricCanvasRef?.current?.getWidth() || selectedPhone.width}
height={fabricCanvasRef?.current?.getHeight() || selectedPhone.height}
src={selectedPhone.svg}
alt=""
priority
/>
</div>
<div className="absolute left-0 -ml-14 z-10 text-white">
<div className="flex flex-col place-items-center gap-4">
<div className="flex flex-col gap-2 rounded-xl p-2 bg-black">
<button className="action-button" onClick={() => undo(canvas)} title="Undo"><HiArrowUturnLeft /></button>
<button className="action-button" onClick={() => redo(canvas)}><HiArrowUturnRight /></button>
</div>
<div className="flex flex-col gap-2 bg-black rounded-xl p-2">
<button className="action-button" onClick={() => addText(canvas, () => saveCanvasState(canvas))}><AiOutlineFontSize /></button>
<button className="action-button" onClick={() => setOpenPopup('open_image_popup')}><IoImageSharp /></button>
<button className="action-button" onClick={() => {
setOpenPopup('open_layer_bottom_sheet');
}}><HiSquare3Stack3D /></button>
<button className="action-button" onClick={() => setOpenPopup('open_background_image_popup')}><AiFillMobile /></button>
</div>
<div className="flex flex-col gap-2 bg-black rounded-xl p-2">
<button className="action-button" onClick={() => exportImage(canvas)}><HiArrowDownOnSquare /></button>
</div>
<div className="flex flex-col gap-2 bg-red-500 rounded-xl p-2">
<button className="action-button" onClick={() => setOpenPopup('open_ask_popup')}><HiMiniTrash /></button>
</div>
</div>
</div>
<div className="absolute top-0 -mt-12 left-4 right-4 text-center">
<div className="my-2 text-black inline-block relative text-xs">
<select
className="px-4 py-2 rounded-lg"
value={selectedPhone?.id} onChange={(e) => {
const selectedPhoneId = e.target.value;
const phone = Phones.find((p: Phone) => p.id === selectedPhoneId);
if (phone != undefined) {
setSelectedPhone(phone);
setIsResetCanvas(isResetCanvas + 1);
}
}}>
<option value="" disabled>Select a phone</option>
{Phones.map((phone: Phone) => (
<option key={phone.id} value={phone.id}>
{phone.name}
</option>
))}
</select>
</div>
</div>
<canvas ref={canvasRef} id="canvas" className="rounded-[50px]" />
</div>
{/* Popup Text Editor */}
{(selectedObject instanceof fabric.IText && canvas) && (
<div
className="bg-gray-300 rounded-2xl h-16"
style={{
position: "absolute",
top: (fabricCanvasRef?.current?.getHeight() ?? 1) + 70,
width: fabricCanvasRef?.current?.getWidth() || selectedPhone.width,
left: canvasRef.current ? canvasRef.current.getBoundingClientRect().left : 0,
padding: "16px",
zIndex: 100,
}}
>
<TextEditor selectedText={selectedObject} canvas={canvas} />
</div>
)}
</div>
<BottomSheet isOpen={openPopup === 'open_layer_bottom_sheet'} onClose={() => setOpenPopup('')}>
<div
className="bg-gray-300 rounded-2xl"
style={{
position: "absolute",
bottom: 0,
width: fabricCanvasRef?.current?.getWidth() || selectedPhone.width,
left: canvasRef.current ? canvasRef.current.getBoundingClientRect().left : 0,
padding: "16px",
zIndex: 100,
}}
>
{
canvas && fabricCanvasRef.current && (
<Layers canvas={canvas} selectedObject={selectedObject} setSelectedObject={setSelectedObject} fabricObjects={objects} />
)
}
</div>
</BottomSheet>
<Modal isOpen={openPopup === 'open_ask_popup'} onClose={() => setOpenPopup('')}>
<div className="max-w-md relative p-4">
<HiXCircle size={36} onClick={() => setOpenPopup('')} className="absolute -mt-2 -mr-2 top-0 right-0 cursor-pointer" />
<h1 className="text-lg font-bold">Are you sure you want to reset the design?</h1>
<p>This action will clear all the designs you have created. You will need to start from scratch. Are you sure you want to proceed?</p>
<div className="flex flex-row gap-8 mt-4 place-content-center">
<button className="border px-6 py-2 rounded-md border-black" onClick={() => setOpenPopup('')}>Cancel</button>
<button className="border px-6 py-2 rounded-md border-red-500 text-red-500" onClick={() => {
setOpenPopup('');
setIsResetCanvas(isResetCanvas + 1);
}}>Reset</button>
</div>
</div>
</Modal>
<Modal isOpen={openPopup === 'open_image_popup'} onClose={() => setOpenPopup('')}>
<div className="max-w-4xl min-w-[70vw] relative">
<div className="p-4 flex flex-row gap-2">
<HiXCircle size={36} onClick={() => setOpenPopup('')} className="absolute -mt-2 -mr-2 top-0 right-0 cursor-pointer" />
<button onClick={() => setSelectedImageTab(0)} className={`border px-3 p-1 rounded-md ${selectedImageTab === 0 && 'bg-black text-white'}`}>Upload an Image</button>
<button onClick={() => setSelectedImageTab(1)} className={`border px-3 p-1 rounded-md ${selectedImageTab === 1 && 'bg-black text-white'}`}>Select an Image</button>
</div>
{
selectedImageTab === 0 && (
<div className="max-h-[70vh] overflow-y-auto">
<div className="inline-block mx-auto min-h-[70vh]">
<label className="border-2 border-black border-dashed m-4 p-8 rounded-md cursor-pointer flex flex-col place-items-center">
<HiArrowUpCircle size={48} />
Upload an Image
<input
type="file"
accept="image/*"
style={{ display: 'none' }}
onChange={(e) => uploadImage(canvas, e, () => {
saveCanvasState(canvas);
setOpenPopup('');
})}
/>
</label>
</div>
</div>
)
}
{
selectedImageTab === 1 && (
<div className="max-h-[70vh] overflow-y-auto">
<div className="grid grid-cols-3 md:grid-cols-4 gap-4">
{images.map((image) => (
<div
key={image.id}
className="cursor-pointer border p-2 hover:shadow-lg"
onClick={() => addImage(canvas, image.largeImageURL, () => {
setOpenPopup('');
saveCanvasState(canvas);
})}
>
<img src={image.webformatURL} alt={image.tags} className="w-full h-auto" />
<p className="text-center mt-2">{image.tags}</p>
</div>
))}
</div>
</div>
)
}
</div>
</Modal>
<Modal isOpen={openPopup === 'open_background_image_popup'} onClose={() => setOpenPopup('')}>
<div className="max-w-4xl min-w-[70vw] relative">
<div className="p-4 flex flex-row gap-2">
<HiXCircle size={36} onClick={() => setOpenPopup('')} className="absolute -mt-2 -mr-2 top-0 right-0 cursor-pointer" />
<button onClick={() => setSelectedImageTab(0)} className={`border px-3 p-1 rounded-md ${selectedImageTab === 0 && 'bg-black text-white'}`}>Upload Background Image</button>
<button onClick={() => setSelectedImageTab(1)} className={`border px-3 p-1 rounded-md ${selectedImageTab === 1 && 'bg-black text-white'}`}>Select Background Image</button>
</div>
{
selectedImageTab === 0 && (
<div className="max-h-[70vh] overflow-y-auto">
<div className="inline-block mx-auto min-h-[70vh]">
<label className="border-2 border-black border-dashed m-4 p-8 rounded-md cursor-pointer flex flex-col place-items-center">
<HiArrowUpCircle size={48} />
Upload an Image
<input
type="file"
accept="image/*"
style={{ display: 'none' }}
onChange={(e) => setBackgroundFromUpload(canvas, e, () => {
saveCanvasState(canvas);
setOpenPopup('');
})}
/>
</label>
</div>
</div>
)
}
{
selectedImageTab === 1 && (
<div className="max-h-[70vh] overflow-y-auto">
<div className="grid grid-cols-3 md:grid-cols-4 gap-4">
{images.map((image) => (
<div
key={image.id}
className="cursor-pointer border p-2 hover:shadow-lg"
onClick={() => setBackgroundFromImage(canvas, image.largeImageURL, () => {
setOpenPopup('');
saveCanvasState(canvas);
})}
>
<img src={image.webformatURL} alt={image.tags} className="w-full h-auto" />
<p className="text-center mt-2">{image.tags}</p>
</div>
))}
</div>
</div>
)
}
</div>
</Modal>
</div>
);
} |
using BSSlurper.Core.BeatSaver.API.Models;
using System.Globalization;
using System.Text.Json;
namespace BSSlurper.Core.BeatSaver.API
{
public static class ApiClient
{
public const string PlaylistsEndpoint = "https://api.beatsaver.com/playlists/latest";
public const string MapsEndpoint = "https://api.beatsaver.com/maps/latest";
public const string ApiDateFormat = "yyyy-MM-ddTHH:mm:ss.fffffffZ";
public delegate Task DataCallback<T>(T data, bool pageEnd, CancellationToken cancellationToken = default);
internal static async Task<T> GetJsonAsync<T>(string url, int retries = 3, CancellationToken cancellationToken = default)
{
cancellationToken.ThrowIfCancellationRequested();
for (int i = 0; i < retries; i++)
{
cancellationToken.ThrowIfCancellationRequested();
try
{
var client = new HttpClient();
Console.WriteLine($"Fetching: {url}");
var response = await client.GetAsync(url, cancellationToken);
response.EnsureSuccessStatusCode();
var responseBody = await response.Content.ReadAsStreamAsync(cancellationToken);
return await JsonSerializer.DeserializeAsync<T>(responseBody, JsonSerializerOptions.Default, cancellationToken);
}
catch (Exception)
{
if (i == retries - 1)
{
throw;
}
}
}
throw new Exception("Exceeded retry attempts.");
}
/// <summary>
/// Fetches data from an API endpoint with pagination and date filters.
/// </summary>
/// <param name="endpoint">The API endpoint.</param>
/// <param name="perPage">Number of items per page (1-100).</param>
/// <param name="before">Fetch data before this date (YYYY-MM-DDTHH:MM:SS+00:00).</param>
/// <param name="after">Fetch data after this date (YYYY-MM-DDTHH:MM:SS+00:00).</param>
/// <returns>A JSON-parsed object.</returns>
private static async Task<ResponseData<T>> GetDatedDataAsync<T>(string endpoint, int perPage = 100, string? before = null, string? after = null, CancellationToken cancellationToken = default) where T : IUpdatedAt
{
var queryParams = new Dictionary<string, string>
{
{ "pageSize", perPage.ToString() },
{ "sort", "UPDATED" }
};
cancellationToken.ThrowIfCancellationRequested();
if (!string.IsNullOrEmpty(before))
{
queryParams.Add("before", before);
}
if (!string.IsNullOrEmpty(after))
{
queryParams.Add("after", after);
}
if (endpoint == MapsEndpoint)
{
queryParams.Add("automapper", "true");
}
var queryString = new FormUrlEncodedContent(queryParams).ReadAsStringAsync(cancellationToken).Result;
var url = $"{endpoint}?{queryString}";
return await GetJsonAsync<ResponseData<T>>(url, 3, cancellationToken);
}
/// <summary>
/// Fetches all data from an API endpoint after a specified date.
/// </summary>
/// <param name="endpoint">The API endpoint.</param>
/// <param name="after">Fetch data more recent than this date (YYYY-MM-DDTHH:MM:SS+00:00).</param>
/// <returns>A list of items.</returns>
private static async Task<List<T>> GetAllDatedDataAfterAsync<T>(string endpoint, string? after = null, CancellationToken cancellationToken = default) where T : IUpdatedAt
{
cancellationToken.ThrowIfCancellationRequested();
var items = new List<T>();
await GetAllDatedDataAfterAsync<T>(endpoint, async (data, pageEnd, cancellationToken) => await Task.Run(() =>
{
cancellationToken.ThrowIfCancellationRequested();
items.Add(data);
}), after, cancellationToken);
return items;
}
/// <summary>
/// Fetches all data from an API endpoint after a specified date.
/// </summary>
/// <param name="callback">A callback called after each item is fetched.</param>
/// <param name="endpoint">The API endpoint.</param>
/// <param name="after">Fetch data more recent than this date (YYYY-MM-DDTHH:MM:SS+00:00).</param>
/// <returns></returns>
private static async Task GetAllDatedDataAfterAsync<T>(string endpoint, DataCallback<T> callback, string? after = null, CancellationToken cancellationToken = default) where T : IUpdatedAt
{
cancellationToken.ThrowIfCancellationRequested();
DateTimeOffset? lastDate = null;
DateTimeOffset? parsedAfter = after != null ? DateTime.Parse(after) : null;
while (!cancellationToken.IsCancellationRequested)
{
var data = await GetDatedDataAsync<T>(endpoint, 100, lastDate?.ToUniversalTime().ToString(ApiDateFormat, CultureInfo.InvariantCulture), after, cancellationToken);
if (data.Docs.Count == 0)
{
break;
}
var items = data.Docs.Select((doc, index) => (doc, index)).ToArray();
foreach (var item in items)
{
cancellationToken.ThrowIfCancellationRequested();
if (after != null && item.doc.UpdatedAt <= parsedAfter)
{
break;
}
lastDate = item.doc.UpdatedAt;
await callback(item.doc, item.index == items.Length - 1);
}
}
}
/// <summary>
/// Fetches all data from an API endpoint before a specified date.
/// </summary>
/// <param name="endpoint">The API endpoint.</param>
/// <param name="after">Fetch data more recent than this date (YYYY-MM-DDTHH:MM:SS+00:00).</param>
/// <returns>A list of items.</returns>
private static async Task<List<T>> GetAllDatedDataBeforeAsync<T>(string endpoint, string? before = null, CancellationToken cancellationToken = default) where T : IUpdatedAt
{
cancellationToken.ThrowIfCancellationRequested();
var items = new List<T>();
await GetAllDatedDataBeforeAsync<T>(endpoint, async (data, pageEnd, cancellationToken) => await Task.Run(() =>
{
cancellationToken.ThrowIfCancellationRequested();
items.Add(data);
}), before, cancellationToken);
cancellationToken.ThrowIfCancellationRequested();
return items;
}
/// <summary>
/// Fetches all data from an API endpoint before a specified date.
/// </summary>
/// <param name="callback">A callback called after each item is fetched.</param>
/// <param name="endpoint">The API endpoint.</param>
/// <param name="after">Fetch data more recent than this date (YYYY-MM-DDTHH:MM:SS+00:00).</param>
/// <returns></returns>
private static async Task GetAllDatedDataBeforeAsync<T>(string endpoint, DataCallback<T> callback, string? before = null, CancellationToken cancellationToken = default) where T : IUpdatedAt
{
cancellationToken.ThrowIfCancellationRequested();
DateTimeOffset? lastDate = before != null ? DateTime.Parse(before) : null;
while (true)
{
cancellationToken.ThrowIfCancellationRequested();
var data = await GetDatedDataAsync<T>(endpoint, 100, lastDate?.ToUniversalTime().ToString(ApiDateFormat, CultureInfo.InvariantCulture), null, cancellationToken);
if (data.Docs.Count == 0)
{
break;
}
foreach (var item in data.Docs.Select((doc, index) => (doc, index)))
{
cancellationToken.ThrowIfCancellationRequested();
lastDate = item.doc.UpdatedAt;
await callback(item.doc, item.index == data.Docs.Count - 1);
}
}
}
public static async Task<List<Playlist>> GetAllPlaylistsAfterAsync(string? after = null, CancellationToken cancellationToken = default) => await GetAllDatedDataAfterAsync<Playlist>(PlaylistsEndpoint, after, cancellationToken);
public static async Task<List<MapDetail>> GetAllMapsAfterAsync(string? after = null, CancellationToken cancellationToken = default) => await GetAllDatedDataAfterAsync<MapDetail>(MapsEndpoint, after, cancellationToken);
public static async Task GetAllPlaylistsAfterAsync(DataCallback<Playlist> callback, string? after = null, CancellationToken cancellationToken = default) => await GetAllDatedDataAfterAsync(PlaylistsEndpoint, callback, after, cancellationToken);
public static async Task GetAllMapsAfterAsync(DataCallback<MapDetail> callback, string? after = null, CancellationToken cancellationToken = default) => await GetAllDatedDataAfterAsync(MapsEndpoint, callback, after, cancellationToken);
public static async Task<List<Playlist>> GetAllPlaylistsBeforeAsync(string? before = null, CancellationToken cancellationToken = default) => await GetAllDatedDataBeforeAsync<Playlist>(PlaylistsEndpoint, before, cancellationToken);
public static async Task<List<MapDetail>> GetAllMapsBeforeAsync(string? before = null, CancellationToken cancellationToken = default) => await GetAllDatedDataBeforeAsync<MapDetail>(MapsEndpoint, before, cancellationToken);
public static async Task GetAllPlaylistsBeforeAsync(DataCallback<Playlist> callback, string? before = null, CancellationToken cancellationToken = default) => await GetAllDatedDataBeforeAsync(PlaylistsEndpoint, callback, before, cancellationToken);
public static async Task GetAllMapsBeforeAsync(DataCallback<MapDetail> callback, string? before = null, CancellationToken cancellationToken = default) => await GetAllDatedDataBeforeAsync(MapsEndpoint, callback, before, cancellationToken);
public static async Task<List<Playlist>> GetAllPlaylistsAfterAsync(DateTimeOffset? after = null, CancellationToken cancellationToken = default) => await GetAllDatedDataAfterAsync<Playlist>(PlaylistsEndpoint, after?.ToUniversalTime().ToString(ApiDateFormat, CultureInfo.InvariantCulture), cancellationToken);
public static async Task<List<MapDetail>> GetAllMapsAfterAsync(DateTimeOffset? after = null, CancellationToken cancellationToken = default) => await GetAllDatedDataAfterAsync<MapDetail>(MapsEndpoint, after?.ToUniversalTime().ToString(ApiDateFormat, CultureInfo.InvariantCulture), cancellationToken);
public static async Task GetAllPlaylistsAfterAsync(DataCallback<Playlist> callback, DateTimeOffset? after = null, CancellationToken cancellationToken = default) => await GetAllDatedDataAfterAsync(PlaylistsEndpoint, callback, after?.ToUniversalTime().ToString(ApiDateFormat, CultureInfo.InvariantCulture), cancellationToken);
public static async Task GetAllMapsAfterAsync(DataCallback<MapDetail> callback, DateTimeOffset? after = null, CancellationToken cancellationToken = default) => await GetAllDatedDataAfterAsync(MapsEndpoint, callback, after?.ToUniversalTime().ToString(ApiDateFormat, CultureInfo.InvariantCulture), cancellationToken);
public static async Task<List<Playlist>> GetAllPlaylistsBeforeAsync(DateTimeOffset? before = null, CancellationToken cancellationToken = default) => await GetAllDatedDataBeforeAsync<Playlist>(PlaylistsEndpoint, before?.ToUniversalTime().ToString(ApiDateFormat, CultureInfo.InvariantCulture), cancellationToken);
public static async Task<List<MapDetail>> GetAllMapsBeforeAsync(DateTimeOffset? before = null, CancellationToken cancellationToken = default) => await GetAllDatedDataBeforeAsync<MapDetail>(MapsEndpoint, before?.ToUniversalTime().ToString(ApiDateFormat, CultureInfo.InvariantCulture), cancellationToken);
public static async Task GetAllPlaylistsBeforeAsync(DataCallback<Playlist> callback, DateTimeOffset? before = null, CancellationToken cancellationToken = default) => await GetAllDatedDataBeforeAsync(PlaylistsEndpoint, callback, before?.ToUniversalTime().ToString(ApiDateFormat, CultureInfo.InvariantCulture), cancellationToken);
public static async Task GetAllMapsBeforeAsync(DataCallback<MapDetail> callback, DateTimeOffset? before = null, CancellationToken cancellationToken = default) => await GetAllDatedDataBeforeAsync(MapsEndpoint, callback, before?.ToUniversalTime().ToString(ApiDateFormat, CultureInfo.InvariantCulture), cancellationToken);
/// <summary>
/// Gets the details for the specified playlist.
/// </summary>
/// <param name="id">The ID of the playlist.</param>
/// <param name="page">The specific page to fetch, if omitted it will fetch all maps.</param>
/// <returns>A playlist details object.</returns>
private static async Task<PlaylistPage> GetPlaylistDetailsAsync(long id, int page, CancellationToken cancellationToken = default)
{
return await GetJsonAsync<PlaylistPage>($"https://api.beatsaver.com/playlists/id/{id}/{page}", 3, cancellationToken);
}
private static async Task<PlaylistPage> GetPlaylistDetailsAsync(long id, CancellationToken cancellationToken = default)
{
int pageNum = 0;
var playlist = await GetPlaylistDetailsAsync(id, pageNum++, cancellationToken);
if (playlist.Maps.Count == 0)
{
return playlist;
}
while (true)
{
cancellationToken.ThrowIfCancellationRequested();
var data = await GetPlaylistDetailsAsync(id, pageNum++, cancellationToken);
playlist.Maps.AddRange(data.Maps);
if (data.Maps.Count == 0)
{
break;
}
}
return playlist;
}
/// <summary>
/// Gets the details for the specified playlist.
/// </summary>
/// <param name="id">The ID of the playlist.</param>
/// <returns>A playlist details object.</returns>
public static async Task<PlaylistPage> GetPlaylistDetailsAsync(int id, CancellationToken cancellationToken = default) => await GetPlaylistDetailsAsync(id, cancellationToken);
/// <summary>
/// Gets the details for the specified playlist.
/// </summary>
/// <param name="playlist">The playlist.</param>
/// <returns>A playlist details object.</returns>
public static async Task<PlaylistPage> GetPlaylistDetailsAsync(Playlist playlist, CancellationToken cancellationToken = default) => await GetPlaylistDetailsAsync(playlist.PlaylistId, cancellationToken);
}
} |
import BaseCommand from "../../utils/structures/BaseCommand";
import DiscordClient from "../../client/client";
import { inspect } from "util";
import {
CommandInteraction,
Message,
ActionRowBuilder,
AttachmentBuilder,
ButtonBuilder,
EmbedBuilder,
ButtonStyle,
MessageActionRowComponentBuilder,
} from "discord.js";
export default class EvalCommand extends BaseCommand {
constructor() {
super("eval", "dev");
}
async run(client: DiscordClient, interaction: CommandInteraction) {
if (["534783899331461123"].includes(interaction.user.id)) {
await evaluate(client, interaction);
} else return;
}
}
async function evaluate(
client: DiscordClient,
interaction: CommandInteraction
) {
const code = interaction.options.data[0].value!.toString();
const XBtn =
new ActionRowBuilder<MessageActionRowComponentBuilder>().addComponents(
new ButtonBuilder()
.setCustomId("delete-" + interaction.user.id)
.setStyle(ButtonStyle.Primary)
.setEmoji("❌")
);
try {
const start = process.hrtime();
let evaled = code.includes("await")
? eval(`(async () => { ${code} })()`)
: eval(code);
if (evaled instanceof Promise) {
evaled = await evaled;
}
const stop = process.hrtime(start);
const response = clean(inspect(evaled));
const evmbed = new EmbedBuilder()
.setColor("#00FF00")
.setFooter({
text: `Time Taken: ${(stop[0] * 1e9 + stop[1]) / 1e6}ms`,
iconURL: client!.user!.displayAvatarURL(),
})
.setTitle("Eval")
.addFields([
{ name: `**Output:**`, value: `\`\`\`js\n${response}\n\`\`\`` },
{ name: `**Type:**`, value: typeof evaled },
]);
if (response.length <= 1024) {
await interaction.reply({
embeds: [evmbed],
components: [XBtn],
});
} else if (response.length <= 2048) {
await interaction.reply({
content: "```js\n" + response + "\n```",
components: [XBtn],
});
} else {
const output = new AttachmentBuilder(Buffer.from(response)).setName(
"output.txt"
);
await interaction.user!.send({ files: [output] });
await interaction.reply({
content: "Sent Output in DM",
components: [XBtn],
});
}
} catch (err: any) {
const errevmbed = new EmbedBuilder()
.setColor("#FF0000")
.setTitle(`ERROR`)
.setDescription(`\`\`\`xl\n${clean(err.toString())}\n\`\`\``)
.setTimestamp()
.setFooter({
text: client!.user!.username,
iconURL: client!.user!.displayAvatarURL(),
});
await interaction.reply({
embeds: [errevmbed],
components: [XBtn],
});
}
function clean(text: string) {
text = text
.replace(/`/g, `\\\`${String.fromCharCode(8203)}`)
.replace(/@/g, `@${String.fromCharCode(8203)}`)
.replace(
new RegExp(client!.token!, "gi"),
`NrzaMyOTI4MnU1NT3oDA1rTk4.pPizb1g.hELpb6PAi1Pewp3wAwVseI72Eo`
)
.replace(/interaction\.reply/g, "channel.send");
return text;
}
} |
import Button from '@/components/Button.tsx';
import { useState } from 'react';
interface Props {
text: string;
maxChars?: number;
}
const ExpandableText = ({ text, maxChars = 50 }: Props) => {
const [showMore, setShowMore] = useState(false);
const onTextCutOff = () => {
setShowMore(!showMore);
};
return (
<>
{showMore ? (
<div>{text}</div>
) : (
<div>{text.substring(0, maxChars)}</div>
)}
<Button
text={showMore ? 'Show less' : 'Show more'}
typeColor='secondary'
onClick={onTextCutOff}
></Button>
</>
);
};
export default ExpandableText; |
import os
from src.analytics.analytics_scheduler import process_conversations
from src.tests.utils import load_mogo_records
from src.utils import MongoDBClient
from src.tests.test_apis.utils import app_client
def test_process_conversations(app_client):
os.environ['ENVIRONMENT'] = 'staging'
load_mogo_records('test_analytics/test_data/collection_find_care.json',
session_file='test_analytics/test_data/session.json',
followup_care_file='test_analytics/test_data/followup.json')
process_conversations()
convo = MongoDBClient.get_convo_analytics().find_one(
{'convo_id': 'NHdfId8aDTWJcTVcDqzCqY9bJTUeK5PToNwRfCS0pRduIt2yw3'})
expected_fields = {
'convo_id': 'NHdfId8aDTWJcTVcDqzCqY9bJTUeK5PToNwRfCS0pRduIt2yw3',
'agent_reached': 'concierge_agent',
'farthest_agent_reached': 'find_care_agent',
'user_id': 'test@test.com',
'chief_complaint': 'Flatulence',
'find_care_address': 'Oslo, Norway',
'convo_created': '2024-03-10T12:02:22.607744',
'location': {
'type': 'Point',
'coordinates': [77.09980453029009, 28.421657406917817]
},
'city': 'Gurugram District',
'state': 'Haryana',
'country': 'India',
'country_code': 'IN',
'specialist': 'gastroenterologist',
'find_care_used': True,
'dx_1': 'IRRITABLE BOWEL SYNDROME (IBS)',
'dx_2': 'GASTRITIS',
'dx_3': 'GASTROENTERITIS',
'last_followup_outcome': 'all_better',
}
for key in convo.keys():
# we don't want to assert these fields
if key in ['_id', 'created', 'updated']:
continue
# Any other field should be present in the expected fields
if key in expected_fields:
assert convo[key] == expected_fields[key]
else:
assert False, f"Unexpected field found in convo: {key}. Update the test case accordingly" |
import React from 'react';
import { useState } from 'react';
import Modal from './modal';
import "./modal.css"
import { Navbar } from '../../components/Navbar/Navbar';
import { Contact } from '../../components/Contact/Contact';
const ModalTest = () => {
const [showModalPopup, setshowModalPopup] = useState(false);
function handleToogleModelPopup() {
setshowModalPopup(!showModalPopup)
}
function onClose() {
setshowModalPopup(false)
}
return (
<>
<Navbar />
<div className="layout">
<div className="topsection">
<div className="btnsection">
<button className="modalbtn" onClick={handleToogleModelPopup}>
Open Modal popup
</button>
{showModalPopup && (
<Modal onClose={onClose} body={<div> Customized Body</div>} />
)}
</div>
</div>
</div>
<Contact/>
</>
);
}
export default ModalTest; |
The sizes of the standard integer types are not fixed by the standard. It's perfectly legal to for instance have an implementation where both `long` and `int` are 32 bits.
What _do_ we know about the sizes of `long` and `int` though?
§[basic.fundamental]¶2 in the standard:
> There are five standard signed integer types : “`signed char`”, “`short int`”, “`int`”, “`long int`”, and “`long long int`”. In this list, each type provides at least as much storage as those preceding it in the list. (...) Plain ints have the natural size suggested by the architecture of the execution environment <sup>47</sup> ; the other signed integer types are provided to meet special needs.
So we know that `long` is at least as big as `int`. But how big is an int? Here's footnote 47:
> `int` must also be large enough to contain any value in the range `[INT_MIN, INT_MAX]`, as defined in the header `<climits>`.
The `<climits>` header is discussed in §[climits.syn]:
> (...)
> `#define INT_MIN` _see below_
> `#define INT_MAX` _see below_
> (...)
> The header `<climits>` defines all macros the same as the C standard library header `<limits.h>`
So it turns out we actually have to go to the C standard to find the answer! And the C standard defines `INT_MIN` and `INT_MAX` to at least have magnitudes −(2<sup>15</sup>−1) and 2<sup>15</sup>−1, i.e. `int` has to be at least 16 bits. For `long`, the minimum magnitudes are −(2<sup>31</sup>−1) and 2<sup>31</sup>−1, i.e. 32 bits. But it's perfectly legal for them both to be 32 bits.
Luckily, in C++20, the minimum widths of integer types will be defined in the actual C++ standard. |
from typing import List, Dict
from fastapi import APIRouter
from starlette.responses import JSONResponse
from Homework_6.database import orders_table, database
from Homework_6.models import Order, OrderIn
router = APIRouter()
async def check_order(order_id: int):
query = orders_table.select().where(orders_table.c.id == order_id)
return await database.fetch_one(query)
@router.get('/get_all_orders/', response_model=List[Order], tags=["orders"])
async def get_all_orders():
query = orders_table.select()
return await database.fetch_all(query)
@router.get('/get_order/{order_id}', response_model=Order | Dict, tags=["orders"])
async def get_order(order_id: int):
query = orders_table.select().where(orders_table.c.id == order_id)
result = await database.fetch_one(query)
if result:
return result
return JSONResponse(status_code=404, content={'error': 'Order Not Found'})
@router.post('/add_order/', response_model=Order, tags=["orders"])
async def add_order(order: Order):
query = orders_table.insert().values(**order.model_dump())
last_record_id = await database.execute(query)
return {**order.model_dump(), "id": last_record_id}
@router.put('/update_order/{order_id}', response_model=Order, tags=["orders"])
async def update_order(new_order: OrderIn, order_id: int):
if not check_order(order_id):
return JSONResponse(status_code=404, content={'error': 'Order Not Found'})
query = orders_table.update().where(orders_table.c.id == order_id).values(**new_order.model_dump())
await database.execute(query)
return {**new_order.model_dump(), "id": order_id}
@router.delete('/delete_order/{order_id}', tags=["orders"])
async def delete_order(order_id: int):
if not check_order(order_id):
return JSONResponse(status_code=404, content={'error': 'Order Not Found'})
query = orders_table.delete().where(orders_table.c.id == order_id)
await database.execute(query)
return {"message": "Product deleted"} |
'''
Given a string s, reverse the order of characters in each word within a sentence while still preserving whitespace and the initial word order.
Example 1:
Input: s = "Let's take LeetCode contest"
Output: "s'teL ekat edoCteeL tsetnoc"
Example 2:
Input: s = "Hello World"
Output: "olleH dlroW"
Example 3:
Input: s = "Python is fun"
Output: "nohtyP si nuf"
Constraints:
1 <= s.length <= 5 * 10^4
s contains printable ASCII characters.
s does not contain any leading or trailing spaces.
There is at least one word in s.
All the words in s are separated by a single space.
'''
#faster much better way
def individualReverse(word):
return word[::-1]
def wordReverse(s):
s=s.strip()
words=s.split(' ')
reversed_words=[]
for word in words:
reversed_words.append(individualReverse(word))
return ' '.join(reversed_words)
s=" hello this is it"
print(wordReverse(s))
'''
def individualReverse(word):
return word[::-1]
def wordReverse(s):
s=s.strip()
n=len(s)
NewS=""
left=0
right=0
while right<n:
if s[right]!= " ":
right+=1
else:
NewS+=individualReverse(s[left:right])
NewS+=" "
right+=1
left=right
NewS+=individualReverse(s[left:right])
return NewS
s=" Hello this is It"
print(wordReverse(s))
''' |
package com.spring.rest.model;
import java.util.Set;
import java.util.UUID;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import jakarta.persistence.CascadeType;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.FetchType;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.Id;
import jakarta.persistence.OneToMany;
import jakarta.persistence.Table;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.ToString;
@Entity
@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor
@ToString
@Table(name = "roles")
public class Role {
@Id
@GeneratedValue
private UUID roleId;
@Column(unique = true, nullable = false)
private String roleName;
@OneToMany(mappedBy = "role", cascade = CascadeType.ALL, fetch = FetchType.EAGER)
@JsonIgnoreProperties("role")
private Set<User> users;
public Role(String roleName) {
super();
this.roleName = roleName;
}
} |
#[cfg(feature = "cargo")]
mod test_build {
use anyhow::Result;
use cargo_metadata::DependencyKind;
use lazy_static::lazy_static;
use regex::Regex;
use std::env;
use vergen::EmitBuilder;
lazy_static! {
static ref CARGO_DEBUG_RE_STR: &'static str =
r"cargo:rustc-env=VERGEN_CARGO_DEBUG=(true|false)";
static ref CARGO_FEA_RE_STR: &'static str =
r"cargo:rustc-env=VERGEN_CARGO_FEATURES=[a-zA-Z0-9-_]+,[a-zA-Z0-9-_]+";
static ref CARGO_OPT_LEVEL_RE_STR: &'static str =
r"cargo:rustc-env=VERGEN_CARGO_OPT_LEVEL=\d{1}";
static ref CARGO_TT_RE_STR: &'static str =
r"cargo:rustc-env=VERGEN_CARGO_TARGET_TRIPLE=[a-zA-Z0-9-_]+";
static ref CARGO_DEP_RE_STR: &'static str = r"cargo:rustc-env=VERGEN_CARGO_DEPENDENCIES=.*";
static ref CARGO_DEP_NAME_RE_STR: &'static str =
r"(?m)^cargo:rustc-env=VERGEN_CARGO_DEPENDENCIES=anyhow 1\.0\.[0-9]{2,}$";
static ref CARGO_DEP_DK_RE_STR: &'static str =
r"(?m)^cargo:rustc-env=VERGEN_CARGO_DEPENDENCIES=gix 0\.57\.[0-9]{1,}$";
static ref CARGO_DEP_RV_RE_STR: &'static str =
r"(?m)^cargo:rustc-env=VERGEN_CARGO_DEPENDENCIES=rustversion 1\.0\.[0-9]{2,}$";
static ref CARGO_REGEX: Regex = {
let re_str = [
*CARGO_DEBUG_RE_STR,
*CARGO_FEA_RE_STR,
*CARGO_OPT_LEVEL_RE_STR,
*CARGO_TT_RE_STR,
*CARGO_DEP_RE_STR,
]
.join("\n");
Regex::new(&re_str).unwrap()
};
static ref CARGO_REGEX_NO_DEP: Regex = {
let re_str = [
*CARGO_DEBUG_RE_STR,
*CARGO_FEA_RE_STR,
*CARGO_OPT_LEVEL_RE_STR,
*CARGO_TT_RE_STR,
]
.join("\n");
Regex::new(&re_str).unwrap()
};
static ref CARGO_REGEX_NAME: Regex = Regex::new(&CARGO_DEP_NAME_RE_STR).unwrap();
static ref CARGO_REGEX_DK: Regex = Regex::new(&CARGO_DEP_DK_RE_STR).unwrap();
static ref CARGO_REGEX_RV: Regex = Regex::new(&CARGO_DEP_RV_RE_STR).unwrap();
}
fn setup() {
env::set_var("CARGO_FEATURE_BUILD", "build");
env::set_var("CARGO_FEATURE_GIT", "git");
env::set_var("DEBUG", "true");
env::set_var("OPT_LEVEL", "1");
env::set_var("TARGET", "x86_64-unknown-linux-gnu");
}
fn teardown() {
env::remove_var("CARGO_FEATURE_BUILD");
env::remove_var("CARGO_FEATURE_GIT");
env::remove_var("DEBUG");
env::remove_var("OPT_LEVEL");
env::remove_var("TARGET");
}
const DISABLED_OUTPUT: &str = r"";
#[test]
#[serial_test::serial]
fn cargo_all_output() -> Result<()> {
setup();
let mut stdout_buf = vec![];
EmitBuilder::builder()
.all_cargo()
.emit_to(&mut stdout_buf)?;
let output = String::from_utf8_lossy(&stdout_buf);
assert!(CARGO_REGEX.is_match(&output));
teardown();
Ok(())
}
#[test]
#[serial_test::serial]
fn cargo_disabled_output() -> Result<()> {
setup();
let mut stdout_buf = vec![];
EmitBuilder::builder()
.all_cargo()
.disable_cargo()
.emit_to(&mut stdout_buf)?;
let output = String::from_utf8_lossy(&stdout_buf);
assert_eq!(DISABLED_OUTPUT, output);
teardown();
Ok(())
}
#[test]
#[serial_test::serial]
fn cargo_all_idempotent_output() -> Result<()> {
setup();
let mut stdout_buf = vec![];
EmitBuilder::builder()
.idempotent()
.all_cargo()
.emit_to(&mut stdout_buf)?;
let output = String::from_utf8_lossy(&stdout_buf);
assert!(CARGO_REGEX.is_match(&output));
teardown();
Ok(())
}
#[test]
#[serial_test::serial]
fn cargo_all_name_filter_none_output() -> Result<()> {
setup();
let mut stdout_buf = vec![];
EmitBuilder::builder()
.all_cargo()
.cargo_dependencies_name_filter(Some("blah"))
.emit_to(&mut stdout_buf)?;
let output = String::from_utf8_lossy(&stdout_buf);
assert!(CARGO_REGEX_NO_DEP.is_match(&output));
teardown();
Ok(())
}
#[test]
#[serial_test::serial]
fn cargo_all_name_filter_some_output() -> Result<()> {
setup();
let mut stdout_buf = vec![];
EmitBuilder::builder()
.all_cargo()
.cargo_dependencies_name_filter(Some("anyhow"))
.emit_to(&mut stdout_buf)?;
let output = String::from_utf8_lossy(&stdout_buf);
assert!(CARGO_REGEX.is_match(&output));
assert!(CARGO_REGEX_NAME.is_match(&output));
teardown();
Ok(())
}
#[test]
#[serial_test::serial]
fn cargo_all_dep_kind_filter_none_output() -> Result<()> {
setup();
let mut stdout_buf = vec![];
EmitBuilder::builder()
.all_cargo()
.cargo_dependencies_dep_kind_filter(Some(DependencyKind::Build))
.emit_to(&mut stdout_buf)?;
let output = String::from_utf8_lossy(&stdout_buf);
assert!(CARGO_REGEX_NO_DEP.is_match(&output));
assert!(CARGO_REGEX_RV.is_match(&output));
teardown();
Ok(())
}
#[test]
#[serial_test::serial]
fn cargo_all_dep_kind_filter_some_output() -> Result<()> {
setup();
let mut stdout_buf = vec![];
EmitBuilder::builder()
.all_cargo()
.cargo_dependencies_name_filter(Some("gix"))
.cargo_dependencies_dep_kind_filter(Some(DependencyKind::Development))
.emit_to(&mut stdout_buf)?;
let output = String::from_utf8_lossy(&stdout_buf);
assert!(CARGO_REGEX.is_match(&output));
assert!(CARGO_REGEX_DK.is_match(&output));
teardown();
Ok(())
}
} |
<template>
<div v-if="isVisible" class="notification" ref="notification">
<div v-if="notifications.length" class="notification__list">
<div
v-for="item in notifications"
:key="item.id"
@click="toggleActive(item);"
:class="{ 'active': item.isActive, 'read': item.is_read }"
class="notification__item">
<p class="notification__item-text">{{item.body}}</p>
</div>
</div>
<p v-else >Оповещений нет</p>
</div>
</template>
<script>
import axios from "axios";
export default {
name: "the-notification",
props: {
isVisible: {
type: Boolean,
required: true,
},
alertsButton: {
type: HTMLButtonElement ,
required: false,
},
},
data() {
return {
notifications: [],
}
},
methods: {
async toggleActive(item) {
try {
if (!item.is_read) {
await axios.post(`/api/not/read/${item.id}/`);
item.is_read = true;
}
item.isActive = !item.isActive;
this.notifications.push()
} catch (error) {
console.error(error);
}
},
closeOnOutsideClick(event) {
const notification = this.$refs.notification
if(notification && !notification.contains(event.target) && !this.alertsButton.contains(event.target)) {
this.$emit('close-notification');
}
},
async getNotifications() {
try {
const response = await axios.get('/api/not/notes/')
this.notifications = response.data.reverse()
} catch (error) {
console.log(error)
}
}
},
mounted() {
if(localStorage.getItem('isAuthorization') !== null) {
this.getNotifications()
}
document.addEventListener('click', this.closeOnOutsideClick);
},
beforeDestroy() {
document.removeEventListener('click', this.closeOnOutsideClick);
}
}
</script> |
/**
* Try
* @returns boolean
*/
function same(arr1, arr2) {
var hasValueCnt = 0;
var tmp1 = arr1.sort((a, b) => b - a); // o(n)
var tmp2 = arr2.sort((a, b) => b - a); // o(n)
for (var i = 0; i < tmp1.length; i++) {
if (tmp2[i] === tmp1[i] * tmp1[i]) {
hasValueCnt++;
}
}
return hasValueCnt === arr1.length;
}
// console.log(same([1, 2, 3], [4, 1, 9]));
// console.log(same([1, 2, 3], [1, 9]));
// console.log(same([1, 2, 1], [4, 4, 1]));
/**
* First example
*/
function same2(arr1, arr2) {
if (arr1.length !== arr2.length) {
return false;
}
// O(n**2)
for (let i = 0; i < arr1.length; i++) {
// O(n)
let correctIndex = arr2.indexOf(arr1[i] ** 2); // O(n)
if (correctIndex === -1) {
return false;
}
// slice: begin 부터, end 까지 새로운 배열을 반환 (원본 유지)
// splice: 지정된 index 에서 두번째 arg 길이만큼 삭제 (원본 변경)
arr2.splice(correctIndex, 1);
}
return true;
}
// console.log(same2([1, 2, 3, 2], [9, 1, 4, 4]));
// console.log(same2([1, 2, 3], [4, 1, 9]));
// console.log(same2([1, 2, 3], [1, 9]));
// console.log(same2([1, 2, 1], [4, 4, 1]));
/**
* Refactored
*/
function same3(arr1, arr2) {
if (arr1.length !== arr2.length) {
return false;
}
let frequencyCounter1 = {};
let frequencyCounter2 = {};
// O(n)
for (let val of arr1) {
frequencyCounter1[val] = (frequencyCounter1[val] || 0) + 1;
}
// O(n)
for (let val of arr2) {
frequencyCounter2[val] = frequencyCounter2[val || 0] + 1;
}
for (let key in frequencyCounter1) {
// O(1)
// in {} key 여부를 확인한다
if (!(key ** 2 in frequencyCounter2)) {
return false;
}
// value 값을 확인한다
if (frequencyCounter2[key ** 2] !== frequencyCounter1[key]) {
return false;
}
}
return true;
}
console.log(same3([1, 2, 3, 2, 5], [9, 1, 4, 4, 25])); |
import { Column, CreateDateColumn, DeleteDateColumn, Entity, JoinColumn, ManyToOne, PrimaryGeneratedColumn, UpdateDateColumn } from "typeorm";
@Entity({ name: 'categories' })
export class Category {
@PrimaryGeneratedColumn({ name: 'id' })
public readonly id: number;
@Column({ name: 'name' })
public name: string;
@Column({ name: 'banner' })
public banner: string;
@Column({ name: 'app_logo' })
public appLogo: string;
@Column({ name: 'parent_id', select: false })
public parentId: number;
@ManyToOne(() => Category)
@JoinColumn({ name: 'parent_id' })
public parentCategory: Category;
@CreateDateColumn({ name: 'created_at' })
public createdAt: Date;
@UpdateDateColumn({ name: 'updated_at', select: false })
public updatedAt: Date;
@DeleteDateColumn({ name: 'deleted_at', select: false })
public deleteAt: Date;
static create(data: Partial<Category>): Category {
return Object.assign(new Category(), data);
}
} |
import {
faHeart as faHeartSolid,
faCircleUser,
} from "@fortawesome/free-solid-svg-icons"
import { useEffect, useState } from "react"
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"
import api from "../services/api"
import ModifyOrUpdate from "./ModifyOrUpdate"
const formatterDate = (date) => {
return (date = new Date(date).toLocaleString())
}
const CommentaireListe = ({ utilisateurId, sujetId }) => {
const [commentaires, setCommentaires] = useState([])
const [apiError, setApiError] = useState(null)
if (!sujetId) {
sujetId = 1
}
useEffect(() => {
api
.get(`/sujets/${sujetId}/commentaires`)
.then((response) => setCommentaires(response.data))
.catch((error) =>
setApiError(error.response ? error.response.data.error : error.message)
)
}, [sujetId])
function liker(commentaire) {
const commentaireId = commentaire.id
api.post(`likes/commentaire`, { utilisateurId, commentaireId })
location.reload()
}
return (
<ul>
{commentaires.map((commentaire) => (
<li key={commentaire.id} className=" mb-3">
<div>
<ModifyOrUpdate commentaire={commentaire} />
</div>
<div>
<div className="p-4 flex flex-row justify-between bg-gray-50 w-full rounded-lg break-words">
<div className="flex flex-col justify-start text-center align-center w-[75px]">
<span className="text-xl mb-2">
<FontAwesomeIcon icon={faCircleUser} />
</span>
<p className="text-md text-indigo-600 font-medium">
{commentaire.auteur}
</p>
</div>
<p className="bg-gray-100 mx-2 p-5 flex-1 rounded-lg w-[600px]">
{commentaire.contenu}
</p>
<span onClick={() => liker(commentaire)}>
<FontAwesomeIcon
icon={faHeartSolid}
className="text-2xl text-lg px-1 text-indigo-600"
title="J'aime"
/>
</span>
<p className="font-bold text-indigo-600">
{commentaire.totalLikes}
</p>
</div>
<p className="text-[0.6em] text-right">
{formatterDate(commentaire.dateCreation)}
</p>
</div>
</li>
))}
</ul>
)
}
export default CommentaireListe |
package com.spit.tph.nike_mvp.utils;
import android.app.Application;
import android.content.Context;
import android.graphics.Color;
import android.graphics.drawable.GradientDrawable;
import android.view.Gravity;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
/**
* Created by ABC on 2019/11/1.
*/
public class ToastUtil {
private static Toast mToast;
/**
* 传入文字
* */
public static void show(Context context , String text){
if (mToast == null){
mToast = Toast.makeText(context, text, Toast.LENGTH_SHORT);
}else {
//如果当前Toast没有消失, 直接显示内容,不需要重新设置
mToast.setText(text);
}
mToast.setGravity(Gravity.BOTTOM , 0 , 30);
// 获取Toast的布局
View toastView = mToast.getView();
// 创建ShapeDrawable并设置圆角
GradientDrawable shapeDrawable = new GradientDrawable();
// 设置圆角半径,根据需要进行调整
shapeDrawable.setCornerRadius(30);
// 设置背景颜色
shapeDrawable.setColor(Color.BLACK);
// 设置ShapeDrawable作为背景
toastView.setBackground(shapeDrawable);
// 获取文本视图
TextView toastText = toastView.findViewById(android.R.id.message);
// 修改文本颜色
toastText.setTextColor(Color.WHITE);
mToast.show();
}
/**
* 传入资源文件
* */
public static void show(Context context, int resId){
if (mToast == null){
mToast = Toast.makeText( context, resId , Toast.LENGTH_SHORT);
}else {
//如果当前Toast没有消失, 直接显示内容,不需要重新设置
mToast.setText(resId);
}
mToast.show();
}
/**
* 传入文字,在中间显示
* */
public static void showCenter( Context context , String text){
if (mToast == null){
mToast = Toast.makeText( context, text , Toast.LENGTH_SHORT);
}else {
//如果当前Toast没有消失, 直接显示内容,不需要重新设置
mToast.setText(text);
}
mToast.setGravity(Gravity.CENTER , 0 , 0);
mToast.show();
}
/**
* 传入文字,带图片
* */
public static void showImg( Context context , String text , int resImg){
if (mToast == null){
mToast = Toast.makeText( context, text , Toast.LENGTH_SHORT);
}else {
//如果当前Toast没有消失, 直接显示内容,不需要重新设置
mToast.setText(text);
}
//添加图片的操作,这里没有设置图片和文字显示在一行的操作呢...
LinearLayout view = (LinearLayout) mToast.getView();
ImageView imageView = new ImageView(context);
imageView.setImageResource(resImg);
view.addView(imageView);
mToast.show();
}
} |
package net.codejava.config;
import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
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.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import net.codejava.CustomUserDetailsService;
@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private DataSource dataSource;
@Bean
public UserDetailsService userDetailsService() {
return new CustomUserDetailsService();
}
@Bean
public BCryptPasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
@Bean
public DaoAuthenticationProvider authenticationProvider() {
DaoAuthenticationProvider authProvider = new DaoAuthenticationProvider();
authProvider.setUserDetailsService(userDetailsService());
authProvider.setPasswordEncoder(passwordEncoder());
return authProvider;
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.authenticationProvider(authenticationProvider());
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/list_users").authenticated()
.anyRequest().permitAll()
.and()
.formLogin()
.loginPage("/signin") //登入的頁面,預設是login
// .loginProcessingUrl("/signin") //登入form中action的地址,也就是處理認證請求的路徑
.usernameParameter("userEmail") //帳號input的name名,預設是username
.passwordParameter("userPassword") //密碼input的name名,預設是password
.defaultSuccessUrl("/list_users")
.permitAll()
.and()
.logout().logoutSuccessUrl("/").permitAll();
}
} |
%% courses.cls
%% Copyright 2024 Mattéo Rossillol‑‑Laruelle.
%
% This work may be distributed and/or modified under the
% conditions of the LaTeX Project Public License, either version 1.3
% of this license or (at your option) any later version.
% The latest version of this license is in
% https://www.latex-project.org/lppl.txt
% and version 1.3c or later is part of all distributions of LaTeX
% version 2008 or later.
%
% This work has the LPPL maintenance status `maintained'.
%
% The Current Maintainer of this work is Mattéo Rossillol‑‑Laruelle.
%
% This work consists of the file courses.cls.
%
% This file is largely inspired by the work of Pierre Poinas, a student at
% ENSIMAG from 2022 to 2025.
\NeedsTeXFormat{LaTeX2e}
\ProvidesClass{courses}[My LaTeX class for courses at ENSIMAG]
\LoadClass[a4paper]{article}
% Font configuration
%% need to be loaded before `unicode-math`
\RequirePackage{amsmath}
\RequirePackage{amssymb}
\RequirePackage{mathtools}
\RequirePackage{fontspec}
\RequirePackage[math-style = french, bold-style = ISO]{unicode-math}
\setmathfont{NewCMMath-Regular.otf}
% Main packages
\RequirePackage[french, strings = unicode]{babel} % localization
\RequirePackage{csquotes} % for `\enquote` command
\RequirePackage[useregional]{datetime2} % better date formatting
\RequirePackage{fancyhdr} % better header
\RequirePackage{icomma} % fix comma space
\RequirePackage[
top = 2cm,
bottom = 2cm,
left = 2cm,
right = 2cm,
headheight = 18pt
]{geometry}
\RequirePackage[hidelinks]{hyperref}
\RequirePackage[most]{tcolorbox}
\RequirePackage{titlesec}
\RequirePackage{tocloft} % for spacing in TOC
\RequirePackage[svgnames, table]{xcolor}
% Additionnal packages
\RequirePackage{enumitem} % better `enumerate`, `itemize`, etc.
\RequirePackage{multicol}
\RequirePackage{nicefrac}
\RequirePackage[arrowdel]{physics}
\RequirePackage{siunitx} % for SI units
\RequirePackage{stmaryrd}
\RequirePackage{svg}
\RequirePackage{tabularx}
\RequirePackage{tikz} % for drawing
% Some command overrides
\renewcommand{\maketitle}{
\makeatletter
\pagestyle{fancy}
\fancyhead[L]{Mattéo R.--L.}
\fancyhead[C]{\@title}
\fancyhead[R]{ENSIMAG 1A}
\begin{center}
\color{Navy} \fontsize{35pt}{12pt} \textbf{\@title} \\
\vspace{10pt}
\color{Black} \fontsize{18pt}{12pt} \textbf{\@author}
\end{center}
\makeatother
\newpage
\tableofcontents
\newpage
}
%% Section headers
\renewcommand{\thesection}{\Roman{section}}
\renewcommand{\thesubsection}{\arabic{subsection}}
\renewcommand{\thesubsubsection}{\alph{subsubsection}}
% New commands
\newcommand{\mydef}[1]{\textcolor{red}{\text{#1}}}
\newcommand{\myimp}[1]{\textcolor{teal}{\text{#1}}}
\newcommand{\newday}[1]{Début du cours du \textcolor{teal}{\DTMdate{#1}}.}
\newcommand{\myand}{\text{ et }}
\newcommand{\myor}{\text{ ou }}
%% Bitwise operators
\newcommand{\notb}{\overline}
\newcommand{\xor}{\oplus}
\newcommand{\xnor}{\notb{\oplus}}
\newcommand{\nand}{\notb{\cdot}}
\newcommand{\nor}{\notb{+}}
% `amsmath`
\DeclareMathOperator{\naturalset}{\mathbb{N}}
\DeclareMathOperator{\realset}{\mathbb{R}}
% `mathtools`
\DeclarePairedDelimiter{\ceil}{\lceil}{\rceil}
\DeclarePairedDelimiter{\floor}{\lfloor}{\rfloor}
\DeclarePairedDelimiter{\iinterval}{\llbracket}{\rrbracket}
% Some `tcolorbox` definitions
%% Styles
\tcbset{
box/.style = {
before upper = {\tcbtitle\quad},
coltitle = black,
detach title,
enhanced,
fonttitle = \bfseries,
frame hidden
}
}
\tcbset{
tab/.style = {
enhanced,
fonttitle = \bfseries,
fontupper = \normalsize\sffamily,
colback = white!10!white,
colframe = red!50!black,
colbacktitle = Salmon!40!white,
coltitle = black,
center title
}
}
%% Environments
\newtcolorbox{mytabular}[2]{
tab,
tabularx* = {\renewcommand{\arraystretch}{1.5}}{#1},
#2
}
%%% `box`es
\newtcolorbox{corollary}{
box,
borderline west = {4pt}{-5pt}{purple, line cap = round},
title = \underline{Corollaire :}
}
\newtcolorbox{definition}{
box,
borderline west = {4pt}{-5pt}{red, line cap = round},
title = \underline{Définition :}
}
\newtcolorbox{lemma}{
box,
borderline west = {4pt}{-5pt}{purple, line cap = round},
title = \underline{Lemme :}
}
\newtcolorbox{method}{
box,
borderline west = {4pt}{-5pt}{blue, line cap = round},
title = \underline{Méthode :}
}
\newtcolorbox{proposal}{
box,
borderline west = {4pt}{-5pt}{green, line cap = round},
title = \underline{Proposition :}
}
\newtcolorbox{remark}{
box,
borderline west = {4pt}{-5pt}{orange, line cap = round},
title = \underline{Remarque :}
}
\newtcolorbox{reminder}{
box,
borderline west = {4pt}{-5pt}{orange, line cap = round},
title = \underline{Rappel :}
}
\newtcolorbox{theorem}{
box,
borderline west = {4pt}{-5pt}{magenta, line cap = round},
title = \underline{Théorème :}
}
%%%% `*example` `tcolorbox`es
\newtcolorbox{dexample}[1]{
box,
borderline west = {4pt}{-5pt}{black, line cap = round},
lefthand ratio = #1,
sidebyside,
sidebyside align = top seam,
title = \underline{Exemple :}
}
\newtcolorbox{example}{
box,
borderline west = {4pt}{-5pt}{black, line cap = round},
title = \underline{Exemple :}
}
% Other package setups
\setlist[itemize]{label = \bullet}
\sisetup{
locale = FR,
group-digits = integer,
group-minimum-digits = 3,
input-complex-root,
list-units = single,
per-mode = power-positive-first,
range-units = single,
retain-explicit-plus,
separate-uncertainty,
separate-uncertainty-units = single,
table-alignment-mode = format,
table-auto-round,
uncertainty-mode = separate
}
% General setup
\cftsetindents{section}{1em}{3em}
\author{Mattéo ROSSILLOL‑‑LARUELLE} |
<?php
namespace JET_ABAF\Dashboard;
#[\AllowDynamicProperties]
class Booking_Meta {
public function __construct() {
$this->apartment_post_type = jet_abaf()->settings->get( 'apartment_post_type' );
if ( $this->apartment_post_type ) {
add_action( 'add_meta_boxes_' . $this->apartment_post_type, [ $this, 'register_meta_box' ] );
add_action( 'admin_enqueue_scripts', [ $this, 'init_upcoming_bookings' ], 99 );
new Units_Manager( $this->apartment_post_type );
}
}
/**
* Register meta box.
*
* Register booking instance post type meta boxes.
*
* @since 2.0.0
* @since 3.2.0 Refactored.
*/
public function register_meta_box() {
add_meta_box(
'jet-abaf',
__( 'Upcoming Bookings', 'jet-booking' ),
[ $this, 'render_meta_box' ],
null,
'normal',
'high'
);
}
/**
* Render meta box.
*
* Render booking instance post type meta boxes.
*
* @since 2.0.0
* @since 2.5.5 Added additional `$post_id` handling.
* @since 3.2.0 Refactored. Move template body to separate file.
*/
public function render_meta_box() {
echo '<div id="jet_abaf_upcoming_bookings"></div>';
}
/**
* Initialize upcoming bookings.
*
* @since 3.2.0
*/
public function init_upcoming_bookings( $hook ) {
if ( ! in_array( $hook, [ 'post.php', 'post-new.php' ] ) ) {
return;
}
if ( $this->apartment_post_type !== get_post_type() ) {
return;
}
$ui_data = jet_abaf()->framework->get_included_module_data( 'cherry-x-vue-ui.php' );
$ui = new \CX_Vue_UI( $ui_data );
$ui->enqueue_assets();
wp_enqueue_script(
'jet-abaf-upcoming-bookings',
JET_ABAF_URL . 'assets/js/admin/upcoming-bookings.js',
[ 'cx-vue-ui', 'wp-api-fetch' ],
JET_ABAF_VERSION,
true
);
global $post;
$post_id = jet_abaf()->db->get_initial_booking_item_id( $post->ID );
$bookings = jet_abaf()->db->get_future_bookings( $post_id );
$bookings = array_map( function ( $booking ) {
$booking['check_in_date'] = date_i18n( get_option( 'date_format' ), $booking['check_in_date'] );
$booking['check_out_date'] = date_i18n( get_option( 'date_format' ), $booking['check_out_date'] );
return $booking;
}, $bookings );
wp_localize_script( 'jet-abaf-upcoming-bookings', 'JetABAFUpcomingBookingsData', [
'api' => jet_abaf()->rest_api->get_urls( false ),
'bookings' => $bookings,
'bookings_link' => add_query_arg( [ 'page' => 'jet-abaf-bookings', ], admin_url( 'admin.php' ) ),
'edit_link' => add_query_arg( [ 'post' => '%id%', 'action' => 'edit', ], admin_url( 'post.php' ) ),
] );
add_action( 'admin_footer', [ $this, 'upcoming_bookings_template' ] );
}
/**
* Load upcoming bookings template.
*
* @since 3.2.0
*/
public function upcoming_bookings_template() {
ob_start();
include JET_ABAF_PATH . 'templates/admin/post-meta/upcoming-bookings.php';
printf( '<script type="text/x-template" id="jet-abaf-upcoming-bookings">%s</script>', ob_get_clean() );
}
} |
import Shimmer from "./Shimmer";
import { useParams } from "react-router-dom";
import { useRestaurantMenu } from "../utils/customHooks";
const RestaurantMenu = () => {
const { resId } = useParams();
const resInfo = useRestaurantMenu(resId);
if (resInfo === null) {
return <Shimmer />;
}
const {
name,
cuisines: cuisineNames = [],
costForTwoMessage = "",
} = resInfo.cards[2]?.card?.card?.info;
const itemCards =
resInfo.cards[4]?.groupedCard?.cardGroupMap?.REGULAR?.cards[2]?.card?.card
?.itemCards;
return (
<div className="container mx-auto px-4 py-8">
<h1 className="text-3xl font-bold">{name}</h1>
<h3 className="text-lg text-gray-500">
{cuisineNames.join(", ")} - {costForTwoMessage}
</h3>
<h3 className="text-xl font-medium mt-4">Menu</h3>
<ul className="list-none mt-4">
{itemCards?.map((item) => (
<li
key={item.card.info.id}
className="flex justify-between border-b border-gray-200 py-2"
>
<span className="text-base font-medium">{item.card.info.name}</span>
<span className="text-base font-medium">
Rs {(item.card.info.price || item.card.info.defaultPrice) / 100}
</span>
</li>
))}
</ul>
</div>
);
};
export default RestaurantMenu; |
<template>
<div class="container">
<div class="row px-3">
<div class="card px-0">
<!-- <div class="col-lg-10 col-xl-9 card px-0"> -->
<!-- <div class="img-left d-none d-md-flex"></div> -->
<div class="card-body row m-5 pb-5">
<CardPost v-for="el in posts" :key="el.id" :post="el" />
<nav aria-label="Page navigation example">
<ul class="pagination justify-content-center">
<li v-for="n in count" :key="n" @click.prevent="pagination(n - 1)" class="page-item">
<a class="page-link" href="#">{{ n }}</a>
</li>
</ul>
</nav>
<!-- <nav aria-label="Page navigation example">
<ul class="pagination">
<li v-for="n in count" :key="n" @click.prevent="pagination(n - 1)" class="page-item">
<a class="page-link" href="#">{{ n }}</a>
</li>
</ul>
</nav> -->
<hr class="my-4" />
<div class="text-center mb-2">
This is our FOOTER
<a class="register-link">Here Is</a>
</div>
</div>
</div>
</div>
</div>
</template>
<script>
import { mapActions, mapState } from "pinia";
import postStore from "../stores/post";
import CardPost from "../components/CardPost.vue";
export default {
name: "HomePage",
data() {},
methods: {
...mapActions(postStore, ["getAllPost", "getAllPostPage"]),
pagination(n) {
this.getAllPostPage(n);
},
},
computed: {
...mapState(postStore, ["posts", "count"]),
},
created() {
this.getAllPost();
},
components: { CardPost },
};
</script>
<style scoped>
.card {
margin-top: 10vh;
overflow: hidden;
border: 0 !important;
border-radius: 20px !important;
box-shadow: 0 0.5rem 1rem 0 rgba(0, 0, 0, 0.1);
}
.img-left {
width: 45%;
background: url("../assets/hacktiv8background.png");
background-size: cover;
background-position: 50%;
}
.card-body {
padding: 2rem;
}
.title {
margin-bottom: 2rem;
}
.form-input {
position: relative;
}
.form-input input {
width: 100%;
height: 45px;
padding-left: 40px;
margin-bottom: 20px;
box-sizing: border-box;
box-shadow: none;
border: 1px solid #00000020;
border-radius: 50px;
outline: none;
background: transparent;
}
.form-input span {
position: absolute;
top: 10px;
padding-left: 15px;
color: #007bff;
}
.form-input input::placeholder {
color: black;
padding-left: 0px;
}
.form-input input:focus,
.form-input input:valid {
border: 2px solid #007bff;
}
.form-input input:focus::placeholder {
color: #454b69;
}
.form-box button[type="submit"] {
width: 100%;
margin-top: 10px;
border: none;
cursor: pointer;
border-radius: 50px;
background: #007bff;
color: #fff;
font-size: 90%;
font-weight: bold;
letter-spacing: 0.1rem;
transition: 0.5s;
padding: 12px;
}
.form-box button[type="submit"]:hover {
background: #0069d9;
}
.register-link {
color: #007bff;
font-weight: bold;
}
.register-link:hover {
color: #0069d9;
text-decoration: none;
}
.form-box .btn-social {
color: white !important;
border: 0;
font-weight: bold;
}
.form-box .btn-google {
background: #da3f34;
}
.form-box .btn-google:hover {
background: #b53f37;
}
</style> |
import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { Pais } from '../../../data/entities/pais.entity';
import { PaisReadDTO } from '../models/dto/pais.read.dto';
import { MapperService } from '../../../common/mapper/services/mapper.service';
import { PaisCreateDTO } from '../models/dto/pais.create.dto';
import { PaisEditDTO } from '../models/dto/pais.edit.dto';
@Injectable()
export class PaisService {
constructor(
@InjectRepository(Pais) private _paisRepository: Repository<Pais>,
private _mapper: MapperService,
) {}
public async getPaises(): Promise<PaisReadDTO[]> {
const paisesDB = await this._paisRepository.find();
if (paisesDB) {
const paisesDTO = this._mapper.toArrayDTO<PaisReadDTO>(
paisesDB,
PaisReadDTO,
);
return paisesDTO;
}
return null;
}
public async getOne(id: number): Promise<PaisReadDTO> {
const paisDB = await this._paisRepository.findOne({ id });
if (paisDB) return this._mapper.toDTO<PaisReadDTO>(paisDB, PaisReadDTO);
return null;
}
public async createOne(pais: PaisCreateDTO): Promise<PaisReadDTO> {
try {
const paisEntity = this._paisRepository.create(pais);
const paisDB = await this._paisRepository.save(paisEntity);
if (paisDB) return this._mapper.toDTO<PaisReadDTO>(paisDB, PaisReadDTO);
return null;
} catch (error) {
return null;
}
}
public async updateOne(pais: PaisEditDTO, id: number): Promise<PaisEditDTO> {
const paisDB = await this.getOne(id);
if (paisDB) {
const paisUpdated = await this._paisRepository.update(paisDB.id, pais);
return paisUpdated.affected > 0 ? pais : null;
}
return null;
}
public async deleteOne(id: number): Promise<number> {
const paisDB = await this.getOne(id);
if (paisDB) {
const deleted = await this._paisRepository.delete(id);
return deleted.affected > 0 ? id : 0;
}
return -1;
}
} |
// SPDX-License-Identifier: GPL-3.0-or-later
// Copyright 2019 Juan Palacios <jpalaciosdev@gmail.com>
#pragma once
#include "exportable.h"
#include "importable.h"
#include "iprofilepartxmlparser.h"
#include <functional>
#include <memory>
#include <optional>
#include <pugixml.hpp>
#include <string>
#include <string_view>
#include <vector>
class Item;
class IProfilePartXMLParserProvider;
class ProfilePartXMLParser : public IProfilePartXMLParser
{
public:
ProfilePartXMLParser(std::string_view id,
Importable::Importer &profilePartImporter,
Exportable::Exporter &profilePartExporter) noexcept;
std::string const &ID() const final override;
void loadFrom(pugi::xml_node const &parentNode) final override;
Importable::Importer &profilePartImporter() const final override;
Exportable::Exporter &profilePartExporter() const final override;
class Factory
{
public:
Factory(IProfilePartXMLParserProvider const &profilePartParserProvider) noexcept;
std::optional<std::reference_wrapper<Exportable::Exporter>>
factory(Item const &i);
virtual void takePartParser(Item const &i,
std::unique_ptr<IProfilePartXMLParser> &&part) = 0;
virtual ~Factory() = default;
private:
std::unique_ptr<IProfilePartXMLParser>
createPartParser(std::string const &componentID) const;
IProfilePartXMLParserProvider const &profilePartParserProvider_;
std::vector<std::unique_ptr<Exportable::Exporter>> factories_;
};
protected:
virtual void resetAttributes() = 0;
virtual void loadPartFrom(pugi::xml_node const &parentNode) = 0;
private:
std::string const id_;
Importable::Importer &importer_;
Exportable::Exporter &exporter_;
}; |
#include<iostream>
#include<stack>
using namespace std;
class node
{
public:
char data;
node *left, *right;
friend class bintree;
node() : left(nullptr), right(nullptr) {}
};
class bintree
{
public:
node *root;
bintree() : root(nullptr) {}
void create_bintree();
void inorder_traversal();
void preorder_traversal();
void postorder_traversal();
void preorder_nonrec();
void inorder_nonrec();
void postorder_nonrec();
private:
void inorder_traversal_recursive(node* root);
void preorder_traversal_recursive(node* root);
void postorder_traversal_recursive(node* root);
};
void bintree::create_bintree()
{
root = new node();
cout << "Enter root data: ";
cin >> root->data;
root->left = root->right = nullptr;
stack<node*> s;
s.push(root);
while (!s.empty())
{
node *temp = s.top();
s.pop();
char choice;
cout << "Do you want to add left child for " << temp->data << " (y/n)? ";
cin >> choice;
if (choice == 'y')
{
node *leftChild = new node();
cout << "Enter left child data for " << temp->data << ": ";
cin >> leftChild->data;
leftChild->left = leftChild->right = nullptr;
temp->left = leftChild;
s.push(leftChild);
}
cout << "Do you want to add right child for " << temp->data << " (y/n)? ";
cin >> choice;
if (choice == 'y')
{
node *rightChild = new node();
cout << "Enter right child data for " << temp->data << ": ";
cin >> rightChild->data;
rightChild->left = rightChild->right = nullptr;
temp->right = rightChild;
s.push(rightChild);
}
}
}
void bintree::inorder_traversal()
{
inorder_traversal_recursive(root);
cout << endl;
}
void bintree::preorder_traversal()
{
preorder_traversal_recursive(root);
cout << endl;
}
void bintree::postorder_traversal()
{
postorder_traversal_recursive(root);
cout << endl;
}
void bintree::inorder_nonrec()
{
std::stack<node*> s;
node *temp = root;
while (temp != nullptr || !s.empty())
{
while (temp != nullptr)
{
s.push(temp);
temp = temp->left;
}
temp = s.top();
s.pop();
cout << temp->data << " ";
temp = temp->right;
}
}
void bintree::preorder_nonrec()
{
std::stack<node*> s;
node *temp = root;
while (temp != nullptr || !s.empty())
{
while (temp != nullptr)
{
cout << temp->data << " ";
s.push(temp);
temp = temp->left;
}
if (!s.empty())
{
temp = s.top();
s.pop();
temp = temp->right;
}
}
}
void bintree::postorder_nonrec() {
std::stack<node*> s;
node *temp = root;
node *lastVisited = nullptr;
while (temp != nullptr || !s.empty()) {
while (temp != nullptr) {
s.push(temp);
temp = temp->left;
}
node *topNode = s.top();
if (topNode->right == nullptr || topNode->right == lastVisited) {
cout << topNode->data << " ";
lastVisited = topNode;
s.pop();
} else {
temp = topNode->right;
}
}
}
void bintree::inorder_traversal_recursive(node* root)
{
if (root == nullptr)
return;
inorder_traversal_recursive(root->left);
cout << root->data << " ";
inorder_traversal_recursive(root->right);
}
void bintree::preorder_traversal_recursive(node* root)
{
if (root == nullptr)
return;
cout << root->data << " ";
preorder_traversal_recursive(root->left);
preorder_traversal_recursive(root->right);
}
void bintree::postorder_traversal_recursive(node* root)
{
if (root == nullptr)
return;
postorder_traversal_recursive(root->left);
postorder_traversal_recursive(root->right);
cout << root->data << " ";
}
int main()
{
char choice;
bintree t;
bool treeCreated = false;
do {
cout << "\nChoose an operation:" << endl;
cout << "1. Create binary tree" << endl;
cout << "2. In-order traversal" << endl;
cout << "3. Pre-order traversal" << endl;
cout << "4. Post-order traversal" << endl;
cout << "5. In-order (Non rec) traversal" << endl;
cout << "6. Pre-order (Non rec) traversal" << endl;
cout << "7. Post order (Non rec) traversal" << endl;
cout << "8. Exit" << endl;
cout << "Enter your choice: ";
cin >> choice;
switch (choice)
{
case '1':
t.create_bintree();
treeCreated = true;
break;
case '2':
if (treeCreated) {
cout << "In-order traversal: ";
t.inorder_traversal();
cout << endl;
} else {
cout << "Binary tree has not been created yet. Please create a tree first." << endl;
}
break;
case '3':
if (treeCreated) {
cout << "Pre-order traversal: ";
t.preorder_traversal();
cout << endl;
} else {
cout << "Binary tree has not been created yet. Please create a tree first." << endl;
}
break;
case '4':
if (treeCreated) {
cout << "Post-order traversal: ";
t.postorder_traversal();
cout << endl;
} else {
cout << "Binary tree has not been created yet. Please create a tree first." << endl;
}
break;
case '5':
if (treeCreated) {
cout << "In-order (Non rec) traversal: ";
t.inorder_nonrec();
cout << endl;
} else {
cout << "Binary tree has not been created yet. Please create a tree first." << endl;
}
break;
case '6':
if (treeCreated) {
cout << "Pre-order (Non rec) traversal: ";
t.preorder_nonrec();
cout << endl;
} else {
cout << "Binary tree has not been created yet. Please create a tree first." << endl;
}
break;
case '7':
if (treeCreated) {
cout << "Post order (Non rec) traversal: ";
t.postorder_nonrec();
cout << endl;
} else {
cout << "Binary tree has not been created yet. Please create a tree first." << endl;
}
break;
case '8':
cout << "Exiting..." << endl;
break;
default:
cout << "Invalid choice. Please enter a valid option." << endl;
break;
}
} while (choice != '8');
return 0;
} |
import {
Box,
Table,
TableContainer,
Tbody,
Td,
Th,
Thead,
Tr,
} from '@chakra-ui/react';
import { useNavigate } from 'react-router';
import { useGetUsers } from '../hooks';
const UsersList = () => {
const { data: users, isLoading, isError } = useGetUsers();
const navigate = useNavigate();
if (isLoading) return <h1>loading user...</h1>;
if (isError) return <h1>something went wrong while loading the users</h1>;
return (
<Box>
<TableContainer>
<Table size='sm'>
<Thead>
<Tr>
<Th>Email</Th>
<Th>Name</Th>
</Tr>
</Thead>
<Tbody>
{users?.map((user) => (
<Tr
key={user.id}
onClick={() => navigate(`/users/${user.id}`)}
sx={{
cursor: 'pointer',
'&:hover': { backgroundColor: 'gray.100' },
}}
>
<Td>{user.email}</Td>
<Td sx={{ textTransform: 'capitalize' }}>
{user.name}
</Td>
</Tr>
))}
</Tbody>
</Table>
</TableContainer>
</Box>
);
};
export default UsersList; |
# FSM Consul集成测试
## 1. 下载并安装 fsm cli
```bash
system=$(uname -s | tr [:upper:] [:lower:])
arch=$(dpkg --print-architecture)
release=v1.2.11
curl -L https://github.com/cybwan/fsm/releases/download/${release}/fsm-${release}-${system}-${arch}.tar.gz | tar -vxzf -
./${system}-${arch}/fsm version
cp ./${system}-${arch}/fsm /usr/local/bin/
```
## 2.部署 Consul 服务
```bash
#部署Consul服务
export DEMO_HOME=https://raw.githubusercontent.com/flomesh-io/springboot-bookstore-demo/main
kubectl apply -n default -f $DEMO_HOME/manifests/consul.yaml
kubectl wait --all --for=condition=ready pod -n default -l app=consul --timeout=180s
POD=$(kubectl get pods --selector app=consul -n default --no-headers | grep 'Running' | awk 'NR==1{print $1}')
kubectl port-forward "$POD" -n default 8500:8500 --address 0.0.0.0
```
## 3. 安装 fsm
```bash
export fsm_namespace=fsm-system
export fsm_mesh_name=fsm
export consul_svc_addr="$(kubectl get svc -l name=consul -o jsonpath='{.items[0].spec.clusterIP}')"
echo $consul_svc_addr
fsm install \
--mesh-name "$fsm_mesh_name" \
--fsm-namespace "$fsm_namespace" \
--set=fsm.certificateProvider.kind=tresor \
--set=fsm.image.registry=cybwan \
--set=fsm.image.tag=1.2.11 \
--set=fsm.image.pullPolicy=Always \
--set=fsm.sidecarLogLevel=debug \
--set=fsm.controllerLogLevel=warn \
--set=fsm.serviceAccessMode=mixed \
--set=fsm.featureFlags.enableAutoDefaultRoute=true \
--set=clusterSet.region=LN \
--set=clusterSet.zone=DL \
--set=clusterSet.group=FLOMESH \
--set=clusterSet.name=LAB \
--set=fsm.cloudConnector.consul.enable=true \
--set=fsm.cloudConnector.consul.deriveNamespace=consul-derive \
--set=fsm.cloudConnector.consul.httpAddr=$consul_svc_addr:8500 \
--set=fsm.cloudConnector.consul.syncToK8S.enable=true \
--set=fsm.cloudConnector.consul.syncToK8S.passingOnly=false \
--set=fsm.cloudConnector.consul.syncToK8S.suffixTag=version \
--set=fsm.cloudConnector.consul.syncFromK8S.enable=true \
--set "fsm.cloudConnector.consul.syncFromK8S.denyK8sNamespaces={default,kube-system,local-path-storage,fsm-system}" \
--timeout=900s
#用于承载转义的consul k8s services 和 endpoints
kubectl create namespace consul-derive
fsm namespace add consul-derive
kubectl patch namespace consul-derive -p '{"metadata":{"annotations":{"flomesh.io/mesh-service-sync":"consul"}}}' --type=merge
```
## 4. Consul集成测试
### 4.1 启用宽松流量模式
**目的: 以便 consul 微服务之间可以相互访问**
```bash
export fsm_namespace=fsm-system
kubectl patch meshconfig fsm-mesh-config -n "$fsm_namespace" -p '{"spec":{"traffic":{"enablePermissiveTrafficPolicyMode":true}}}' --type=merge
```
### 4.2 启用外部流量宽松模式
**目的: 以便 consul 微服务可以访问 consul 服务中心**
```bash
export fsm_namespace=fsm-system
kubectl patch meshconfig fsm-mesh-config -n "$fsm_namespace" -p '{"spec":{"traffic":{"enableEgress":true}}}' --type=merge
```
### 4.3 启用访问控制策略
```bash
export fsm_namespace=fsm-system
kubectl patch meshconfig fsm-mesh-config -n "$fsm_namespace" -p '{"spec":{"featureFlags":{"enableAccessControlPolicy":true}}}' --type=merge
```
### 4.4 设置访问控制策略
**目的: 以便consul 服务中心可以访问 consul 微服务**
```bash
kubectl apply -f - <<EOF
kind: AccessControl
apiVersion: policy.flomesh.io/v1alpha1
metadata:
name: consul
namespace: consul-derive
spec:
sources:
- kind: Service
namespace: default
name: consul
EOF
```
### 4.5 部署业务 POD
```bash
#模拟业务服务
export DEMO_HOME=https://raw.githubusercontent.com/flomesh-io/springboot-bookstore-demo/main
kubectl create namespace bookwarehouse
kubectl create namespace bookstore
kubectl create namespace bookbuyer
fsm namespace add bookstore bookbuyer bookwarehouse
kubectl apply -n bookwarehouse -f $DEMO_HOME/manifests/consul/bookwarehouse-consul.yaml
kubectl wait --all --for=condition=ready pod -n bookwarehouse -l app=bookwarehouse --timeout=180s
kubectl apply -n bookstore -f $DEMO_HOME/manifests/consul/bookstore-consul.yaml
kubectl apply -n bookstore -f $DEMO_HOME/manifests/consul/bookstore-v2-consul.yaml
kubectl wait --all --for=condition=ready pod -n bookstore -l app=bookstore --timeout=180s
kubectl apply -n bookbuyer -f $DEMO_HOME/manifests/consul/bookbuyer-consul.yaml
kubectl wait --all --for=condition=ready pod -n bookbuyer -l app=bookbuyer --timeout=180s
```
### 4.6 业务端口转发
```bash
BUYER_V1_POD="$(kubectl get pods --selector app=bookbuyer,version=v1 -n bookbuyer --no-headers | grep 'Running' | awk 'NR==1{print $1}')"
STORE_V1_POD="$(kubectl get pods --selector app=bookstore,version=v1 -n bookstore --no-headers | grep 'Running' | awk 'NR==1{print $1}')"
STORE_V2_POD="$(kubectl get pods --selector app=bookstore,version=v2 -n bookstore --no-headers | grep 'Running' | awk 'NR==1{print $1}')"
kubectl port-forward $BUYER_V1_POD -n bookbuyer 8080:14001 --address 0.0.0.0 &
kubectl port-forward $STORE_V1_POD -n bookstore 8084:14001 --address 0.0.0.0 &
kubectl port-forward $STORE_V2_POD -n bookstore 8082:14001 --address 0.0.0.0 &
```
### 4.6 设置分流策略
#### 4.6.1 流量全部走bookstore-v1
```bash
kubectl apply -n consul-derive -f - <<EOF
apiVersion: split.smi-spec.io/v1alpha4
kind: TrafficSplit
metadata:
name: bookstore-split
spec:
service: bookstore
backends:
- service: bookstore-v1
weight: 100
- service: bookstore-v2
weight: 0
EOF
```
#### 4.6.2 流量全部走bookstore-v2
```bash
kubectl apply -n consul-derive -f - <<EOF
apiVersion: split.smi-spec.io/v1alpha4
kind: TrafficSplit
metadata:
name: bookstore-split
spec:
service: bookstore
backends:
- service: bookstore-v1
weight: 0
- service: bookstore-v2
weight: 100
EOF
```
#### 4.6.3 流量均分
```bash
kubectl apply -n consul-derive -f - <<EOF
apiVersion: split.smi-spec.io/v1alpha4
kind: TrafficSplit
metadata:
name: bookstore-split
spec:
service: bookstore
backends:
- service: bookstore-v1
weight: 50
- service: bookstore-v2
weight: 50
EOF
``` |
import React, { useEffect, useRef, useState } from "react";
import {
Box,
TextField,
FormControl,
InputLabel,
Select,
MenuItem,
Button,
Typography,
CircularProgress,
Link,
} from "@mui/material";
import { LoadScript } from "@react-google-maps/api";
import getDoctorsBySpeciality from "../Utility/getDoctorsBySpeciality";
import axios from "axios";
import DoctorsCard from "../DoctorsCard/DoctorsCard";
import "../../Signup/Signup.css";
import "./DoctorSearchForm.css";
function DoctorSearchForm({ addressOfUser }) {
const [isLoaded, setIsLoaded] = useState(false);
const speciality = [
{ id: 1, specialityName: "General practitioner" },
{ id: 2, specialityName: "Doctor" },
{ id: 3, specialityName: "Diabetologist" },
{ id: 4, specialityName: "Homeopath" },
{ id: 5, specialityName: "Medical clinic" },
{ id: 6, specialityName: "Pulmonologist" },
{ id: 7, specialityName: "Surgeon" },
{ id: 8, specialityName: "Dermatologist" },
{ id: 9, specialityName: "ENT Specialist" },
{ id: 10, specialityName: "Pediatrician" },
{ id: 11, specialityName: "Orthopedic surgeon" },
{ id: 12, specialityName: "Pharmacy" },
{ id: 13, specialityName: "Hospital" },
{ id: 14, specialityName: "Urology clinic" },
{ id: 15, specialityName: "Urologist" },
{ id: 16, specialityName: "Gynecologist" },
{ id: 17, specialityName: "General hospital" },
{ id: 18, specialityName: "Obstetrician-gynecologist" },
{ id: 19, specialityName: "Private hospital" },
{ id: 20, specialityName: "Psychiatrist" },
{ id: 21, specialityName: "Medical Center" },
{ id: 22, specialityName: "Occupational medical physician" },
{ id: 23, specialityName: "Medical diagnostic imaging center" },
{ id: 24, specialityName: "Endocrinologist" },
];
const [chosenSpeciality, setChosenSpeciality] = useState("");
const [chosenDistance, setChosenDistance] = useState(0);
const [show, setShow] = useState(false);
const [distanceFilteredDoctors, setDistanceFilteredDoctors] = useState([]);
const [inNetworkDocs, setInNetworkDocs] = useState([]);
const [outNetworkDocs, setOutNetworkDocs] = useState([]);
const [showDoctors, setShowDoctors] = useState(false);
const [userPlanCode, setUserPlanCode] = useState("");
const [doneFilteringByDistance, setDoneFilteringByDistance] = useState(false);
const [showLoadingIcon, setShowLoadingIcon] = useState(false);
async function getFilteredDoctors() {
setShowLoadingIcon(true);
setInNetworkDocs([]);
setOutNetworkDocs([]);
setDistanceFilteredDoctors([]);
setDoneFilteringByDistance(false);
const filteredDoctorsBySpeciality = await getDoctorsBySpeciality(
chosenSpeciality
);
if (filteredDoctorsBySpeciality.length > 0) {
console.log("calling get distances function");
await getDistances(filteredDoctorsBySpeciality);
/*const filteredByDistance = */
}
}
useEffect(() => {
if (doneFilteringByDistance) {
for (const doc of distanceFilteredDoctors) {
const docPlanCode = doc.vendor_id_map;
if (docPlanCode.includes(userPlanCode)) {
setInNetworkDocs((prevItems) => [...prevItems, doc]);
} else {
setOutNetworkDocs((prevItems) => [...prevItems, doc]);
}
}
setShowLoadingIcon(false);
setShowDoctors(true);
}
}, [doneFilteringByDistance]);
async function getUserPlanCode() {
try {
const response = await axios.get(
"https://server-nearby-doctor-production.up.railway.app/getDetails",
{
withCredentials: true,
}
);
if (response.data !== null) {
setUserPlanCode(response.data.user_plan_code);
}
} catch (err) {
console.log("Error fetching user's plan code:", err);
}
}
async function getDistances(filteredDoctorsBySpeciality) {
if (userPlanCode === "") {
await getUserPlanCode();
}
const userLat = +addressOfUser.latitude;
const userLong = +addressOfUser.longitude; // getting users latitude and longitude
for (const doc of filteredDoctorsBySpeciality) {
// for..in loop will have doc as index so using for...of where doc is each element of array
const docLat = +doc.doc_lat; // getting each doctors latitude and longitude
const docLong = +doc.doc_long;
try {
const response = await axios.get(
`http://127.0.0.1:5000/route/v1/driving/${userLong},${userLat};${docLong},${docLat}?overview=false`
);
if (response.data.code !== null && response.data.code === "Ok") {
const distanceFromUser = Math.floor(
response.data.routes[0].legs[0].distance / 1000
); // rounding to kilometers from meters
if (distanceFromUser <= chosenDistance) {
setDistanceFilteredDoctors((prevItems) => [...prevItems, doc]);
}
}
} catch (err) {
console.log("Error contacting OSRM server:", err);
}
}
setDoneFilteringByDistance(true);
}
useEffect(() => {
if (addressOfUser) setShow(true);
}, [addressOfUser]);
const onLoad = () => {
// this tells the children component USerToDoctorMap that LoadScript is loaded and ready
setIsLoaded(true);
};
return (
<div>
<Box
className="signup-box-doc-search slide-in-fade"
style={{ marginTop: "5em" }}
component="form"
sx={{ "& > :not(style)": { my: 2, mx: "auto", width: "35ch" } }}
noValidate
autoComplete="off"
>
<h1 className="noto-sans-text" style={{ marginBottom: "2em" }}>
Search doctors filtered on speciality and distance
</h1>
<FormControl fullWidth>
<InputLabel id="demo-simple-select-label">Speciality</InputLabel>
<Select
labelId="demo-simple-select-label"
id="demo-simple-select"
value={chosenSpeciality}
label="Doctor Speciality"
onChange={(e) => {
setChosenSpeciality(e.target.value);
}}
>
{speciality.map((specialityItem) => (
<MenuItem
key={specialityItem.id}
value={specialityItem.specialityName}
>
{specialityItem.specialityName}
</MenuItem>
))}
</Select>
</FormControl>
<TextField
className="noto-sans-text"
type="text"
id="outlined-basic-distance"
label="Distance (Kms)"
variant="outlined"
onChange={(e) => {
setChosenDistance(e.target.value);
}}
required
/>
{show && (
<Button
disableRipple
onClick={getFilteredDoctors}
className="button"
variant="contained"
disabled={true} // for production
>
Find nearby doctors
</Button>
)}
<Typography
style={{ textAlign: "center", opacity: "50%", width: "fit-content", display: "inline" }}
variant="body2"
className="noto-sans-text"
>
*The search functionality has been disabled in Production as it is
heavily data-dependent and requires OSRM Docker images to be run on
the cloud, which would require a paid commercial setup. However, you
can watch our video demo{" "}
<a
href="https://youtu.be/j8WYotfl5e4"
target="_blank"
rel="noopener noreferrer"
style={{ color: "blue", textDecoration: "underline" }}
>
here
</a>
.
</Typography>
{showLoadingIcon && (
<CircularProgress size={80} style={{ margin: "0 45%" }} />
)}
</Box>
{/*Since LoadScript can be loaded only once,
Added LoadScript here as the UserToDoctorMap would load it multiple times on each call and that would throw an error*/}
<LoadScript
googleMapsApiKey={import.meta.env.VITE_GOOGLE_API_KEY}
onLoad={onLoad}
>
<Box className="doctors-cards" sx={{ "& > :not(style)": { my: 2 } }}>
{showDoctors && (
<Typography
style={{ fontWeight: "bold" }}
variant="h5"
className="noto-sans-text"
>
In-Network Doctors
</Typography>
)}
{showDoctors &&
inNetworkDocs.map((doctor) => (
<DoctorsCard
key={doctor.doctorid}
doctors={doctor}
userAddr={addressOfUser}
isLoaded={isLoaded}
/>
))}
{showDoctors && (
<Typography
style={{ fontWeight: "bold" }}
variant="h5"
className="noto-sans-text"
>
Out-Network Doctors
</Typography>
)}
{showDoctors &&
outNetworkDocs.map((doctor) => (
<DoctorsCard
key={doctor.doctorid}
doctors={doctor}
userAddr={addressOfUser}
isLoaded={isLoaded}
/>
))}
</Box>
</LoadScript>
</div>
);
}
export default DoctorSearchForm; |
import { useState, useEffect } from 'react';
import localStorageSetup from '@/utils/localStorageSetup';
import { setDataAttributes } from '@/utils/dom';
function useTheme() {
const themeStorage = localStorageSetup('theme');
const fontStorage = localStorageSetup('font');
const [theme, setTheme] = useState('');
const [font, setFont] = useState('');
useEffect(() => {
const currentTheme = themeStorage.get() || 'light';
const currentFont = fontStorage.get() || 'Inter';
setTheme(currentTheme);
setFont(currentFont);
setDataAttributes(currentTheme, currentFont);
}, []);
useEffect(() => {
themeStorage.set(theme);
document.documentElement.setAttribute('data-theme', theme);
}, [theme]);
useEffect(() => {
fontStorage.set(font);
document.documentElement.setAttribute('data-font', font);
}, [font]);
return { theme, font, setTheme, setFont };
}
export default useTheme; |
import numpy as np
import sys
import re
from collections import defaultdict
sys.setrecursionlimit(100000)
G = [l.strip() for l in open("./input.txt").readlines()]
G = [re.sub(r"[<^>v]", ".", l) for l in G]
SRC = (1, 1)
DST = (len(G) - 2, len(G[0]) - 2)
W = len(G[0])
H = len(G)
# return manhattan neighbors (U, D, L, R) for a given square
def mnh_nbrs(r, c):
d = [(-1, 0), (1, 0), (0, -1), (0, 1)]
return [(r + dr, c + dc) for dr, dc in d if 0 <= r + dr < H and 0 <= c + dc < W]
def walk_edges(edge_squares, node_squares):
edges = []
while len(edge_squares):
q = [list(edge_squares)[0]]
dist = 0
endpoints = []
while len(q):
r, c = q.pop(0)
edge_squares.remove((r, c))
dist += 1
for nr, nc in mnh_nbrs(r, c):
if (nr, nc) in edge_squares:
q.append((nr, nc))
elif (nr, nc) in node_squares:
endpoints.append((nr, nc))
if len(endpoints) == 2:
edges.append((endpoints[0], endpoints[1], dist))
return edges
# build a simplified graph by collapsing long branch-less paths
# and removing dead-ends
def build_graph():
node_squares = set()
edge_squares = set()
for r, c in [s for s in np.ndindex(H, W) if G[s[0]][s[1]] != "#"]:
if G[r][c] == "#":
continue
nbr_cnt = len([1 for nr, nc in mnh_nbrs(r, c) if G[nr][nc] != "#"])
if nbr_cnt > 2:
node_squares.add((r, c))
else:
edge_squares.add((r, c))
# walk edges to create pairs of connected nodes
edges = walk_edges(edge_squares, node_squares)
graph = defaultdict(list)
for src_node, dst_node, distance in edges:
graph[src_node].append((dst_node, distance))
graph[dst_node].append((src_node, distance))
return graph
# recursively explore paths from start to end node, saving longest
def solve(src, dst):
graph = build_graph()
vis = {k: 0 for k in graph.keys()}
lp = {k: 0 for k in graph.keys()}
def _solve_recursive(cur, distance):
vis[cur] = 1
lp[cur] = max(lp[cur], distance)
if cur == dst:
return
for next_node, d in graph[cur]:
if vis[next_node] == 1:
continue
vis[next_node] = 1
_solve_recursive(next_node, distance + d + 1)
vis[next_node] = 0
_solve_recursive(src, 0)
return lp[DST]
print("part 2:", solve(SRC, DST)) |
<div style="margin-left: 1%">
<p style="color: green"><%= notice %></p>
<h3><%= t('appointment.index.search') %></h3>
<%= form_with url: "/appointments/", method: :get do |f| %>
<%= f.label :search_date, style: "display: block" %>
<%= f.date_field :date %>
<br>
<%= f.label :status, style: "display: block" %>
<%= radio_button_tag(:status, "wait") %>
<%= label_tag(:status_wait, "Wait status") %>
<%= radio_button_tag(:status, "done") %>
<%= label_tag(:status_done, "Done status") %>
<br>
<%= submit_tag t('appointment.index.search') %>
<% end %>
<% if can? :create, Appointment %>
<%= link_to t('appointment.index.new_appointment'), new_appointment_path %>
<% end %>
<% if patient_signed_in? %>
<h1><%= t('appointment.index.patient_appointments') %></h1>
<table class="table">
<thead class="thead-dark">
<tr>
<th scope="col"><%= t('appointment.index.photo') %></th>
<th scope="col"><%= t('appointment.index.doctor') %></th>
<th scope="col"><%= t('appointment.index.status') %></th>
<th scope="col"><%= t('appointment.index.date') %></th>
<th scope="col"><%= t('appointment.index.deteils') %></th>
</tr>
</thead>
<tbody>
<% @appointments.each do |appointment| %>
<tr>
<td>#</td>
<td>
<%= "#{appointment.doctor.surname} #{appointment.doctor.name} - #{appointment.doctor.category.title}" %>
</td>
<td><%= appointment.status %></td>
<td><%= appointment.date %></td>
<td><%= link_to t('appointment.index.show_appointment'), appointment %></td>
</tr>
<% end %>
</tbody>
</table>
<% elsif doctor_signed_in? %>
<h1><%= t('appointment.index.doctor_appointments') %></h1>
<table class="table">
<thead class="thead-dark">
<tr>
<th scope="col"><%= t('appointment.index.patient') %></th>
<th scope="col"><%= t('appointment.index.status') %></th>
<th scope="col"><%= t('appointment.index.date') %></th>
<th scope="col"><%= t('appointment.index.deteils') %></th>
</tr>
</thead>
<tbody>
<% @appointments.each do |appointment| %>
<% if appointment.doctor_id.eql? current_doctor.id %>
<tr>
<td>
<%= "#{appointment.patient.surname} #{appointment.patient.name} #{appointment.patient.phone}" %>
</td>
<td><%= appointment.status %></td>
<td><%= appointment.date %></td>
<td><%= link_to t('appointment.index.show_appointment'), appointment %></td>
</tr>
<% end %>
<% end %>
</tbody>
</table>
<% else %>
<h1><%= t('appointment.index.not_authorized') %></h1>
<% end %>
<%= paginate @appointments %>
</div> |
<!DOCTYPE html>
<html lang="es">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Estudiantes</title>
<link rel="stylesheet" href="style.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css">
<style>
/* Ajustes para el selector */
.select2-container {
width: 100% !important;
}
/* Estilos para el contenedor de información */
.info-container {
max-width: 800px;
margin-top: 20px;
padding: 20px;
background-color: #fff;
border-radius: 8px;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
}
.info-group {
display: flex;
margin-bottom: 10px;
}
.info-group label {
width: 200px;
font-weight: bold;
}
.info-group p {
flex: 1;
color: #333;
}
#editarBtn:hover {
background-color: #0056b3;
}
</style>
</head>
<body>
<div class="sidebar">
<h2>
<img src="./Logo2021.png" alt="Logo" width="40" height="40"> SA-EDU
</h2>
<ul>
<li><a href="inicioprofesor.html">Tablero <i class="fas fa-tachometer-alt"></i></a></li>
<li><a href="verinfoprofesor.html">Alumnos <i class="fas fa-user-graduate"></i></a></li>
<li><a href="gestionarcursos.html">Cursos <i class="fas fa-book"></i></a></li>
<li><a href="horarioprofesor.html">Horario <i class="fas fa-calendar-alt"></i></a></li>
<li><a href="subirnotas.html">Calificaciones <i class="fas fa-chart-bar"></i></a></li>
<li><a href="mensajesprofesor.html">Bandeja de Entrada <i class="fas fa-envelope"></i></a></li>
</ul>
</div>
<div class="main-content">
<div class="top-bar">
<div class="icons">
<a href="login.component.html"><i class="fas fa-sign-out-alt"></i></a> <!-- Salir -->
</div>
</div>
<div>
<label for="alumnos">Estudiantes</label>
<select id="alumnos" style="width: 100%;">
<option value="">Seleccione un estudiante</option>
<option value="1">Rojas Chomba, Victor Manuel</option>
</select>
</div>
<div id="infoContainer" class="info-container" style="display: none;">
<div class="info-group"><label>Apellido Paterno:</label><p id="apellidoPaterno"></p></div>
<div class="info-group"><label>Apellido Materno:</label><p id="apellidoMaterno"></p></div>
<div class="info-group"><label>Nombres:</label><p id="nombres"></p></div>
<div class="info-group"><label>Nombre Completo:</label><p id="nombreCompleto"></p></div>
<div class="info-group"><label>Fecha Nacimiento:</label><p id="fechaNacimiento"></p></div>
<div class="info-group"><label>Sexo:</label><p id="sexo"></p></div>
<div class="info-group"><label>País de Nacimiento:</label><p id="paisNacimiento"></p></div>
<div class="info-group"><label>Nacionalidad:</label><p id="nacionalidad"></p></div>
<div class="info-group"><label>Departamento:</label><p id="departamento"></p></div>
<div class="info-group"><label>Provincia:</label><p id="provincia"></p></div>
<div class="info-group"><label>Distrito:</label><p id="distrito"></p></div>
<div class="info-group"><label>Lugar de Nacimiento:</label><p id="lugarNacimiento"></p></div>
<div class="info-group"><label>Tipo de Documento:</label><p id="tipoDocumento"></p></div>
<div class="info-group"><label>Nro. Documento:</label><p id="nroDocumento"></p></div>
<div class="info-group"><label>Religión:</label><p id="religion"></p></div>
<div class="info-group"><label>Bautizo:</label><p id="bautizo"></p></div>
<div class="info-group"><label>Comunión:</label><p id="comunion"></p></div>
<div class="info-group"><label>Email:</label><p id="email"></p></div>
<div class="info-group"><label>Responsable de Pago:</label><p id="responsablePago"></p></div>
<div class="info-group"><label>Responsable de Matrícula:</label><p id="responsableMatricula"></p></div>
<div class="info-group"><label>Con quién vive:</label><p id="conQuienVive"></p></div>
<div class="info-group"><label>Nacimiento Registrado:</label><p id="nacimientoRegistrado"></p></div>
</div>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.13/js/select2.min.js"></script>
<script>
// Datos de los alumnos
const alumnos = {
"1": {
apellidoPaterno: "Rojas",
apellidoMaterno: "Chomba",
nombres: "Victor Manuel,",
nombreCompleto: "Rojas Chomba, Victor Manuel",
fechaNacimiento: "10/08/2002",
sexo: "Masculino",
paisNacimiento: "Perú",
nacionalidad: "Peruana",
departamento: "Cajamarca",
provincia: "Cajamarca",
distrito: "Cajamarca",
lugarNacimiento: "Cajamarca",
tipoDocumento: "DNI",
nroDocumento: "78703031",
religion: "Católico",
bautizo: "Sí",
comunion: "No",
email: "victor123@gmail.com",
responsablePago: "Padre",
responsableMatricula: "Padre",
conQuienVive: "Madre",
nacimientoRegistrado: "Sí"
},
// Agrega más datos de alumnos aquí
};
$(document).ready(function() {
// Inicializa Select2
$('#alumnos').select2({
placeholder: "Seleccione un estudiante",
allowClear: true
});
// Evento de cambio para actualizar la información del alumno
$('#alumnos').on('change', function() {
const alumnoId = $(this).val();
if (alumnoId && alumnos[alumnoId]) {
const alumno = alumnos[alumnoId];
// Muestra la información del alumno en los campos correspondientes
$('#apellidoPaterno').text(alumno.apellidoPaterno);
$('#apellidoMaterno').text(alumno.apellidoMaterno);
$('#nombres').text(alumno.nombres);
$('#nombreCompleto').text(alumno.nombreCompleto);
$('#fechaNacimiento').text(alumno.fechaNacimiento);
$('#sexo').text(alumno.sexo);
$('#paisNacimiento').text(alumno.paisNacimiento);
$('#nacionalidad').text(alumno.nacionalidad);
$('#departamento').text(alumno.departamento);
$('#provincia').text(alumno.provincia);
$('#distrito').text(alumno.distrito);
$('#lugarNacimiento').text(alumno.lugarNacimiento);
$('#tipoDocumento').text(alumno.tipoDocumento);
$('#nroDocumento').text(alumno.nroDocumento);
$('#religion').text(alumno.religion);
$('#bautizo').text(alumno.bautizo);
$('#comunion').text(alumno.comunion);
$('#email').text(alumno.email);
$('#responsablePago').text(alumno.responsablePago);
$('#responsableMatricula').text(alumno.responsableMatricula);
$('#conQuienVive').text(alumno.conQuienVive);
$('#nacimientoRegistrado').text(alumno.nacimientoRegistrado);
// Muestra el contenedor de información
$('#infoContainer').show();
} else {
// Oculta el contenedor de información si no se selecciona un alumno
$('#infoContainer').hide();
}
});
});
</script>
</div>
</body>
</html> |
<div id="pj_3" ></div>
<script>
require.config({
paths: {
echarts: './mapT/dist'
}
});
require(
[
'echarts',
'echarts/blue',
'echarts/chart/map',
'echarts/chart/line',
'echarts/chart/bar',
'echarts/chart/pie',
'echarts/chart/scatter',
'echarts/chart/radar',
'echarts/chart/funnel'
],
function (ec,theme) {
var option= {
title : {
text: '职位招聘求职(2008年度)',
x:'center'
},
tooltip : {
trigger: 'axis',
axisPointer : {
type : 'shadow'
},
formatter:'职位:{b}</br>{a}:{c}人'
},
legend: {
data:['招聘','求职'],
x:'right',
y:'4%'
},
grid:{
x:'10%',
y:'20%',
x2:40,
y2:40
},
toolbox: {
show : false,
feature : {
mark : {show: true},
dataView : {show: true, readOnly: true},
magicType : {show: true, type: ['line', 'bar']},
restore : {show: true},
saveAsImage : {show: true}
}
},
calculable : true,
xAxis : [
{
type : 'category',
boundaryGap : false,
data : ['船长','船副','助理船副','轮机长','管轮','助理管轮','机架长','电机员','无线操作员','水手']
}
],
yAxis : [
{
type : 'value',
name:'人数',
boundaryGap:[0,0.02],
axisLabel : {
formatter: '{value}'
}
}
],
series : [
{
name:'招聘',
type:'line',
smooth:true,
data:[110, 110, 150, 130, 120, 130, 100,345,567,234],
markPoint : {
data : [
{type : 'max', name: '最大值'},
{type : 'min', name: '最小值'}
]
},
markLine : {
data : [
{type : 'average', name: '平均值'}
]
}
},
{
name:'求职',
type:'line',
smooth:true,
data:[120, 130, 100,345,567,234,678,345,234,222],
markPoint : {
data : [
{type : 'max', name: '最大值'},
{type : 'min', name: '最小值'}
]
},
markLine : {
data : [
{type : 'average', name : '平均值'}
]
}
}
]
};
var postJobChart3=ec.init(document.getElementById("pj_3"),theme);
postJobChart3.setOption(option);
window.onresize = postJobChart3.resize;
// 模拟动态数据
var newData=function(item,min,max){
item=item||5,min=min||0,max=max||100;
var dataNEW=[];
for(var i=0;i<item;i++){
dataNEW.push(Math.floor(Math.random()*(max-min+1)+min))
}
return dataNEW
};
var time=2008;
var timer_postJobChart3=setInterval(function(){
var changeData=option.series;
option.title.text="职位招聘求职("+(time<2017?++time:time=2008)+"年度)";
for(var i=0;i<changeData.length;i++){
changeData[i].data=newData(10,100,1000);
}
postJobChart3.setOption(option,true);
},1600);
$("#pj_3").hover(function () {
clearInterval(timer_postJobChart3);
},function(){
timer_postJobChart3=setInterval(function(){
var changeData=option.series;
option.title.text="职位招聘求职("+(time<2017?++time:time=2008)+"年度)";
for(var i=0;i<changeData.length;i++){
changeData[i].data=newData(10,100,1000);
}
postJobChart3.setOption(option,true);
},1600);
})
})
</script> |
#pragma once
#include <QHashFunctions>
#include <QString>
#include <QList>
class Download_tracker;
class QSettings;
class QFile;
namespace bendode {
struct Metadata;
}
namespace util {
struct Download_resources {
QString dl_path;
QList<QFile *> file_handles;
Download_tracker * tracker = nullptr;
};
struct Packet_metadata {
std::int32_t piece_idx = 0;
std::int32_t piece_offset = 0;
std::int32_t byte_cnt = 0;
[[nodiscard]] constexpr bool operator==(const Packet_metadata rhs) const noexcept { return byte_cnt == rhs.byte_cnt && piece_idx == rhs.piece_idx && piece_offset == rhs.piece_offset; }
};
[[nodiscard]] constexpr std::size_t qHash(const Packet_metadata packet_metadata, const std::size_t seed = 0) noexcept {
return ::qHashMulti(seed, packet_metadata.byte_cnt, packet_metadata.piece_idx, packet_metadata.piece_offset);
}
template <typename result_type, typename = std::enable_if_t<std::is_arithmetic_v<result_type>>> result_type extract_integer(const QByteArray & raw_data, qsizetype offset = 0);
template <typename dl_metadata_type> void begin_setting_group(QSettings & settings) noexcept;
namespace conversion {
enum class Format { Speed, Memory };
QBitArray convert_to_bits(QByteArrayView bytes) noexcept;
QByteArray convert_to_bytes(const QBitArray & bits) noexcept;
template <typename numeric_type, typename = std::enable_if_t<std::is_arithmetic_v<numeric_type>>> QByteArray convert_to_hex(numeric_type num) noexcept;
template <typename numeric_type_x, typename numeric_type_y, typename = std::enable_if_t<std::is_arithmetic_v<std::common_type_t<numeric_type_x, numeric_type_y>>>>
QString convert_to_percent_format(numeric_type_x dividend, numeric_type_y divisor) noexcept;
template <typename byte_type, typename = std::enable_if_t<std::is_arithmetic_v<byte_type>>> QString stringify_bytes(byte_type received_byte_cnt, byte_type total_byte_cnt) noexcept;
template <typename byte_type, typename = std::enable_if_t<std::is_arithmetic_v<byte_type>>>
[[nodiscard]] constexpr std::pair<double, std::string_view> stringify_bytes(const byte_type byte_cnt, const Format conversion_fmt) noexcept {
constexpr auto kb_byte_cnt = 1024;
constexpr auto mb_byte_cnt = kb_byte_cnt * 1024;
constexpr auto gb_byte_cnt = mb_byte_cnt * 1024;
using namespace std::string_view_literals;
if(byte_cnt >= gb_byte_cnt) {
return {static_cast<double>(byte_cnt) / gb_byte_cnt, conversion_fmt == Format::Speed ? "gb (s) / sec"sv : "gb (s)"sv};
}
if(byte_cnt >= mb_byte_cnt) {
return {static_cast<double>(byte_cnt) / mb_byte_cnt, conversion_fmt == Format::Speed ? "mb (s) / sec"sv : "mb (s)"sv};
}
if(byte_cnt >= kb_byte_cnt) {
return {static_cast<double>(byte_cnt) / kb_byte_cnt, conversion_fmt == Format::Speed ? "kb (s) / sec"sv : "kb (s)"sv};
}
return {byte_cnt, conversion_fmt == Format::Speed ? "byte (s) / sec"sv : "byte (s)"sv};
}
} // namespace conversion
} // namespace util |
/************************************************************
* @author: Grzegorz Skaruz
* Date: 2016-11-13
* This is a test for GNE_SFA2_Search_Controller class
*
* Modification History
* Date Name Description
*************************************************************/
@isTest
private class GNE_SFA2_Search_Controller_Test {
private static String testString = 'testSearch';
static testMethod void testCtrl() {
ApexPages.currentPage().getParameters().put('searchString', testString);
GNE_SFA2_Search_Controller app = new GNE_SFA2_Search_Controller();
system.AssertEquals(app.sObjectsMap.size(), 0);
system.AssertEquals(app.sectionHeadersMap.size(), 0);
system.AssertEquals(app.getResultsFound(), false);
}
private static SFA2_Search_Settings_gne__c prepareSearchSettings(String fieldNames, String headerLabel, String objectName, String filterName){
GNE_SFA2_User_App_Context_gne__c userApplicationContext = GNE_SFA2_Util.getUserApplicationContext();
SFA2_Search_Settings_gne__c searchSettings = new SFA2_Search_Settings_gne__c(
Fields_gne__c = fieldNames,
Header_Label_gne__c = headerLabel,
Object_gne__c = objectName,
Filter_gne__c = filterName,
Product_gne__c = userApplicationContext.Brand_gne__c,
Role_gne__c = userApplicationContext.Role_gne__c,
Application_Name_gne__c = userApplicationContext.App_Name_gne__c
);
insert searchSettings;
return searchSettings;
}
private static List<SFA2_Search_Settings_gne__c> prepareSearchSettingsList(String fieldNames, String headerLabel, String objectName, String filterName){
SFA2_Search_Settings_gne__c searchSettings = prepareSearchSettings(fieldNames, headerLabel, objectName, filterName);
List<SFA2_Search_Settings_gne__c> searchSettingsList = new List<SFA2_Search_Settings_gne__c>();
searchSettingsList.add(searchSettings);
return searchSettingsList;
}
static testMethod void testGetSearchSettings() {
SFA2_Search_Settings_gne__c searchSettings = prepareSearchSettings(
'Id;Name;Category_gne__c;Position_gne__c;Title_gne__c',
'Questions',
'Question_gne__c',
null
);
Test.startTest();
ApexPages.currentPage().getParameters().put('searchString', testString);
GNE_SFA2_Search_Controller app = new GNE_SFA2_Search_Controller();
List<SFA2_Search_Settings_gne__c> result = app.getSearchSettings(GNE_SFA2_Util.getUserApplicationContext());
Test.stopTest();
system.assertEquals(result.size(), 1);
system.assertEquals(result.get(0).Object_gne__c, searchSettings.Object_gne__c);
system.assertEquals(result.get(0).Fields_gne__c, searchSettings.Fields_gne__c);
system.assertEquals(result.get(0).Header_Label_gne__c, searchSettings.Header_Label_gne__c);
system.assertEquals(result.get(0).Field_Header_gne__c, searchSettings.Field_Header_gne__c);
}
static testMethod void testGetRecordsBySearchCriteria() {
List<SFA2_Search_Settings_gne__c> searchSettingsList = prepareSearchSettingsList(
'Id;Name;Category_gne__c;Position_gne__c;Title_gne__c',
'Questions',
'Question_gne__c',
null
);
Questionnaire_gne__c questionnaire = GNE_SFA2_Triggers_Test_Util.prepareQuestionnaire_gne( false );
questionnaire.No_Edit_gne__c = true;
insert questionnaire;
Question_gne__c question = GNE_SFA2_Triggers_Test_Util.prepareQuestion_gne( questionnaire.Id );
question.Title_gne__c = testString;
insert question;
Test.setFixedSearchResults(new List<String>{question.Id});
Test.startTest();
ApexPages.currentPage().getParameters().put('searchString', testString);
GNE_SFA2_Search_Controller app = new GNE_SFA2_Search_Controller();
List<String> searchQueries = app.buildListOfSearchQueries(searchSettingsList);
List<List<Question_gne__c>> result = app.getRecordsBySearchCriteria(searchQueries);
Test.stopTest();
system.assertEquals(result.size(), 1);
system.assertEquals(result.get(0).get(0).get('Title_gne__c'), testString);
}
static testMethod void testBuildListOfSearchQueriesContact() {
List<SFA2_Search_Settings_gne__c> searchSettingsList = prepareSearchSettingsList(
'Id;Name;Title_gne__c;AccountId;DoNotCall;Phone;MobilePhone;Email;Status_gne__c',
'Contacts',
'Contact',
'IsPersonAccount = false'
);
Account a = new Account(Name = 'TestAccount1');
insert a;
Contact c = new Contact(LastName = testString, AccountId = a.Id);
insert c;
Test.startTest();
ApexPages.currentPage().getParameters().put('searchString', testString);
GNE_SFA2_Search_Controller app = new GNE_SFA2_Search_Controller();
List<String> searchQueries = app.buildListOfSearchQueries(searchSettingsList);
Test.stopTest();
system.assertEquals(searchQueries.size(), 1);
system.assertEquals(searchQueries.get(0), 'FIND \'testSearch*\' IN ALL FIELDS RETURNING Contact(Id, Name, Title_gne__c, AccountId, DoNotCall, Phone, MobilePhone, Email, Status_gne__c WHERE IsPersonAccount = false LIMIT 25)');
}
static testMethod void testBuildListOfSearchQueriesAccount() {
List<SFA2_Search_Settings_gne__c> searchSettingsList = prepareSearchSettingsList(
'LastName;IsPersonAccount ',
'Accounts',
'Account',
null
);
RecordType personAccount = [ SELECT Id FROM RecordType WHERE Name = 'Professional_vod' AND SObjectType = 'Account' LIMIT 1];
insert new Account(LastName = testString, RecordTypeId = personAccount.Id);
Test.startTest();
ApexPages.currentPage().getParameters().put('searchString', testString);
GNE_SFA2_Search_Controller app = new GNE_SFA2_Search_Controller();
List<SFA2_Search_Settings_gne__c> searchSettings2 = app.getSearchSettings(GNE_SFA2_Application_Cache.userApplicationContext);
List<String> searchQueries = app.buildListOfSearchQueries(searchSettings2);
Test.stopTest();
system.assertEquals(searchQueries.size(), 1);
system.assertEquals(searchQueries.get(0), 'FIND \'testSearch*\' IN ALL FIELDS RETURNING Account(LastName, IsPersonAccount, Id LIMIT 25)');
}
static testMethod void testGetSectionHeadersMap() {
List<SFA2_Search_Settings_gne__c> searchSettingsList = prepareSearchSettingsList(
'LastName;IsPersonAccount ',
'Accounts',
'Account',
null
);
RecordType personAccount = [ SELECT Id FROM RecordType WHERE Name = 'Professional_vod' AND SObjectType = 'Account' LIMIT 1];
insert new Account(FirstName = testString, LastName = testString, RecordTypeId = personAccount.Id);
Test.startTest();
ApexPages.currentPage().getParameters().put('searchString', testString);
GNE_SFA2_Search_Controller app = new GNE_SFA2_Search_Controller();
Map<String, String> sectionHeadersMap = app.getSectionHeadersMap(searchSettingsList);
Test.stopTest();
system.assertEquals(sectionHeadersMap.size(), 1);
system.assertEquals(sectionHeadersMap.get('Account'), 'Accounts');
}
static testMethod void testUpdateViewColumnLabels() {
SFA2_Search_Settings_gne__c searchSettings = prepareSearchSettings(
'LastName;IsPersonAccount ',
'Accounts',
'Account',
null
);
searchSettings.Field_Header_gne__c = 'LastName = '+testString+'';
GNE_SFA2_User_App_Context_gne__c userApplicationContext = GNE_SFA2_Util.getUserApplicationContext();
Schema.DescribeSObjectResult sObjectDescribe = GNE_SFA2_Application_Cache.describeObject(searchSettings.Object_gne__c);
Map<String, Schema.SObjectField> sObjectFieldMap = sObjectDescribe.fields.getMap();
Schema.SObjectField sObjectField = sObjectFieldMap.get('LastName');
List<GNE_SFA2_Search_Controller.ViewColumnDescribe> viewColumns = new List<GNE_SFA2_Search_Controller.ViewColumnDescribe>();
GNE_SFA2_Search_Controller.ViewColumnDescribe viewColumn = new GNE_SFA2_Search_Controller.ViewColumnDescribe(sObjectField.getDescribe());
viewColumns.add(viewColumn);
Test.startTest();
ApexPages.currentPage().getParameters().put('searchString', testString);
GNE_SFA2_Search_Controller app = new GNE_SFA2_Search_Controller();
app.updateViewColumnLabels(viewColumns, searchSettings);
Test.stopTest();
system.assertEquals(viewColumns.get(0).label, testString);
}
} |
import numpy as np
import pandas as pd
from scipy.stats import pearsonr, chi2_contingency
import matplotlib.pyplot as plt
import seaborn as sns
import codecademylib3
np.set_printoptions(suppress=True, precision=2)
nba = pd.read_csv('./nba_games.csv')
# Subset Data to 2010 Season, 2014 Season
nba_2010 = nba[nba.year_id == 2010]
nba_2014 = nba[nba.year_id == 2014]
print(nba_2010.head())
print(nba_2014.head())
# Define knicks_pts_10 and nets_pts_10
knicks_pts_10 = nba_2010[nba_2010.fran_id == 'Knicks'].pts
nets_pts_10 = nba_2010[nba_2010.fran_id == 'Nets'].pts
# Calculate mean scores
knicks_mean_score = np.mean(knicks_pts_10)
nets_mean_score = np.mean(nets_pts_10)
# Calculate the difference in means
diff_means_2010 = knicks_mean_score - nets_mean_score
plt.hist(knicks_pts_10, alpha=0.8, weights=np.ones_like(knicks_pts_10) / len(knicks_pts_10), label='Knicks')
plt.hist(nets_pts_10, alpha=0.8, weights=np.ones_like(nets_pts_10) / len(nets_pts_10), label='Nets')
plt.legend()
plt.title("2010 Season: Knicks vs Nets Points Distribution")
plt.xlabel("Points")
plt.ylabel("Density")
plt.show()
# Define knicks_pts_14 and nets_pts_14
knicks_pts_14 = nba_2014[nba_2014.fran_id == 'Knicks'].pts
nets_pts_14 = nba_2014[nba_2014.fran_id == 'Nets'].pts
# Calculate mean scores for 2014
knicks_mean_score_14 = np.mean(knicks_pts_14)
nets_mean_score_14 = np.mean(nets_pts_14)
# Calculate the difference in means for 2014
diff_means_2014 = knicks_mean_score_14 - nets_mean_score_14
print("Difference in means for 2014:", diff_means_2014)
# Plot overlapping histograms for 2014
plt.clf() # Clear previous plots
plt.hist(knicks_pts_14, alpha=0.8, weights=np.ones_like(knicks_pts_14) / len(knicks_pts_14), label='Knicks')
plt.hist(nets_pts_14, alpha=0.8, weights=np.ones_like(nets_pts_14) / len(nets_pts_14), label='Nets')
plt.legend()
plt.title("2014 Season: Knicks vs Nets Points Distribution")
plt.xlabel("Points")
plt.ylabel("Density")
plt.show()
plt.clf() # Clear previous plots
sns.boxplot(data=nba_2010, x='fran_id', y='pts')
plt.title("2010 Season: Points Scored by Franchise")
plt.xlabel("Franchise")
plt.ylabel("Points")
plt.show()
# Calculate the contingency table
location_result_freq = pd.crosstab(nba_2010['game_result'], nba_2010['game_location'])
# Print the result
print(location_result_freq)
# Calculate the table of proportions
location_result_proportions = location_result_freq / len(nba_2010)
# Print the result
print(location_result_proportions)
# Calculate the Chi-Square statistic and expected frequencies
chi2, pval, dof, expected = chi2_contingency(location_result_freq)
# Print the expected table and Chi-Square statistic
print("Expected Table:")
print(expected)
print("Chi-Square Statistic:", chi2)
# Calculate the covariance matrix
cov_matrix = np.cov(nba_2010['forecast'], nba_2010['point_diff'])
# Extract the covariance between forecast and point_diff
point_diff_forecast_cov = cov_matrix[0, 1]
# Print the result
print("Covariance between forecast and point_diff:", point_diff_forecast_cov)
# Calculate the correlation
point_diff_forecast_corr, _ = pearsonr(nba_2010['forecast'], nba_2010['point_diff'])
# Print the result
print("Correlation between forecast and point_diff:", point_diff_forecast_corr)
plt.clf() # Clear previous plots
plt.scatter(nba_2010['forecast'], nba_2010['point_diff'])
plt.xlabel('Forecasted Win Probability')
plt.ylabel('Point Differential')
plt.title('Scatter Plot of Forecast vs. Point Differential')
plt.show() |
import * as WT from "../dist/world-tree.mjs";
test("2D point addition and subtraction", () => {
const p0 = new WT.Point2D(6, 7);
const p1 = new WT.Point2D(10, 12);
const add = p1.add(p0);
const sub = p1.sub(p0);
expect(add.x).toBe(16);
expect(add.y).toBe(19);
expect(sub.x).toBe(4);
expect(sub.y).toBe(5);
});
test("2D point orientation", () => {
const p0 = new WT.Point2D(1, 1);
const p1 = new WT.Point2D(2, 2);
const p2 = new WT.Point2D(1, 3);
const p3 = new WT.Point2D(3, 3);
expect(WT.Point2D.orientation(p0, p2, p1)).toBe(WT.Orientation.Clockwise);
expect(WT.Point2D.orientation(p0, p1, p2)).toBe(
WT.Orientation.CounterClockwise
);
expect(WT.Point2D.orientation(p0, p1, p3)).toBe(WT.Orientation.Colinear);
});
test("2D segment intersection (vertically parallel)", () => {
const p0 = new WT.Point2D(1, 1);
const p1 = new WT.Point2D(1, 3);
const p2 = new WT.Point2D(2, 1);
const p3 = new WT.Point2D(2, 3);
const s0 = new WT.Segment2D(p0, p1);
const s1 = new WT.Segment2D(p2, p3);
expect(s0.contains(p2)).toBe(false);
expect(s0.contains(p3)).toBe(false);
expect(s0.intersects(s1)).toBe(false);
expect(s1.contains(p0)).toBe(false);
expect(s1.contains(p1)).toBe(false);
expect(s1.intersects(s0)).toBe(false);
});
test("2D segment intersection (horizontally parallel)", () => {
const p0 = new WT.Point2D(1, 1);
const p1 = new WT.Point2D(3, 1);
const p2 = new WT.Point2D(1, 2);
const p3 = new WT.Point2D(3, 2);
const s0 = new WT.Segment2D(p0, p1);
const s1 = new WT.Segment2D(p2, p3);
expect(s0.contains(p2)).toBe(false);
expect(s0.contains(p3)).toBe(false);
expect(s0.intersects(s1)).toBe(false);
expect(s1.contains(p0)).toBe(false);
expect(s1.contains(p1)).toBe(false);
expect(s1.intersects(s0)).toBe(false);
});
test("2D point on 2D segment", () => {
const p0 = new WT.Point2D(1, 1);
const p1 = new WT.Point2D(3, 1);
const p2 = new WT.Point2D(1, 3);
const p4 = new WT.Point2D(1, 2);
const p3 = new WT.Point2D(2, 1);
const s0 = new WT.Segment2D(p0, p1);
const s1 = new WT.Segment2D(p0, p2);
expect(s0.contains(p3)).toBe(true);
expect(s1.contains(p3)).toBe(false);
expect(s1.contains(p4)).toBe(true);
expect(s0.contains(p4)).toBe(false);
});
test("2D segment intersection with shared point", () => {
const p0 = new WT.Point2D(1, 1);
const p1 = new WT.Point2D(3, 1);
const p3 = new WT.Point2D(3, 2);
const s0 = new WT.Segment2D(p0, p1);
const s1 = new WT.Segment2D(p0, p3);
expect(s0.intersects(s1)).toBe(false);
expect(s1.intersects(s0)).toBe(false);
});
test("2D segments crossing", () => {
const p0 = new WT.Point2D(1, 1);
const p1 = new WT.Point2D(3, 3);
const p2 = new WT.Point2D(1, 3);
const p3 = new WT.Point2D(3, 1);
const s0 = new WT.Segment2D(p0, p1);
const s1 = new WT.Segment2D(p2, p3);
expect(s0.intersects(s1)).toBe(true);
expect(s1.intersects(s0)).toBe(true);
});
test("3D point arithmetic", () => {
const p0 = new WT.Point3D(1, 2, 3);
const p1 = new WT.Point3D(10, 9, 8);
const v0 = new WT.Vector3D(2, 3, 4);
const diff = p0.vec_diff(p1);
const add = p0.add(v0);
const sub = p1.sub(v0);
expect(diff.x).toBe(-9);
expect(diff.y).toBe(-7);
expect(diff.z).toBe(-5);
expect(add.x).toBe(3);
expect(add.y).toBe(5);
expect(add.z).toBe(7);
expect(sub.x).toBe(8);
expect(sub.y).toBe(6);
expect(sub.z).toBe(4);
});
test("compare 3D points", () => {
const p0 = new WT.Point3D(1.5, 2.5, 3.5);
const p1 = new WT.Point3D(1.5, 2.5, 3.5);
const p2 = new WT.Point3D(1.6, 2.2, 3.1);
const p3 = new WT.Point3D(2, 2, 3);
expect(p0.isSameAs(p1)).toBe(true);
expect(p1.isSameAs(p2)).toBe(false);
expect(p2.isSameAsRounded(p0)).toBe(false);
expect(p2.isSameAsRounded(p3)).toBe(true);
});
test("vertex plane", () => {
const dims = new WT.Dimensions(2, 2, 2);
const centre = new WT.Point3D(1, 1, 1);
const widthVec = new WT.Vector3D(2, 0, 0);
const depthVec = new WT.Vector3D(0, 2, 0);
const heightVec = new WT.Vector3D(0, 0, 2);
const bounds = new WT.BoundingCuboid(centre, dims);
// four points that could represent the base of a cube
const p0 = bounds.minLocation;
const p1 = bounds.minLocation.add(depthVec);
const p2 = bounds.minLocation.add(widthVec);
const p3 = p2.add(depthVec);
const v0 = new WT.Vertex3D(p3, p2, p1);
const v1 = new WT.Vertex3D(p0, p1, p2);
expect(v0.normal.equal(v1.normal)).toBe(true);
});
test("cuboid geometry construction", () => {
const dims = new WT.Dimensions(10, 10, 10);
const centre = new WT.Point3D(5, 5, 5);
const bounds = new WT.BoundingCuboid(centre, dims);
expect(new WT.CuboidGeometry(bounds)).toBeDefined();
});
test("ramp up west construction", () => {
const dims = new WT.Dimensions(10, 10, 10);
const centre = new WT.Point3D(5, 5, 5);
const bounds = new WT.BoundingCuboid(centre, dims);
expect(new WT.RampUpWestGeometry(bounds)).toBeDefined();
});
test("ramp up east construction", () => {
const dims = new WT.Dimensions(10, 10, 10);
const centre = new WT.Point3D(5, 5, 5);
const bounds = new WT.BoundingCuboid(centre, dims);
expect(new WT.RampUpEastGeometry(bounds)).toBeDefined();
});
test("cuboid obstruction", () => {
const dims = new WT.Dimensions(10, 10, 10);
const centre = new WT.Point3D(5, 5, 5);
const bounds = new WT.BoundingCuboid(centre, dims);
const cube = new WT.CuboidGeometry(bounds);
const p0 = new WT.Point3D(5, 5, 11);
const p1 = new WT.Point3D(5, 5, -1);
const p2 = new WT.Point3D(-1, 5, 5);
const p3 = new WT.Point3D(11, 5, 5);
const p4 = new WT.Point3D(5, -1, 5);
const p5 = new WT.Point3D(5, 11, 5);
expect(cube.obstructsRay(p0, p1)).toBeDefined();
expect(cube.obstructsRay(p1, p0)).toBeDefined();
expect(cube.obstructsRay(p2, p3)).toBeDefined();
expect(cube.obstructsRay(p3, p2)).toBeDefined();
expect(cube.obstructsRay(p4, p5)).toBeDefined();
expect(cube.obstructsRay(p5, p4)).toBeDefined();
const p6 = new WT.Point3D(0.1, 0.1, 11);
const p7 = new WT.Point3D(0.1, 0.1, -1);
const p8 = new WT.Point3D(9.9, 9.9, 11);
const p9 = new WT.Point3D(9.9, 9.9, -1);
expect(cube.obstructsRay(p6, p7)).toBeDefined();
expect(cube.obstructsRay(p7, p6)).toBeDefined();
expect(cube.obstructsRay(p8, p9)).toBeDefined();
expect(cube.obstructsRay(p9, p8)).toBeDefined();
const p10 = new WT.Point3D(-1, 0.1, 0.1);
const p11 = new WT.Point3D(11, 0.1, 0.1);
const p12 = new WT.Point3D(-1, 9.9, 9.9);
const p13 = new WT.Point3D(11, 9.9, 9.9);
expect(cube.obstructsRay(p10, p11)).toBeDefined();
expect(cube.obstructsRay(p11, p10)).toBeDefined();
expect(cube.obstructsRay(p12, p13)).toBeDefined();
expect(cube.obstructsRay(p13, p12)).toBeDefined();
const p14 = new WT.Point3D(0.1, -1, 0.1);
const p15 = new WT.Point3D(0.1, 11, 0.1);
const p16 = new WT.Point3D(9.9, -1, 9.9);
const p17 = new WT.Point3D(9.9, 11, 9.9);
expect(cube.obstructsRay(p14, p15)).toBeDefined();
expect(cube.obstructsRay(p15, p14)).toBeDefined();
expect(cube.obstructsRay(p16, p17)).toBeDefined();
expect(cube.obstructsRay(p17, p16)).toBeDefined();
const p18 = new WT.Point3D(-0.1, -0.1, 11);
const p19 = new WT.Point3D(-0.1, -0.1, -1);
const p20 = new WT.Point3D(10.1, 10, 11);
const p21 = new WT.Point3D(10.1, 10.1, -1);
expect(cube.obstructsRay(p18, p19)).toBeNull();
expect(cube.obstructsRay(p19, p18)).toBeNull();
expect(cube.obstructsRay(p20, p21)).toBeNull();
expect(cube.obstructsRay(p21, p20)).toBeNull();
const p22 = new WT.Point3D(-1, -0.1, -0.1);
const p23 = new WT.Point3D(11, -0.1, -0.1);
const p24 = new WT.Point3D(-1, 10.1, 10.1);
const p25 = new WT.Point3D(11, 10.1, 10.1);
expect(cube.obstructsRay(p22, p23)).toBeNull();
expect(cube.obstructsRay(p23, p22)).toBeNull();
expect(cube.obstructsRay(p24, p25)).toBeNull();
expect(cube.obstructsRay(p25, p24)).toBeNull();
const p26 = new WT.Point3D(-0.1, -1, -0.1);
const p27 = new WT.Point3D(-0.1, 11, -0.1);
const p28 = new WT.Point3D(10.1, -1, 10.1);
const p29 = new WT.Point3D(10.1, 11, 10.1);
expect(cube.obstructsRay(p26, p27)).toBeNull();
expect(cube.obstructsRay(p27, p26)).toBeNull();
expect(cube.obstructsRay(p28, p29)).toBeNull();
expect(cube.obstructsRay(p29, p28)).toBeNull();
});
test("ramp up west plane intersection", () => {
const width = 10;
const depth = 10;
const height = 10;
const dims = new WT.Dimensions(width, depth, height);
const centre = new WT.Point3D(5, 5, 5);
const widthVec = new WT.Vector3D(width, 0, 0);
const depthVec = new WT.Vector3D(0, depth, 0);
const heightVec = new WT.Vector3D(0, 0, height);
const bounds = new WT.BoundingCuboid(centre, dims);
// four points that could represent the slope of a ramp
const p2 = bounds.minLocation.add(widthVec);
const p3 = bounds.maxLocation.sub(heightVec);
const p4 = bounds.minLocation.add(heightVec);
const p5 = bounds.maxLocation.sub(widthVec);
const v0 = new WT.Vertex3D(p2, p4, p3);
const v1 = new WT.Vertex3D(p5, p3, p4);
const face = new WT.QuadFace3D(v0, v1);
// up/down the ramp the middle, no intersection
const p6 = new WT.Point3D(10, 5, 0.2);
const p7 = new WT.Point3D(0, 5, 10.1);
expect(v0.intersects(p6, p7)).toBeNull();
expect(v1.intersects(p6, p7)).toBeNull();
expect(v0.intersects(p7, p6)).toBeNull();
expect(v1.intersects(p7, p6)).toBeNull();
expect(face.intersectsPlane(p6, p7)).toBeNull();
expect(face.intersectsPlane(p7, p6)).toBeNull();
expect(face.intersectsPlane(p6, p7) && face.intersects(p7)).toBeNull();
expect(face.intersectsPlane(p7, p6) && face.intersects(p6)).toBeNull();
// up/down the ramp the middle, with intersection
const p8 = new WT.Point3D(10, 5, -1);
const p9 = new WT.Point3D(0, 5, 10.1);
expect(v0.intersects(p8, p9)).toBeDefined();
expect(v1.intersects(p8, p9)).toBeDefined();
expect(v0.intersects(p9, p8)).toBeDefined();
expect(v1.intersects(p9, p8)).toBeDefined();
expect(face.intersectsPlane(p8, p9)).toBeDefined();
expect(face.intersectsPlane(p9, p8)).toBeDefined();
expect(face.intersects(p9)).toBeDefined();
expect(face.intersects(p8)).toBeDefined();
});
test("ramp up west obstruction", () => {
const dims = new WT.Dimensions(10, 10, 10);
const centre = new WT.Point3D(5, 5, 5);
const bounds = new WT.BoundingCuboid(centre, dims);
const ramp = new WT.RampUpWestGeometry(bounds);
const p0 = new WT.Point3D(-1, 5, 1);
const p1 = new WT.Point3D(15, 5, 1);
// Through the ramp east/west.
expect(ramp.obstructsRay(p0, p1)).toBeDefined();
expect(ramp.obstructsRay(p1, p0)).toBeDefined();
const p2 = new WT.Point3D(5, 0, 5.1);
const p3 = new WT.Point3D(5, 11, 5.1);
// Across the ramp north/south
expect(ramp.obstructsRay(p2, p3)).toBeNull();
expect(ramp.obstructsRay(p3, p2)).toBeNull();
const p4 = new WT.Point3D(5, 0, 4.9);
const p5 = new WT.Point3D(5, 11, 4.9);
// Through the ramp north/south
expect(ramp.obstructsRay(p4, p5)).toBeDefined();
expect(ramp.obstructsRay(p5, p4)).toBeDefined();
// up/down the ramp the middle
const p6 = new WT.Point3D(10, 5, 0.2);
const p7 = new WT.Point3D(0, 5, 10.1);
expect(ramp.obstructsRay(p6, p7)).toBeNull();
expect(ramp.obstructsRay(p7, p6)).toBeNull();
});
test("ramp up east obstruction", () => {
const dims = new WT.Dimensions(10, 10, 10);
const centre = new WT.Point3D(5, 5, 5);
const bounds = new WT.BoundingCuboid(centre, dims);
const ramp = new WT.RampUpEastGeometry(bounds);
const p0 = new WT.Point3D(-1, 5, 1);
const p1 = new WT.Point3D(15, 5, 1);
// Through the ramp east/west.
expect(ramp.obstructsRay(p0, p1)).toBeDefined();
expect(ramp.obstructsRay(p1, p0)).toBeDefined();
const p2 = new WT.Point3D(5, 0, 5.1);
const p3 = new WT.Point3D(5, 11, 5.1);
// Across the ramp north/south
expect(ramp.obstructsRay(p2, p3)).toBeNull();
expect(ramp.obstructsRay(p3, p2)).toBeNull();
const p4 = new WT.Point3D(5, 0, 4.9);
const p5 = new WT.Point3D(5, 11, 4.9);
// Through the ramp north/south
expect(ramp.obstructsRay(p4, p5)).toBeDefined();
expect(ramp.obstructsRay(p5, p4)).toBeDefined();
// up/down the ramp the middle.
const p6 = new WT.Point3D(10, 5, 10.2);
expect(ramp.obstructsRay(p0, p6)).toBeNull();
expect(ramp.obstructsRay(p6, p0)).toBeNull();
// up/down the ramp between min to max.
const minLocation = bounds.minLocation;
const maxLocation = bounds.maxLocation;
const p9 = minLocation.add(new WT.Vector3D(0, 0, 0.1));
const p10 = maxLocation.add(new WT.Vector3D(0, 0, 0.1));
expect(ramp.obstructsRay(p9, p10)).toBeNull();
expect(ramp.obstructsRay(p9, maxLocation)).toBeDefined();
expect(ramp.obstructsRay(p10, minLocation)).toBeDefined();
expect(ramp.obstructsRay(p10, p9)).toBeNull();
});
test("ramp up north obstruction", () => {
const dims = new WT.Dimensions(10, 10, 10);
const centre = new WT.Point3D(5, 5, 5);
const bounds = new WT.BoundingCuboid(centre, dims);
const ramp = new WT.RampUpNorthGeometry(bounds);
const p0 = new WT.Point3D(-1, 5, 5.2);
const p1 = new WT.Point3D(15, 5, 5.2);
// Across the ramp east/west.
expect(ramp.obstructsRay(p0, p1)).toBeNull();
expect(ramp.obstructsRay(p1, p0)).toBeNull();
const p2 = new WT.Point3D(5, 0, 10.1);
const p3 = new WT.Point3D(5, 11, 0.1);
// up/down the ramp the middle.
expect(ramp.obstructsRay(p2, p3)).toBeNull();
expect(ramp.obstructsRay(p3, p2)).toBeNull();
const p4 = new WT.Point3D(5, -1, 2);
const p5 = new WT.Point3D(5, 11, 2);
// Blocked through the ramp south/north
expect(ramp.obstructsRay(p4, p5)).toBeDefined();
expect(ramp.obstructsRay(p5, p4)).toBeDefined();
const p6 = new WT.Point3D(-1, 5, 4.9);
const p7 = new WT.Point3D(15, 5, 4.9);
// Through the ramp east/west.
expect(ramp.obstructsRay(p6, p7)).toBeDefined();
expect(ramp.obstructsRay(p7, p6)).toBeDefined();
// up/down the ramp between min to max.
const topCorner = bounds.minLocation.add(new WT.Vector3D(0, 0, 10.1));
const bottomCorner = bounds.maxLocation.sub(new WT.Vector3D(0, 0, 9.9));
expect(ramp.obstructsRay(topCorner, bottomCorner)).toBeNull();
expect(ramp.obstructsRay(bottomCorner, topCorner)).toBeNull();
expect(ramp.obstructsRay(topCorner, bounds.minLocation)).toBeDefined();
expect(ramp.obstructsRay(bottomCorner, bounds.minLocation)).toBeDefined();
});
test("ramp up south obstruction", () => {
const dims = new WT.Dimensions(10, 10, 10);
const centre = new WT.Point3D(5, 5, 5);
const bounds = new WT.BoundingCuboid(centre, dims);
const ramp = new WT.RampUpSouthGeometry(bounds);
const p0 = new WT.Point3D(-1, 5, 5.2);
const p1 = new WT.Point3D(15, 5, 5.2);
// Across the ramp east/west.
expect(ramp.obstructsRay(p0, p1)).toBeNull();
expect(ramp.obstructsRay(p1, p0)).toBeNull();
const p2 = new WT.Point3D(5, -0.5, 0.1);
const p3 = new WT.Point3D(5, 10, 10.1);
// up/down the ramp the middle.
expect(ramp.obstructsRay(p2, p3)).toBeNull();
expect(ramp.obstructsRay(p3, p2)).toBeNull();
const p4 = new WT.Point3D(5, -1, 2);
const p5 = new WT.Point3D(5, 11, 2);
// Blocked through the ramp south/north
expect(ramp.obstructsRay(p4, p5)).toBeDefined();
expect(ramp.obstructsRay(p5, p4)).toBeDefined();
const p6 = new WT.Point3D(-1, 5, 4.9);
const p7 = new WT.Point3D(15, 5, 4.9);
// Through the ramp east/west.
expect(ramp.obstructsRay(p6, p7)).toBeDefined();
expect(ramp.obstructsRay(p7, p6)).toBeDefined();
// up/down the ramp between min to max.
const topCorner = bounds.maxLocation.add(new WT.Vector3D(0, 0, 0.1));
const bottomCorner = bounds.minLocation.add(new WT.Vector3D(0, 0, 0.1));
expect(ramp.obstructsRay(topCorner, bottomCorner)).toBeNull();
expect(ramp.obstructsRay(bottomCorner, topCorner)).toBeNull();
}); |
<!DOCTYPE html>
<html lang="es" ng-app="ShoppingListAsApp">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="style.css">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js"></script>
<script src="app.js"></script>
<title>Custom Service</title>
</head>
<body>
<h1>Custom Service</h1>
<div ng-controller="ShoppingListAddController as itemAdder">
<input type="text" ng-model="itemAdder.itemName" placeholder="item name">
<input type="text" ng-model="itemAdder.itemQuantity" placeholder="quantity">
<button ng-click="itemAdder.addItem();">Add item to shopping list</button>
<!-- <div ng-controller="ChildController1">
</div> -->
</div>
<div ng-controller="ShoppingListRemoveController as removeItem">
<input type="text" ng-model="removeItem.id" placeholder="id item to remove">
<button ng-click="removeItem.removeItemId();">Remove item</button>
</div>
<div ng-controller="ShoppingListShowController as showList">
<ol>
<li ng-repeat="item in showList.items">
{{item.quantity}} of {{item.name}}
</li>
</ol>
</div>
</body>
</html> |
import React from "react";
const { useState, useRef } = React;
import Try from "./Try";
function getNumbers() {
const candidate = [1, 2, 3, 4, 5, 6, 7, 8, 9];
const arr = [];
for (let i = 0; i < 4; ++i) {
const chosen = candidate.splice(
Math.floor(Math.random() * candidate.length),
1
)[0];
arr.push(chosen);
}
return arr;
}
const NumberBaseball = () => {
const [result, setResult] = useState("");
const [value, setValue] = useState("");
const [answer, setAnswer] = useState(getNumbers());
const [tries, setTries] = useState([]);
const onSubmitForm = (e) => {
e.preventDefault();
if (value === answer.join("")) {
setResult("홈런");
setTries((prevTries) => {
return [...prevTries, { try: value, result: "홈런" }];
});
alert("게임을 다시 시작합니다");
setValue("");
setAnswer(getNumbers());
setTries([]);
} else {
const answerArray = value.split("").map((v) => parseInt(v));
let strike = 0;
let ball = 0;
if (tries.length >= 9) {
setResult(`10번 넘게 틀려스 실패! 답은 ${answer.join(",")}였습니다.`);
alert("게임을 다시 시작합니다");
setValue("");
setAnswer(getNumbers());
setTries([]);
} else {
for (let i = 0; i < 4; ++i) {
if (answerArray[i] === answer[i]) {
strike++;
} else if (answer.includes(answerArray[i])) {
ball++;
}
}
setTries((prevTries) => {
return [
...prevTries,
{ try: value, result: `${strike}스트라이크, ${ball}볼 입니다.` },
];
});
setValue("");
}
}
};
const onChangeInput = (e) => {
console.log(answer);
setValue(e.target.value);
};
return (
<>
<h1>{result}</h1>
<form onSubmit={onSubmitForm}>
<input maxLength={4} value={value} onChange={onChangeInput}></input>
</form>
<div>시도 : {tries.length}</div>
<ul>
{tries.map((v, i) => {
return <Try key={`${i + 1}차 시도 : `} tryInfo={v} />;
})}
</ul>
</>
);
};
export default NumberBaseball;
// import React, { PureComponent } from "react";
// //const { useState, useRef } = React;
// import Try from "./Try";
// function getNumbers() {
// const candidate = [1, 2, 3, 4, 5, 6, 7, 8, 9];
// const arr = [];
// for (let i = 0; i < 4; ++i) {
// const chosen = candidate.splice(
// Math.floor(Math.random() * candidate.length),
// 1
// )[0];
// arr.push(chosen);
// }
// return arr;
// }
// class NumberBaseball extends PureComponent {
// state = {
// result: "",
// value: "",
// answer: getNumbers(),
// tries: [],
// };
// onSubmitForm = (e) => {
// e.preventDefault();
// if (this.state.value === this.state.answer.join("")) {
// this.setState((prevState) => {
// return {
// result: "홈런",
// tries: [
// ...prevState.tries,
// { try: this.state.value, result: "홈런" },
// ],
// };
// });
// alert("게임을 다시 시작합니다");
// this.setState({
// value: "",
// answer: getNumbers(),
// tries: [],
// });
// } else {
// const answerArray = this.state.value.split("").map((v) => parseInt(v));
// let strike = 0;
// let ball = 0;
// if (this.state.tries.length >= 9) {
// this.setState({
// result: `10번 넘게 틀려스 실패! 답은 ${this.state.answer.join(
// ""
// )}였습니다.`,
// });
// alert("게임을 다시 시작합니다");
// this.setState({
// value: "",
// answer: getNumbers(),
// tries: [],
// });
// } else {
// for (let i = 0; i < 4; ++i) {
// if (answerArray[i] === this.state.answer[i]) {
// strike++;
// } else if (this.state.answer.includes(answerArray[i])) {
// ball++;
// }
// }
// this.setState((prevState) => {
// return {
// tries: [
// ...prevState.tries,
// {
// try: this.state.value,
// result: `${strike}스트라이크, ${ball}볼 입니다.`,
// },
// ],
// value: "",
// };
// });
// }
// }
// };
// onChangeInput = (e) => {
// console.log(this.state.answer);
// this.setState({
// value: e.target.value,
// });
// };
// render() {
// return (
// <>
// <h1>{this.state.result}</h1>
// <form onSubmit={this.onSubmitForm}>
// <input
// maxLength={4}
// value={this.state.value}
// onChange={this.onChangeInput}
// ></input>
// </form>
// <div>시도 : {this.state.tries.length}</div>
// <ul>
// {this.state.tries.map((v, i) => {
// return <Try key={`${i + 1}차 시도 : `} tryInfo={v} />;
// })}
// </ul>
// </>
// );
// }
// }
// export default NumberBaseball; |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta name="description" content="Shashwat Khandelwal's anime-themed portfolio showcasing skills in web development, programming, and projects.">
<title>Portfolio website </title>
<!-- Font Awesome for icons -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.6.0/css/all.min.css" />
<!-- Google Fonts (Poppins) -->
<link href="https://fonts.googleapis.com/css2?family=Poppins:wght@100;200;300;400;500;600;700;800;900&display=swap" rel="stylesheet">
<!-- CSS file -->
<link rel="stylesheet" href="styles.css" />
</head>
<body>
<nav class="navbar">
<a href="#" class="logo">SHASHWAT KHANDELWAL</a>
<div class="hamburger" onclick="toggleMenu()">
<i class="fas fa-bars"></i>
</div>
<ul class="nav-links">
<li class="active"><a href="#about">About</a></li>
<li><a href="#skills">Skills</a></li>
<li><a href="#projects">Projects</a></li>
<li><a href="#awards">Awards</a></li>
<li><a href="#resume">Resume</a></li>
<li><a href="#contact">Contact</a></li>
</ul>
</nav>
<header class="main">
<div class="main-info">
<h1>Shashwat Khandelwal</h1>
<p>B.Tech CSE Student | Web Development Enthusiast</p>
<blockquote>
"Building digital experiences that inspire and engage—let's explore the web together!"
</blockquote>
</div>
<div class="image-wrapper">
<div class="image">
<img src="1.jfif" alt="Shashwat Khandelwal" />
</div>
</div>
</header>
<section id="about" class="fade-in">
<h2>About Me</h2>
<p>
I am <span class="highlight">Shashwat Khandelwal</span>, a dedicated B.Tech CSE student currently in my third semester. I possess strong skills in programming languages such as <span class="highlight">C</span> and <span class="highlight">C++</span>, alongside expertise in web development with <span class="highlight">HTML</span> and <span class="highlight">CSS</span>. Additionally, my experience with <span class="highlight">Arduino</span> enables me to integrate hardware and software solutions effectively. I am passionate about leveraging technology to create innovative web experiences and continuously seek opportunities to expand my knowledge and skills in the ever-evolving tech landscape.
</p>
</section>
<section id="skills" class="fade-in">
<h2>Key Skills</h2>
<ul>
<li>Programming Languages: <span class="highlight">C</span>, <span class="highlight">C++</span>, <span class="highlight">JavaScript</span></li>
<li>Web Development: <span class="highlight">HTML</span>, <span class="highlight">CSS</span>, <span class="highlight">JavaScript</span></li>
<li>Embedded Systems: <span class="highlight">Arduino</span></li>
<li>Problem Solving: Strong analytical and critical thinking skills</li>
</ul>
</section>
<section id="awards" class="fade-in">
<h2>Awards and Honors</h2>
<ul>
<li>
<a href="link-to-award1-details" target="_blank">
<img src="2.jfif" alt="Participation in Robowars 2024" />
<span>Award Name - Robowars Participation - Year 2024</span>
</a>
</li>
<li>
<a href="link-to-award2-details" target="_blank">
<img src="3.jfif" alt="First Place in Robolution 2.0 2024" />
<span>Award Name - Robolution 2.0 First Place - Year 2024</span>
</a>
</li>
<li>
<a href="link-to-award3-details" target="_blank">
<img src="award3.jpg" alt="Award Name 3" />
<span>Award Name 3 - Year</span>
</a>
</li>
</ul>
</section>
<section id="projects" class="fade-in">
<h2>Projects</h2>
<div class="project">
<h3>Voyage Vibes</h3>
<p>Travelling website using HTML and CSS</p>
<a href="https://shashwat13244.github.io/CODSOFT-Travelling-website-LANDING-PAGE-/" target="_blank">View Project</a>
<img src="project1-image.jpg" alt="Project 1" />
</div>
<div class="project">
<h3>Personal portfolio website</h3>
<p>Personal portfolio website using html and css</p>
<a href="link-to-project2" target="_blank">View Project</a>
<img src="project2-image.jpg" alt="Project 2" />
</div>
<div class="project">
<h3> Simple Calculator </h3>
<p>Simple-Calculator web-application built using html css and JavaScript</p>
<a href="https://shashwat13244.github.io/codsoft-simple-calculator/" target="_blank">View Project</a>
<img src="project3-image.jpg" alt="Project 3" />
</div>
</section>
<section id="resume" class="fade-in">
<h2>Resume</h2>
<a href="Shashwat Khandelwal.pdf" download>Download My Resume</a>
</section>
<section id="contact" class="fade-in">
<h2>Contact Me</h2>
<form action="your_form_handler.php" method="POST">
<input type="text" name="name" placeholder="Your Name" required />
<input type="email" name="email" placeholder="Your Email" required />
<textarea name="message" placeholder="Your Message" required></textarea>
<button type="submit">Send Message</button>
</form>
<p>Email: <a href="mailto:shashwat.khandelwal2023@ssipmt.com">shashwat.khandelwal2023@ssipmt.com</a></p>
<p>Phone: +91 626-033-4502</p>
</section>
<div class="theme-toggle">
<button id="toggle-button">Toggle Dark/Light Mode</button>
</div>
<footer>
<p>© 2024 Shashwat Khandelwal. All rights reserved.</p>
<p>
<a href="https://www.linkedin.com/in/shashwat-khandelwal-a0564532b/" target="_blank">LinkedIn</a> |
<a href="https://github.com/SHASHWAT13244" target="_blank">GitHub</a> |
<a href="http://127.0.0.1:5500/index.html" target="_blank">Portfolio</a>
</p>
</footer>
<script>
function toggleMenu() {
const navLinks = document.querySelector('.nav-links');
navLinks.classList.toggle('active');
}
document.getElementById('toggle-button').addEventListener('click', function() {
document.body.classList.toggle('light-mode');
});
window.addEventListener('scroll', () => {
const sections = document.querySelectorAll('section');
const triggerBottom = window.innerHeight / 5 * 4;
sections.forEach(section => {
const sectionTop = section.getBoundingClientRect().top;
if(sectionTop < triggerBottom) {
section.classList.add('visible');
} else {
section.classList.remove('visible');
}
});
});
</script>
</body>
</html> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.