Support
Quality
Security
License
Reuse
kandi has reviewed halo and discovered the below as its top functions. This is intended to give you an instant insight into halo implemented functionality, and help decide if they suit your requirements.
✍ 一款现代化的开源博客 / CMS 系统。
Fat Jar
curl -L https://github.com/halo-dev/halo/releases/download/v1.4.17/halo-1.4.17.jar --output halo.jar
Docker
docker run -it -d --name halo -p 8090:8090 -v ~/.halo:/root/.halo --restart=always halohub/halo
How to use TypeScript to make sure two objects have a same structure (without interface)?
const en = {
title: "My Website Project",
description: "This is an example of a file which contains phrases and their keys",
hello: "Hello!",
};
const de: Record<keyof typeof en, string> = {
title: "Proyek Website Saya",
description: "Ini adalah contoh dari sebuah file yang mengandung beberapa frasa beserta kata kuncinya",
hello: "Halo!",
cat: "Kucing", // this is highlighted as an error
};
Saving an ID value from an API to a User with GraphQL
const { data } = await completeGame({
variables: { addGame: { ...gameToComplete } },
});
const { data } = await completeGame({
variables: { addGame: { gameId } },
});
-----------------------
const { data } = await completeGame({
variables: { addGame: { ...gameToComplete } },
});
const { data } = await completeGame({
variables: { addGame: { gameId } },
});
Formatting ForEach-Object Output in PS Script
$output = Import-CSV $DatabasePath -Delimiter "`t" | Sort-Object @{Expression= 'Year'; Descending = $true}, @{Expression='Song'; Ascending=$true}
#$output
$output | ForEach-Object {
$album = $_.Album
$year = $_.Year
$year = $_.Song
Write-Host "$Album ($Year)"
etc...
}
-----------------------
$prop1 =@{Expression= 'Year'; Descending = $true}
$prop2 =@{Expression='Album'; Ascending=$true}
$prop3 =@{Expression='Song'; Ascending=$true}
$tab = [char]9
$output = Import-CSV $DatabasePath -Delimiter "`t" | Sort-Object $prop1, $prop2, $prop3
$test = @()
$count = 0
$output | ForEach-Object {
$album = $_.Album
$year = $_.Year
$song = $_.Song
if ($output[$count].album -like $output[$count -1].album){
$test += "$tab$Song"
} else{
$test += "$Album ($Year)"
$test += "$tab$Song"
} $count++
}
if ($path.Length -gt 0){
$test | Out-File -Path $Path
} else {
$test | ForEach-Object {
Write-Host $_
}
}
How to grab the ID of an artist so i can insert the album into the database with the artist's ID?
INSERT INTO albums (name, artist)
SELECT 'Holy Diver' AS album_name, id AS artist
FROM artists
WHERE name = 'Dio'
ON CONFLICT DO NOTHING;
INSERT INTO albums (name, artist)
SELECT album_name, id AS artist
FROM artists,
(
VALUES ('Holy Diver'),
('Dream Evil')
) t(album_name)
WHERE name = 'Dio'
ON CONFLICT DO NOTHING;
INSERT INTO albums (name, artist)
SELECT album_name, id AS artist
FROM artists,
(SELECT 'Holy Diver' AS album_name
UNION
SELECT 'Dream Evil') t
WHERE name = 'Dio'
ON CONFLICT DO NOTHING;
INSERT INTO albums (name, artist)
SELECT UNNEST(ARRAY['Holy Diver','Dream Evil']) AS album_name,
id AS artist
FROM artists
WHERE name = 'Dio'
ON CONFLICT DO NOTHING;
-----------------------
INSERT INTO albums (name, artist)
SELECT 'Holy Diver' AS album_name, id AS artist
FROM artists
WHERE name = 'Dio'
ON CONFLICT DO NOTHING;
INSERT INTO albums (name, artist)
SELECT album_name, id AS artist
FROM artists,
(
VALUES ('Holy Diver'),
('Dream Evil')
) t(album_name)
WHERE name = 'Dio'
ON CONFLICT DO NOTHING;
INSERT INTO albums (name, artist)
SELECT album_name, id AS artist
FROM artists,
(SELECT 'Holy Diver' AS album_name
UNION
SELECT 'Dream Evil') t
WHERE name = 'Dio'
ON CONFLICT DO NOTHING;
INSERT INTO albums (name, artist)
SELECT UNNEST(ARRAY['Holy Diver','Dream Evil']) AS album_name,
id AS artist
FROM artists
WHERE name = 'Dio'
ON CONFLICT DO NOTHING;
-----------------------
INSERT INTO albums (name, artist)
SELECT 'Holy Diver' AS album_name, id AS artist
FROM artists
WHERE name = 'Dio'
ON CONFLICT DO NOTHING;
INSERT INTO albums (name, artist)
SELECT album_name, id AS artist
FROM artists,
(
VALUES ('Holy Diver'),
('Dream Evil')
) t(album_name)
WHERE name = 'Dio'
ON CONFLICT DO NOTHING;
INSERT INTO albums (name, artist)
SELECT album_name, id AS artist
FROM artists,
(SELECT 'Holy Diver' AS album_name
UNION
SELECT 'Dream Evil') t
WHERE name = 'Dio'
ON CONFLICT DO NOTHING;
INSERT INTO albums (name, artist)
SELECT UNNEST(ARRAY['Holy Diver','Dream Evil']) AS album_name,
id AS artist
FROM artists
WHERE name = 'Dio'
ON CONFLICT DO NOTHING;
-----------------------
INSERT INTO albums (name, artist)
SELECT 'Holy Diver' AS album_name, id AS artist
FROM artists
WHERE name = 'Dio'
ON CONFLICT DO NOTHING;
INSERT INTO albums (name, artist)
SELECT album_name, id AS artist
FROM artists,
(
VALUES ('Holy Diver'),
('Dream Evil')
) t(album_name)
WHERE name = 'Dio'
ON CONFLICT DO NOTHING;
INSERT INTO albums (name, artist)
SELECT album_name, id AS artist
FROM artists,
(SELECT 'Holy Diver' AS album_name
UNION
SELECT 'Dream Evil') t
WHERE name = 'Dio'
ON CONFLICT DO NOTHING;
INSERT INTO albums (name, artist)
SELECT UNNEST(ARRAY['Holy Diver','Dream Evil']) AS album_name,
id AS artist
FROM artists
WHERE name = 'Dio'
ON CONFLICT DO NOTHING;
Is there a need or how to write a test on main.pl which is not module and run it using Perl Devel cover
$ perl -I. -MDevel::Cover main.pl
$ cover
Detect if an image is negative
# Imports:
import numpy as np
import cv2
# Image path
path = "D://opencvImages//"
fileName = "RPWBn.png"
# Reading an image in default mode:
inputImage = cv2.imread(path + fileName)
# Convert RGB to grayscale:
originalGrayscale = cv2.cvtColor(inputImage, cv2.COLOR_BGR2GRAY)
# Equalize histogram
grayscaleImage = cv2.equalizeHist(originalGrayscale)
# It might be interesting to you to check out the image equalization:
cv2.imshow("Image Equalized", grayscaleImage)
cv2.waitKey(0)
# Binarize the image with a fixed threshold:
minThresh = 128
_, binaryImage = cv2.threshold(grayscaleImage, minThresh, 255, cv2.THRESH_BINARY)
# Compute the percent of white pixels:
(imageHeight, imageWidth) = binaryImage .shape[:2]
whitePercent = cv2.countNonZero(binaryImage)/(imageHeight * imageWidth)
if whitePercent > 0.5:
print("Correcting images...")
# Correct the original (unequalized) image:
originalGrayscale = 255 - originalGrayscale
cv2.imshow("Correction - Original Image", originalGrayscale)
# Correct the equalized image:
grayscaleImage = 255 - grayscaleImage
cv2.imshow("Correction - Equalized Image", grayscaleImage )
cv2.waitKey(0)
# Improve the brightness + contrast of the original image via
# CLAHE.
# Gray to BGR conversion:
originalGrayscale = cv2.cvtColor(originalGrayscale , cv2.COLOR_GRAY2BGR)
# Conversion to LAB:
lab = cv2.cvtColor(originalGrayscale, cv2.COLOR_BGR2LAB)
# Split the channels:
l, a, b = cv2.split(lab)
# Apply CLAHE to L-channel:
# You might need to fiddle with the parameters:
clahe = cv2.createCLAHE(clipLimit=7.0, tileGridSize=(1, 1))
cl = clahe.apply(l)
# Merge the CLAHE enhanced L-channel with the a and b channel:
limg = cv2.merge((cl, a, b))
# Conversion from LAB to BGR:
final = cv2.cvtColor(limg, cv2.COLOR_LAB2BGR)
cv2.imshow("Original Corrected and Enhanced", final)
cv2.waitKey(0)
-----------------------
# Imports:
import numpy as np
import cv2
# Image path
path = "D://opencvImages//"
fileName = "RPWBn.png"
# Reading an image in default mode:
inputImage = cv2.imread(path + fileName)
# Convert RGB to grayscale:
originalGrayscale = cv2.cvtColor(inputImage, cv2.COLOR_BGR2GRAY)
# Equalize histogram
grayscaleImage = cv2.equalizeHist(originalGrayscale)
# It might be interesting to you to check out the image equalization:
cv2.imshow("Image Equalized", grayscaleImage)
cv2.waitKey(0)
# Binarize the image with a fixed threshold:
minThresh = 128
_, binaryImage = cv2.threshold(grayscaleImage, minThresh, 255, cv2.THRESH_BINARY)
# Compute the percent of white pixels:
(imageHeight, imageWidth) = binaryImage .shape[:2]
whitePercent = cv2.countNonZero(binaryImage)/(imageHeight * imageWidth)
if whitePercent > 0.5:
print("Correcting images...")
# Correct the original (unequalized) image:
originalGrayscale = 255 - originalGrayscale
cv2.imshow("Correction - Original Image", originalGrayscale)
# Correct the equalized image:
grayscaleImage = 255 - grayscaleImage
cv2.imshow("Correction - Equalized Image", grayscaleImage )
cv2.waitKey(0)
# Improve the brightness + contrast of the original image via
# CLAHE.
# Gray to BGR conversion:
originalGrayscale = cv2.cvtColor(originalGrayscale , cv2.COLOR_GRAY2BGR)
# Conversion to LAB:
lab = cv2.cvtColor(originalGrayscale, cv2.COLOR_BGR2LAB)
# Split the channels:
l, a, b = cv2.split(lab)
# Apply CLAHE to L-channel:
# You might need to fiddle with the parameters:
clahe = cv2.createCLAHE(clipLimit=7.0, tileGridSize=(1, 1))
cl = clahe.apply(l)
# Merge the CLAHE enhanced L-channel with the a and b channel:
limg = cv2.merge((cl, a, b))
# Conversion from LAB to BGR:
final = cv2.cvtColor(limg, cv2.COLOR_LAB2BGR)
cv2.imshow("Original Corrected and Enhanced", final)
cv2.waitKey(0)
-----------------------
# Imports:
import numpy as np
import cv2
# Image path
path = "D://opencvImages//"
fileName = "RPWBn.png"
# Reading an image in default mode:
inputImage = cv2.imread(path + fileName)
# Convert RGB to grayscale:
originalGrayscale = cv2.cvtColor(inputImage, cv2.COLOR_BGR2GRAY)
# Equalize histogram
grayscaleImage = cv2.equalizeHist(originalGrayscale)
# It might be interesting to you to check out the image equalization:
cv2.imshow("Image Equalized", grayscaleImage)
cv2.waitKey(0)
# Binarize the image with a fixed threshold:
minThresh = 128
_, binaryImage = cv2.threshold(grayscaleImage, minThresh, 255, cv2.THRESH_BINARY)
# Compute the percent of white pixels:
(imageHeight, imageWidth) = binaryImage .shape[:2]
whitePercent = cv2.countNonZero(binaryImage)/(imageHeight * imageWidth)
if whitePercent > 0.5:
print("Correcting images...")
# Correct the original (unequalized) image:
originalGrayscale = 255 - originalGrayscale
cv2.imshow("Correction - Original Image", originalGrayscale)
# Correct the equalized image:
grayscaleImage = 255 - grayscaleImage
cv2.imshow("Correction - Equalized Image", grayscaleImage )
cv2.waitKey(0)
# Improve the brightness + contrast of the original image via
# CLAHE.
# Gray to BGR conversion:
originalGrayscale = cv2.cvtColor(originalGrayscale , cv2.COLOR_GRAY2BGR)
# Conversion to LAB:
lab = cv2.cvtColor(originalGrayscale, cv2.COLOR_BGR2LAB)
# Split the channels:
l, a, b = cv2.split(lab)
# Apply CLAHE to L-channel:
# You might need to fiddle with the parameters:
clahe = cv2.createCLAHE(clipLimit=7.0, tileGridSize=(1, 1))
cl = clahe.apply(l)
# Merge the CLAHE enhanced L-channel with the a and b channel:
limg = cv2.merge((cl, a, b))
# Conversion from LAB to BGR:
final = cv2.cvtColor(limg, cv2.COLOR_LAB2BGR)
cv2.imshow("Original Corrected and Enhanced", final)
cv2.waitKey(0)
-----------------------
def invert_if_negative(img):
img = my_contrast_stretch(img)
# assuming image has fixed size of (1396, 1676)
# corners
top_left = img[:200, :200].flatten()
top_right = img[:200, 1250:].flatten()
# more or less center
center = img[1000:1300, 500:800].flatten()
threshold = 120 # or computed from average
top_left = top_left > threshold
top_right = top_right > threshold
center = center > threshold
perc_white_corners = (sum(top_left) + sum(top_right)) / (len(top_left) + len(top_right))
perc_white_center = sum(center) / len(center)
if perc_white_corners > perc_white_center:
img = 255 - img
return img
def my_contrast_stretch(img):
if img.dtype == np.float64:
img = (img * 255).astype(np.uint8)
M=np.max(img)
m=np.min(img)
res = img - m
res = res * (255 / (M - m))
return res.astype(np.uint8)
-----------------------
def invert_if_negative(img):
img = my_contrast_stretch(img)
# assuming image has fixed size of (1396, 1676)
# corners
top_left = img[:200, :200].flatten()
top_right = img[:200, 1250:].flatten()
# more or less center
center = img[1000:1300, 500:800].flatten()
threshold = 120 # or computed from average
top_left = top_left > threshold
top_right = top_right > threshold
center = center > threshold
perc_white_corners = (sum(top_left) + sum(top_right)) / (len(top_left) + len(top_right))
perc_white_center = sum(center) / len(center)
if perc_white_corners > perc_white_center:
img = 255 - img
return img
def my_contrast_stretch(img):
if img.dtype == np.float64:
img = (img * 255).astype(np.uint8)
M=np.max(img)
m=np.min(img)
res = img - m
res = res * (255 / (M - m))
return res.astype(np.uint8)
New programmer having trouble setting up a discord bot in discord.py to return amount of members in a voice channel
# I'm suggest putting this outside of the on_message event
def game_plz(channel:discord.VoiceChannel):
members = channel.members #finds members connected to the channel
# channel.members is a list of discord.Member objects
return len(members) # returns amount of members in the channel
# within your on_message event
voice_channel = message.author.voice.channel
msg = message.content
if msg.startswith('!plz'):
await message.channel.send(game_plz(voice_channel))
# pass voice_channel as an argument into game_plz
# voice_channel should be a discord.VoiceChannel object
Highcharts - Getting a 3d effect with selected pie chart slices
plotOptions: {
pie: {
type: 'pie',
innerSize: '80%',
allowPointSelect: true,
slicedOffset: 0,
states: {
hover: {
halo: null,
brightness: 0,
},
},
point: {
events: {
mouseOver: (obj) => {
obj.target.graphic.attr({
'stroke-width': 50,
stroke: obj.target.color,
zIndex: 3,
filter: 'drop-shadow(0 0 10px black)'
}).css({
borderRadius: 20
})
.add();
},
mouseOut: (obj) => {
obj.target.graphic.attr({
'stroke-width': 1,
stroke: obj.target.color,
filter: 'transparent'
}).css({
borderRadius: 0
})
.add();
},
}
}
}
},
-----------------------
document.addEventListener('DOMContentLoaded', function() {
const chart = Highcharts.chart('container', getChartOptions())
})
/**
* Gets the highchart options for the pie chart.
* Each data point has event handlers added to them
* To set the correct border widths
*/
function getChartOptions() {
return {
series: [{
type: 'pie',
innerSize: '80%',
allowPointSelect: true,
slicedOffset: 0,
states: {
// Remove default hover settings
hover: {
halo: null,
brightness: 0,
},
},
data: getMockData()
}],
};
}
/**
* Generates mock data for highcharts
* Each data point has event handlers set up in the `events` property
*/
function getMockData() {
return [{
color: '#aaf',
borderColor: '#aaf',
y: 4,
events: getEventHandlers(),
},
{
color: '#afa',
borderColor: '#afa',
y: 3,
events: getEventHandlers(),
},
{
color: '#faa',
borderColor: '#faa',
y: 8,
events: getEventHandlers(),
},
]
}
/**
* Event handlers for highchart data points.
* The border width of the slice is set to 20 for `select` and `mouseOver`
* The border width of the slice is set to 0 for `unselect` and `mouseOut` (except when the event is selected, in which case `mouseOut` shouldn't do anything)
*/
function getEventHandlers() {
return {
select: (obj) => {
obj.target.update({
borderWidth: 20
});
obj.target.graphic.toFront();
},
unselect: (obj) => {
obj.target.update({
borderWidth: 0
});
},
mouseOver: (obj) => {
obj.target.update({
borderWidth: 20
});
obj.target.graphic.toFront();
},
mouseOut: (obj) => {
if (!obj.target['selected']) {
obj.target.update({
borderWidth: 0
});
}
},
};
}
/* A drop shadow is the effect I want to accomplish, but it should be above the other slices. */
.highcharts-pie-series .highcharts-point-hover,
.highcharts-pie-series .highcharts-point-select {
filter: drop-shadow(0 0 10px black);
}
<script src="https://code.highcharts.com/highcharts.js"></script>
<div id="container" style="width:100%; height:400px;"></div>
-----------------------
document.addEventListener('DOMContentLoaded', function() {
const chart = Highcharts.chart('container', getChartOptions())
})
/**
* Gets the highchart options for the pie chart.
* Each data point has event handlers added to them
* To set the correct border widths
*/
function getChartOptions() {
return {
series: [{
type: 'pie',
innerSize: '80%',
allowPointSelect: true,
slicedOffset: 0,
states: {
// Remove default hover settings
hover: {
halo: null,
brightness: 0,
},
},
data: getMockData()
}],
};
}
/**
* Generates mock data for highcharts
* Each data point has event handlers set up in the `events` property
*/
function getMockData() {
return [{
color: '#aaf',
borderColor: '#aaf',
y: 4,
events: getEventHandlers(),
},
{
color: '#afa',
borderColor: '#afa',
y: 3,
events: getEventHandlers(),
},
{
color: '#faa',
borderColor: '#faa',
y: 8,
events: getEventHandlers(),
},
]
}
/**
* Event handlers for highchart data points.
* The border width of the slice is set to 20 for `select` and `mouseOver`
* The border width of the slice is set to 0 for `unselect` and `mouseOut` (except when the event is selected, in which case `mouseOut` shouldn't do anything)
*/
function getEventHandlers() {
return {
select: (obj) => {
obj.target.update({
borderWidth: 20
});
obj.target.graphic.toFront();
},
unselect: (obj) => {
obj.target.update({
borderWidth: 0
});
},
mouseOver: (obj) => {
obj.target.update({
borderWidth: 20
});
obj.target.graphic.toFront();
},
mouseOut: (obj) => {
if (!obj.target['selected']) {
obj.target.update({
borderWidth: 0
});
}
},
};
}
/* A drop shadow is the effect I want to accomplish, but it should be above the other slices. */
.highcharts-pie-series .highcharts-point-hover,
.highcharts-pie-series .highcharts-point-select {
filter: drop-shadow(0 0 10px black);
}
<script src="https://code.highcharts.com/highcharts.js"></script>
<div id="container" style="width:100%; height:400px;"></div>
-----------------------
document.addEventListener('DOMContentLoaded', function() {
const chart = Highcharts.chart('container', getChartOptions())
})
/**
* Gets the highchart options for the pie chart.
* Each data point has event handlers added to them
* To set the correct border widths
*/
function getChartOptions() {
return {
series: [{
type: 'pie',
innerSize: '80%',
allowPointSelect: true,
slicedOffset: 0,
states: {
// Remove default hover settings
hover: {
halo: null,
brightness: 0,
},
},
data: getMockData()
}],
};
}
/**
* Generates mock data for highcharts
* Each data point has event handlers set up in the `events` property
*/
function getMockData() {
return [{
color: '#aaf',
borderColor: '#aaf',
y: 4,
events: getEventHandlers(),
},
{
color: '#afa',
borderColor: '#afa',
y: 3,
events: getEventHandlers(),
},
{
color: '#faa',
borderColor: '#faa',
y: 8,
events: getEventHandlers(),
},
]
}
/**
* Event handlers for highchart data points.
* The border width of the slice is set to 20 for `select` and `mouseOver`
* The border width of the slice is set to 0 for `unselect` and `mouseOut` (except when the event is selected, in which case `mouseOut` shouldn't do anything)
*/
function getEventHandlers() {
return {
select: (obj) => {
obj.target.update({
borderWidth: 20
});
obj.target.graphic.toFront();
},
unselect: (obj) => {
obj.target.update({
borderWidth: 0
});
},
mouseOver: (obj) => {
obj.target.update({
borderWidth: 20
});
obj.target.graphic.toFront();
},
mouseOut: (obj) => {
if (!obj.target['selected']) {
obj.target.update({
borderWidth: 0
});
}
},
};
}
/* A drop shadow is the effect I want to accomplish, but it should be above the other slices. */
.highcharts-pie-series .highcharts-point-hover,
.highcharts-pie-series .highcharts-point-select {
filter: drop-shadow(0 0 10px black);
}
<script src="https://code.highcharts.com/highcharts.js"></script>
<div id="container" style="width:100%; height:400px;"></div>
Erasing Antialiased Shapes from a JavaFX Canvas
if (stroke) {
gc.setStroke(BG_COLOR);
gc.strokeOval(screenX, screenY, CIRCLE_DIAMETER, CIRCLE_DIAMETER);
}
import javafx.application.Application;
import javafx.application.Platform;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.canvas.Canvas;
import javafx.scene.canvas.GraphicsContext;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.layout.*;
import javafx.scene.paint.Color;
import javafx.stage.Stage;
import java.util.Random;
public class Main extends Application {
static final int NUM_CIRCLES = 500;
static final int CIRCLE_DIAMETER = 10;
static final double PANEL_WIDTH = 75.0;
static final double PANEL_HEIGHT = 40.0;
static final Color FG_COLOR = Color.rgb(10, 0, 200);
static final Color BG_COLOR = Color.rgb(255, 255, 255);
static final double BUTTON_WIDTH = 50.0;
GraphicsContext gc;
Random rand = new Random();
private boolean stroke;
double[] px = new double[NUM_CIRCLES];
double[] py = new double[NUM_CIRCLES];
void randomizeParticlePositions() {
for (int i = 0; i < NUM_CIRCLES; i++) {
px[i] = rand.nextDouble() * PANEL_WIDTH;
py[i] = rand.nextDouble() * PANEL_HEIGHT;
}
}
void drawCircles(Color color) {
gc.setFill(color);
for (int i = 0; i < NUM_CIRCLES; i++) {
var screenX = px[i] * CIRCLE_DIAMETER;
var screenY = py[i] * CIRCLE_DIAMETER;
gc.fillOval(screenX, screenY, CIRCLE_DIAMETER, CIRCLE_DIAMETER);
if (stroke) {
gc.setStroke(BG_COLOR);
gc.strokeOval(screenX, screenY, CIRCLE_DIAMETER, CIRCLE_DIAMETER);
}
}
}
@Override
public void start(Stage stage) {
String javaVersion = System.getProperty("java.version");
String javafxVersion = System.getProperty("javafx.version");
stage.setTitle("AntiAliasingGhosts -- erasing objects leaves ghosts in JavaFX");
Label versionLabel = new Label("JavaFX " + javafxVersion
+ ", running on Java " + javaVersion + ".");
double canvasWidth = (PANEL_WIDTH * CIRCLE_DIAMETER);
double canvasHeight = (PANEL_HEIGHT * CIRCLE_DIAMETER);
Canvas canvasRef = new Canvas(canvasWidth, canvasHeight);
gc = canvasRef.getGraphicsContext2D();
Button deBtn = new Button("Draw");
deBtn.setPrefWidth(BUTTON_WIDTH);
deBtn.setOnAction(e -> {
String txt = deBtn.getText();
switch (txt) {
case "Draw" -> {
randomizeParticlePositions();
drawCircles(FG_COLOR);
deBtn.setText("Erase");
stroke = true;
}
case "Erase" -> {
drawCircles(BG_COLOR);
deBtn.setText("Draw");
stroke = false;
}
default ->
Platform.exit();
}
});
Button exBtn = new Button("Exit");
exBtn.setPrefWidth(BUTTON_WIDTH);
exBtn.setOnAction(e -> Platform.exit());
TilePane tp = new TilePane();
tp.setAlignment(Pos.CENTER);
tp.setHgap(10);
tp.getChildren().addAll(deBtn, exBtn);
VBox root = new VBox();
root.setPadding(new Insets(7));
root.setSpacing(10);
root.setAlignment(Pos.CENTER);
root.getChildren().addAll(versionLabel, canvasRef, tp);
StackPane sp = new StackPane(root);
BackgroundFill bf = new BackgroundFill(BG_COLOR, CornerRadii.EMPTY, Insets.EMPTY);
Background bg = new Background(bf);
sp.setBackground(bg);
Scene scene = new Scene(sp, 640.0, 480.0);
stage.setScene(scene);
stage.show();
}
public static void main(String[] args) {
launch();
}
}
-----------------------
if (stroke) {
gc.setStroke(BG_COLOR);
gc.strokeOval(screenX, screenY, CIRCLE_DIAMETER, CIRCLE_DIAMETER);
}
import javafx.application.Application;
import javafx.application.Platform;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.canvas.Canvas;
import javafx.scene.canvas.GraphicsContext;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.layout.*;
import javafx.scene.paint.Color;
import javafx.stage.Stage;
import java.util.Random;
public class Main extends Application {
static final int NUM_CIRCLES = 500;
static final int CIRCLE_DIAMETER = 10;
static final double PANEL_WIDTH = 75.0;
static final double PANEL_HEIGHT = 40.0;
static final Color FG_COLOR = Color.rgb(10, 0, 200);
static final Color BG_COLOR = Color.rgb(255, 255, 255);
static final double BUTTON_WIDTH = 50.0;
GraphicsContext gc;
Random rand = new Random();
private boolean stroke;
double[] px = new double[NUM_CIRCLES];
double[] py = new double[NUM_CIRCLES];
void randomizeParticlePositions() {
for (int i = 0; i < NUM_CIRCLES; i++) {
px[i] = rand.nextDouble() * PANEL_WIDTH;
py[i] = rand.nextDouble() * PANEL_HEIGHT;
}
}
void drawCircles(Color color) {
gc.setFill(color);
for (int i = 0; i < NUM_CIRCLES; i++) {
var screenX = px[i] * CIRCLE_DIAMETER;
var screenY = py[i] * CIRCLE_DIAMETER;
gc.fillOval(screenX, screenY, CIRCLE_DIAMETER, CIRCLE_DIAMETER);
if (stroke) {
gc.setStroke(BG_COLOR);
gc.strokeOval(screenX, screenY, CIRCLE_DIAMETER, CIRCLE_DIAMETER);
}
}
}
@Override
public void start(Stage stage) {
String javaVersion = System.getProperty("java.version");
String javafxVersion = System.getProperty("javafx.version");
stage.setTitle("AntiAliasingGhosts -- erasing objects leaves ghosts in JavaFX");
Label versionLabel = new Label("JavaFX " + javafxVersion
+ ", running on Java " + javaVersion + ".");
double canvasWidth = (PANEL_WIDTH * CIRCLE_DIAMETER);
double canvasHeight = (PANEL_HEIGHT * CIRCLE_DIAMETER);
Canvas canvasRef = new Canvas(canvasWidth, canvasHeight);
gc = canvasRef.getGraphicsContext2D();
Button deBtn = new Button("Draw");
deBtn.setPrefWidth(BUTTON_WIDTH);
deBtn.setOnAction(e -> {
String txt = deBtn.getText();
switch (txt) {
case "Draw" -> {
randomizeParticlePositions();
drawCircles(FG_COLOR);
deBtn.setText("Erase");
stroke = true;
}
case "Erase" -> {
drawCircles(BG_COLOR);
deBtn.setText("Draw");
stroke = false;
}
default ->
Platform.exit();
}
});
Button exBtn = new Button("Exit");
exBtn.setPrefWidth(BUTTON_WIDTH);
exBtn.setOnAction(e -> Platform.exit());
TilePane tp = new TilePane();
tp.setAlignment(Pos.CENTER);
tp.setHgap(10);
tp.getChildren().addAll(deBtn, exBtn);
VBox root = new VBox();
root.setPadding(new Insets(7));
root.setSpacing(10);
root.setAlignment(Pos.CENTER);
root.getChildren().addAll(versionLabel, canvasRef, tp);
StackPane sp = new StackPane(root);
BackgroundFill bf = new BackgroundFill(BG_COLOR, CornerRadii.EMPTY, Insets.EMPTY);
Background bg = new Background(bf);
sp.setBackground(bg);
Scene scene = new Scene(sp, 640.0, 480.0);
stage.setScene(scene);
stage.show();
}
public static void main(String[] args) {
launch();
}
}
How to remove the halo of MUI slider thumb when focused?
.MuiSlider-thumb:hover {
-webkit-box-shadow: none;
box-shadow: none;
}
.Mui-focusVisible {
-webkit-box-shadow: none!important;
box-shadow: none!important;
}
QUESTION
How to use TypeScript to make sure two objects have a same structure (without interface)?
Asked 2022-Apr-15 at 15:19I'm currently working on a web project which heavily utilizes internationalization (i18n) and I have a hard time figuring out how to make sure all languages share exact same keys.
Here's a simple example of src/lang/en.ts
file:
export default {
title: "My Website Project",
description: "This is an example of a file which contains phrases and their keys",
hello: "Hello!",
};
and here's a simple example of src/lang/id.ts
file:
export default {
title: "Proyek Website Saya",
description: "Ini adalah contoh dari sebuah file yang mengandung beberapa frasa beserta kata kuncinya",
hello: "Halo!",
};
Now, I want TypeScript to make sure those files have same keys (not more, not less). So if I put cat
property into src/lang/id.ts
, then:
export default {
title: "Proyek Website Saya",
description: "Ini adalah contoh dari sebuah file yang mengandung beberapa frasa beserta kata kuncinya",
hello: "Halo!",
cat: "Kucing", // <-- this must be error because "cat" doesn't exist in en.ts file!
};
But I can't build an interface like this
export default interface LanguageStruct {
title: string,
description: string,
hello: string,
};
Because there's hundreds of phrases for each language in the real project and writing those keys one-by-one would be both time consuming and exhausting. I wonder if there's a trick to do with TypeScript for that problem, or at least there's some kind of automation to do that job.
ANSWER
Answered 2022-Apr-15 at 15:19Use keyof typeof someObject
to construct a type from the keys of an object (e.g. the first language strings). Then restrict your other object (the other languages) to have that type as key, and string as value using Record
. So the type you're looking for is Record<keyof typeof someObject, string>
. Example:
const en = {
title: "My Website Project",
description: "This is an example of a file which contains phrases and their keys",
hello: "Hello!",
};
const de: Record<keyof typeof en, string> = {
title: "Proyek Website Saya",
description: "Ini adalah contoh dari sebuah file yang mengandung beberapa frasa beserta kata kuncinya",
hello: "Halo!",
cat: "Kucing", // this is highlighted as an error
};
See working example here.
Community Discussions, Code Snippets contain sources that include Stack Exchange Network
No vulnerabilities reported
Save this library and start creating your kit
Save this library and start creating your kit