text stringlengths 1 2.12k | source dict |
|---|---|
javascript, typescript, user-interface, vue.js
const emit = defineEmits<Emits>();
defineExpose({scrollTop, scrollToItem, scrollToIndex});
const virtualScrollerSelector = ref<string>('');
const transformedVirtualEntries = ref<VirtualEntry[]>(props.virtualEntries);
const maxColumns = ref<number>(1);
const rootElementRef = ref<HTMLElement | null>(null);
const rootElementHeight = ref<number>(500);
const rootElementWidth = ref<number>(500);
const rootElementRenderedHeight = ref<number>(1000);
const itemHeights = ref<number[]>([]);
const renderedItemHeights = ref<number[]>([]);
const totalItemHeight = ref<number>(0);
const scrolling = ref<boolean>(false);
const scrollStopTimeout = ref<ReturnType<typeof setTimeout> | null>(null);
const scrollOffsetY = ref<number>(0);
const scrollPreviousOffsetY = ref<number>(0);
const scrollDirection = ref<'up' | 'down'>('down');
const scrollDelta = ref<number>(0);
const scrollSpeed = ref<number>(0);
const scrollSpeedHistorySize = ref<number>(10);
const scrollSpeedHistory = ref<number[]>([]);
onMounted(() => {
init();
window.addEventListener('resize', windowResizeHandler);
});
onBeforeUnmount(() => {
window.removeEventListener('resize', windowResizeHandler);
});
const renderedItems = computed(() =>
transformedVirtualEntries.value.slice(
scrolledItemsCount.value,
scrolledItemsCount.value + renderedItemsCount.value
)
);
const isTopReached = computed(() => scrollOffsetY.value === 0);
const isBottomReached = computed(
() =>
Math.ceil(scrollOffsetY.value + rootElementHeight.value) >=
totalItemHeight.value
);
const isTopTriggerReached = computed(
() =>
Math.ceil(scrollOffsetY.value + rootElementHeight.value) >=
props.topOffsetTrigger
);
const isBottomTriggerReached = computed(
() =>
Math.ceil(scrollOffsetY.value + rootElementHeight.value) >=
totalItemHeight.value - props.bottomOffsetTrigger
); | {
"domain": "codereview.stackexchange",
"id": 45384,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "javascript, typescript, user-interface, vue.js",
"url": null
} |
javascript, typescript, user-interface, vue.js
const viewportOffsetY = computed(() =>
itemHeights.value
.slice(0, scrolledItemsCount.value)
.reduce((accumulator, current) => accumulator + (current || 0), 0)
);
const virtualScrollerStyle = computed(() => ({
height: `${totalItemHeight.value}px`
}));
const viewportStyle = computed(() => ({
transform: `translateY(${viewportOffsetY.value}px)`
}));
const scrolledItemsCount = computed(() => {
let itemHeightSum = 0;
let counter = 0;
itemHeights.value.forEach(height => {
if (itemHeightSum <= scrollOffsetY.value) {
itemHeightSum += height;
counter += 1;
}
});
return counter - 1;
});
const renderedItemsCount = computed(() => {
let itemHeightSum = 0;
let itemsNeededToFitRootContainer = 0;
itemHeights.value.forEach(height => {
if (itemHeightSum < rootElementHeight.value) {
itemHeightSum += height;
itemsNeededToFitRootContainer += 1;
}
});
return itemsNeededToFitRootContainer + props.bufferItemCount;
});
watch(
() => props.virtualEntries,
() => {
update();
updateLazy();
nextTick(() => {
updateLazy();
});
},
{
deep: true,
immediate: true
}
);
watch(isTopReached, newValue => {
emit('top-reached', newValue);
});
watch(isBottomReached, newValue => {
emit('bottom-reached', newValue);
});
watch(isTopTriggerReached, newValue => {
emit('top-offset-trigger', newValue);
});
watch(isBottomTriggerReached, newValue => {
emit('bottom-offset-trigger', newValue);
});
function init() {
virtualScrollerSelector.value = `.sigma-scrollkit[scroller-index="${props.scrollerId}"]`;
update();
updateLazy();
nextTick(() => {
emit('viewport-mounted', {
viewport: rootElementRef,
selector: virtualScrollerSelector.value
});
initRootElementResizeObserver();
});
}
function setVirtualScrollerSelector() {
virtualScrollerSelector.value = `.sigma-scrollkit[scroller-index="${props.scrollerId}"]`;
} | {
"domain": "codereview.stackexchange",
"id": 45384,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "javascript, typescript, user-interface, vue.js",
"url": null
} |
javascript, typescript, user-interface, vue.js
function transformItems() {
transformedVirtualEntries.value = entriesToRows();
}
function entriesToRows(): VirtualEntry[] {
if (props.virtualEntries.length === 0) {
return [];
}
let newRows: VirtualEntry[] = [];
if (props.layoutType === 'grid') {
maxColumns.value = Math.floor(
rootElementWidth.value / props.minColumnWidth
);
} else {
maxColumns.value = 1;
}
props.virtualEntries.forEach(row => {
const newItems = chunkArray(row.items, maxColumns.value);
newItems.forEach(chunk => {
row.id = uniqueId();
newRows.push({
...row,
items: chunk
});
});
});
return newRows;
}
function chunkArray<T>(array: T[], chunkSize: number): T[][] {
if (chunkSize <= 0) {
chunkSize = 1;
}
const result: T[][] = [];
for (let i = 0; i < array.length; i += chunkSize) {
const chunk = array.slice(i, i + chunkSize);
result.push(chunk);
}
return result;
}
function update() {
if (!rootElementRef.value || transformedVirtualEntries.value.length === 0) {
return;
}
scrollOffsetY.value = rootElementRef.value.scrollTop;
nextTick(() => {
setRenderedItemHeights();
});
}
function updateLazy() {
setVirtualScrollerSelector();
setRootElementRenderedHeight();
setRootElementHeight();
transformItems();
setItemHeights();
emit('is-scrollable', isScrollable());
}
function initRootElementResizeObserver() {
const element = getVirtualScrollerElement()?.parentElement;
if (!element) {
return;
}
observeRootElementResize(element, rootElementResizeHandler);
}
function observeRootElementResize(
element: HTMLElement,
callback: ElementResizeCallback
) {
const observer = new ResizeObserver(entries => {
for (const entry of entries) {
if (entry.target === element) {
callback(entry);
}
}
});
observer.observe(element);
return observer;
}
function rootElementResizeHandler() {
update();
updateLazy();
} | {
"domain": "codereview.stackexchange",
"id": 45384,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "javascript, typescript, user-interface, vue.js",
"url": null
} |
javascript, typescript, user-interface, vue.js
function rootElementResizeHandler() {
update();
updateLazy();
}
function windowResizeHandler() {
update();
updateLazy();
}
function isScrollable() {
if (!rootElementRef.value) {
return false;
}
return rootElementRef.value.scrollHeight > rootElementRef.value.clientHeight;
}
function scrollHandler(event: UIEvent) {
handleScrollStart();
handleScrollStop();
setScrollStatus(rootElementRef.value);
update();
emit('scroll', {
event: event satisfies UIEvent,
scrollOffsetY: scrollOffsetY.value,
scrollDelta: scrollDelta.value,
scrollDirection: scrollDirection.value,
scrollSpeed: scrollSpeed.value
});
}
function handleScrollStart() {
scrolling.value = true;
emit('scrolling', true);
}
function handleScrollStop() {
if (scrollStopTimeout.value) {
clearTimeout(scrollStopTimeout.value);
}
scrollStopTimeout.value = setTimeout(() => {
scrolling.value = false;
emit('scrolling', false);
}, 100);
}
function setScrollStatus(element: HTMLElement | null) {
scrollPreviousOffsetY.value = scrollOffsetY.value;
scrollOffsetY.value = element?.scrollTop || 0;
scrollDelta.value = scrollOffsetY.value - scrollPreviousOffsetY.value;
scrollDirection.value = scrollDelta.value > 0 ? 'down' : 'up';
if (props.calcExtraInfo) {
recordScrollSpeedHistory(scrollDelta.value);
const speedSum = Math.abs(
scrollSpeedHistory.value.reduce(
(accumulator, current) => accumulator + current,
0
)
);
scrollSpeed.value = speedSum / scrollSpeedHistory.value.length;
}
}
function recordScrollSpeedHistory(_scrollSpeed: number) {
if (scrollSpeedHistory.value.length > scrollSpeedHistorySize.value) {
scrollSpeedHistory.value.splice(0, 1);
}
scrollSpeedHistory.value.push(_scrollSpeed);
}
function setRootElementHeight() {
const virtualScrollerParentElement = getVirtualScrollerElement()
?.parentElement satisfies HTMLElement | undefined | null; | {
"domain": "codereview.stackexchange",
"id": 45384,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "javascript, typescript, user-interface, vue.js",
"url": null
} |
javascript, typescript, user-interface, vue.js
if (virtualScrollerParentElement) {
rootElementHeight.value = virtualScrollerParentElement.offsetHeight;
rootElementWidth.value = virtualScrollerParentElement.offsetWidth;
}
}
function setRootElementRenderedHeight() {
const virtualScrollerElement = getVirtualScrollerElement();
if (virtualScrollerElement) {
rootElementRenderedHeight.value = virtualScrollerElement.offsetHeight;
}
}
function getVirtualScrollerElement() {
return document.querySelector(
virtualScrollerSelector.value
) satisfies HTMLElement | null;
}
function setRenderedItemHeights() {
renderedItemHeights.value = renderedItems.value.map(
item => item.height + item.rowGap
);
}
function setItemHeights() {
itemHeights.value = transformedVirtualEntries.value.map(
item => item.height + item.rowGap
);
totalItemHeight.value = itemHeights.value.reduce(
(accumulator, current) => accumulator + (current || 0),
0
);
}
function scrollTop() {
rootElementRef?.value?.scrollTo?.({top: 0, behavior: 'smooth'});
}
function scrollToItem(params: { key: string; value: unknown }) {
const targetItemIndex = transformedVirtualEntries.value.findIndex(
(virtualEntry: VirtualEntry) =>
!!virtualEntry.items.find(
(item: VirtualEntryItem) => item[params.key] === params.value
)
);
if (targetItemIndex !== -1) {
scrollToIndex(targetItemIndex);
}
}
function scrollToIndex(index: number) {
if (rootElementRef.value) {
rootElementRef.value.scrollTop = getIndexOffsetY(index);
}
}
function getIndexOffsetY(index: number) {
return transformedVirtualEntries.value
.slice(0, index)
.reduce(
(accumulator, current) =>
accumulator + (current.height + current.rowGap || 0),
0
);
}
setVirtualScrollerSelector();
</script> | {
"domain": "codereview.stackexchange",
"id": 45384,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "javascript, typescript, user-interface, vue.js",
"url": null
} |
javascript, typescript, user-interface, vue.js
setVirtualScrollerSelector();
</script>
<template>
<div ref="rootElementRef"
class="sigma-scrollkit"
:scroller-index="props.scrollerId"
@scroll="scrollHandler">
<div class="sigma-scrollkit__viewport-container"
:style="virtualScrollerStyle">
<div class="sigma-scrollkit__viewport"
:style="viewportStyle">
<slot name="viewport"
:rendered-items="renderedItems"
:scrolling="scrolling"
:max-columns="maxColumns" />
</div>
</div>
</div>
</template>
<style>
.sigma-scrollkit {
height: 100%;
overflow-x: hidden;
overflow-y: auto;
}
</style>
Answer: Found the problem - the filter: blur() rule was causing the issue, when I added it to the cards in the virtual list.
And the Webkit doesn't use hardware acceleration, until you force it with CSS. | {
"domain": "codereview.stackexchange",
"id": 45384,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "javascript, typescript, user-interface, vue.js",
"url": null
} |
c, unix, winapi, portability
Title: Executing a shell command OS-independently
Question: The goal of the code is to convert a Graphviz DOT file to an SVG file, and it achieves this by creating a child process and executing the "dot" command.
#include <stdio.h>
#include <stdlib.h>
#if defined(_WIN32)
#include <windows.h>
#define OS_WINDOWS 1
#elif defined(__unix__) || defined(__unix) || defined(__linux__) || (defined(__APPLE__) && defined(__MACH__)))
#include <sys/wait.h>
#include <unistd.h>
#define OS_UNIX 1
#endif
int main(void)
{
#if defined(OS_UNIX)
const int pid = fork();
if (pid == -1) {
fprintf(stderr, "Error: could not fork a child: %s\n",
strerror(errno));
return EXIT_FAILURE;
} else if (pid == 0) {
static char *const args[] = {"dot", "-Tsvg", "trie.dot", "-o", "trie.svg", (char *)NULL};
if (execv("/usr/bin/dot", args) == -1) {
fprintf(stderr, "Error: could not execute the child: %s\n",
sterror(errno));
_Exit(EXIT_FAILURE);
}
} else {
int rv;
if (wait(&rv) == -1) {
fprintf(stderr, "Error: could not wait for the forked child: %s\n",
sterror(errno));
return EXIT_FAILURE;
}
if (!WIFEXITED(rv)) {
fprintf(stderr, "Error: child exited with an error status: %d\n", WEXITSTATUS(rv);
return EXIT_FAILURE;
}
}
#else
STARTUPINFO si;
PROCESS_INFORMATION pi;
ZeroMemory(&si, sizeof(si));
si.cb = sizeof(si);
ZeroMemory(&pi, sizeof(pi));
static char *const cmd= "dot -Tsvg trie.dot -o trie.svg";
if (!CreateProcess(NULL, cmd, NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi)) {
fprintf(stderr, "CreateProcess() failed (%d).\n", GetLastError());
return EXIT_FAILURE;
} | {
"domain": "codereview.stackexchange",
"id": 45385,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c, unix, winapi, portability",
"url": null
} |
c, unix, winapi, portability
const DWORD rv = WaitForSingleObject(pi.hProcess, INFINITE);
switch(rv) {
case WAIT_ABANDONED:
fprintf(stderr, "Error: mutex object was not released by the thread that"
"owned the mutex object before the owning thread terminated.\n");
return EXIT_FAILURE;
case WAIT_OBJECT_0:
fprintf(stderr, "Error: the child thread state was signaled.\n");
return EXIT_FAILURE;
case WAIT_TIMEOUT:
fprintf(stderr, "Error: time-out interval elapsed, and the child thread's state is nonsignaled.\n");
return EXIT_FAILURE;
case WAIT_FAILED:
fprintf(stderr, "Error: WaitForSingleObject() failed, error status: %d.\n", GetLastError());
return EXIT_FAILURE;
}
CloseHandle(pi.hProcess);
CloseHandle(pi.hThread);
return EXIT_SUCCESS;
#endif
}
The code compiles successfully on both Windows 10 and Linux Mint 21, which serves my purpose.
Review request:
Are there any simplifications or improvements that can be made to the code?
Is the current implementation sufficient for its intended purpose, or are there potential pitfalls that need addressing?
Is the error-handling approach used in the code appropriate?
Edit: The code is part of a larger command-line program, which has to be ported over to Windows. The only thing non-portable about the program is fork() and exec().
Answer: Just use system()
While system() is often abused, here it is exactly what you want. It's a standard C function, so it's very portable:
#include <stdlib.h>
int main(void)
{
int result = system("dot -Tsvg trie.dot -o trie.svg");
if (result != 0) {
// Something went wrong, handle the error
…
return EXIT_FAILURE;
}
} | {
"domain": "codereview.stackexchange",
"id": 45385,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c, unix, winapi, portability",
"url": null
} |
kotlin, extension-methods
Title: Turn List> into Either>
Question: I'm trying to integrate Arrow-kt's Either into an application that needs to parse and validate filter input. This input is a comma separated list of criteria. Either sound like a good candidate for that job because it does both jobs at the same time.
Big-Picture
I've got a parser that takes care of the first step:
interface Parse<out T> {
operator fun invoke(value: String): Either<String, T>
}
object ParseList : Parse<List<String>> {
override fun invoke(value: String): Either<String, List<String>> {
val values =
value
.split(",")
.map { it.trim() }
.filter { it.isNotEmpty() }
return if (values.any()) Either.Right(values)
else Either.Left("Value is not a list.")
}
}
and other parsers that take care of an individual value like a date:
class ParseDate : Parse<LocalDate> {
@Suppress("MemberVisibilityCanBePrivate")
var formatter: DateTimeFormatter = DateTimeFormatter.ofLocalizedDate(FormatStyle.SHORT)
override fun invoke(value: String) =
runCatching { formatter.parse(value) }
.map { LocalDate.from(it) }
.map { Either.Right(it) }
.getOrElse { Either.Left("Value is not a date.") }
}
Combining these to components results in:
List<Either<String, T>>
so it needs to be converted into this:
Either<String, List<T>>
API
In orther to convert a List of Eithers into an Either of Lists i wrote the merge extension that processes each item and stops at the first Left, but keeps running on Right and collecting their values into a new list that is then return as a new Either:
fun <A, B> List<Either<A, B>>.merge(): Either<A, List<B>> {
val result = mutableListOf<B>()
for (x in this) {
when (x) {
is Either.Right -> result.add(x.value)
is Either.Left -> return Either.Left(x.value)
}
}
return Either.Right(result)
} | {
"domain": "codereview.stackexchange",
"id": 45386,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "kotlin, extension-methods",
"url": null
} |
kotlin, extension-methods
class MergeTest : FunSpec({
test("Can stop on left.") {
val list = listOf(
"foo".right(),
"bar".left(),
)
list.merge() shouldBe "bar".left()
}
test("Can merge right.") {
val list = listOf(
"foo".right(),
"bar".right(),
)
list.merge() shouldBe listOf("foo", "bar").right()
}
})
Is it necessary to do this on your own or is there a more clever way?
Answer: I think there is not simple built-in way to do this.
That said, your approach can be simplified a little bit:
fun <A, B> List<Either<A, B>>.merge(): Either<A, List<B>> =
Either.Right(map {
when (it) {
is Either.Right -> it.value
is Either.Left -> return it
}
})
It can be even reduced to a single line:
fun <A, B> List<Either<A, B>>.merge(): Either<A, List<B>> =
Either.Right(map { (it as? Either.Right)?.value ?: return it as Either.Left })
Although this one is significantly less readable. | {
"domain": "codereview.stackexchange",
"id": 45386,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "kotlin, extension-methods",
"url": null
} |
java, reflection
Title: Add field and value into an object by reflection
Question: original code:
import, hide some irrelevant company package
import cn.hutool.core.date.LocalDateTimeUtil;
import java.lang.reflect.Field;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.Objects;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.binding.MapperMethod;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.SqlCommandType;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.plugin.Intercepts;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.plugin.Signature;
import org.springframework.stereotype.Component;
code:
private static final int ACTION_CREATE_FLAG = 0;
private static final int ACTION_UPDATE_FLAG = 1;
private static final String FIELD_ZONE_CODE = "zoneCode";
private static final String FIELD_ZONE_NAME = "zoneName";
private static final String FIELD_CREATE_USER_ID = "createUserId";
private static final String FIELD_CREATE_USER_NAME = "createUserName";
private static final String FIELD_CREATE_TIME = "createTime";
private static final String FIELD_UPDATE_USER_ID = "updateUserId";
private static final String FIELD_UPDATE_USER_NAME = "updateUserName";
private static final String FIELD_UPDATE_TIME = "updateTime"; | {
"domain": "codereview.stackexchange",
"id": 45387,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "java, reflection",
"url": null
} |
java, reflection
private Object procUserInfo(Object obj, int type) {
OauthUserInfo authUser = GpJwtUtils.current();
if (obj == null) {
return null;
}
if (authUser == null) {
authUser = new OauthUserInfo();
authUser.setUserId("system");
authUser.setUserName("systemUser");
}
Field[] fields = ConvertUtils.getAllFields(obj);
for (Field field : fields) {
try {
if (!FIELD_ZONE_CODE.equals(field.getName())
&& !FIELD_ZONE_NAME.equals(field.getName())
&& !FIELD_CREATE_USER_ID.equals(field.getName())
&& !FIELD_CREATE_USER_NAME.equals(field.getName())
&& !FIELD_CREATE_TIME.equals(field.getName())
&& !FIELD_UPDATE_USER_ID.equals(field.getName())
&& !FIELD_UPDATE_USER_NAME.equals(field.getName())
&& !FIELD_UPDATE_TIME.equals(field.getName())) {
continue;
}
field.setAccessible(true);
if ((type == ACTION_CREATE_FLAG && FIELD_CREATE_TIME.equals(field.getName()))) {
if (LocalDateTime.class == field.getType()) {
field.set(obj, LocalDateTimeUtil.now());
} else {
field.set(obj, new Date());
}
} else if (type == ACTION_UPDATE_FLAG && FIELD_UPDATE_TIME.equals(field.getName())) {
if (LocalDateTime.class == field.getType()) {
field.set(obj, LocalDateTimeUtil.now());
} else {
field.set(obj, new Date());
}
}
if (field.get(obj) != null) {
continue;
}
// zoneCode
if (FIELD_ZONE_CODE.equals(field.getName())) {
Object value = field.get(obj);
String zoneCode = (String) ThreadContextHandler.get(CommonConstant.CONTEXT_ZONE_CODE); | {
"domain": "codereview.stackexchange",
"id": 45387,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "java, reflection",
"url": null
} |
java, reflection
if (type == ACTION_CREATE_FLAG && value == null && zoneCode != null) {
field.set(obj, zoneCode);
}
}
if (FIELD_ZONE_NAME.equals(field.getName())) {
Object value = field.get(obj);
String zoneName = (String) ThreadContextHandler.get(CommonConstant.CONTEXT_ZONE_NAME);
if (type == ACTION_CREATE_FLAG && value == null && zoneName != null) {
field.set(obj, zoneName);
}
}
// createUser
if (type == ACTION_CREATE_FLAG && FIELD_CREATE_USER_ID.equals(field.getName())) {
field.set(obj, authUser.getUserId());
}
if (type == ACTION_CREATE_FLAG && FIELD_CREATE_USER_NAME.equals(field.getName())) {
field.set(obj, authUser.getUserName());
}
// updateUser
if (FIELD_UPDATE_USER_ID.equals(field.getName())) {
field.set(obj, authUser.getUserId());
}
if (FIELD_UPDATE_USER_NAME.equals(field.getName())) {
field.set(obj, authUser.getUserName());
}
} catch (Exception e) {
log.warn("procUserInfo fail:", e);
}
}
return obj;
} | {
"domain": "codereview.stackexchange",
"id": 45387,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "java, reflection",
"url": null
} |
java, reflection
method call:
MappedStatement ms = (MappedStatement) invocation.getArgs()[0];
int actionFlag = ms.getSqlCommandType() == SqlCommandType.INSERT ? ACTION_CREATE_FLAG : ACTION_UPDATE_FLAG;
procUserInfo(parameterObject, actionFlag);
my try:
private static final int ACTION_CREATE_FLAG = 0;
private static final int ACTION_UPDATE_FLAG = 1;
private static final String FIELD_CREATE_TIME = "createTime";
private static final String FIELD_UPDATE_TIME = "updateTime";
private static final LinkedList<String> ZONE_CODE_NAMES = (LinkedList<String>)
Arrays.asList("zoneCode","zoneName");
private static final LinkedList<String> FIELD_CREATE_NAMES = (LinkedList<String>)
Arrays.asList("createUserId", "createUserName", FIELD_CREATE_TIME);
private static final LinkedList<String> FIELD_UPDATE_NAMES = (LinkedList<String>)
Arrays.asList("updateUserId", "updateUserName", FIELD_UPDATE_TIME); | {
"domain": "codereview.stackexchange",
"id": 45387,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "java, reflection",
"url": null
} |
java, reflection
/**
* add zone info and createUser or updateUser info into an object
*
* @param obj any database related obj
* @param type 0 createUser,1 updateUser
* @return obj with zone info and createUser or updateUser info
*/
private Object procUserInfo(Object obj, int type) throws NoSuchFieldException {
if (type != ACTION_UPDATE_FLAG && type != ACTION_CREATE_FLAG) {
return obj;
}
if (obj == null) {
return null;
}
for (Map.Entry<String,Object> fieldInfo:getFieldInfos(type,obj,getAuthUser()).entrySet()) {
try {
setField(obj,fieldInfo.getKey(),fieldInfo.getValue());
} catch (Exception e) {
log.warn("procUserInfo fail", e);
}
}
return obj;
}
private OauthUserInfo getAuthUser(){
OauthUserInfo authUser = GpJwtUtils.current();
if (authUser == null) {
authUser = new OauthUserInfo();
authUser.setUserId("system");
authUser.setUserName("systemUser");
}
return authUser;
}
private void setField(Object obj, String fieldName, Object value) throws NoSuchFieldException {
if (value == null) {
return;
}
Field field = obj.getClass().getField(fieldName);
ReflectionUtils.makeAccessible(field);
ReflectionUtils.setField(field,obj,value);
}
private Map<String,Object> getFieldInfos(int type,Object obj,OauthUserInfo authUser) throws NoSuchFieldException {
LinkedList<String> fieldNames = ZONE_CODE_NAMES;
fieldNames.addAll(type == ACTION_CREATE_FLAG ? FIELD_CREATE_NAMES : FIELD_UPDATE_NAMES);
List<Object> values = getValues(obj,authUser);
return IntStream.range(0, fieldNames.size()).boxed().collect(Collectors.toMap(fieldNames::get, values::get));
}
private LinkedList<Object> getValues(Object obj,OauthUserInfo authUser) throws NoSuchFieldException {
LinkedList<Object> result = new LinkedList<>();
result.add(ThreadContextHandler.get(CommonConstant.CONTEXT_ZONE_CODE)); | {
"domain": "codereview.stackexchange",
"id": 45387,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "java, reflection",
"url": null
} |
java, reflection
result.add(ThreadContextHandler.get(CommonConstant.CONTEXT_ZONE_CODE));
result.add(ThreadContextHandler.get(CommonConstant.CONTEXT_ZONE_NAME));
result.add(authUser.getUserId());
result.add(authUser.getUserName());
result.add(LocalDateTime.class == obj.getClass().getField(FIELD_CREATE_TIME).getType() ?
LocalDateTimeUtil.now() : new Date());
result.add(LocalDateTime.class == obj.getClass().getField(FIELD_UPDATE_TIME).getType() ?
LocalDateTimeUtil.now() : new Date());
return result;
} | {
"domain": "codereview.stackexchange",
"id": 45387,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "java, reflection",
"url": null
} |
java, reflection
description:
I know the method name is not the best name, but I didn't find a better name now.
Control a method by int type maybe a code smell, but I didn't find a better solution either.
Declare a static variable combine with enum and string maybe a bad practice, such as FIELD_CREATE_NAMES, any better solution?
Answer: It's too bad that the review context omits import statements.
They would have helped with looking up relevant documentation.
EDIT: Ok, I see those recently added Apache Ibatis imports, thank you.
length
This method is entirely too long.
Fortunately, I see that below there's a revision which breaks out helpers, good.
javadoc
This is super vague:
private Object procUserInfo(Object obj, int type) {
No idea what that object is all about, so I will just keep reading.
Maybe it is a "user info" object?
The type looks like it wants to be an Enum.
I guess we have an abbreviation for the verb "process", here?
But that's a pretty vague verb, so I don't know what
promise
this method makes to its caller.
Spell it out, if I guessed correctly.
Maybe use a verb like "alter"?
Maybe ditch the type parameter,
and turn this into a pair of methods,
so an engineer can call
createUserInfo(), or
updateUserInfo()
Most importantly, if a three-word identifier cannot communicate
to the reader what this function does, then offer a one-sentence
/** javadoc */ explanation of what it does.
What's the post-condition?
How could I tell that the right thing happened, after calling it?
Oh good, I see that such a sentence has been added in the revised version.
defer work
OauthUserInfo authUser = GpJwtUtils.current(); | {
"domain": "codereview.stackexchange",
"id": 45387,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "java, reflection",
"url": null
} |
java, reflection
In the case that obj is null, there's no need to make this call.
So just defer it until after that test.
Making someone the systemUser in the case that the .current() call failed
seems an odd default.
We don't want to make it harder to become systemUser?
skip unknown field
Testing for unknown field name seems tediously long.
Maybe throw those known names into a HashSet, and test for membership?
Couldn't an Enum accomplish the same thing for us?
Consider turning some ifs into a switch statement.
It's not clear why we need the INSERT / UPDATE type flag,
nor why it's OK for caller to specify mismatched type and name
and then we just silently ignore it.
Maybe we don't need that type parameter at all?
The field name seems to already specify what the caller intended.
re-throw
At the end we log any exception that happened and then swallow it,
so caller believes we succeeded.
This seems Bad.
Prefer to log it and re-throw it, perhaps first wrapping it in a RuntimeException
if that makes the signatures more convenient.
Moving on to the revised version.
javadoc
This is an improvement over nothing, but it's still not great.
/**
* add zone info and createUser or updateUser info into an object
*
* @param obj any database related obj
* @param type 0 createUser,1 updateUser
* @return obj with zone info and createUser or updateUser info
*/ | {
"domain": "codereview.stackexchange",
"id": 45387,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "java, reflection",
"url": null
} |
java, reflection
Let's start with that "any database related obj" description,
which makes it clear that we chose the wrong identifier.
It isn't any old object obj.
It's a database object dbObj.
I still wish you'd given me a hint about some representative
class to which it might belong.
The review context just offers parameterObject,
which doesn't bring me any closer to enlightenment.
Offering unit tests
would have been helpful -- they have instructional value.
When I try to parse the sentence,
"add zone info and createUser or updateUser info into [a database] object,"
I get a little closer to understanding the promise made,
better than "process user info," but I'm still left wanting more detail,
perhaps from a second sentence.
I at least now know the verb "process" implies the side effect
of either creating or updating some user info.
helpers
Breaking out four helper methods,
starting with getAuthUser,
is a big win, thank you.
I appreciate that the contract is "getAuthUser shall never return null",
which simplifies logic up in the caller.
We validate pre-conditions,
then loop through some reads and writes,
very straightforward.
After logging an error we should re-throw,
rather than swallow the exception.
fatal error
In setField it appears it may be better
to throw fatal RuntimeException,
rather than silently ignore a null input
which caller should never have sent us in the first place.
Writing lots of code involves writing some bugs.
When we write bugs we prefer that they be shallow bugs.
It should be easy to pin the blame on where the bug started,
and fix it there, rather than debugging through a call stack
in search of the root cause. | {
"domain": "codereview.stackexchange",
"id": 45387,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "java, reflection",
"url": null
} |
c++, c++20, deque
Title: C++ Deque Implementation
Question: Took a shot at implementing std::deque in C++. I aimed for amortized O(1) push_front and push_back, O(1) pop_front and pop_back, and O(1) random access.
I do this by maintaining two vectors of pointers to fixed-size blocks of size 16, called front_blocks and back_blocks. Initially, push_front operations add to the blocks in front_blocks, and push_back operations add to the blocks in back_blocks. However, I also keep track of the front_block_idx and the back_block_idx, to denote which block the current front and current back are in.
These indices can either be 0 or positive, meaning that the current front/back is in back_blocks, or they can be negative, meaning the current front/back is in front_blocks. This was the cleanest way I could think of to get the desired complexities while keeping with the fixed-size block concept from the STL and keeping iterators valid when possible.
I did not aim for this to be a 100% copy of the STL, however, so please let me know if I am missing any crucial functionality, but I did not attempt to get the exact same typedefs as the STL, or all of the possible overloads for all the methods, etc.
The Deque class is below:
template <typename T>
class Deque {
public:
using iterator = Iterator<T, T>;
using const_iterator = Iterator<T, const T>;
using reverse_iterator = std::reverse_iterator<iterator>;
using const_reverse_iterator = std::reverse_iterator<const_iterator>;
constexpr Deque()
: front_blocks{}, back_blocks{}, front_block_idx{0},
front_idx_in_block{0}, back_block_idx{0},
back_idx_in_block{0}, m_size{0} {
back_blocks.push_back(new T[BLOCK_SIZE]);
}
~Deque() {
clear();
for (T* block : front_blocks) {
delete[] block;
}
for (T* block : back_blocks) {
delete[] block;
}
} | {
"domain": "codereview.stackexchange",
"id": 45388,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, c++20, deque",
"url": null
} |
c++, c++20, deque
for (T* block : back_blocks) {
delete[] block;
}
}
constexpr Deque(std::initializer_list<T> items) : Deque() {
assign(items.begin(), items.end());
}
constexpr Deque(const Deque& other) : Deque() {
// with this implementation, the underlying representation
// of values in the deque may be different, but the values
// themselves and the order remain the same
assign(other.cbegin(), other.cend());
}
constexpr Deque& operator=(const Deque& other) {
Deque temp{other};
swap(temp);
return *this;
}
constexpr Deque(Deque&& other) noexcept : Deque() {
swap(other);
}
constexpr Deque& operator=(Deque&& other) noexcept {
swap(other);
return *this;
}
constexpr bool operator==(const Deque& other) {
if (size() != other.size())
return false;
for (std::size_t idx = 0; idx < size(); ++idx) {
if ((*this)[idx] != other[idx])
return false;
}
return true;
}
T& front() {
return (*this)[0];
}
T& back() {
return (*this)[m_size - 1];
}
template <typename... Args>
constexpr void emplace_front(Args&&... args) {
decrement(front_idx_in_block, front_block_idx);
expand_front_if_needed();
T* block = get_block(front_block_idx, front_blocks, back_blocks);
new (std::addressof(block[front_idx_in_block]))
T(std::forward<Args>(args)...);
++m_size;
}
constexpr void push_front(const T& value) {
emplace_front(value);
}
constexpr void push_front(T&& value) {
emplace_front(std::move(value));
}
constexpr void pop_front() {
T* block = get_block(front_block_idx, front_blocks, back_blocks);
std::destroy_at(std::addressof(block[front_idx_in_block])); | {
"domain": "codereview.stackexchange",
"id": 45388,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, c++20, deque",
"url": null
} |
c++, c++20, deque
increment(front_idx_in_block, front_block_idx);
m_size--;
}
template <typename... Args>
constexpr void emplace_back(Args&&... args) {
T* block = get_block(back_block_idx, front_blocks, back_blocks);
new (std::addressof(block[back_idx_in_block]))
T(std::forward<Args>(args)...);
increment(back_idx_in_block, back_block_idx);
expand_back_if_needed();
++m_size;
}
constexpr void push_back(const T& value) {
emplace_back(value);
}
constexpr void push_back(T&& value) {
emplace_back(std::move(value));
}
constexpr void pop_back() {
decrement(back_idx_in_block, back_block_idx);
T* block = get_block(back_block_idx, front_blocks, back_blocks);
std::destroy_at(std::addressof(block[back_idx_in_block]));
--m_size;
}
constexpr T& operator[](std::size_t idx) const {
auto [cur_block, idx_within_cur_block] = idx_to_block_position(idx);
return get_block(cur_block, front_blocks,
back_blocks)[idx_within_cur_block];
}
constexpr T& operator[](std::size_t idx) {
auto [cur_block, idx_within_cur_block] = idx_to_block_position(idx);
return get_block(cur_block, front_blocks,
back_blocks)[idx_within_cur_block];
}
constexpr std::size_t size() const noexcept {
return m_size;
}
constexpr bool empty() const noexcept {
return m_size == 0;
}
constexpr void swap(Deque& other) noexcept {
using std::swap;
swap(front_blocks, other.front_blocks);
swap(back_blocks, other.back_blocks);
swap(front_block_idx, other.front_block_idx);
swap(front_idx_in_block, other.front_idx_in_block);
swap(back_block_idx, other.back_block_idx);
swap(back_idx_in_block, other.back_idx_in_block);
swap(m_size, other.m_size);
}
/* Iterator support */ | {
"domain": "codereview.stackexchange",
"id": 45388,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, c++20, deque",
"url": null
} |
c++, c++20, deque
/* Iterator support */
iterator begin() {
return iterator(front_blocks, back_blocks, front_block_idx,
front_idx_in_block, 0);
}
iterator end() {
return iterator(front_blocks, back_blocks, back_block_idx,
back_idx_in_block, size());
}
const_iterator cbegin() const {
return const_iterator(front_blocks, back_blocks, front_block_idx,
front_idx_in_block, 0);
}
const_iterator cend() const {
return const_iterator(front_blocks, back_blocks, back_block_idx,
back_idx_in_block, size());
}
reverse_iterator rbegin() {
return reverse_iterator(end());
}
reverse_iterator rend() {
return reverse_iterator(begin());
}
const_reverse_iterator crbegin() const {
return const_reverse_iterator(cend());
}
const_reverse_iterator crend() const {
return const_reverse_iterator(cbegin());
}
template <typename InputIt>
void assign(InputIt begin, InputIt end) {
for (auto&& it = begin; it != end; ++it) {
push_back(*it);
}
}
iterator insert(iterator pos, const T& value) {
return insert(pos, 1, value);
}
iterator insert(iterator pos, std::size_t count, const T& value) {
if (count == 0)
return pos;
int pos_idx = std::distance(begin(), pos);
int new_size = m_size + count;
// Ensure there is enough space for the new elements
while (idx_to_block_position(new_size - 1).first >=
back_blocks.size()) {
back_blocks.push_back(new T[BLOCK_SIZE]);
}
// Move existing elements to make space for the new elements
for (int i = int(m_size) - 1; i >= pos_idx; --i) {
move_deque_element(i, i + count);
} | {
"domain": "codereview.stackexchange",
"id": 45388,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, c++20, deque",
"url": null
} |
c++, c++20, deque
// Construct new elements in place
for (std::size_t i = 0; i < count; ++i) {
new (std::addressof((*this)[pos_idx + i])) T(value);
}
m_size = new_size;
return iterator(front_blocks, back_blocks,
idx_to_block_position(pos_idx).first,
idx_to_block_position(pos_idx).second, pos_idx);
}
iterator erase(iterator pos) {
return erase(pos, 1);
}
iterator erase(iterator pos, int count) {
if (count == 0)
return pos;
int pos_idx = std::distance(begin(), pos);
int new_size = m_size - count;
// destroy elements being erased
for (int i = pos_idx; i < pos_idx + count; ++i) {
auto [block_idx, idx_in_block] = idx_to_block_position(i);
T* block = get_block(block_idx, front_blocks, back_blocks);
std::destroy_at(std::addressof(block[block_idx]));
}
// move elements back
for (int i = pos_idx + count; i < pos_idx + 2 * count; ++i) {
move_deque_element(i, i - count);
}
m_size = new_size;
return iterator(front_blocks, back_blocks,
idx_to_block_position(pos_idx).first,
idx_to_block_position(pos_idx).second, pos_idx);
}
void clear() noexcept {
for (auto&& elem : *this) {
elem.~T();
}
m_size = 0;
}
private:
std::vector<T*> front_blocks, back_blocks;
int front_block_idx, front_idx_in_block;
int back_block_idx, back_idx_in_block;
std::size_t m_size;
constexpr void expand_front_if_needed() {
if (get_front_block_vector_idx(front_block_idx) >=
front_blocks.size()) {
front_blocks.push_back(new T[BLOCK_SIZE]);
}
} | {
"domain": "codereview.stackexchange",
"id": 45388,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, c++20, deque",
"url": null
} |
c++, c++20, deque
constexpr void expand_back_if_needed() {
if (back_block_idx >= back_blocks.size()) {
back_blocks.push_back(new T[BLOCK_SIZE]);
}
}
constexpr std::pair<int, int>
idx_to_block_position(std::size_t idx) const noexcept {
int num_blocks = idx / BLOCK_SIZE;
int cur_block = front_block_idx + num_blocks;
int offset = idx % BLOCK_SIZE;
int idx_within_cur_block = front_idx_in_block + offset;
if (idx_within_cur_block >= BLOCK_SIZE) {
cur_block += 1;
idx_within_cur_block %= BLOCK_SIZE;
}
return {cur_block, idx_within_cur_block};
}
void move_deque_element(int src_idx, int dest_idx) {
auto [src_block, src_block_idx] = idx_to_block_position(src_idx);
auto [dest_block, dest_block_idx] = idx_to_block_position(dest_idx);
T* src = get_block(src_block, front_blocks, back_blocks);
T* dest = get_block(dest_block, front_blocks, back_blocks);
new (std::addressof(dest[dest_block_idx]))
T(std::move(src[src_block_idx]));
std::destroy_at(std::addressof(src[src_block_idx]));
}
};
The Iterator class this uses:
template <typename T, typename ElementType>
class Iterator {
public:
using difference_type = std::ptrdiff_t;
using value_type = T;
using pointer = T*;
using reference = T&;
using iterator_category = std::random_access_iterator_tag;
Iterator(const std::vector<T*>& front_blocks,
const std::vector<T*>& back_blocks,
int block_idx,
int idx_within_block,
int deque_idx)
: front_blocks{front_blocks},
back_blocks{back_blocks}, block_idx{block_idx},
idx_within_block{idx_within_block}, deque_idx{deque_idx} {
}
ElementType& operator*() const {
return *current();
}
ElementType* operator->() const {
return current();
} | {
"domain": "codereview.stackexchange",
"id": 45388,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, c++20, deque",
"url": null
} |
c++, c++20, deque
Iterator& operator++() {
increment(idx_within_block, block_idx);
return *this;
}
Iterator operator++(int) {
Iterator temp = *this;
++(*this);
return temp;
}
Iterator& operator--() {
decrement(idx_within_block, block_idx);
return *this;
}
Iterator operator--(int) {
Iterator temp = *this;
--(*this);
return temp;
}
Iterator& operator+=(difference_type n) {
deque_idx += n;
shift_indices(block_idx, idx_within_block, n);
return *this;
}
Iterator& operator-=(difference_type n) {
deque_idx -= n;
shift_indices(block_idx, idx_within_block, -n);
return *this;
}
Iterator operator+(difference_type n) const {
Iterator temp = *this;
return temp += n;
}
Iterator operator-(difference_type n) const {
Iterator temp = *this;
return temp -= n;
}
difference_type operator-(const Iterator& other) const {
return this->deque_idx - other.deque_idx;
}
bool operator==(const Iterator& other) const {
return front_blocks == other.front_blocks and
back_blocks == other.back_blocks and
block_idx == other.block_idx and
idx_within_block == other.idx_within_block;
}
bool operator!=(const Iterator& other) const {
return !(*this == other);
}
private:
const std::vector<T*>&front_blocks, &back_blocks;
int block_idx, idx_within_block, deque_idx;
ElementType* current() const {
return get_block(block_idx, front_blocks, back_blocks) +
idx_within_block;
}
};
Some utility functions/constants (along with the headers used for the whole class):
#include <algorithm>
#include <cstddef>
#include <exception>
#include <memory>
#include <stdexcept>
#include <utility>
static constexpr std::size_t BLOCK_SIZE = 16; | {
"domain": "codereview.stackexchange",
"id": 45388,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, c++20, deque",
"url": null
} |
c++, c++20, deque
static constexpr std::size_t BLOCK_SIZE = 16;
constexpr int get_front_block_vector_idx(int block_idx) {
if (block_idx >= 0) {
throw std::out_of_range("only works with negative values");
}
return abs(block_idx) - 1;
}
constexpr void increment(int& idx_in_block, int& block_idx) noexcept {
idx_in_block++;
if (idx_in_block == BLOCK_SIZE) {
idx_in_block = 0;
block_idx++;
}
}
constexpr void decrement(int& idx_in_block, int& block_idx) noexcept {
if (idx_in_block > 0) {
idx_in_block--;
} else {
idx_in_block = BLOCK_SIZE - 1;
block_idx -= 1;
}
}
template <typename T>
constexpr T* get_block(int block_idx,
const std::vector<T*>& front_blocks,
const std::vector<T*>& back_blocks) {
if (block_idx >= 0) {
return back_blocks[block_idx];
} else {
return front_blocks[get_front_block_vector_idx(block_idx)];
}
}
constexpr void shift_indices(int& block_idx, int& idx_within_block, int shift) {
// Calculate the total index relative to the start of the deque
int total_idx = block_idx * BLOCK_SIZE + idx_within_block + shift;
// Update block_idx and idx_within_block based on the new total index
block_idx = total_idx / BLOCK_SIZE;
idx_within_block = total_idx % BLOCK_SIZE;
// Handle negative indices, ensuring block_idx and idx_within_block are
// always valid
while (idx_within_block < 0) {
idx_within_block += BLOCK_SIZE;
block_idx--;
}
}
And finally some unit tests:
#define BOOST_TEST_MODULE DequeTest
#include <boost/test/included/unit_test.hpp>
#include <deque>
#include "Deque.h"
BOOST_AUTO_TEST_CASE(TestConstructors) {
Deque<int> dq1;
BOOST_CHECK(dq1.size() == 0);
Deque<int> dq2{1, 2, 3, 4, 5};
BOOST_CHECK(dq2.size() == 5);
BOOST_CHECK(dq2[0] == 1 && dq2[4] == 5); | {
"domain": "codereview.stackexchange",
"id": 45388,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, c++20, deque",
"url": null
} |
c++, c++20, deque
Deque<int> dq3(dq2);
BOOST_CHECK(dq3.size() == dq2.size());
BOOST_CHECK(dq3[0] == dq2[0] && dq3[4] == dq2[4]);
Deque<int> dq4(std::move(dq2));
BOOST_CHECK(dq4.size() == 5);
BOOST_CHECK(dq2.size() == 0);
}
BOOST_AUTO_TEST_CASE(TestPushPop) {
Deque<int> dq;
dq.push_back(1);
dq.push_front(2);
BOOST_CHECK(dq.size() == 2);
BOOST_CHECK(dq[0] == 2 && dq[1] == 1);
dq.pop_back();
BOOST_CHECK(dq.size() == 1 && dq[0] == 2);
dq.pop_front();
BOOST_CHECK(dq.empty());
for (int i = 1; i <= 100; ++i) {
dq.push_front(i);
BOOST_CHECK(dq.size() == i);
}
for (int i = 99; i >= 0; --i) {
dq.pop_back();
BOOST_CHECK(dq.size() == i);
}
}
BOOST_AUTO_TEST_CASE(TestIterators) {
Deque<int> dq;
for (int i = 0; i < 100; ++i) {
dq.push_back(i);
}
Deque<int> dq2;
for (auto it = dq.begin(); it != dq.end(); ++it) {
dq2.push_back(*it);
}
BOOST_CHECK(dq == dq2);
Deque<int> rev;
for (auto it = dq.rbegin(); it != dq.rend(); ++it) {
rev.push_back(*it);
}
for (int i = 0, j = rev.size() - 1; i < j; i++, j--) {
swap(rev[i], rev[j]);
}
BOOST_CHECK(dq == rev);
}
BOOST_AUTO_TEST_CASE(TestBoundaryInsertionAndDeletion) {
Deque<int> dq;
dq.insert(dq.begin(), 1);
BOOST_CHECK(dq.size() == 1 && dq[0] == 1);
dq.insert(dq.end(), 2);
BOOST_CHECK(dq.size() == 2 && dq[1] == 2);
dq.erase(dq.begin());
BOOST_CHECK(dq.size() == 1 && dq[0] == 2);
dq.erase(dq.begin());
BOOST_CHECK(dq.empty());
}
BOOST_AUTO_TEST_CASE(TestLargeDataHandling) {
Deque<int> dq;
const std::size_t large_size = 100000;
for (std::size_t i = 0; i < large_size; ++i) {
dq.push_back(i);
}
BOOST_CHECK(dq.size() == large_size);
BOOST_CHECK(dq[large_size - 1] == large_size - 1);
for (std::size_t i = 0; i < large_size; ++i) {
dq.pop_front();
}
BOOST_CHECK(dq.empty());
} | {
"domain": "codereview.stackexchange",
"id": 45388,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, c++20, deque",
"url": null
} |
c++, c++20, deque
BOOST_AUTO_TEST_CASE(TestConsistencyAfterMultipleOperations) {
Deque<int> dq;
for (int i = 0; i < 1000; ++i) {
dq.push_back(i);
dq.push_front(-i);
}
BOOST_CHECK(dq.size() == 2000);
for (int i = 0; i < 1000; ++i) {
BOOST_CHECK(dq[i] == -999 + i);
BOOST_CHECK(dq[1999 - i] == 999 - i);
}
for (int i = 0; i < 1000; ++i) {
dq.pop_back();
dq.pop_front();
}
BOOST_CHECK(dq.empty());
}
BOOST_AUTO_TEST_CASE(TestEmplacement) {
Deque<std::pair<int, std::string>> dq;
dq.emplace_back(1, "one");
BOOST_CHECK(dq.back().first == 1 && dq.back().second == "one");
dq.emplace_front(0, "zero");
BOOST_CHECK(dq.front().first == 0 && dq.front().second == "zero");
BOOST_CHECK(dq.size() == 2);
BOOST_CHECK(dq[0].first == 0 && dq[1].first == 1);
}
BOOST_AUTO_TEST_CASE(TestNonIntTypes) {
Deque<std::string> dq;
dq.push_back("Hello");
dq.push_back("World");
BOOST_CHECK(dq.size() == 2);
BOOST_CHECK(dq[0] == "Hello" && dq[1] == "World");
}
BOOST_AUTO_TEST_CASE(TestStringLargeDataHandling) {
Deque<std::string> dq;
const std::size_t large_size = 10000;
for (std::size_t i = 0; i < large_size; ++i) {
dq.push_back("String " + std::to_string(i));
}
BOOST_CHECK(dq.size() == large_size);
BOOST_CHECK(dq[large_size - 1] ==
"String " + std::to_string(large_size - 1));
for (std::size_t i = 0; i < large_size; ++i) {
dq.pop_front();
}
BOOST_CHECK(dq.empty());
} | {
"domain": "codereview.stackexchange",
"id": 45388,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, c++20, deque",
"url": null
} |
c++, c++20, deque
Answer: It leaks memory when used as a queue
The name "deque" stands for double-ended queue. A typical way to use a deque is when you need a queue where you push only into one end and pop only from the other end. Often, the total number of elements in a deque has a small upper bound. However, in this scenario, your Deque will allocate more and more memory the longer it is used, as it never deletes blocks until the whole Deque object is destructed.
Use more helper classes
It's already great that you used std::vector for front_blocks and back_blocks, that saves you a lot of trouble having to manage memory for those. But you can create some more classes yourself to simplify Deque itself. For example, you could create a class Block that represents one block, with helper functions to construct, access and destroy its elements.
Use std::unique_ptr to avoid managing memory for the blocks.
Also consider creating a class Index that groups a block_idx and idx_in_block together. You can then for example add operator++() and operator--() member functions to make modying an index as simple as possible.
Use std::size_t for counts and indices
You use int for counts and indices, but an int might not be large enough to handle all the elements you could store in memory. Instead, use std::size_t. Of course, if you really need to handle negative indices, you need something else, like std::ptrdiff_t.
Also, consider that a single std::size_t is large enough to be able to index any amount of elements that could ever be stored in memory. So instead of having a "block index" and "index in block", you can have a single index where the low bits are the index inside the block, and the high bits the block index.
Reduce the size of an Iterator | {
"domain": "codereview.stackexchange",
"id": 45388,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, c++20, deque",
"url": null
} |
c++, c++20, deque
Reduce the size of an Iterator
Your Iterator stores two pointers and three integers. That's quite a lot. You can simplify this by storing just a pointer to the Deque object itself, and you can store the index in a single integer; I've already mentioned that above, and it seems deque_idx already fulfills that role.
The reduced size will help a lot in case a user wants to store many iterators somewhere. And while it looks less efficient to dereference a Deque* to get a pointer to front_blocks and/or back_blocks, the code will be inlined anyway, and the compiler will very likely be able to optimize that away.
Make BLOCK_SIZE a static member
Instead of having a global constant BLOCK_SIZE, make it a static constexpr member variable. This way, you can make it have a different value depending on sizeof(T). Consider for example having a Deque<char>: allocating only 16 bytes for a block is very inefficient, while for Deque<HugeClass> you might even want to have a BLOCK_SIZE of 1.
Missing const versions of front() and back()
You added const iterators and several other const member functions, but you forgot to add const versions of front() and back().
Unnecessary swap()
Your swap() just calls swap() on all member variables. In that case, you don't need to implement swap() at all.
Don't declare Iterator in the global namespace
While the name Deque is quite unique, what if you also want to implement your own Vector, Array and Map? These would all need their own iterator types, so you will then run into an issue if you have the genericly named Iterator in the global namespace. There are several solutions: | {
"domain": "codereview.stackexchange",
"id": 45388,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, c++20, deque",
"url": null
} |
c++, c++20, deque
Rename Iterator to DequeIterator.
Create a unique namespace where you can put this Iterator in.
Move Iterator into class Deque. | {
"domain": "codereview.stackexchange",
"id": 45388,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, c++20, deque",
"url": null
} |
c++, strings, search
Title: Fast search for the longest repeating substrings in large text
Question: Is there a chance to implement the code below better with the features of recent C++ versions?
Functional specification
Having a large text and already built prefix array find the longest substrings (limited by the number of repetitions) getting benefit from already existing prefix array, if reasonable. Provide the version which would benefit from multi-threading keeping the code as simple as possible.
Implementation
The fully functional demo.
Reservation: current implementation utilizes execution policies, so using ranges/projections/views under the question; would work if multi-threading requirement from above met.
The code has raised my question on SO Is there a way to introduce transparent sentinels before the begin and at the end of std::vector data?, where I tried to simplify array borders checking guards, introducing sentinels and people answered that here we need to simplify the code first to see if this ever needed. So, I publish the code to see if this code could be written much simpler before trying sentinels.
Most important pieces of code under the question are below.
Helper function to simplify the core search function:
std::size_t findMatchLength(const char* text, std::size_t index1, std::size_t index2) {
// Limit the offset so we do not read past the beginning of the array.
auto limit = std::min(index1, index2);
for (std::size_t offset = 0; offset <= limit; ++offset)
if (text[index1 - offset] != text[index2 - offset])
return offset;
return limit + 1;
} | {
"domain": "codereview.stackexchange",
"id": 45389,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, strings, search",
"url": null
} |
c++, strings, search
return limit + 1;
}
As a second thought, I am in two minds about the findMatchLength function. It works pretty well to simplify the findLongestSimilarSequences function and self-documenting its flow, but violates Occam's razor principle, introducing a new essence. When I figured out the name for it, I based on the usage context in the findLongestSimilarSequences function. On the other hand, I can't explain its existence in higher scope, namely I can't give it a good generic name which explains what exactly it does and can't explain usage of both indexes out of context of findLongestSimilarSequences. So, from this perspective, this is a bad candidate for extraction and generalization. Please, correct me if I am wrong here.
Another helper function template to update maximum value in multi-threading environment.
template<typename T>
void update_max(std::atomic<T>& max_value, T const& value) noexcept
{
T prev_value = max_value;
while (prev_value < value &&
!max_value.compare_exchange_weak(prev_value, value))
{}
}
The search function itself:
void findLongestSimilarSequences(std::string& text, const std::vector<int>& index) {
constexpr std::size_t largest_sequence = std::numeric_limits<std::size_t>::max();
const int max_repetitions = 5; // Could be replaced with smallest sequence to find
std::vector <std::size_t> adjacent_matches(index.size());
for (int repetitions = 2; repetitions <= max_repetitions; ++repetitions) {
std::atomic<std::size_t> max_match_length = 0;
std::for_each(std::execution::par_unseq, index.begin(), index.end() - (repetitions - 1), [&](const int& item) {
size_t idx = &item - std::data(index);
std::size_t match_length = findMatchLength(text.c_str(), item, *(&item + (repetitions-1)));
adjacent_matches[idx] = match_length; | {
"domain": "codereview.stackexchange",
"id": 45389,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, strings, search",
"url": null
} |
c++, strings, search
adjacent_matches[idx] = match_length;
if (match_length < largest_sequence) {
update_max(max_match_length, match_length);
}
});
if (max_match_length < 1)
continue;
std::cout << "Longest equal sequence(s) repeated " << repetitions << " times is " << max_match_length << " chars" << std::endl;
std::cout << "The susequence(s) are:" << std::endl;
for (int i = 0; i < adjacent_matches.size()-1; ++i) {
if (adjacent_matches[i] == max_match_length) {
std::cout << text.substr(index[i] - (max_match_length - 1),max_match_length) << std::endl;
}
}
}
}
Concerns for this function
I don’t like the code structure, is there a way to simplify it and make more readable?
I don’t like two responsibilities of the function, namely to find substrings and to print them, but I don’t see better solutions (maybe callback for printing?) because the text size is large and there could be too many results to keep them in maps and other dynamic structures which will cause significant memory fragmentation and could be time-consuming.
Some other questions are in form of comments in the code.
The main function is quite simple:
int main()
{
std::string text = "This-string-contains-repetitions-and-these-repetitions-the-string-contains-as-repetitions-these-repetitions";
// Am I correct that this wouldn't create a copy of array on return from function?
// Will copy elision do its work or should I do something explicit?
auto prefix_array_index = buildPrefixArrayIndex(text);
findLongestSimilarSequences(text, prefix_array_index);
} | {
"domain": "codereview.stackexchange",
"id": 45389,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, strings, search",
"url": null
} |
c++, strings, search
findLongestSimilarSequences(text, prefix_array_index);
}
Please don’t pay much attention to using std::string and its functions here, in the real code the text is compiled in lexems ids and stored in std::vector<int>, but this implementation would grow the code size here which I want to avoid.
Please don’t pay much attention to the function buildPrefixArrayIndex, as well, since it is provided only to make the code executable and testable. In real code it is based on std::vector and offsets.
std::vector<int> buildPrefixArrayIndex(const std::string& str) {
std::vector<int> suffix_array(str.length());
std::iota(suffix_array.begin(), suffix_array.end(), 0);
std::sort(std::execution::par_unseq, suffix_array.begin(), suffix_array.end(), [&](int lhs, int rhs) {
auto lstr = str.substr(0, lhs + 1);
// Could be replaced with rbegin(), but I am not sure that code will be readable
std::reverse(lstr.begin(),lstr.end());
auto rstr = str.substr(0,rhs+1);
std::reverse(rstr.begin(), rstr.end());
return lstr < rstr;
});
return suffix_array;
}
Can you please conduct code review and show the way to implement this code with the latest versions of C++?
I want to keep with pure C++ without any libraries like boost (of course, STL is applicable).
Answer: Redesign the interface
You already have some doubts about your code's structure, in particular that findLongestSimilarSequences() has too many responsibilities. You want the function to just do the finding part, and move the loop that prints the longest sequences out of it. So ideally, you want to be able to write something like:
for (int repetitions = 2; repetitions <= 5; ++repetitions) {
std::cout << "Longest equal sequence(s) repeated " << repetitions << " times:\n";
for (auto sequence: findLongestSimilarSequences(text, index, repetitions)) {
std::cout << sequence << "\n";
}
} | {
"domain": "codereview.stackexchange",
"id": 45389,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, strings, search",
"url": null
} |
c++, strings, search
So findLongestSimilarSequences() has to return something that can be iterated over. That can be as simple as a std::vector<std::string_view>, which is quite efficient. Consider that you already allocate a vector of size index.size() in your function.
std::vector<std::string_view>
findLongestSimilarSequences(const std::string& text,
const std::vector<int>& index,
int min_repetitions)
{
// Build adjacent_matches
…
// Create the result
std::vector<std::string_view> result;
for (int i = 0; i < adjacent_matches.size() - 1; ++i) {
if (adjacent_matches[i] == max_match_length) {
result.emplace_back(text.data() + index[i] - (max_match_length - 1), max_match_length);
}
}
return result;
}
But when looking at your code, I also have other questions about the interface:
Why is your text not passed as a const reference?
Why not use std::string_view for text?
Why limit it to strings at all? It seems to me that you could make this work for any kind of range.
Why does the caller need to pass a vector named index? What if you pass the wrong "index"? Either let findLongestSimilarSequences calculate this index, or create a class that encapsulates both the text and index, and pass a reference to that to this function.
Why does the name say "SimilarSequences"? That implies they might not be exactly identical. I think "RepeatedSubsequences" would be a better name. | {
"domain": "codereview.stackexchange",
"id": 45389,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, strings, search",
"url": null
} |
c++, strings, search
Keep code simple and clear
I had to read findMatchLength() a few times to understand why it works, as normally I would expect a function like this to compare to substrings in the forward direction. I guess it's smart to pass indices to the end of the substrings, so you can use the minimum of those to avoid out-of-bounds reads, and in this particular use case you don't care about finding the match length of the strings reversed.
A much more intuitive interface would be to just pass two substrings, and compare them forwards. Then you can also use STL algorithms such as std::mismatch(), or even better, its ranges version:
std::size_t findMatchLength(std::string_view str1, std::string_view str2) {
return std::ranges::mismatch(str1, str2).in1 - str1.begin();
}
The standard library might get an atomic max function
There have been proposals to get atomic max and min functions into the standard library. While your update_max() looks fine, consider renaming it and changing the interface to the proposed atomic_fetch_max(), which will have an interface very similar to std::atomic_fetch_add(). This would make refactoring your code later to make use of a standard function simpler.
template<typename T>
T atomic_fetch_max(std::atomic<T>* obj, typename std::atomic<T>::value_type arg) noexcept
{
auto prev = obj->load(std::memory_order_relaxed);
while (prev < arg && !obj->compare_exchange_weak(prev, arg)) {}
return prev;
}
Your code can return duplicates
Try adding a dash at the end of your test string in main(). Your code doesn't find subsequences with an exact number of repetitions, but rather with a minimum number of repetitions. And when the actual number of repetitions found is larger than the minimum number of repetitions, it will print the same subsequence multiple times.
Other issues | {
"domain": "codereview.stackexchange",
"id": 45389,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, strings, search",
"url": null
} |
c++, strings, search
Use "\n" instead of std::endl; the latter is equivalent to the former, but also forces the output to be flushed, which is usually unnecessary and has a negative impact on performance.
You use int in some places to hold sizes, like the loop iterator i and as the value type of the vector index. If the text is larger than can be represented by an int, your code will no longer work correctly. Always prefer to use std::size_t for sizes, counts and indices.
You can avoid the atomic variable by changing the for_each() into a transform_reduce(). However, it probably doesn't improve performance in a significant way. | {
"domain": "codereview.stackexchange",
"id": 45389,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, strings, search",
"url": null
} |
java, logging
Title: utility to manipulate java.util.logging config using command-line system properties
Question: This is intended for temporary ad-hoc changes to logging config, for example when debugging etc. Also included are functions to easily manipulate config from a code (for example at the beginning of a given program's main method or from @BeforeClass JUnit method).
I'm looking mainly for reviews of the API design (whether something can be changed to be more convenient or more intuitive to use).
This class is a part of a small java.util.logging utility lib that I've created.
// Copyright (c) Piotr Morgwai Kotarbinski, Licensed under the Apache License, Version 2.0
package pl.morgwai.base.jul;
import java.io.*;
import java.util.*;
import java.util.function.BiFunction;
import java.util.function.Function;
import java.util.logging.Level;
import java.util.logging.LogManager;
/**
* Utilities to manipulate {@code java.util.logging} config, among others allows to override log
* levels with system properties in existing java apps without rebuilding: see
* {@link #overrideLogLevelsWithSystemProperties(String...)} and {@link #JulConfigurator()}.
*/
public class JulConfigurator { | {
"domain": "codereview.stackexchange",
"id": 45390,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "java, logging",
"url": null
} |
java, logging
/**
* Overrides {@link Level}s of {@code java.util.logging} {@link java.util.logging.Logger}s and
* {@link java.util.logging.Handler}s with values obtained from system properties.
* Fully-qualified names of {@link java.util.logging.Logger Logger}s and
* {@link java.util.logging.Handler Handler}s whose {@link Level}s should be overridden, can be
* provided as {@code loggerAndHandlerNames} arguments and/or comma separated on
* {@value #OVERRIDE_LEVEL_PROPERTY} system property.
* <p>
* Name of the system property containing a new {@link Level} for a given
* {@link java.util.logging.Logger}/{@link java.util.logging.Handler} is constructed by
* appending {@value #LEVEL_SUFFIX} to the given
* {@link java.util.logging.Logger}'s / {@link java.util.logging.Handler}'s
* fully-qualified name.<br/>
* If a system property with a new {@link Level} is missing, it is simply ignored.</p>
* <p>
* <b>Example:</b><br/>
* Output all entries from <code>com.example</code> name-space with level <code>FINE</code> or
* higher to the console. Entries from other name-spaces will be logged only if they have at
* least level <code>WARNING</code> (unless configured otherwise in the default
* <code>logging.properties</code> file) :</p>
* <pre>{@code
* java -cp ${CLASSPATH}:/path/to/jul-utils.jar \
* -Djava.util.logging.config.class=pl.morgwai.base.jul.JulConfigurator \
* -Djava.util.logging.overrideLevel=,com.example,java.util.logging.ConsoleHandler \
* -D.level=WARNING \
* -Dcom.example.level=FINE \
* -Djava.util.logging.ConsoleHandler.level=FINE \
* com.example.someproject.MainClass}</pre>
* <p>
* (Name of the root {@link java.util.logging.Logger} is an empty string, hence the value of
* {@value #OVERRIDE_LEVEL_PROPERTY} starts with a comma, so that the first element of the list | {
"domain": "codereview.stackexchange",
"id": 45390,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "java, logging",
"url": null
} |
java, logging
* {@value #OVERRIDE_LEVEL_PROPERTY} starts with a comma, so that the first element of the list
* is an empty string, while {@code -D.level} provides the new {@link Level} for the root
* {@link java.util.logging.Logger}).</p>
* <p>
* Note: overriding can be applied to existing java apps at startup without rebuilding: just add
* {@code jul-utils.jar} to the command-line class-path and define
* {@value #JUL_CONFIG_CLASS_PROPERTY} as in the example above.</p>
*/
public static void overrideLogLevelsWithSystemProperties(String... loggerAndHandlerNames) {
final var loggerAndHandlerNamesSet = new HashSet<String>();
Collections.addAll(loggerAndHandlerNamesSet, loggerAndHandlerNames);
final var namesFromProperty = System.getProperty(OVERRIDE_LEVEL_PROPERTY);
if (namesFromProperty != null) {
Collections.addAll(loggerAndHandlerNamesSet, namesFromProperty.split(","));
}
if (loggerAndHandlerNamesSet.isEmpty()) return;
overrideLogLevelsWithSystemProperties(loggerAndHandlerNamesSet);
} | {
"domain": "codereview.stackexchange",
"id": 45390,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "java, logging",
"url": null
} |
java, logging
static void overrideLogLevelsWithSystemProperties(Set<String> loggerAndHandlerNames) {
final var newLogLevels = new Properties(); // loggerName.level -> newLevel
int characterCount = 30; // first line date comment character length
for (final var loggerOrHandlerName: loggerAndHandlerNames) {
// read a system property with the new level and put it into newLogLevels
final var newLevelPropertyName = loggerOrHandlerName + LEVEL_SUFFIX;
final var newLevel = System.getProperty(newLevelPropertyName);
if (newLevel == null) continue;
newLogLevels.put(newLevelPropertyName, newLevel);
characterCount += newLevelPropertyName.length();
characterCount += newLevel.length();
characterCount += 2; // '=' and '\n'
}
if (newLogLevels.isEmpty()) return;
logManagerUpdateConfiguration(
LogManager.getLogManager(),
newLogLevels,
characterCount * 2, // *2 is for UTF characters and \ escapes
addOrReplaceMapper
);
} | {
"domain": "codereview.stackexchange",
"id": 45390,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "java, logging",
"url": null
} |
java, logging
/**
* Reads logging config normally and then calls
* {@link #overrideLogLevelsWithSystemProperties(String...)}.
* For use with {@value #JUL_CONFIG_CLASS_PROPERTY} system property: when this property is set
* to the {@link Class#getName() fully-qualified name} of this class, then {@link LogManager}
* will call this constructor instead of reading its configuration the normal way.
* <p>
* Note: overriding can be applied to existing java apps without rebuilding: just add
* {@code jul-utils.jar} to command-line class-path. See the example in
* {@link #overrideLogLevelsWithSystemProperties(String...)} documentation.</p>
* @see LogManager
*/
public JulConfigurator() throws IOException {
final var julConfigClassPropertyBackup = System.getProperty(JUL_CONFIG_CLASS_PROPERTY);
System.clearProperty(JUL_CONFIG_CLASS_PROPERTY);
LogManager.getLogManager().readConfiguration();
overrideLogLevelsWithSystemProperties();
System.setProperty(JUL_CONFIG_CLASS_PROPERTY, julConfigClassPropertyBackup);
}
/**
* Name of the system property that can contain comma separated,
* {@link Class#getName() fully-qualified names} of {@link java.util.logging.Logger}s and
* {@link java.util.logging.Handler}s whose {@link java.util.logging.Level}s will be overridden
* by {@link #overrideLogLevelsWithSystemProperties(String...)}.
*/
public static final String OVERRIDE_LEVEL_PROPERTY = "java.util.logging.overrideLevel";
/** {@value #LEVEL_SUFFIX} */
public static final String LEVEL_SUFFIX = ".level";
/** {@value #JUL_CONFIG_CLASS_PROPERTY} */
public static final String JUL_CONFIG_CLASS_PROPERTY = "java.util.logging.config.class";
static final Function<String, BiFunction<String,String,String>> addOrReplaceMapper =
(key) -> (oldVal, newVal) -> newVal != null ? newVal : oldVal; | {
"domain": "codereview.stackexchange",
"id": 45390,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "java, logging",
"url": null
} |
java, logging
/**
* Similar to {@link LogManager#updateConfiguration(InputStream, Function)}, but takes a
* {@link Properties} argument instead of an {@link InputStream}.
* This is somewhat a low-level method: in most situations
* {@link #addOrReplaceLoggingConfigProperties(Properties)} or
* {@link #addOrReplaceLoggingConfigProperties(Map)} will be more convenient.
* @param estimatedLoggingConfigUpdatesByteSize estimated size of loggingConfigUpdates in bytes.
* It will be passed to {@link ByteArrayOutputStream#ByteArrayOutputStream(int)}.
*/
public static void logManagerUpdateConfiguration(
LogManager logManager,
Properties loggingConfigUpdates,
int estimatedLoggingConfigUpdatesByteSize,
Function<String, BiFunction<String,String,String>> mapper
) {
try {
final var outputBytes =
new NoCopyByteArrayOutputStream(estimatedLoggingConfigUpdatesByteSize);
try (outputBytes) { loggingConfigUpdates.store(outputBytes, null); }
try (
final var inputBytes =
new ByteArrayInputStream(outputBytes.getBuffer(), 0, outputBytes.size())
) {
logManager.updateConfiguration(inputBytes, mapper);
}
} catch (IOException neverHappens) { // byte array streams don't throw
throw new RuntimeException(neverHappens);
}
}
static class NoCopyByteArrayOutputStream extends ByteArrayOutputStream {
public byte[] getBuffer() { return buf; }
public NoCopyByteArrayOutputStream(int initialSize) { super(initialSize); }
} | {
"domain": "codereview.stackexchange",
"id": 45390,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "java, logging",
"url": null
} |
java, logging
/**
* Adds to or replaces logging config properties with entries from {@code loggingConfigUpdates}.
*/
public static void addOrReplaceLoggingConfigProperties(Properties loggingConfigUpdates) {
logManagerUpdateConfiguration(
LogManager.getLogManager(),
loggingConfigUpdates,
80 * loggingConfigUpdates.size(), // in most cases more efficient than calculating
addOrReplaceMapper
);
}
/**
* Variant of {@link #addOrReplaceLoggingConfigProperties(Properties)} that takes a {@link Map}
* as an argument.
* This allows to use {@link Map#of(Object, Object) Map.of(...)} function family inline, for
* example:
* <pre>{@code
* addOrReplaceLoggingConfigProperties(Map.of(
* ".level", "FINE",
* "java.util.logging.ConsoleHandler.level", "FINEST",
* "com.example.level", "FINEST",
* "com.thirdparty.level", "WARNING"
* ));}</pre>
*/
public static void addOrReplaceLoggingConfigProperties(Map<String, String> loggingConfigUpdates)
{
final var propertiesUpdates = new Properties(loggingConfigUpdates.size());
propertiesUpdates.putAll(loggingConfigUpdates);
addOrReplaceLoggingConfigProperties(propertiesUpdates);
}
}
Answer: Javadocs may be found
here.
copyright notice
// Copyright (c) Piotr Morgwai Kotarbinski, ...
Let's assume you wish to enjoy
USPTO
copyright protection under U.S. law.
Then elide the (c), as it has no special meaning
(or replace it with © if you prefer).
Their circular
explains you are missing one of the three elements of a copyright notice.
Add the year, e.g. // Copyright 2024 Piotr ...
overrideLogLevelsWithSystemProperties
Name ... is an empty string
Thank you, I found that explanation very helpful.
final var loggerAndHandlerNamesSet = ... | {
"domain": "codereview.stackexchange",
"id": 45390,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "java, logging",
"url": null
} |
java, logging
Thank you, I found that explanation very helpful.
final var loggerAndHandlerNamesSet = ...
I'm not crazy about that identifier, nor about the ...Set suffix.
This local is "the same as" the input String array,
just organized for more efficient access.
So give it a simple local variable name like names and be done with it.
No need for "Gimli, son of Glóin, son of Gróin"
when a simple "Gimli" is sufficient among friends.
I do like how we finish by calling the private helper overrideLogLevelsWithSystemProperties().
However, the helper has same name, different signature,
yet it performs a different task,
as it never calls System.getProperty().
So perhaps we would prefer that these two functions had slightly different names?
In the helper, I similarly would prefer to see for (name: names) {
characterCount += 2; // '=' and '\n'
This is a good example of offering the "why" rather than the "how".
I thank you for the explanation.
Similarly for the UTF-16 remark (it seems UTF-32 is not of interest, cool).
checked exception
public JulConfigurator() throws IOException {
Possibly this signature is not convenient for callers?
Consider re-throwing, wrapped in an unchecked RuntimeException.
(I also appreciate the neverHappens name.)
We clear, read config, and set.
Suppose that reading failed with an I/O error.
Would it maybe be nicer to read config, then clear, and set?
So a thrown exception won't reveal the "cleared" state?
magic number
80 * loggingConfigUpdates.size(), // in most cases more efficient than calculating
This seems nice enough as-is.
But consider naming that integer,
just so you can give it a Javadoc entry
that warns unusual callers there is room to lose
in rare circumstances. | {
"domain": "codereview.stackexchange",
"id": 45390,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "java, logging",
"url": null
} |
c, bitwise, portability
Title: Unpacking a byte into 8 bytes, where the LSB of each byte corresponds to a bit of the original byte
Question: I needed to unpack a byte into the LSBs of each byte in an 8-byte integer. After some testing, I derived a surprisingly efficient and elegant solution that uses magic numbers multiplication, though this is nothing new. Upon further investigation I found a similar solution, and from that I have adopted another.
My first function ex8 stores the least significant bit in the least significant byte. The second least significant bit into the second least significant byte, etc. They are extracted by bitshifting and masking.
The second function ex8l stores the least significant bit in the byte with the least significant memory address. So that will do the same as the other function on little-endian machines, but will have byteswapped results on a big-endian machine. I did that by producing the magic number using a union with individual bytes, so the value will depend on the byte order, and not the other way around.
unsigned long long ex8(unsigned char n) {
return n * 0x2040810204081ULL & 0x101010101010101ULL;
}
#include <assert.h>
unsigned long long ex8l(unsigned char n) {
static_assert(sizeof(long long) >= 8);
const union {
unsigned char b[8];
unsigned long long u;
} static m = {128, 64, 32, 16, 8, 4, 2, 1};
return n * (m.u >> 7) & 0x101010101010101ULL;
} | {
"domain": "codereview.stackexchange",
"id": 45391,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c, bitwise, portability",
"url": null
} |
c, bitwise, portability
Answer: Reliance on a certain endian and width
ex8l() code is not portable if a different endian is used. Description has "but will have byteswapped results on a big-endian machine", yet such a critical restriction deserves to be in code and/or use a static_assert().
If unsigned long long is wider than 64-bit, code fails too. Use uint64_t u; in the union instead. Signature unsigned long long ex8l(unsigned char n) remains a good choice.
Unneeded use of LL
0x101010101010101ULL is sufficient as 0x101010101010101U. The LL serves no purpose here.
What if unsigned long long is 128-bit?
0x2040810204081ULL obliges a unsigned long long which may be much wider than 64-bit.
Consider LL may oblige 128-bit operations on future machines - although such machines will likely optimize.
Not a big issue with 0x2040810204081ULL, but code could use UINT64_C(0x2040810204081) to not force excessive wide math.
Wrong test (Covered by @Toby Speight)
static_assert(sizeof(long long) >= 8);, assuming CHAR_BIT == 8 is not needed as C specifies the range of long long requiring at least 64-bits.
What would be useful is static_assert(CHAR_BIT == 8); as OP's code relies on that. | {
"domain": "codereview.stackexchange",
"id": 45391,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c, bitwise, portability",
"url": null
} |
shell, posix, sh
Title: Yet another sh script to backup one directory
Question: A single directory should simply be backed up with the zip tool, and the time of the backup should be preserved in the file name. I have written a Posix shell script for this.
Can this script simply be converted into a .bashrc alias?
#!/bin/sh
if [ -z "$1" ]
then
echo "No argument supplied"
exit
fi
fn=$(echo "backup_${1%/}_$(date +%F_%T).zip" | sed s/:/-/g)
echo "$fn"
zip -r "$fn" "$1"
Answer: This script is not super friendly.
(Also, absent some articulated motivation for turning it into a bash alias,
I would just leave it as a Bourne sh script.)
echo "No argument supplied"
exit
The word "argument" is true, but it's not very helpful.
Instead, prompt the user to enter "an input filename"
so it can be backed up.
We call this a diagnostic message,
one which offers a hint of "do this and you will win!"
rather than just announcing "you lose!".
Exiting with status 0 here seems Bad.
Prefer exit 1, so make and other callers
will know that things went horribly wrong.
A common idiom would be to first assign a meaningful parameter name:
in_file="$1"
and then work with the name rather than the arg position number.
filename
fn=$(echo "backup_${1%/}_$(date +%F_%T).zip" | sed s/:/-/g) | {
"domain": "codereview.stackexchange",
"id": 45392,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "shell, posix, sh",
"url": null
} |
shell, posix, sh
The abbreviation is for "filename". Fine, we'll just accept that as-is.
The % percent is entirely too cryptic.
It strips trailing / slash,
but not e.g. trailing /readme, leaving that one intact.
You didn't offer any # comments, nor review context,
to motivate the "strip trailing slash" feature.
Recommend you just delete it.
I feel you probably want to use $(basename "${in_file}") here.
That would be a more salient concept.
As written, fn can include embedded / slashes,
and it seems that would be undesirable.
Using basename is an easy way to eliminate that possibility.
The sed is lovely.
Consider rephrasing it as tr : -
quoting
I like the consistent use of quoting,
just in case filenames contain embedded SPACE characters.
Possibly you used shellcheck on this, which definitely is helpful. | {
"domain": "codereview.stackexchange",
"id": 45392,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "shell, posix, sh",
"url": null
} |
python, python-3.x, numpy, linear-algebra
Title: Partial pivoting code in python
Question: import numpy as np
def eliminateCol(A, k=0):
# guarantee that A is float type
if A.dtype.kind != 'f' and A.dtype.kind != 'c': return None
# load dimensions
dim0,dim1 = np.shape(A)
# initialize outputs
swap = np.identity(dim0,dtype=float)
oper = np.identity(dim0,dtype=float)
# k < dim1
k = k%dim1
# if the column k is zero column, return
if A[:,k].any() == False: return swap,oper
i0 = 0
if k != 0:
# find a row i0 whose leftmost k-1 entries are all zero
while i0 < dim0:
if not A[i0, 0:k].any():
break
i0 += 1
# find a nonzero element A[i, k] to use as a pivot
i = i0
while i < dim0:
if A[i, k] != 0:
break
i += 1
if i == dim0:
return swap, oper
# Partial Pivoting: ensures that the largest element of the column is placed on the diagonal
max_index = np.argmax(np.abs(A[i0:, k])) + i0
A[[i0, max_index], ] = A[[max_index, i0], ]; swap[[i0, max_index], ] = swap[[max_index, i0], ]
# row i0 is the pivot row and A[j, k] is zero for i0 < j <= i
for i in range(i0 + 1, dim0):
if A[i, k] != 0:
quot = A[i, k] / A[i0, k]
A[i, :] -= quot * A[i0, :]
oper[i, i0] = -quot
return swap, oper
def eliminateRow(A, k=-1):
# guarantee that A is float type
if A.dtype.kind != 'f' and A.dtype.kind != 'c': return None
# load dimensions
dim0,dim1 = np.shape(A)
# initialize outputs
oper = np.identity(dim0,dtype=float)
# k < dim0
k = k%dim0
# if the row k is zero column, return
if k == 0 or A[k,:].any() == False: return oper | {
"domain": "codereview.stackexchange",
"id": 45393,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, python-3.x, numpy, linear-algebra",
"url": null
} |
python, python-3.x, numpy, linear-algebra
# find a nonzero element A[k,j] to use as a pivot
for j in range(dim1):
if A[k, j] != 0: break
for i in range(k - 1, -1, -1):
if A[i, j] != 0:
quot = A[i, j] / A[k, j]
A[i, :] -= quot * A[k, :]
oper[i, k] = -quot
return oper
def eliminateScale(A):
# guarantee that A is float type
if A.dtype.kind != 'f' and A.dtype.kind != 'c': return None
# load dimensions
dim0,dim1 = np.shape(A)
# initialize outputs
oper = np.identity(dim0,dtype=float)
# find pivots
i = 0
while i < dim0:
j = 0
while j < dim1:
if A[i,j] == 0: j+= 1; continue
else:
oper[i,i] = 1/A[i,j]
A[i,j:] = A[i,j:]/A[i,j]
break
j+= 1
i+= 1
return oper
def get_reduced_echelon_form (A):
for k in range(A.shape[1]):
eliminateCol(A, k)
eliminateRow(A, k)
# Finally, scale the matrix
eliminateScale(A)
return A
def get_echelon_form(A):
dim0, dim1 = np.shape(A)
for k in range(min(dim0, dim1)):
# Eliminate below diagonal in column k
swap, oper = eliminateCol(A, k)
return A
# Example Usage:
B = np.array([[0.02, 0.01, 0.0, 0.0, 0.02],
[1.0, 2.0, 1.0, 0.0, 1.0],
[0.0, 1.0, 2.0, 1.0, 4.0],
[0.0, 0.0, 100.0, 200.0, 800.0]], dtype=float)
A = np.array([[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
[10, 11, 12]], dtype=float)
echelon = get_echelon_form(A.copy())
reduced = get_reduced_echelon_form(A.copy())
print(B)
print(echelon)
print(reduced) | {
"domain": "codereview.stackexchange",
"id": 45393,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, python-3.x, numpy, linear-algebra",
"url": null
} |
python, python-3.x, numpy, linear-algebra
print(B)
print(echelon)
print(reduced)
This is my code to find echelon and reduced echelon form of a matrix using partial pivoting. Please help me to any bugs or shortcomings.(please ignore using for loop instead of while loop)
At the result of execution, correct reduced row echelon form is found for zero column matrix, zero row matrix, and a example usage matrix for partial pivoting. I am looking for a bug or shortcoming
Answer: lint
def eliminateCol(A, k=0):
You are sharing code, seeking to collaborate with the broader python community.
One of the community guidelines,
pep8,
asks that you spell it eliminate_col.
(I won't pursue A, as I understand that math conventions can also be helpful.)
It would have been a kindness to the reader to annotate A
as being of type np.ndarray.
Please run your source code through
black
before asking others to read it.
exceptions
This is just Wrong:
if A.dtype.kind != 'f' and A.dtype.kind != 'c': return None
I read the signature.
You made a promise.
By the time eliminate_col() returns,
it shall have eliminated a column.
But in this case it fails to make good on that promise.
That is incorrect behavior.
Also, please don't condense two lines down to one.
And especially avoid abominations like this: if A[i,j] == 0: j+= 1; continue
This code should check the mandatory pre-condition, and throw when caller messed up:
if A.dtype.kind not in ('f', 'c'):
raise ValueError(f"unsupported dtype: {A.dtype.kind}") | {
"domain": "codereview.stackexchange",
"id": 45393,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, python-3.x, numpy, linear-algebra",
"url": null
} |
python, python-3.x, numpy, linear-algebra
Skipping down to the return statement, it's unclear how
the (swap, oper) tuple satisfies your original promise
to eliminate a column.
You elected not to offer a """docstring""" for this function
which explains what it does.
In the review context you elected not to Cite Your Reference(s),
so it's unclear what math theorems you are relying on here.
All of which makes it much more difficult for the reader
to examine this and confidently proclaim, "oh, yes, this definitely
does the right thing with all input matrices."
Absent a citation, I arbitrarily choose to impose
this one
for purposes of reviewing the code.
All right, back to checking pre-conditions.
I really do appreciate that the .shape tuple unpack
strictly enforces that the ndarray passed in shall be a 2-D array,
or we die with a helpful diagnostic.
extract helper
# find a nonzero element A[i, k] to use as a pivot
It seems pretty clear here that the code is asking you
to extract a helper function, so you can write
i = find_nonzero_pivot(A, k)
div by zero
if A[i, k] != 0:
quot = A[i, k] / A[i0, k] | {
"domain": "codereview.stackexchange",
"id": 45393,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, python-3.x, numpy, linear-algebra",
"url": null
} |
python, python-3.x, numpy, linear-algebra
div by zero
if A[i, k] != 0:
quot = A[i, k] / A[i0, k]
I don't understand that logic.
It would be a bad thing for the quotient to be zero?!?
It seems like testing the denominator for zeroness is the more pressing concern.
DRY
I don't understand eliminateRow.
It is related to eliminateCol, but different,
in ways the comments fail to motivate
and which the missing docstring fails to describe.
You have not made it easy to trace from elements
of the cited reference to elements of the implementation.
I'm willing to say that this function will return oper.
More than that?
It's up to you to offer a more eloquent argument
for a stronger post-condition.
validation
You did not describe why sympy's
rref()
is unsuitable for your use case.
More worryingly, you did not offer a
test suite
that {compares, contrasts} how this implementation
and others available on pypi will handle matrices
of interest.
One way to instill confidence in the correctness
of an implementation is to show how it behaves
similarly to pre-existing implementations that
folks have placed their trust in.
I am happy for you that the example reduced echelon form meets your needs.
I would not be willing to call this code in a production setting
where maintenance engineers might be called on to diagnose or repair this code. | {
"domain": "codereview.stackexchange",
"id": 45393,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, python-3.x, numpy, linear-algebra",
"url": null
} |
rust
Title: How to replace filter and map with filter_map?
Question: The following sample code is for finding DIGIT_WORDS and their first occurrence in sentence line (Rust Playground)
fn main() {
const DIGIT_WORDS: &'static [&'static str] = &[
"one", "two", "three", "four", "five", "six", "seven", "eight", "nine",
];
let line = "threehpbsevenffnqgdjcftjkdjhhk7dvzmkmqthreefflb";
let result: Vec<_> = DIGIT_WORDS
.iter()
.filter(|word| line.contains(*word))
.map(|word| (word, line.find(word).unwrap()))
.collect();
println!("{:?}", result); //output: [("three", 0), ("seven", 8)]
}
Not sure how could I combine the filter and map into one filter_map? I tried to use filter_map and str::find but the unwrap will fail if the word doesn't exist in the sentence.
Answer: Code (Rust Playground):
fn main() {
const DIGIT_WORDS: [&str; 9] = [
"one", "two", "three", "four", "five", "six", "seven", "eight", "nine",
];
let line = "threehpbsevenffnqgdjcftjkdjhhk7dvzmkmqthreefflb";
let result: Vec<_> = DIGIT_WORDS
.iter()
.filter_map(|word| line.find(word).map(|index| (*word, index)))
.collect();
println!("{:?}", result);
}
Explanation: I see that you've answered your own question and figured out that the supplied closure to filter_map must return an Option.
A more concise way of writing what you are currently doing with the match keyword in your answer (morphing an Option<usize> into an Option<(&str, usize)>) is by calling map on the Option<usize> returned by str::find and having the supplied closure to map return a (&str, usize), as shown in the above snippet. | {
"domain": "codereview.stackexchange",
"id": 45394,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "rust",
"url": null
} |
performance, rust, primes, memory-optimization
Title: Construct a performant sieve of Atkin in Rust | {
"domain": "codereview.stackexchange",
"id": 45395,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "performance, rust, primes, memory-optimization",
"url": null
} |
performance, rust, primes, memory-optimization
Question: I have implemented the sieve of Atkin in Rust. It can find all primes till 1,000,000,000 in 4.5 s using 34.4 MiB on my 1.4 GHz machine. This is a direct implementation (with some optimisations made from empirical observations) of Atkin and Bernstein's paper. Here, sieve is Vec<u16> in which the ith element indicates whether the 16 numbers 60 * i + d are prime, where d is a coprime residue modulo 60. Further, isqrt is the integer square root function (implementation not shown here) which I had to use because integer square roots are not stabilised in Rust.
/// A. O. L. Atkin and D. J. Bernstein, "Prime Sieves Using Binary Quadratic
/// Forms", in Mathematics of Computation, vol. 73, no. 246, pp. 1023–1030.
pub struct SieveOfAtkin {
limit: usize,
limit_rounded: usize,
limit_rounded_root: usize,
sieve: Vec<u16>,
}
impl SieveOfAtkin {
// Consecutive differences between coprime residues modulo 60: 1, 7, 11,
// 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 49, 53 and 59.
const OFFSETS: [usize; 16] = [6, 4, 2, 4, 2, 4, 6, 2, 6, 4, 2, 4, 2, 4, 6, 2];
// Position of the bit indicating the primality of a coprime residue modulo
// 60 in a 16-element bitfield. For non-coprime residues, the value is 16.
const SHIFTS: [u8; 60] = [
16, 0, 16, 16, 16, 16, 16, 1, 16, 16, 16, 2, 16, 3, 16, 16, 16, 4, 16, 5, 16, 16, 16, 6,
16, 16, 16, 16, 16, 7, 16, 8, 16, 16, 16, 16, 16, 9, 16, 16, 16, 10, 16, 11, 16, 16, 16,
12, 16, 13, 16, 16, 16, 14, 16, 16, 16, 16, 16, 15,
];
}
impl SieveOfAtkin {
/// Construct the sieve of Atkin up to and including the given number.
///
/// * `limit` - Non-strict upper bound.
///
/// -> Sieve of Atkin.
pub fn new(limit: usize) -> SieveOfAtkin {
// Strict upper bound divisible by 60.
let limit_rounded = (limit - limit % 60)
.checked_add(60)
.expect("overflow detected; argument too large"); | {
"domain": "codereview.stackexchange",
"id": 45395,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "performance, rust, primes, memory-optimization",
"url": null
} |
performance, rust, primes, memory-optimization
.checked_add(60)
.expect("overflow detected; argument too large");
let mut sieve_of_atkin = SieveOfAtkin {
limit,
limit_rounded,
limit_rounded_root: isqrt(limit_rounded as i64) as usize,
sieve: vec![0; limit / 60 + 1],
};
sieve_of_atkin.init();
sieve_of_atkin
}
fn init(&mut self) {
// Note: it runs faster like this than with loops.
self.algorithm_3_1(1);
self.algorithm_3_1(13);
self.algorithm_3_1(17);
self.algorithm_3_1(29);
self.algorithm_3_1(37);
self.algorithm_3_1(41);
self.algorithm_3_1(49);
self.algorithm_3_1(53);
self.algorithm_3_2(7);
self.algorithm_3_2(19);
self.algorithm_3_2(31);
self.algorithm_3_2(43);
self.algorithm_3_3(11);
self.algorithm_3_3(23);
self.algorithm_3_3(47);
self.algorithm_3_3(59); | {
"domain": "codereview.stackexchange",
"id": 45395,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "performance, rust, primes, memory-optimization",
"url": null
} |
performance, rust, primes, memory-optimization
// Mark composite all numbers divisible by the squares of primes.
let mut num: usize = 1;
let mut offset = SieveOfAtkin::OFFSETS.iter().cycle();
'sieve: for sieve_idx in 0..self.sieve.len() {
for shift in 0..16 {
if self.sieve[sieve_idx] >> shift & 1 == 1 {
let num_sqr = num.pow(2);
for multiple in (num_sqr..)
.step_by(num_sqr)
.take_while(|&multiple| multiple < self.limit_rounded)
{
let multiple_div_60 = multiple / 60;
let multiple_mod_60 = multiple % 60;
self.sieve[multiple_div_60] &=
!(1u32 << SieveOfAtkin::SHIFTS[multiple_mod_60]) as u16;
}
}
num += offset.next().unwrap();
if num > self.limit_rounded_root {
break 'sieve;
}
}
}
}
fn algorithm_3_1(&mut self, delta: i32) {
for f in 1..=15 {
for g in (1..=30).step_by(2) {
let quadratic = 4 * f * f + g * g;
if delta == quadratic % 60 {
self.algorithm_4_1(delta, f, g, quadratic / 60);
}
}
}
}
fn algorithm_3_2(&mut self, delta: i32) {
for f in (1..=10).step_by(2) {
for g in [2, 4, 8, 10, 14, 16, 20, 22, 26, 28] {
let quadratic = 3 * f * f + g * g;
if delta == quadratic % 60 {
self.algorithm_4_2(delta, f, g, quadratic / 60);
}
}
}
}
fn algorithm_3_3(&mut self, delta: i32) {
for (f, gstart) in (1..=10).zip([2, 1].into_iter().cycle()) {
for g in (gstart..=30).step_by(2) {
let quadratic = 3i32 * f * f - g * g; | {
"domain": "codereview.stackexchange",
"id": 45395,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "performance, rust, primes, memory-optimization",
"url": null
} |
performance, rust, primes, memory-optimization
let quadratic = 3i32 * f * f - g * g;
// Remainder can be negative, so perform modulo operation.
if delta == quadratic.rem_euclid(60) {
self.algorithm_4_3(delta, f, g, quadratic.div_euclid(60));
}
}
}
}
fn algorithm_4_1(&mut self, delta: i32, f: i32, g: i32, h: i32) {
let (mut x, mut y0, mut k0) = (f as i64, g as i64, h as i64);
while k0 < self.sieve.len() as i64 {
(k0, x) = (k0 + 2 * x + 15, x + 15);
}
loop {
(k0, x) = (k0 - 2 * x + 15, x - 15);
if x <= 0 {
return;
}
while k0 < 0 {
(k0, y0) = (k0 + y0 + 15, y0 + 30);
}
let (mut k, mut y) = (k0, y0);
while k < self.sieve.len() as i64 {
self.sieve[k as usize] ^= 1u16 << SieveOfAtkin::SHIFTS[delta as usize];
(k, y) = (k + y + 15, y + 30);
}
}
}
fn algorithm_4_2(&mut self, delta: i32, f: i32, g: i32, h: i32) {
let (mut x, mut y0, mut k0) = (f as i64, g as i64, h as i64);
while k0 < self.sieve.len() as i64 {
(k0, x) = (k0 + x + 5, x + 10);
}
loop {
(k0, x) = (k0 - x + 5, x - 10);
if x <= 0 {
return;
}
while k0 < 0 {
(k0, y0) = (k0 + y0 + 15, y0 + 30);
}
let (mut k, mut y) = (k0, y0);
while k < self.sieve.len() as i64 {
self.sieve[k as usize] ^= 1u16 << SieveOfAtkin::SHIFTS[delta as usize];
(k, y) = (k + y + 15, y + 30);
}
}
}
fn algorithm_4_3(&mut self, delta: i32, f: i32, g: i32, h: i32) {
let (mut x, mut y0, mut k0) = (f as i64, g as i64, h as i64);
loop {
while k0 >= self.sieve.len() as i64 {
if x <= y0 {
return; | {
"domain": "codereview.stackexchange",
"id": 45395,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "performance, rust, primes, memory-optimization",
"url": null
} |
performance, rust, primes, memory-optimization
if x <= y0 {
return;
}
(k0, y0) = (k0 - y0 - 15, y0 + 30);
}
let (mut k, mut y) = (k0, y0);
while k >= 0 && y < x {
self.sieve[k as usize] ^= 1u16 << SieveOfAtkin::SHIFTS[delta as usize];
(k, y) = (k - y - 15, y + 30);
}
(k0, x) = (k0 + x + 5, x + 10);
}
}
pub fn is_prime(&self, num: usize) -> bool {
if num < 2 {
return false;
}
if num == 2 || num == 3 || num == 5 {
return true;
}
let num_div_60 = num / 60;
let num_mod_60 = num % 60;
if num_div_60 >= self.sieve.len() {
panic!("queried number is out of range of the sieve")
}
self.sieve[num_div_60] & (1u32 << SieveOfAtkin::SHIFTS[num_mod_60]) as u16 != 0
}
pub fn iter(&self) -> impl Iterator<Item = i64> + '_ {
let mut num: usize = 1;
let mut offset = SieveOfAtkin::OFFSETS.iter().cycle();
[2, 3, 5]
.into_iter()
.chain(
self.sieve
.iter()
.flat_map(|bitfield| (0..16).map(move |shift| bitfield >> shift & 1 == 1))
.filter_map(move |is_prime| {
let filtered = if is_prime { Some(num) } else { None };
num += offset.next().unwrap();
filtered
}),
)
.take_while(|&num| num <= self.limit)
.map(|num| num as i64)
}
} | {
"domain": "codereview.stackexchange",
"id": 45395,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "performance, rust, primes, memory-optimization",
"url": null
} |
performance, rust, primes, memory-optimization
Bernstein's implementation runs in 3.0 s, but it has a ton of optimisations in the form of lookups instead of branches and calculations in a number of places, so I am not looking to emulate the same. Nonetheless, cargo-flamegraph tells me that this code spends most of the time running algorithms 4.1, 4.2 and 4.3, and the iter method.
Are there any (possibly mathematical) optimisations I can make to further improve the performance?
I realise that algorithms 3.1, 3.2 and 3.3 are similar (as are algorithms 4.1 and 4.2). Could some parts be factored out without blowing up the argument list? (Not at the cost of performance, though, since these are small functions.)
Documentation is clearly lacking; however, being that this is an implementation of a paper which explains everything in detail, what comments can I add without duplicating the paper (and things like bit-clear or bit-set, which I think are common knowledge)?
Is there a better (and faster) way to write the iter method?
Answer: Thank you for the citation.
The comments describing OFFSETS and SHIFTS are illuminating
and I thank you for them. But I'm a little sad to see the
math relationships written in English rather than as a
trivial algorithm. If we stored the cited [1, 7, ..., 53, 59],
then helpers could come up with the offset and shift values.
compiler optimization
// Note: it runs faster like this than with loops.
This is a fascinating remark,
which leaves the reader curious about what intra-function
optimizations the compiler was able to see in the "constant" case,
and what it would take to enable similar behavior in the "variable" case.
Sorry, you lost me with these temp vars:
let multiple_div_60 = multiple / 60;
let multiple_mod_60 = multiple % 60;
self.sieve[multiple_div_60] &=
!(1u32 << SieveOfAtkin::SHIFTS[multiple_mod_60]) as u16; | {
"domain": "codereview.stackexchange",
"id": 45395,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "performance, rust, primes, memory-optimization",
"url": null
} |
performance, rust, primes, memory-optimization
It's unclear why those two expressions were worth naming.
Maybe it was just a debugging thing, during development?
Or maybe they're leftover from an attempt to make "addition and conditional"
go faster than integer division?
That's something that could possibly help .iter(),
given its sequential scan.
Or maybe start a bunch of threads, each focused on just a single mod 60 offset?
In any event, thank you for the nicely named limit_rounded
and limit_rounded_root identifiers, they are very clear.
Similarly, I like the traceability that the algorithm_X_Y names give us.
The source is inseparable from the paper; they must be read together.
I feel the source has the appropriate amount of documentation and comments.
There are some md5 hashes at the end of the paper,
which an accompanying rust test suite could go to the trouble of verifying. | {
"domain": "codereview.stackexchange",
"id": 45395,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "performance, rust, primes, memory-optimization",
"url": null
} |
java, canvas, javafx
Title: A JavaFX canvas - based UI view component for representing data points in three dimensions
Question: I have this pie chart. It encodes data points in three dimensions, which are encoded via
sector radius,
sector angle,
color intensity of the sector.
How it looks like?
(See here.)
Code
com.github.coderodde.javafx.PieChart3D.java:
package com.github.coderodde.javafx;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import javafx.scene.canvas.Canvas;
import javafx.scene.canvas.GraphicsContext;
import javafx.scene.paint.Color;
import javafx.scene.shape.ArcType;
/**
* This class implements a pie chart that can communicate data points in three
* dimensions:
* <ol>
* <li>the radius of a sector,</li>
* <li>the angle of a sector,</li>
* <li>color intensity of a sector.</li>
* </ol>
*
* @author Rodion "rodde" Efremov
* @version 1.6 (Dec 18, 2023)
* @since 1.6 (Dec 18, 2023)
*/
public final class PieChart3D extends Canvas {
private static final Color DEFAULT_BOX_COLOR = Color.WHITE;
private static final Color DEFAULT_CHART_BACKGROUND_COLOR = Color.WHITE;
private static final Color DEFAULT_ORIGINAL_INTENSITY_COLOR = Color.BLACK;
private Color boxColor = DEFAULT_BOX_COLOR;
private Color chartBackgroundColor = DEFAULT_CHART_BACKGROUND_COLOR;
private Color originalIntensityColor = DEFAULT_ORIGINAL_INTENSITY_COLOR;
private double angleOffset = 0.0;
private final List<PieChart3DEntry> entries = new ArrayList<>();
public PieChart3D(double dimension) {
checkDimension(dimension);
super.setWidth(dimension);
super.setHeight(dimension);
}
public Color getBoxBackgroundColor() {
return boxColor;
}
public Color getChartBackgroundColor() {
return chartBackgroundColor;
} | {
"domain": "codereview.stackexchange",
"id": 45396,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "java, canvas, javafx",
"url": null
} |
java, canvas, javafx
public Color getChartBackgroundColor() {
return chartBackgroundColor;
}
public Color getOriginalIntensityColor() {
return originalIntensityColor;
}
public double getAngleOffset() {
return angleOffset;
}
public void setBoxBackgroundColor(Color boxColor) {
this.boxColor =
Objects.requireNonNull(boxColor, "The input color is null.");
}
public void setChartBackgroundColor(Color chartBackgroundColor) {
this.chartBackgroundColor =
Objects.requireNonNull(
chartBackgroundColor,
"The input color is null.");
} | {
"domain": "codereview.stackexchange",
"id": 45396,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "java, canvas, javafx",
"url": null
} |
java, canvas, javafx
public void setOriginalIntensityColor(Color originalIntensityColor) {
this.originalIntensityColor =
Objects.requireNonNull(
originalIntensityColor,
"The input color is null.");
}
public void setAngleOffset(double angleOffset) {
checkAngleOffset(angleOffset);
angleOffset %= 360.0;
if (angleOffset < 0.0) {
angleOffset += 360.0;
}
this.angleOffset = angleOffset;
}
public PieChart3DEntry get(int index) {
return entries.get(index);
}
public void set(int index, PieChart3DEntry entry) {
entries.set(index, Objects.requireNonNull(entry, "The entry is null."));
}
public int size() {
return entries.size();
}
public void add(PieChart3DEntry entry) {
entries.add(Objects.requireNonNull(entry, "The entry is null."));
}
public void add(int index, PieChart3DEntry entry) {
entries.add(index, Objects.requireNonNull(entry, "The entry is null."));
}
public void remove(int index) {
entries.remove(index);
}
public void draw() {
GraphicsContext gc = getGraphicsContext2D();
drawBoundingBox(gc);
drawEntirePieChart(gc);
if (!entries.isEmpty()) {
// Once here, we have entries to draw:
drawChart(gc);
}
}
private void drawBoundingBox(GraphicsContext gc) {
gc.setFill(getBoxBackgroundColor());
gc.fillRect(0.0,
0.0,
getWidth(),
getHeight());
}
private void drawEntirePieChart(GraphicsContext gc) {
gc.setFill(getChartBackgroundColor());
gc.fillOval(0.0,
0.0,
getHeight(),
getWidth());
}
private void drawChart(GraphicsContext gc) { | {
"domain": "codereview.stackexchange",
"id": 45396,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "java, canvas, javafx",
"url": null
} |
java, canvas, javafx
getWidth());
}
private void drawChart(GraphicsContext gc) {
double sumOfRelativeAngles = computeSumOfRelativeAngles();
double maximumRadiusValue = getMaximumRadiusValue();
double maximumColorIntensityValue = getMaximumColorIntensity();
double startAngle = 90.0 - angleOffset;
for (PieChart3DEntry entry : entries) {
double actualAngle = 360.0 * entry.getSectorAngleValue()
/ sumOfRelativeAngles;
double actualRadius =
(getHeight() / 2.0) * (entry.getSectorRadiusValue()
/ maximumRadiusValue);
Color actualColor =
obtainColor(entry.getSectorColorIntensityValue() /
maximumColorIntensityValue);
double sectorStartAngle = startAngle - actualAngle;
startAngle -= actualAngle;
drawSector(gc,
sectorStartAngle,
actualAngle,
actualRadius,
actualColor);
}
}
/**
* Draws a single sector.
*
* @param gc the graphics context.
* @param startAngle the start angle.
* @param angle the end angle.
* @param actualRadius the radius of the sector.
* @param color the color of the sector.
*/
private void drawSector(GraphicsContext gc,
double startAngle,
double angle,
double actualRadius,
Color color) {
double canvasDimension = getHeight();
double centerX = canvasDimension / 2.0;
double centerY = canvasDimension / 2.0; | {
"domain": "codereview.stackexchange",
"id": 45396,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "java, canvas, javafx",
"url": null
} |
java, canvas, javafx
double centerY = canvasDimension / 2.0;
gc.setFill(color);
gc.fillArc(centerX - actualRadius,
centerY - actualRadius,
2.0 * actualRadius,
2.0 * actualRadius,
startAngle,
angle,
ArcType.ROUND);
}
private double computeSumOfRelativeAngles() {
double angleSum = 0.0;
for (PieChart3DEntry entry : entries) {
angleSum += entry.getSectorAngleValue();
}
return angleSum;
}
private static void checkDimension(double dimension) {
checkIsNotNaN(dimension, "The dimension is NaN.");
checkIsNotInfinite(dimension,
"The dimention is infinite in absolute value.");
if (dimension <= 0.0) {
throw new IllegalArgumentException(
"The dimension is non-positive.");
}
}
private static void checkAngleOffset(double angleOffset) {
checkIsNotNaN(angleOffset, "The angle offset is NaN.");
checkIsNotInfinite(angleOffset,
"The angle offset is infinite in absolute value.");
}
private static void checkIsNotNaN(double value, String exceptionMessage) {
if (Double.isNaN(value)) {
throw new IllegalArgumentException(exceptionMessage);
}
}
private static void checkIsNotInfinite(double value,
String exceptionMessage) {
if (Double.isInfinite(value)) {
throw new IllegalArgumentException(exceptionMessage);
}
}
private double getMaximumRadiusValue() {
Optional<PieChart3DEntry> optional =
entries.stream().max((e1, e2) -> {
return Double.compare(e1.getSectorRadiusValue(),
e2.getSectorRadiusValue());
}); | {
"domain": "codereview.stackexchange",
"id": 45396,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "java, canvas, javafx",
"url": null
} |
java, canvas, javafx
e2.getSectorRadiusValue());
});
if (optional.isEmpty()) {
throw new IllegalStateException("No entries in this chart.");
}
return optional.get().getSectorRadiusValue();
}
private double getMaximumColorIntensity() {
Optional<PieChart3DEntry> optional =
entries.stream().max((e1, e2) -> {
return Double.compare(e1.getSectorColorIntensityValue(),
e2.getSectorColorIntensityValue());
});
if (optional.isEmpty()) {
throw new IllegalStateException("No entries in this chart.");
}
return optional.get().getSectorColorIntensityValue();
}
private double getSumOfEntrySectorAngles() {
double sum = 0.0;
for (PieChart3DEntry entry : entries) {
sum += entry.getSectorAngleValue();
}
return sum;
}
private double normalizeSectorAngle(PieChart3DEntry entry) {
return 360.0 *
(entry.getSectorAngleValue() /
getSumOfEntrySectorAngles());
}
private Color obtainColor(double intensity) {
double r = originalIntensityColor.getRed();
double g = originalIntensityColor.getGreen();
double b = originalIntensityColor.getBlue();
r += (1.0 - r) * (1.0 - intensity);
g += (1.0 - g) * (1.0 - intensity);
b += (1.0 - b) * (1.0 - intensity);
return new Color(r, g, b, 1.0);
}
} | {
"domain": "codereview.stackexchange",
"id": 45396,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "java, canvas, javafx",
"url": null
} |
java, canvas, javafx
com.github.coderodde.javafx.PieChart3DEntry.java:
package com.github.coderodde.javafx;
/**
* This class implements the pie chart entry.
*
* @author Rodion "rodde" Efremov
* @version 1.6 (Dec 18, 2023)
* @since 1.6 (Dec 18, 2023)
*/
public final class PieChart3DEntry {
/**
* Holds the sector radius of this entry.
*/
private double sectorRadiusValue;
/**
* Holds the sector angle of this entry.
*/
private double sectorAngleValue;
/**
* Holds the sector color intensity of this entry.
*/
private double sectorColorIntensityValue;
public double getSectorRadiusValue() {
return sectorRadiusValue;
}
public double getSectorAngleValue() {
return sectorAngleValue;
}
public double getSectorColorIntensityValue() {
return sectorColorIntensityValue;
}
public void setSectorRadiusValue(double sectorRadiusValue) {
checkValue(sectorRadiusValue);
this.sectorRadiusValue = sectorRadiusValue;
}
public void setSectorAngleValue(double sectorAngleValue) {
checkValue(sectorAngleValue);
this.sectorAngleValue = sectorAngleValue;
} | {
"domain": "codereview.stackexchange",
"id": 45396,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "java, canvas, javafx",
"url": null
} |
java, canvas, javafx
public void setSectorColorIntensityValue(double sectorColorIntensityValue) {
checkValue(sectorColorIntensityValue);
this.sectorColorIntensityValue = sectorColorIntensityValue;
}
public PieChart3DEntry withSectorRadiusValue(double sectorRadiusValue) {
setSectorRadiusValue(sectorRadiusValue);
return this;
}
public PieChart3DEntry withSectorAngleValue(double sectorAngleValue) {
setSectorAngleValue(sectorAngleValue);
return this;
}
public PieChart3DEntry withSectorColorIntensityValue(
double sectorColorIntensityValue) {
setSectorColorIntensityValue(sectorColorIntensityValue);
return this;
}
@Override
public String toString() {
return "[sectorRadiusValue = "
+ sectorRadiusValue
+ ", sectorAngleValue = "
+ sectorAngleValue
+ ", sectorColorIntensityValue = "
+ sectorColorIntensityValue
+ "]";
}
private static void checkValue(double value) {
if (Double.isNaN(value)) {
throw new IllegalArgumentException("The input value is NaN.");
}
if (Double.isInfinite(value)) {
throw new IllegalArgumentException("The input value is infinite.");
}
if (value < 0.0) {
throw new IllegalArgumentException("The input value is negative.");
}
}
}
com.github.coderodde.javafx.PieChart3DDemo.java: | {
"domain": "codereview.stackexchange",
"id": 45396,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "java, canvas, javafx",
"url": null
} |
java, canvas, javafx
import java.util.Random;
import javafx.application.Application;
import javafx.application.Platform;
import javafx.concurrent.Task;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.layout.StackPane;
import javafx.scene.paint.Color;
import javafx.stage.Stage;
import javafx.stage.WindowEvent;
public class PieChart3DDemo extends Application {
private static final double DIMENSION = 500.0;
private static final double CANVAS_DIMENSION = 400.0;
private static final int MAXIMUM_NUMBER_OF_SECTORS = 20;
private static final double MAXIMUM_VALUE = 200.0;
private static final double FULL_ANGLE = 360.0;
private static final Color CHART_BACKGROUND_COLOR = new Color(0.9,
0.9,
0.9,
1.0);
private static final DemoTask DEMO_TASK = new DemoTask();
public static void main(String[] args) {
Runtime.getRuntime()
.addShutdownHook(
new Thread(() -> {
DEMO_TASK.stop();
}));
launch(args);
}
@Override
public void start(Stage primaryStage) {
primaryStage.setTitle("PieChart3D demo");
StackPane root = new StackPane();
primaryStage.setScene(
new Scene(root,
DIMENSION,
DIMENSION));
DEMO_TASK.setRoot(root);
DEMO_TASK.setStage(primaryStage);
new Thread(DEMO_TASK).start();
primaryStage.show();
}
private static Color getRandomColor(Random random) {
return new Color(random.nextDouble(),
random.nextDouble(),
random.nextDouble(),
1.0);
} | {
"domain": "codereview.stackexchange",
"id": 45396,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "java, canvas, javafx",
"url": null
} |
java, canvas, javafx
random.nextDouble(),
1.0);
}
private static int getRandomNumberOfSectors(Random random) {
return random.nextInt(MAXIMUM_NUMBER_OF_SECTORS + 1);
}
private static double getRandomValue(Random random) {
return MAXIMUM_VALUE * random.nextDouble();
}
private static double getRandomAngleOffset(Random random) {
return FULL_ANGLE * random.nextDouble();
}
static PieChart3D getRandomChart(Random random) {
double angleOffset = getRandomAngleOffset(random);
int numberOfSectors = getRandomNumberOfSectors(random);
PieChart3D chart = new PieChart3D(CANVAS_DIMENSION);
chart.setChartBackgroundColor(CHART_BACKGROUND_COLOR);
chart.setAngleOffset(angleOffset);
chart.setOriginalIntensityColor(getRandomColor(random));
for (int i = 0; i < numberOfSectors; i++) {
PieChart3DEntry entry =
new PieChart3DEntry()
.withSectorAngleValue(getRandomValue(random))
.withSectorColorIntensityValue(getRandomValue(random))
.withSectorRadiusValue(getRandomValue(random));
chart.add(entry);
}
return chart;
}
} | {
"domain": "codereview.stackexchange",
"id": 45396,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "java, canvas, javafx",
"url": null
} |
java, canvas, javafx
final class DemoTask extends Task<Void> {
private static final long SLEEP_DURATION_IN_MILLISECONDS = 1L;
private static final int FRAMES_PER_CHART = 2_000;
private volatile boolean doRun = true;
private final Random random = new Random();
private StackPane root;
private Stage stage;
void stop() {
doRun = false;
}
void setRoot(StackPane root) {
this.root = root;
}
void setStage(Stage stage) {
this.stage = stage;
}
@Override
protected Void call() throws Exception {
stage.setOnCloseRequest(new EventHandler<WindowEvent>() {
@Override
public void handle(WindowEvent t) {
System.out.println("Exiting...");
Platform.exit();
System.exit(0);
}
});
int iterations = 0;
while (doRun) {
PieChart3D chart = PieChart3DDemo.getRandomChart(random);
for (int i = 0; i < FRAMES_PER_CHART; i++) {
Platform.runLater(() -> {
root.getChildren().clear();
root.getChildren().add(chart);
chart.setAngleOffset(chart.getAngleOffset() + 0.1);
chart.draw();
});
try {
Thread.sleep(SLEEP_DURATION_IN_MILLISECONDS);
} catch (InterruptedException ex) {}
}
System.out.println("Iterated: " + ++iterations);
}
return null;
}
}
Critique request
As always, I would like to hear any comment about improving the code. | {
"domain": "codereview.stackexchange",
"id": 45396,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "java, canvas, javafx",
"url": null
} |
java, canvas, javafx
Critique request
As always, I would like to hear any comment about improving the code.
Answer: Small issue, I don't think private static final DemoTask DEMO_TASK = new DemoTask(); needs static.
My other issue is with DemoTask extending Task<Void>. Most time I see Thread.sleep(SLEEP_DURATION_IN_MILLISECONDS); in a JavaFX app, I think something is wrong. In your case, getRandomChart(random) does not appear to do a large amount of work. I think you should implement this using TimeLine. The way your Task is designed goes against how it was designed to be used. You should not be dependent on a boolean to stop and start a Task. Moreover, you should not try to stop a Task to begin with. Task should do some work and return some state they will allow you to get a value, update the GUI, or move forward. | {
"domain": "codereview.stackexchange",
"id": 45396,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "java, canvas, javafx",
"url": null
} |
python, beginner, chess
Title: Chess_Board Validator from Automate the Boring Stuff Ch 5
Question: I recently started learning python and came up with this solution to the "Chess Dictionary Validator" exercise which is given in the end of chapter 5 in the book "Automate the Boring Stuff" by Al Sweigart:
In this chapter, we used the dictionary value {'1h': 'bking', '6c': 'wqueen', '2g': 'bbishop', '5h': 'bqueen', '3e': 'wking'} to represent a chess board. Write a function named isValidChessBoard() that takes a dictionary argument and returns True or False depending on if the board is valid.
A valid board will have exactly one black king and exactly one white king. Each player can only have at most 16 pieces, at most 8 pawns, and all pieces must be on a valid space from '1a' to '8h'; that is, a piece can’t be on space '9z'. The piece names begin with either a 'w' or 'b' to represent white or black, followed by 'pawn', 'knight', 'bishop', 'rook', 'queen', or 'king'. This function should detect when a bug has resulted in an improper chess board.
What suggestions do you have in order to improve this solution?
# prerequisites
# board: a-h, 1-8
# pieces: max 16 per player
# 8x "pawn",
# "knight",
# "bishop",
# "rook",
# 1x "king",
# 1x "queen"
#mainfunction
def chessCheck(brett):
# empty dict, should later collect the number of all figures (no matter if w or s)
valueCheck = {}
stri =""
#list of valid fields
validFields = ["a","b","c","d","e","f","g","h"]
#if all is valid, should remain == 0, if not then > 0
wrongSettings = 0 | {
"domain": "codereview.stackexchange",
"id": 45397,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, beginner, chess",
"url": null
} |
python, beginner, chess
#first loop through keys from dictionary
for k in brett.keys():
stri = str(k)
#go through each key as a string in subloop
for x in stri:
#here the first part of the key value (numbers) is checked
if int(x.isdecimal() ):
xpos = int(x)
#check if valid
if xpos <= 8:
pass
else:
#if no valid pos, then valid count becomes greater than 0
wrongSettings += 1
else:
#here it is checked whether letter part of string is NOT present in sample list
# if not present -> error counter high
if x not in validFields:
wrongSettings += 1
#loopt trough item pairs from dict
for k,v in brett.items():
# adds keys to new dict, than count for that key
valueCheck.setdefault(v, 0)
valueCheck[v] = valueCheck[v] +1
# check after creating the frequency list of the figures, whether conditions are met
# separate created dictionary into black and white
blackChess = {}
whiteChess = {}
# loop through count dictionary from above
for k,v in valueCheck.items():
#if "key" begins with "w" -> in white dict
if str(k).startswith("w"):
whiteChess[k] = v
#otherwise fill black dict at key position with value
elif str(k).startswith("b"):
blackChess[k] = v
# check here NUMBER of chess pieces PER player
# apply function, returned number, save in both vars
wpieces = countFigures(whiteChess)
bpieces = countFigures(blackChess)
#check here if LESS than 16 figures per player
if wpieces > 16:
print("Too many pieces")
wrongSettings += 1
elif bpieces > 16:
wrongSettings += 1 | {
"domain": "codereview.stackexchange",
"id": 45397,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, beginner, chess",
"url": null
} |
python, beginner, chess
elif bpieces > 16:
wrongSettings += 1
#check for white with test function
#update number of errors 1
wrongSettings = figureChecks(whiteChess, wrongSettings)
#anz fehler updaten part 2
wrongSettings = figureChecks(blackChess, wrongSettings)
#checks at the end how counter stands for false condition
if wrongSettings > 0:
return False
else:
return True
#function to check number of pieces per player
def figureChecks(figureDict,wrongcounter):
for k,v in figureDict.items():
# pawns max 8
if str(k) == "wpawn" and v > 8:
print("Too many pawns white")
wrongcounter += 1
elif str(k) =="wking" and v > 1: #king
print("Too many kings white")
wrongcounter +=1
elif str(k) =="wqueen" and v > 1: #queen
print("Too many quuens white")
wrongcounter +=1
return wrongcounter
#function for number of figures for black and white count
def countFigures(player):
piece = 0
for i in player.values():
piece = piece + int(i)
return piece
# example dict
# Example 1: valid chessboard (each player has 16 pieces)
exp1 = {'1a': 'wrook', '1b': 'wknight', '1c': 'wbishop', '1d': 'wqueen', '1e': 'wking', '1f': 'wbishop', '1g': 'wknight', '1h': 'wrook',
'2a': 'wpawn', '2b': 'wpawn', '2c': 'wpawn', '2d': 'wpawn', '2e': 'wpawn', '2f': 'wpawn', '2g': 'wpawn', '2h': 'wpawn',
'8a': 'brook', '8b': 'bknight', '8c': 'bbishop', '8d': 'bqueen', '8e': 'bking', '8f': 'bbishop', '8g': 'bknight', '8h': 'brook',
'7a': 'bpawn', '7b': 'bpawn', '7c': 'bpawn', '7d': 'bpawn', '7e': 'bpawn', '7f': 'bpawn', '7g': 'bpawn', '7h': 'bpawn'}
print(
chessCheck(exp1)
)
Answer: signature
def chessCheck(brett): | {
"domain": "codereview.stackexchange",
"id": 45397,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, beginner, chess",
"url": null
} |
python, beginner, chess
print(
chessCheck(exp1)
)
Answer: signature
def chessCheck(brett):
Pep8
asks that you spell it chess_check.
It's unclear what a brett might be,
and you chose not to annotate it with a type.
You passed up the opportunity to add a function """docstring"""
or even a # comment.
This signature communicates much less to the reader than I was hoping it would.
vague comment
# empty dict, should later collect the number of all figures (no matter if w or s)
valueCheck = {}
Thank you for trying.
I appreciate that you felt a comment was needed.
But I'm afraid I still don't know what value_check should hold.
I think a "figure" is a chess piece, and it might be the dictionary key.
But I don't know what "w" or "s" denotes.
Maybe "w" or "b"? For white or black?
OIC, a subsequent comment "anz fehler updaten" reveals
that author's Muttersprache is not English,
wir verwenden hier Deutsch, gut.
Ich lese weiß oder schwarz.
Changing tongue mid-sentence can be disorienting.
terminology
#list of valid fields
validFields = ["a","b","c","d","e","f","g","h"]
Elide the comment, as it says nothing beyond what the code eloquently stated.
The usual terms from the Business Domain would
be "rank" and "file".
I imagine I should translate "field" to "file" (column) as I'm reading this?
inconsistent naming
stri = str(k)
That's a bit jarring.
Expected to see strk.
Maybe the loop index used to be i?
It's unclear why introducing a temp var is a win
over just using the original str() expression.
use pass only where needed
if xpos <= 8:
pass
else:
#if no valid pos, then valid count becomes greater than 0
wrongSettings += 1
No, please don't do that.
Prefer to phrase it this way:
if xpos > 8:
wrongSettings += 1 | {
"domain": "codereview.stackexchange",
"id": 45397,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, beginner, chess",
"url": null
} |
python, beginner, chess
We use pass only in a situation where it is
syntactically necessary,
for example when defining a new Error class
that doesn't override any of the behaviors it inherits.
simplify logic
Validating coordinates works fine as-is.
But rather than looping, it would be simpler and more direct
to just unpack the expected pair of characters and validate each one:
assert isinstance(k, str)
file, rank = k # or str(k), if I guessed wrong and k isn't always a string
if file not in valid_fields: ...
if rank not in range(1, 9): ...
When creating the black_ and white_chess dicts,
you similarly should not need str(k).
Just use if k.startswith("w"):
default dict
valueCheck.setdefault(v, 0)
valueCheck[v] = valueCheck[v] +1
Ok, now I'm starting to understand this data structure.
It appears it should have been named checked_values.
Initialize
in this way:
from collections import defaultdict
...
checked_values = defaultdict(int)
...
checked_values[v] += 1
@rdesparbes observes that
Counter
offers similar functionality.
consistent error reporting
print("Too many pieces")
Recommend you report "Too many white pieces".
And then fill in the corresponding black report, which currently is missing.
This function is getting to be Too Long,
and counting pieces is one of several
excellent opportunities to break out
a small helper function.
API design
This is kind of weird:
wrongSettings = figureChecks(whiteChess, wrongSettings)
It would be more natural to phrase it:
wrong_settings += figure_checks(white_chess)
No need for figure_checks() to know about how many errors have happened already,
since that won't alter its result.
use a boolean expression to return a boolean
if wrongSettings > 0:
return False
else:
return True
Prefer:
return wrongSettings == 0 | {
"domain": "codereview.stackexchange",
"id": 45397,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, beginner, chess",
"url": null
} |
java, security, cryptography, aes
Title: Encrypt a String using AES in CBC mode
Question: Your opinion interests me regarding this program.
This program encrypts a text message using the AES256 algorithm and CBC.
It allows the creation of an encrypted message that contains:
The salt used for the creation of the AES256 key
The salt used for the creation of the derived key used for calculating the HMAC for message integrity verification
The initialization vector
The size of the message
The encrypted message
The HMAC for integrity verification
Do you have any security remarks about this code?
Does it seem secure to you?
If not, why?
package security;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.Arrays;
import javax.crypto.Cipher;
import javax.crypto.Mac;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.SecretKeySpec;
public class Sample {
public static void main(String[] args) throws Exception {
String password = "12341234@xxxx!'9876";
String msg = "This is the message";
System.out.println("Encrypt '" + msg + "'");
byte[] encrypted = encrypt(msg, password);
System.out.println(bytesToHex(encrypted));
String msg2 = decrypt(encrypted, password);
System.out.println("restultat='" + msg2 + "'");
} | {
"domain": "codereview.stackexchange",
"id": 45398,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "java, security, cryptography, aes",
"url": null
} |
java, security, cryptography, aes
}
public static byte[] encrypt(String message, String password) throws Exception {
SecureRandom rand = new SecureRandom();
try (ByteArrayOutputStream out = new ByteArrayOutputStream()) {
try (DataOutputStream dout = new DataOutputStream(out)) {
try (InputStream in = new ByteArrayInputStream(
message.getBytes(StandardCharsets.UTF_8))) {
byte[] salt = new byte[8];
rand.nextBytes(salt);
out.write(salt);
byte[] derivatedSalt = new byte[8];
rand.nextBytes(derivatedSalt);
out.write(derivatedSalt);
byte[] iv = new byte[16];
rand.nextBytes(iv);
out.write(iv);
dout.writeLong(message.getBytes().length);
byte[] aesKey = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256")
.generateSecret(new PBEKeySpec(password.toCharArray(), salt, 60000, 256))
.getEncoded();
Cipher ci = Cipher.getInstance("AES/CBC/PKCS5Padding");
ci.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(aesKey, "AES"),
new IvParameterSpec(iv));
Mac hmac = Mac.getInstance("HmacSHA256");
byte[] key1 = saltedSHA256(saltedSHA256(aesKey, derivatedSalt), derivatedSalt);
hmac.init(new SecretKeySpec(key1, "HmacSHA256"));
hmac.update(iv);
hmac.update(salt);
byte[] ibuf = new byte[8192];
int len; | {
"domain": "codereview.stackexchange",
"id": 45398,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "java, security, cryptography, aes",
"url": null
} |
java, security, cryptography, aes
byte[] ibuf = new byte[8192];
int len;
while ((len = in.read(ibuf)) != -1) {
byte[] obuf = ci.update(ibuf, 0, len);
if (obuf != null) {
out.write(obuf);
hmac.update(ibuf, 0, len);
}
}
byte[] obuf = ci.doFinal();
if (obuf != null) {
out.write(obuf);
}
byte[] bmac = hmac.doFinal();
out.write(bmac);
return out.toByteArray();
}
}
}
}
public static String decrypt(byte[] xx, String password) throws Exception {
try (InputStream in = new ByteArrayInputStream(xx)) {
try (DataInputStream din = new DataInputStream(in)) {
try (ByteArrayOutputStream out = new ByteArrayOutputStream()) {
byte[] salt = new byte[8];
read(in, salt);
byte[] derivatedSalt = new byte[8];
read(in, derivatedSalt);
byte[] iv = new byte[16];
read(in, iv);
long taille = din.readLong();
byte[] aesKey = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256")
.generateSecret(new PBEKeySpec(password.toCharArray(), salt, 60000, 256))
.getEncoded();
Cipher ci = Cipher.getInstance("AES/CBC/PKCS5Padding");
ci.init(Cipher.DECRYPT_MODE, new SecretKeySpec(aesKey, "AES"), new IvParameterSpec(iv)); | {
"domain": "codereview.stackexchange",
"id": 45398,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "java, security, cryptography, aes",
"url": null
} |
java, security, cryptography, aes
byte[] key1 = saltedSHA256(saltedSHA256(aesKey, derivatedSalt), derivatedSalt);
Mac hmac = Mac.getInstance("HmacSHA256");
hmac.init(new SecretKeySpec(key1, "HmacSHA256"));
hmac.update(iv);
hmac.update(salt);
long tailleToread = (taille / 16 + 1) * 16;
long resteALire = tailleToread;
int bufsize = 8192;
while (resteALire > 0) {
int blockToRead = Math.min(
(resteALire < bufsize ? (int) resteALire : bufsize + 500), bufsize);
// astuce pour gérer une taille de message long avec une taille de buffer en in
byte[] ibuf = in.readNBytes(blockToRead);
int len = ibuf.length;
resteALire -= len;
byte[] obuf = ci.update(ibuf, 0, len);
if (obuf != null) {
out.write(obuf);
hmac.update(obuf);
}
}
byte[] obuf = ci.doFinal();
if (obuf != null) {
out.write(obuf);
hmac.update(obuf);
}
// recalcul
byte[] bmac = hmac.doFinal();
byte[] readsha = in.readAllBytes();
if (!Arrays.equals(bmac, readsha)) {
throw new Exception("HMAC error");
}
return out.toString(StandardCharsets.UTF_8);
}
}
}
} | {
"domain": "codereview.stackexchange",
"id": 45398,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "java, security, cryptography, aes",
"url": null
} |
java, security, cryptography, aes
}
private static void read(InputStream inputStream, byte[] buffer) throws IOException {
int bufferLength = buffer.length;
int totalBytesRead = 0;
int bytesRead;
while ((bytesRead = inputStream.read(buffer, totalBytesRead, bufferLength - totalBytesRead)) != -1) {
totalBytesRead += bytesRead;
if (totalBytesRead == bufferLength) {
break;
}
}
}
private static byte[] saltedSHA256(byte[] data, byte[] salt) throws NoSuchAlgorithmException {
byte[] bytes = new byte[data.length + salt.length];
System.arraycopy(data, 0, bytes, 0, data.length);
System.arraycopy(salt, 0, bytes, data.length, salt.length);
MessageDigest digest = MessageDigest.getInstance("SHA-256");
return digest.digest(bytes);
}
public static String bytesToHex(byte[] bytes) {
StringBuilder hexStringBuilder = new StringBuilder(2 * bytes.length);
for (byte b : bytes) {
hexStringBuilder.append(String.format("%02x", b));
}
return hexStringBuilder.toString();
}
}
Answer: The main thing to be wary of is that this kind of ciphertext can be cracked "offline", i.e. at the convenience of the adversary using as many machines as possible. That means that bad passwords are immediately vulnerable even though PBKDF2 is used to derive the data encryption & MAC keys. If possible it should be avoided.
Security / Cryptography
When it comes to the cryptography, the following can be noted: | {
"domain": "codereview.stackexchange",
"id": 45398,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "java, security, cryptography, aes",
"url": null
} |
java, security, cryptography, aes
Instead of inventing your own AEAD cipher, it is probably better and less error prone to use AES in GCM mode. There are reasons to prefer HMAC in some cases, but generally those are rather specific.
The number of iterations is an important security parameter, which should be clearly documented. It should definitely be higher than 60000 in most cases, more towards a million.
If there is a random salt for each encryption then you will get a different key for each encryption; using a different IV isn't really required (it can remain as an all-zero IV).
It may be a better idea to use public key encryption and signing instead of using secret keys. That would allow you to protect the plaintext with a real key instead of a password (a password can be used to protect the private keys).
There is no reason to call saltedSHA256 twice, it has no security consequences.
HMAC forgets to include the plaintext size in the calculation; as it is an adversary could alter the size after which decryption fails (currently they probably need to remain within the block though).
Note that saltedSHA256 basically implements a Key Derivation Function. There are official key derivation functions such as HKDF.
Conciseness
Clearly the code can be more concise, for instance:
A single try can be used to control multiple streams at once, e.g.
try (var s1 = new Stream(); var s2 = new Stream(s1)) {
// code goes here
} | {
"domain": "codereview.stackexchange",
"id": 45398,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "java, security, cryptography, aes",
"url": null
} |
java, security, cryptography, aes
Instead of performing the cipher and HMAC update yourself you could have used CipherOutputStream and DigestOutputStream.
In modern Java versions you can use the var keyword, e.g. var ba = new ByteArrayOutputStream().
Instead of creating a buffer etc. it is possible to use InputStream.transferTo(OutputStream out)
But while we are at it, we don't need any InputStream, if we have CipherOutputStream we can just write the encoded message directly.
Instead of using ByteArrayOutputStream simply use DataOutputStream#write, then it is possible to use var out = new DataOutputStream(new ByteArrayOutputStream()) (far out, eh?).
The size of the ciphertext can easily be predicted. As the result is being returned in a byte array, it makes more sense to use ByteBuffer or byte[]. The good thing about ByteBuffer is that Cipher can use it as output buffer, but that it also has put(byte[]) and putLong(long) methods defined for it. So the encode method doesn't require streaming anyway.
Code
Some variable names could be improved, e.g. cipher instead of ci.
The exception handling basically lets the user handle all (checked) exceptions; it is better to turn most of these into RuntimeException instances, see here how to handle the various exceptions.
Java can only destroy strings by using garbage collection, and normally Java doesn't destroy string instances. A password is often shown as using char[] because the char values in the array can be overwritten by methods such as Arrays.fill, which would usually destroy the contents. If the method takes a String that using a char[] becomes pointless.
Recommendations
These are recommendations for creating a streaming implementation, as mentioned in the comments as goal (next time include that information in the question text): | {
"domain": "codereview.stackexchange",
"id": 45398,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "java, security, cryptography, aes",
"url": null
} |
java, security, cryptography, aes
If the code needs to use GCM then it does limit to 2 GiB of data due to the array size. For file encryption HMAC can be used, but it makes more sense to e.g. copy the ideas within DigestOutputStream and DigestInputStream to allow for streaming in that case.
At a very minimum make the password handling as robust as possible (e.g. indicate weak passwords and/or recommend strong ones).
Somehow register the iteration count with the ciphertext so it can be upgraded later.
Include as much information in the HMAC calculation as possible. | {
"domain": "codereview.stackexchange",
"id": 45398,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "java, security, cryptography, aes",
"url": null
} |
python, javascript, random
Title: Seeded PRNG in JavaScript and Python yielding same results
Question: So I need a PRNG in Python and JavaScript that yields the same results, which is the reason I can't use the built-in methods. It doesn't have to be very good or even cryptographically secure, since it's only for generating mock data for tests.
The algorithm used is the very short one by George Marsaglia described here.
The Python version:
import typing
class SimpleRandom:
def __init__(self, seed: int = 0):
if seed < 0 or seed >= 2**32 - 2:
raise ValueError("seed must be between 0 and 2^32 - 3")
self.mz = seed + 1
self.mw = seed + 2
def next(self) -> int:
self.mz = (36969 * (self.mz & 65535) + (self.mz >> 16)) % 2**32
self.mw = (18000 * (self.mw & 65535) + (self.mw >> 16)) % 2**32
return ((self.mz << 16) % 2**32 + self.mw) % 2**32
def randrange(self, start: int, stop: int) -> int:
if start >= stop:
raise ValueError("start must be less than stop")
if start < 0 or stop < 0:
raise ValueError("both start and stop must be positive")
if stop - start > 2**32:
raise ValueError("stop - start must be less than 2^32")
return self.next() % (stop - start) + start
def choice(self, seq: typing.Sequence) -> typing.Any:
return seq[self.randrange(0, len(seq))]
def choices(self, seq: typing.Sequence, k: int) -> typing.Sequence:
return [self.choice(seq) for i in range(k)]
if __name__ == "__main__":
random = SimpleRandom(0)
print(f"First random integer: {random.next()}")
for i in range(10000):
random.next()
print(f"Random int after 10000 calls: {random.next()}")
print(f"Random int 1000 <= {random.randrange(1000, 2000)} < 2000")
arr = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j"] | {
"domain": "codereview.stackexchange",
"id": 45399,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, javascript, random",
"url": null
} |
python, javascript, random
arr = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j"]
print(f"Random choice from a-j: {random.choice(arr)}")
print(f"Random choices from a-j: {', '.join(random.choices(arr, 7))}")
And the JavaScript version:
function SimpleRandom (seed = 0) {
if (seed < 0 || seed > 0xffffffff - 2) throw new Error('seed must be between 0 and 2^32 - 3')
this.mz = seed + 1
this.mw = seed + 2
this.next = function () {
this.mz = 36969 * (this.mz & 65535) + (this.mz >>> 16)
this.mw = 18000 * (this.mw & 65535) + (this.mw >>> 16)
return ((this.mz << 16) + this.mw) >>> 0
}
this.randRange = function (min, max) {
if (min === max) return min
if (min > max) throw new Error('min > max')
if (max - min > 0xffffffff) throw new Error('Range too large')
return min + (this.next() % (max - min))
}
this.choice = function (arr) {
return arr[this.randRange(0, arr.length)]
}
this.choices = function (arr, k) {
if (!Number.isInteger(k) || k < 0) throw new Error('k must be a positive integer')
if (!Array.isArray(arr)) throw new Error('arr must be an array')
const result = []
for (let i = 0; i < k; i++) {
result.push(this.choice(arr))
}
return result
}
}
if (require.main === module) {
const random = new SimpleRandom(0)
console.log(`First random integer: ${random.next()}`)
for (let i = 0; i < 10000; i++) {
random.next()
}
console.log(`Random int after 10000 calls: ${random.next()}`)
console.log(`Random int 1000 <= ${random.randRange(1000, 2000)} < 2000`)
const arr = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']
console.log(`Random choice from a-j: ${random.choice(arr)}`)
console.log(`Random choices from a-j: ${random.choices(arr, 7).join(', ')}`)
} | {
"domain": "codereview.stackexchange",
"id": 45399,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, javascript, random",
"url": null
} |
python, javascript, random
Answer: SimpleRandom is an incredibly generic name. I'd call the thing after which it is designed; MwcRandomGenerator would be more appropriate. One problem with this generator is that it seems to be first defined in a USENET post, which is possibly you may not want to use as a reference. This one has some more code as well as test vectors. Note that it simply uses w and z as variable names; I'd keep to original variable names rather than deviating from them.
One problem that I have with the algorithm is that the seed cannot be just any value but that it needs to be within 0 and 2^32 - 2. That makes it more appropriate as some kind of implementation detail than for generic usage (creating a test set of values would be a valid use case of course). I'd rather do a mod 2^32 - 3 than simply trowing an error, creating a very dangerous runtime failure mode in a class called SimpleRandom; at the very least it should be clearly documented.
The error displayed on the seed must be between 0 and 2^32 - 3 should clearly indicate if the values are incusive or exclusive. Now it is inclusive for 0 and exclusive for 2^32. This is common method for ranges in programming, but for human language it is inconclusive. I don't think this error is for user consumption so indicating that it should be in the range [0, 2^32 - 3) would probably be better.
Obviously testing the RNG should consist of much more than simply printing out a few values. It is important to test the the bounds given in the algorithm, e.g.the ones for the seed talked about before. Furthermore, I would at least test against official test vectors or otherwise a known-good implementation. Just comparing some values by hand is not sufficient.
Disclaimer: I did not do an in depth review of the language specific features nor to test if the random implementation is correct. | {
"domain": "codereview.stackexchange",
"id": 45399,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, javascript, random",
"url": null
} |
rust
Title: Make a config, that is periodically refreshed by a background thread, easily accessible to the rest of the program
Question: I'm learning rust by implementing simple use-cases that are common and trivial in other languages. Recently, I decided to prototype a small component for retrieving some "config" from a remote source every X minutes. The local version of config should also be made available to the rest of the program.
This is what I came up with. I'm looking for improvements in my code, especially within the get_config method where I had to clone the entire config. Note that a lot of stuff (like error handling and graceful shutdown) has been left out for brevity.
use std::{sync::{Arc, RwLock}, thread::{self, JoinHandle, sleep}, time::Duration};
#[derive(Clone, Debug)]
struct Config {
// Simplest possible config.
pub quote: String
}
struct ConfigProvider {
refresher: Option<JoinHandle<()>>,
config: Arc<RwLock<Config>>
}
impl ConfigProvider {
pub fn new() -> ConfigProvider {
let mut provider = ConfigProvider{
refresher: None,
config: Arc::new(RwLock::new(Config {quote: "(empty)".to_owned() }))
};
let data_ref = Arc::clone(&provider.config);
let th = thread::spawn(move || ConfigProvider::refresh(data_ref));
provider.refresher = Some(th);
provider
}
fn get_config(&self) -> Config {
// Question: How to avoid cloning here, so this method
// becomes as cheap as possible ?
return self.config.read().unwrap().clone();
}
fn refresh(dest: Arc<RwLock<Config>>) {
loop {
sleep(Duration::from_secs(5));
println!("Refreshing quote..");
let response = reqwest::blocking::get("https://api.quotable.io/random");
if response.is_err() {
println!("Error fetching quote: {:?}", response.err().unwrap());
continue;
} | {
"domain": "codereview.stackexchange",
"id": 45400,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "rust",
"url": null
} |
rust
let text = response.unwrap().text();
if text.is_err() {
println!("Error reading quote: {:?}", text.err().unwrap());
continue;
}
let quote = text.unwrap();
{
let mut config = dest.write().unwrap();
config.quote = quote;
}
}
}
}
fn main() {
let provider = ConfigProvider::new();
loop {
sleep(Duration::from_secs(3));
let config = provider.get_config();
println!("Retrieved quote: {}", config.quote);
}
}
Answer: You can change
config: Arc<RwLock<Config>>
...
fn get_config(&self) -> Config {
to
config: Arc<RwLock<Arc<Config>>>,
...
fn get_config(&self) -> Arc<Config> {
This way, while you do still need to clone() the value out of the lock, the clone simply consists of incrementing the reference count, not copying all data in the Config.
A further refinement of this approach is to use the arc-swap library, which lets you avoid using any locking at all, but update the config by atomically swapping in a new Arc<Config> pointer. This has the advantage that the config updater cannot ever cause the config readers to block. In that case, you'd write
config: ArcSwap<Config>,
and the ArcSwap type handles all the rest of the functionality.
Another thing: Right now, ConfigProvider is structured around both updating the config and handing it out. Notably, it isn't Clone. This may prove inconvenient later, because code which needs the config cannot own something that lets it fetch the latest config. I recommend that you explicitly split out the “sending” role from the “receiving” one, like channels do. Now, in the case of the code you've shown here, there is actually nothing to do but stop storing the JoinHandle:
#[derive(Clone, Debug)]
struct ConfigProvider {
config: Arc<RwLock<Arc<Config>>>,
} | {
"domain": "codereview.stackexchange",
"id": 45400,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "rust",
"url": null
} |
rust
// or if you take the above advice to use `arc-swap`,
#[derive(Clone, Debug)]
struct ConfigProvider {
// need an outer Arc to make it shareable by cloning
config: Arc<ArcSwap<Config>>,
}
Now, any code that wants to track the latest config can clone and hang onto a ConfigProvider indefinitely; it acts as the receiving side of the channel, and the thread acts as the sending side. | {
"domain": "codereview.stackexchange",
"id": 45400,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "rust",
"url": null
} |
python, beginner, python-3.x, programming-challenge, rock-paper-scissors
Title: Making a Rock Paper Scissors game in Python - How to reduce repetition and make it more effective?
Question: I am a "new" coder to Python - saying this because I got stuck in the tutorial hell - and I saw that doing projects was a way of consolidating what I had learnt from those tutorials, so here I am.
I made a little rock paper scissors game, and I am kind of a novice when it comes to making my code effective. So please be as critical as possible with my it (obviously only constructive criticism), so in the future I may get better at this. By the way, if you have any other project that you could suggest for my level I would be glad to do it :)
main.py
# My attempt on making rock paper scissors
from multiplayer_mode import multiplayer
from player_cpu import playerVsCPU
choose_Gamemode = ""
text = ""
user_input = ""
temp = False
while choose_Gamemode != "exit":
choose_Gamemode = input("Choose your game mode (\"mul\" for multiplayer, \"solo\" to play against computer, \"exit\" to exit.): ")
if choose_Gamemode.lower() == "mul":
text = multiplayer()
user_input = input("Do you want to add the date of today (Y/N)?")
if user_input.upper() == "Y":
user_input = input("Enter the date of today: ")
temp = True
with open("victory_log.txt", "a") as file:
if temp:
file.write(f"\nAs of {user_input} the winners are (from first to last):\n")
file.write(f"{text}\n")
elif choose_Gamemode.lower() == "solo":
playerVsCPU()
elif choose_Gamemode.lower() == "exit":
break
else:
print("Invalid input! Try again!")
print("Thank you for playing the game!")
multiplayer_mode.py
def multiplayer():
import random
import os
win = False
player1 = ""
player2 = ""
player1_Choice = ""
player2_Choice = ""
victory_cond = {"scissors":"paper", "paper":"rock","rock":"scissors"} | {
"domain": "codereview.stackexchange",
"id": 45401,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, beginner, python-3.x, programming-challenge, rock-paper-scissors",
"url": null
} |
python, beginner, python-3.x, programming-challenge, rock-paper-scissors
os.system('cls' if os.name == 'nt' else 'clear')
player1 = input("Welcome to rock, paper, scissors! Enter player 1's name: ")
player2 = input("Input player 2's name: ")
os.system('cls' if os.name == 'nt' else 'clear')
while win != True:
player1_Choice = input(f"{player1}'s turn (Enter rock, paper or scissors): ")
os.system('cls' if os.name == 'nt' else 'clear')
player2_Choice = input(f"{player2}'s turn (Enter rock, paper or scissors): ")
os.system('cls' if os.name == 'nt' else 'clear')
if player1_Choice.lower() == player2_Choice.lower() and player1_Choice.lower() in victory_cond.keys() and player2_Choice.lower() in victory_cond.values():
print("It's a draw! Try again!")
elif player1_Choice.lower() != player2_Choice.lower() and player1_Choice.lower() in victory_cond.keys() and player2_Choice.lower() in victory_cond.values():
for i, j in victory_cond.items():
if player1_Choice.lower() == i and player2_Choice.lower() == j:
win = True
print(f"{player1} wins over {player2} using {player1_Choice} against {player2_Choice}!")
return player1
else:
win = True
print(f"{player2} wins over {player1} using {player2_Choice} against {player1_Choice}!")
return player2
else:
print("Oops, invalid input! Try again!")
player_cpu.py
def playerVsCPU():
import random
import os
win = False
list_of_rcp = ["rock", "paper", "scissors"]
victory_cond = {"scissors":"paper", "paper":"rock","rock":"scissors"}
while win != True:
user_input = input("Welcome to rock, paper, scissors! Your turn (Enter rock, paper or scissors): ")
cpu_choice = random.choice(list_of_rcp)
if user_input.lower() == cpu_choice.lower():
print("It's a draw! Try again!\n") | {
"domain": "codereview.stackexchange",
"id": 45401,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, beginner, python-3.x, programming-challenge, rock-paper-scissors",
"url": null
} |
python, beginner, python-3.x, programming-challenge, rock-paper-scissors
if user_input.lower() == cpu_choice.lower():
print("It's a draw! Try again!\n")
elif user_input.lower() != cpu_choice.lower() and user_input.lower() in victory_cond.keys() and cpu_choice.lower() in victory_cond.values():
for i, j in victory_cond.items():
if user_input.lower() == i and cpu_choice.lower() == j:
win = True
os.system('cls' if os.name == 'nt' else 'clear')
print(f"You win against the computer using {user_input} against {cpu_choice}!\n")
else:
win = True
os.system('cls' if os.name == 'nt' else 'clear')
print(f"Computer wins against you using {cpu_choice} against {user_input}!\n")
else:
os.system('cls' if os.name == 'nt' else 'clear')
print("Oops, invalid input! Try again!\n")
Answer:
if you have any other project that you could suggest
Here's a fun one.
Implement flood fill.
docstring
# My attempt on making rock paper scissors
This is nice enough, I suppose.
Python has a special form called a docstring,
which you may have seen on functions and classes.
Here, you might re-phrase this as module-level docstring:
"""My attempt on making rock paper scissors"""
lint
choose_Gamemode = ""
Pep8
asks that you spell it choose_gamemode.
Similarly for player2_choice and player_vs_cpu.
quoting
... = input("Choose your game mode (\"mul\" for multiplayer, \"solo\" to ...")
Clearly those \ backwhacks work fine.
But they're ugly.
Often you can use the "other" kind of quote so they're no longer needed:
... = input('Choose your game mode ("mul" for multiplayer, "solo" to ...') | {
"domain": "codereview.stackexchange",
"id": 45401,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, beginner, python-3.x, programming-challenge, rock-paper-scissors",
"url": null
} |
python, beginner, python-3.x, programming-challenge, rock-paper-scissors
If you had been using
black
it would have noticed that detail
and canonicalized the spelling for you.
DRY
You only care about the downcased (.lower()) game mode.
So assign that once, rather than re-computing it several times.
use the standard libraries
This is a little weird:
user_input = input("Enter the date of today: ")
Prefer to use the
datetime
library.
import datetime as dt
...
today = dt.date.today()
context manager
Kudos on using a with to ensure the file you open'ed will be properly close'd.
pick one approach for control flow
while choose_gamemode != "exit":
...
elif choose_gamemode.lower() == "exit":
break
I recommend that you use just the while test,
or that you use just the break (inside while True:).
Using both leads to confusion, and hard-to-diagnose bugs.
On which topic, the inconsistent downcasing (in some places but not others)
is not a good practice.
imports at top
def multiplayer():
import random
import os
Please don't do that.
Pep8
explains that imports belong at top-of-file.
Lint with ruff
to have weird items called out.
Your code should lint clean when you execute $ ruff *.py
Use isort to organize your imports properly.
ANSI escapes
os.system('cls' if os.name == 'nt' else 'clear')
I'm glad to see you've been trying out if expressions.
Forking a child process is a pretty heavy weight approach,
compared to print(end=chr(27) + "[2J", flush=True).
If you search pypi.org, you'll find there's more than
one package that would be happy to help you put convenient names on
ANSI
escape sequences.
Also, DRY!
You use this expression several times.
Use def to package it up as a tiny helper function,
and make several calls to that function.
a boolean is already a boolean expression
while win != True:
Prefer:
while not win: | {
"domain": "codereview.stackexchange",
"id": 45401,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, beginner, python-3.x, programming-challenge, rock-paper-scissors",
"url": null
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.