text stringlengths 1 2.12k | source dict |
|---|---|
python, beginner, object-oriented, hangman
def _guess_letter(self, letter):
"""
Replaces the guessed letter in the blanks and adds the
letter to a set containing all the letters used so far.
"""
for i, char in enumerate(self.secret_word_low):
if char == letter:
self.blanks[i] = letter
self.found_letters.add(letter)
def _valid_input(self, letter):
"""
Checks if the string entered by the user has a length of 1
and if all characters in the string are in the alphabet.
"""
return len(letter) != 1 or not letter.isalpha()
def _win(self):
"""
Asigns a boolean value of True if the user guess the secret word.
"""
return self._blanks_string == self.secret_word_low
def _play(self):
"""
The game stage.
"""
print(f'\nSecret word: {self._blanks_string}')
print(self._draw_hangman())
print(self._spacer())
while self.trials > 0 and not self._win():
letter = input('\nEnter a letter: ').lower() | {
"domain": "codereview.stackexchange",
"id": 42917,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, beginner, object-oriented, hangman",
"url": null
} |
python, beginner, object-oriented, hangman
if self._valid_input(letter):
print('The value entered is invalid.\n')
elif letter in self.found_letters:
print('This letter has already been entered. Enter another letter.\n')
elif letter in self.secret_word_low:
self.found_letters.add(letter)
self._guess_letter(letter)
print(self._blanks_string)
else:
self.found_letters.add(letter)
self.trials -= 1
print(f'\nYou missed and lost a life. You have {self.trials} trials left.')
print(self._draw_hangman())
print(self._spacer())
if self._win():
print(f'\nYou won. The secret word is: {self.secret_word}.')
else:
print(f'\nYou lost. The secret word is: {self.secret_word}.')
def main():
"""
Selects a word from a list of words.
This word is to be guessed in the game.
"""
with open('words.txt', 'r+', encoding='utf-8') as words:
secret_word = random.choice(words.read().split())
secret_word = ''.join(secret_word)
game = Hangman(secret_word)
game._play()
if __name__ == '__main__':
main()
```
Answer: Gameplay
Secret word: _____
How many letters are in this secret word? I'd recommend telling the player rather than them guessing, or needing to do something like highlighting the underscores one by one.
You could tell the player explicitly, or make it easier to count the letters. Whatever you prefer.
Secret word (5 letters): _ _ _ _ _
How many guesses does a player start with? The player isn't told 'trials' until they miss with a guess. | {
"domain": "codereview.stackexchange",
"id": 42917,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, beginner, object-oriented, hangman",
"url": null
} |
python, beginner, object-oriented, hangman
Naming things is hard
In Python, a leading underscore in front of a variable name has a specific meaning. It is a marker that the method is private. Marking a method as private means anything outside of the class should not use it.
Hangman._play looks like it should not be private. As it is intended to be used outside of the Hangman class, it should public. The main method has an example of using _play outside of the class.
def main():
...
game = Hangman(secret_word)
game._play()
_play can be renamed to just play.
This applies to any method or attribute in the class. If it is meant to be used outside of the class, don't mark it as private.
def _valid_input(self, letter):
"""
Checks if the string entered by the user has a length of 1
and if all characters in the string are in the alphabet.
"""
return len(letter) != 1 or not letter.isalpha()
valid_input will return a boolean. Does True mean the input is valid? Or does True mean the input had a problem, and then False means the input is valid? Try to make sure the most simple interpretation of the name matches what the function will do.
In this case, True means the input was invalid, which is the opposite of what I would have expected. You have the choice of changing the name, or inverting the logic.
I think inverting the logic will make the whole function more simple to read and understand. As a second tweak, I would include the prefix is as an indicator that the method will return a boolean value.
def is_valid_input(self, letter):
"""
Return True if the input is a single letter in the alphabet.
"""
return len(letter) == 1 and letter.isalpha()
This will need a change wherever the method is used.
def has_won(self):
"""
Asigns a boolean value of True if the user guess the secret word.
"""
return self._blanks_string == self.secret_word_low | {
"domain": "codereview.stackexchange",
"id": 42917,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, beginner, object-oriented, hangman",
"url": null
} |
python, beginner, object-oriented, hangman
This is ok, but a little confusing at first. When would a blank string be the same as the secret word unless the secret word was blank? I missed the 's' at the end of 'blanks'.
Perhaps a better name than blanks_string is blanks? I don't feel all that fondly about it though.
I would instead suggest implementing this a different way. You could count the number of correct letters so far. You might check that there are no blanks left in the blanks_string, which would mean all the letters have been guessed.
Small restructure
There is a lot going on in the main loop of the play method.
if not self.is_valid_input(letter):
print('The value entered is invalid.\n')
elif letter in self.found_letters:
print('This letter has already been entered. Enter another letter.\n')
elif letter in self.secret_word_low:
self.found_letters.add(letter)
self.guess_letter(letter)
print(self._blanks_string)
else:
self.found_letters.add(letter)
self.trials -= 1
print(f'\nYou missed and lost a life. You have {self.trials} trials left.')
print(self.draw_hangman())
I would try and split the logic to better show invalid vs valid and correct vs incorrect.
if not self.is_valid(letter):
print('The value entered is invalid.\n')
continue
if letter in self.found_letters:
print('This letter has already been entered. Enter another letter.\n')
continue
if letter in self.secret_word_low:
self.found_letters.add(letter)
self.guess_letter(letter)
print(self._blanks_string)
else:
self.found_letters.add(letter)
self.trials -= 1
print(f'\nYou missed and lost a life. You have {self.trials} trials left.')
print(self.draw_hangman()) | {
"domain": "codereview.stackexchange",
"id": 42917,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, beginner, object-oriented, hangman",
"url": null
} |
python, beginner, object-oriented, hangman
Based on this, it looks like the name found_letters is not quite right. It also tracks guessed but incorrect letters. I think used_letters is a better name.
def guess_letter(self, letter):
"""
Replaces the guessed letter in the blanks and adds the
letter to a set containing all the letters used so far.
"""
for i, char in enumerate(self.secret_word_low):
if char == letter:
self.blanks[i] = letter
self.found_letters.add(letter)
It looks like the method guess_letter doesn't actual check the guess, it updates the blanks (if we already knew the letter was in the secret word). It also does extra work, as both guess_letter and play marked a letter as used.
I think it would be worth making guess_letter do more of the work. It should track if the letter was correct alongside marking where the letter appears in the blanks. I don't think guess_letter should care about a repeated guess, as the guess letter is already checked beforehand. Incidentally, a repeated guess won't waste a trial, so it shouldn't matter to someone playing the game.
def guess_letter(self, letter):
"""
Replace the guessed letter in the blanks where it matches in the secret word and
return True if that letter appeared in the secret word.
"""
good_guess = False
for i, char in enumerate(self.secret_word_low):
if char == letter:
good_guess = True
self.blanks[i] = letter
return good_guess
And the loop contents would be something like:
if not self.is_valid(letter):
print('The value entered is invalid.\n')
continue
if letter in self.used_letters:
print('This letter has already been entered. Enter another letter.\n')
continue
guess_was_good = self.guess_letter(letter)
self.used_letters.add(letter) | {
"domain": "codereview.stackexchange",
"id": 42917,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, beginner, object-oriented, hangman",
"url": null
} |
python, beginner, object-oriented, hangman
guess_was_good = self.guess_letter(letter)
self.used_letters.add(letter)
if guess_was_good:
print(self._blanks_string)
else:
self.trials -= 1
print(f'\nYou missed and lost a life. You have {self.trials} trials left.')
print(self.draw_hangman())
Polish
There are a few small details to look at. They won't make or break the experience, but are nice to fix.
The first time I ran the code, I got an error message: FileNotFoundError: [Errno 2] No such file or directory: 'words.txt'. Don't forget to include first time instructions, even if they are just a rough list of bullet points.
After creating an empty file called words.txt I got the error message: IndexError: Cannot choose from an empty sequence. For someone looking to play the game, this doesn't mean much. Could the error message tell the player what went wrong? Even better, could it say what to try if this happens?
You missed and lost a life. You have 1 trials left.
Should be "1 trial left."
You lost. The secret word is: ...
You won. The secret word is: ...
Should be "The secret word was: ..." | {
"domain": "codereview.stackexchange",
"id": 42917,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, beginner, object-oriented, hangman",
"url": null
} |
python, python-3.x, google-bigquery
Title: How to fine tune the complex python function for creating merge command to run in bigquery | {
"domain": "codereview.stackexchange",
"id": 42918,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, python-3.x, google-bigquery",
"url": null
} |
python, python-3.x, google-bigquery
Question: I created a python code to run the merge command in Google BigQuery, which is used to do UPDATE, INSERT, and DELETE in a single statement. I'd appreciate it if someone could assist me in fine-tuning this code since i believe there are lot of redundant code which can be improved to a greater extent. I have tried my best but cannot make it any more better so need someone's help.
def merge_cmd(database, table, dc, keys, columns, filter_column, new_main_column_type_list):
try:
if dc != '-1':
merge_query = "MERGE INTO " + database + "." + table + "_" + dc + " TARGET USING " + database + "_stg." + table + "_" + dc + "_stg SOURCE "
else:
merge_query = "MERGE INTO " + database + "." + table + " TARGET USING " + database + "_stg." + table + "_stg SOURCE "
if dc != '-1':
keys = keys + ',dc'
key_list = keys.split(',')
col_no_key = columns.split(',')
for i in range(len(key_list)):
key_list[i] = key_list[i].lower()
for i in range(len(col_no_key)):
col_no_key[i] = col_no_key[i].lower()
for key in key_list:
col_no_key.remove(key)
cols_list = columns.split(',')
key_list_type = get_key_list_type(key_list, new_main_column_type_list)
col_no_key_list_type = get_key_list_type(col_no_key, new_main_column_type_list)
cols_list_type = get_key_list_type(cols_list, new_main_column_type_list)
ON = " ON "
b = 1
for key_type in key_list_type:
key = key_type.split(':')[0]
type_ = key_type.split(':')[1]
ON = ON + " TARGET." + key + " = CAST(SOURCE." + key + " as " + type_ + ")"
if b < len(key_list):
ON = ON + " AND "
b = b + 1 | {
"domain": "codereview.stackexchange",
"id": 42918,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, python-3.x, google-bigquery",
"url": null
} |
python, python-3.x, google-bigquery
ON = ON + " AND "
b = b + 1
UPDATE = " WHEN MATCHED THEN UPDATE SET "
c = 1
for col_list_type in col_no_key_list_type:
col = col_list_type.split(':')[0]
type_ = col_list_type.split(':')[1]
if col == 'dt':
UPDATE = UPDATE + " TARGET." + col + " = " + " CAST(SOURCE.calendar_date as date)"
else:
UPDATE = UPDATE + " TARGET." + col + " = " + "CAST(SOURCE." + col + " as " + type_ + ")"
if c < len(col_no_key):
UPDATE = UPDATE + ","
c = c + 1
INSERT = " WHEN NOT MATCHED BY TARGET THEN INSERT (" + columns + ") VALUES ("
d = 1
for col_list_type in cols_list_type:
col = col_list_type.split(':')[0]
type_ = col_list_type.split(':')[1]
if col == 'dt':
INSERT = INSERT + " CAST(SOURCE.calendar_date as date)"
else:
INSERT = INSERT + " CAST(SOURCE." + col + " as " + type_ + ")"
if d < len(cols_list):
INSERT = INSERT + ","
d = d + 1
INSERT = INSERT + ")"
merge_query = merge_query + ON + UPDATE + INSERT
merge_query = "'" + merge_query + "'"
merge_cmd = "bq --location=us query --use_legacy_sql=false " + merge_query
print(merge_cmd)
return_cd, out, err = run_sys_command(merge_cmd)
if return_cd != 0:
for i in range(20):
time.sleep(30)
return_cd, out, err = run_sys_command(merge_cmd)
if return_cd == 0:
break
if return_cd != 0:
raise Exception('Merge Failed') | {
"domain": "codereview.stackexchange",
"id": 42918,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, python-3.x, google-bigquery",
"url": null
} |
python, python-3.x, google-bigquery
if __name__ == "__main__":
merge_cmd('testdb', 'test', 8134, 'load_id | test_load_id', 'invoice_id,dt', 'last_change_ts', 'invoice_id:INT64')
Answer: Syntax errors:
You have a try with nothing else.
merge_query is trying to concatenate a int into a str.
for key in key_list: col_no_key.remove(key) is trying to remove items from a different list
get_key_list_type is not defined (neither is run_sys_command, but that's not really part of your question). I put in some stubs to get this to run.
This is wide open to an SQL injection (eg https://xkcd.com/327/). If anyone other than you is putting anything into your database at any point, be very careful. If anyone other than you is calling this function, start over from scratch.
Other items: | {
"domain": "codereview.stackexchange",
"id": 42918,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, python-3.x, google-bigquery",
"url": null
} |
python, python-3.x, google-bigquery
I got rid of the bare try.
f-strings are really nice when you are combining lots of literal strings with variables.
You have if dc!=-1:...else:...if dc!=-1:.... Just combine the ifs.
for i in range(len(key_list)) is always a red flag. You generally want to say for item in listofitems. You can't in this case, because you need the index to reassign to. This means that you would need the enumerate function. But you can avoid all of that by using map or a list comprehension.
split takes a second argument that tells how many splits to do. This means you can combine your splits into one line.
Try to use variable += instead of variable = variable +. It shortens things up, and makes it clear that you're appending.
The only point of b, c, and d is to count where you are in the loop. I would recommend reusing them instead of declaring a new one. I would recommend enumerate. I would recommend a list comprehension with join.
Your function is a bit long. We should break it up into smaller pieces. The merge_query, ON, UPDATE, and INSERT make it clear what those smaller pieces should be. (This is a bit easier after the previous point.)
I'm ok with abreviating command as cmd. I'm not ok with abreviateing code as cd. Spell out return_code.
If you exit the last for loop without breaking, it's because return_code is not zero. Let's not test something we already know to be true, and just raise the exception. We should also use err to pass along useful information.
You shouldn't print(merge_cmd). If you end up calling this function a large number of times, that will flood your console. Use the Python debugger if you're not sure about the content of the variable.
The Python recommendations are that ALL_CAPS should be constant variables. But SQL doesn't really go by this, so it makes some sense for your code to not go by that as well.
import time | {
"domain": "codereview.stackexchange",
"id": 42918,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, python-3.x, google-bigquery",
"url": null
} |
python, python-3.x, google-bigquery
import time
def on_piece(key_type:str) -> str:
#key,type_ = key_type.split(':') # if you know there's only one :
key,type_ = key_type.split(':',1)
#key,type_,_ = key_type.split(':',2) # if more than that could happen
return f" TARGET.{key} = CAST(SOURCE.{key} as {type_})"
def update_piece(col_list_type:str) -> str:
col,type_ = col_list_type.split(':',1)
if col == 'dt':
return f" TARGET.{col} = CAST(SOURCE.calendar_date as date)"
else:
return f" TARGET.{col} = CAST(SOURCE.{col} as {type_})"
def insert_piece(col_list_type:str) -> str:
col,type_ = col_list_type.split(':',1)
if col == 'dt':
return " CAST(SOURCE.calendar_date as date)"
else:
return f" CAST(SOURCE.{col} as {type_})"
def merge_cmd(database:str, table:str, dc:int, keys:str, columns:str, filter_column:str, new_main_column_type_list:str) -> None:
if dc != '-1':
merge_query = f"MERGE INTO {database}.{table}_{dc} TARGET USING {database}_stg.{table}_{dc}_stg SOURCE "
keys += ',dc'
else:
merge_query = f"MERGE INTO {database}.{table} TARGET USING {database}_stg.{table}_stg SOURCE "
key_list = [ key.lower() for key in keys.split(',') ]
col_no_key = [ col.lower() for col in columns.split(',') ]
#for key in key_list: # ValueError: list.remove(x): x not in list
# col_no_key.remove(key)
cols_list = columns.split(',')
key_list_type = get_key_list_type(key_list, new_main_column_type_list)
col_no_key_list_type = get_key_list_type(col_no_key, new_main_column_type_list)
cols_list_type = get_key_list_type(cols_list, new_main_column_type_list)
ON = " ON " + " AND ".join( on_piece(key_type) for key_type in key_list_type )
UPDATE = " WHEN MATCHED THEN UPDATE SET "
UPDATE += ",".join( update_piece(col_list_type)
for col_list_type in col_no_key_list_type ) | {
"domain": "codereview.stackexchange",
"id": 42918,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, python-3.x, google-bigquery",
"url": null
} |
python, python-3.x, google-bigquery
INSERT = " WHEN NOT MATCHED BY TARGET THEN INSERT (" + columns + ") VALUES ("
INSERT += ",".join( insert_piece(col_list_type)
for col_list_type in cols_list_type )
INSERT += ")"
merge_query += ON + UPDATE + INSERT
merge_query = "'" + merge_query + "'"
merge_cmd = "bq --location=us query --use_legacy_sql=false " + merge_query
return_code, out, err = run_sys_command(merge_cmd)
if return_code != 0:
for i in range(20):
time.sleep(30)
return_code, out, err = run_sys_command(merge_cmd)
if return_code == 0:
break
raise Exception('Merge Failed: '+err) # if err is a string
#raise Exception('Merge Failed') from err # if err is an Exception
def run_sys_command(merge_cmd):
return 0,'out','err'
def get_key_list_type(some_list, new_main_column_type_list):
return [ 'STUB:STUB' for _ in some_list ]
if __name__ == "__main__":
merge_cmd('testdb', 'test', 8134, 'load_id | test_load_id', 'invoice_id,dt', 'last_change_ts', 'invoice_id:INT64') | {
"domain": "codereview.stackexchange",
"id": 42918,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, python-3.x, google-bigquery",
"url": null
} |
python, python-2.x, geospatial
Title: Loop through polyline vertices and update coordinate
Question: I have a Python 2.7 script that loops through GIS polylines and updates a coordinate.
The coordinate is called an "M" coordinate (aka a "Measure-value"). M coordinates are similar to X and Y coordinates, but are used for specialized linear referencing purposes.
import arcpy
connection = "Database Connections\my_conn.sde"
fc = connection + "\my_owner.my_fc"
spatialRef = arcpy.Describe(fc).spatialReference
with arcpy.da.Editor(connection) as editSession:
with arcpy.da.UpdateCursor(fc, ["ASSET_ID", "SHAPE@"]) as cursor:
for row in cursor:
feature = row[1].densify ("ANGLE", 10000, 0.174533)
partNum = 0
partArray = arcpy.Array()
for part in feature:
pointArray = arcpy.Array()
n = len(part)
for i in range(n):
point = part.getObject(i)
point.M = feature.measureOnLine(point)
pointArray.append(point)
partArray.append(pointArray)
partNum += 1
row[1] = arcpy.Polyline(partArray, spatialRef)
cursor.updateRow(row)
How can the script be improved?
Answer: Unfortunately, I have neither Python 2.7 nor some test data.
However, I would like to point out a few things:
row[1].densify("ANGLE", 10000, 0.174533) returns a geometry (object), you may want to rename the variable to geometry
partNum is not really used, you may want to get rid of it altogether
There is no need to use range(n) since part is an array (arcpy.Array) and iterable
Personally, I would call partArray just parts and pointArray just points (and use snake_case for variable names following the PEP8 style guide)
Below an example of the script with the suggested improvements. Note: Script is not tested but should work.
import arcpy
connection = "Database Connections\my_conn.sde"
feature_class = connection + "\my_owner.my_fc" | {
"domain": "codereview.stackexchange",
"id": 42919,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, python-2.x, geospatial",
"url": null
} |
python, python-2.x, geospatial
connection = "Database Connections\my_conn.sde"
feature_class = connection + "\my_owner.my_fc"
spatial_reference = arcpy.Describe(feature_class).spatialReference
with arcpy.da.Editor(connection) as edit_session:
with arcpy.da.UpdateCursor(feature_class, ["ASSET_ID", "SHAPE@"]) as cursor:
for row in cursor:
geometry = row[1].densify("ANGLE", 10000, 0.174533)
parts = arcpy.Array()
for part in geometry:
points = arcpy.Array()
for point in part:
point.M = geometry.measureOnLine(point)
points.append(point)
parts.append(points)
row[1] = arcpy.Polyline(parts, spatial_reference)
cursor.updateRow(row) | {
"domain": "codereview.stackexchange",
"id": 42919,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, python-2.x, geospatial",
"url": null
} |
javascript, css, comparative-review, vue.js
Title: Show progress bar for different states
Question: I have this working code which shows the progress bar based on different states ("not-started", "progressing" and "done"). Each state will have its own class.
I notice it is not Don't Repeat Yourself (DRY) enough but not sure how I can refactor it. Appreciate your code review. | {
"domain": "codereview.stackexchange",
"id": 42920,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "javascript, css, comparative-review, vue.js",
"url": null
} |
javascript, css, comparative-review, vue.js
new Vue({
el: "#page",
data: {
currentStepNumber:10,
totalEformStepNumber: 9,
totalVerificationStepNumber: 2,
totalReviewStepNumber: 1,
eFormProgress: "not-started",
verificationProgress: "not-started",
reviewProgress: "not-started",
verificationDone: false,
encourageText: "Let's Start"
},
computed: {
checkEFormProgress() {
if (this.eFormProgress === "not-started") {
return "step-indicator-not-started";
} else if (this.eFormProgress === "progressing") {
return "step-indicator-progressing";
} else if (this.eFormProgress === "done") {
return "step-indicator-done";
}
},
checkVerificationProgress() {
if (this.verificationProgress === "not-started") {
return "step-indicator-not-started";
} else if (this.verificationProgress === "progressing") {
return "step-indicator-progressing";
} else if (this.verificationProgress === "done") {
return "step-indicator-done";
}
},
checkReviewProgress() {
if (this.reviewProgress === "not-started") {
return "step-indicator-not-started";
} else if (this.reviewProgress === "progressing") {
return "step-indicator-progressing";
} else if (this.reviewProgress === "done") {
return "step-indicator-done";
}
},
totalStepNumber() {
return (
this.totalEformStepNumber +
this.totalVerificationStepNumber +
this.totalReviewStepNumber
);
},
eformCurrentStepNumber() {
if (this.currentStepNumber === 0) {
this.eFormProgress = "not-started";
} else if (this.currentStepNumber < this.totalEformStepNumber) {
this.eFormProgress = "progressing";
} else if (this.currentStepNumber >= this.totalEformStepNumber) {
this.eFormProgress = "done";
}
return (this.currentStepNumber / this.totalEformStepNumber) * 100;
},
verifcationCurrentStepNumber() { | {
"domain": "codereview.stackexchange",
"id": 42920,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "javascript, css, comparative-review, vue.js",
"url": null
} |
javascript, css, comparative-review, vue.js
},
verifcationCurrentStepNumber() {
debugger;
if (this.currentStepNumber >= this.totalEformStepNumber) {
if (this.currentStepNumber < this.totalEformStepNumber) {
this.verificationProgress = "not-started";
} else if (this.currentStepNumber > this.totalEformStepNumber && this.currentStepNumber < this.totalStepNumber) {
this.verificationProgress = "progressing";
} else if (this.currentStepNumber === this.totalStepNumber) {
this.verificationProgress = "done";
this.reviewProgress = "done";
}
return (
((this.currentStepNumber - this.totalEformStepNumber) /
this.totalVerificationStepNumber) *
100
);
} else {
return 0;
}
},
eformProgressWidth() {
return this.eformCurrentStepNumber > 100
? { width: "100%" }
: { width: this.eformCurrentStepNumber + "%" };
},
verificationProgressWidth() {
return this.verifcationCurrentStepNumber >= 100
? { width: "100%" }
: { width: this.verifcationCurrentStepNumber + "%" };
}
},
methods: {},
created() {}
});
@import url("https://fonts.googleapis.com/css2?family=Roboto&display=swap");
p {
margin: 0;
}
#page {
font-family: Roboto;
width: 100%;
background: #f8f9fa;
display: flex;
flex-direction: column;
align-items: center;
}
.container {
width: 70%;
text-align: center;
}
.progress-bar {
display: flex;
flex-direction: row;
align-items: flex-start;
width: 100%;
}
.point {
width: 38px;
display: flex;
flex-direction: column;
align-items: center;
gap: 8px;
color: #28a745;
}
.step-indicator-not-started {
width: 15px;
height: 15px;
border-radius: 100px;
background: #ecedee;
box-sizing: border-box;
border: none;
}
.step-indicator-progressing {
width: 15px;
height: 15px; | {
"domain": "codereview.stackexchange",
"id": 42920,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "javascript, css, comparative-review, vue.js",
"url": null
} |
javascript, css, comparative-review, vue.js
border: none;
}
.step-indicator-progressing {
width: 15px;
height: 15px;
border-radius: 100px;
background: #ecedee;
box-sizing: border-box;
border: 4px solid #28a745;
}
.step-indicator-done {
width: 15px;
height: 15px;
border-radius: 100px;
background: #28a745;
box-sizing: border-box;
border: 4px solid #28a745;
}
.bar {
width: 100%;
height: 16px;
display: grid;
align-items: center;
}
.bar-eform {
width: 80%;
}
.bar-verification {
width: 20%;
}
.bar-bg {
height: 4px;
background-color: #ecedee;
position: relative;
}
.bar-arrow {
position: absolute;
top: 0;
left: 0;
height: 4px;
background-color: #28a745;
}
.page-indicator {
color: #28a745;
font-size: 14px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
<div id="page">
<div class="container">
<h3>{{encourageText}}</h3>
<div class="progress-bar">
<div class="point">
<div :class="checkEFormProgress">
</div>
<p><strong>EForm</strong></p>
</div>
<div class="bar bar-eform">
<div class="bar-bg">
<div class="bar-arrow" v-bind:style="eformProgressWidth"></div>
</div>
</div>
<div class="point">
<div :class="checkVerificationProgress">
</div>
<p><strong>Verification</strong></p>
</div>
<div class="bar bar-verification">
<div class="bar-bg">
<div class="bar-arrow" v-bind:style="verificationProgressWidth"></div>
</div>
</div>
<div class="point">
<div :class="checkReviewProgress">
</div>
<p><strong>Review</strong></p>
</div>
</div>
</div>
<div class="page-indicator"> | {
"domain": "codereview.stackexchange",
"id": 42920,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "javascript, css, comparative-review, vue.js",
"url": null
} |
javascript, css, comparative-review, vue.js
</div>
</div>
</div>
<div class="page-indicator">
<strong>{{currentStepNumber}}/{{totalStepNumber}}</strong>
</div>
</div> | {
"domain": "codereview.stackexchange",
"id": 42920,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "javascript, css, comparative-review, vue.js",
"url": null
} |
javascript, css, comparative-review, vue.js
Version 2, I have done some refactoring as below.
const stateProgress = {
NOTSTARTED: "not-started",
PROGRESSING: "progressing",
DONE: "done"
};
const stateProgressClassName = {
NOTSTARTED: "step-indicator-not-started",
PROGRESSING: "step-indicator-progressing",
DONE: "step-indicator-done"
}; | {
"domain": "codereview.stackexchange",
"id": 42920,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "javascript, css, comparative-review, vue.js",
"url": null
} |
javascript, css, comparative-review, vue.js
new Vue({
el: "#page",
data: {
currentStepNumber: 2,
totalEformStepNumber: 9,
totalVerificationStepNumber: 2,
totalReviewStepNumber: 1,
eFormProgress: stateProgress.NOTSTARTED,
verificationProgress: stateProgress.NOTSTARTED,
reviewProgress: stateProgress.NOTSTARTED,
encourageText: "Let's Start"
},
computed: {
checkEFormProgress() {
return this.getProgressClassName(this.eFormProgress);
},
checkVerificationProgress() {
return this.getProgressClassName(this.verificationProgress);
},
checkReviewProgress() {
return this.getProgressClassName(this.reviewProgress);
},
totalStepNumber() {
return (
this.totalEformStepNumber +
this.totalVerificationStepNumber +
this.totalReviewStepNumber
);
},
eformCurrentStepNumber() {
if (this.currentStepNumber <= 0) {
this.eFormProgress = stateProgress.NOTSTARTED;
} else if (this.currentStepNumber < this.totalEformStepNumber) {
this.eFormProgress = stateProgress.PROGRESSING;
} else if (this.currentStepNumber >= this.totalEformStepNumber) {
this.eFormProgress = stateProgress.DONE;
}
return (this.currentStepNumber / this.totalEformStepNumber) * 100;
},
verifcationCurrentStepNumber() {
debugger;
if (this.currentStepNumber >= this.totalEformStepNumber) {
if (this.currentStepNumber < this.totalEformStepNumber) {
this.verificationProgress = stateProgress.NOTSTARTED;
} else if (
this.currentStepNumber > this.totalEformStepNumber &&
this.currentStepNumber < this.totalStepNumber
) {
this.verificationProgress = stateProgress.PROGRESSING;
} else if (this.currentStepNumber === this.totalStepNumber) {
this.verificationProgress = stateProgress.DONE;
this.reviewProgress = stateProgress.PROGRESSING;
}
return ( | {
"domain": "codereview.stackexchange",
"id": 42920,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "javascript, css, comparative-review, vue.js",
"url": null
} |
javascript, css, comparative-review, vue.js
this.reviewProgress = stateProgress.PROGRESSING;
}
return (
((this.currentStepNumber - this.totalEformStepNumber) /
this.totalVerificationStepNumber) *
100
);
} else {
return 0;
}
},
eformProgressWidth() {
return this.eformCurrentStepNumber > 100
? { width: "100%" }
: { width: this.eformCurrentStepNumber + "%" };
},
verificationProgressWidth() {
return this.verifcationCurrentStepNumber >= 100
? { width: "100%" }
: { width: this.verifcationCurrentStepNumber + "%" };
}
},
methods: {
getProgressClassName : function(progressState) {
if (progressState === stateProgress.NOTSTARTED) {
return stateProgressClassName.NOTSTARTED;
} else if (progressState === stateProgress.PROGRESSING) {
return stateProgressClassName.PROGRESSING;
} else if (progressState === stateProgress.DONE) {
return stateProgressClassName.DONE;
}
}
},
created() {}
});
@import url("https://fonts.googleapis.com/css2?family=Roboto&display=swap");
p {
margin: 0;
}
#page {
font-family: Roboto;
width: 100%;
background: #f8f9fa;
display: flex;
flex-direction: column;
align-items: center;
}
.container {
width: 70%;
text-align: center;
}
.progress-bar {
display: flex;
flex-direction: row;
align-items: flex-start;
width: 100%;
}
.point {
width: 38px;
display: flex;
flex-direction: column;
align-items: center;
gap: 8px;
color: #28a745;
}
.step-indicator-not-started {
width: 15px;
height: 15px;
border-radius: 100px;
background: #ecedee;
box-sizing: border-box;
border: none;
}
.step-indicator-progressing {
width: 15px;
height: 15px;
border-radius: 100px;
background: #ecedee;
box-sizing: border-box;
border: 4px solid #28a745;
} | {
"domain": "codereview.stackexchange",
"id": 42920,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "javascript, css, comparative-review, vue.js",
"url": null
} |
javascript, css, comparative-review, vue.js
background: #ecedee;
box-sizing: border-box;
border: 4px solid #28a745;
}
.step-indicator-done {
width: 15px;
height: 15px;
border-radius: 100px;
background: #28a745;
box-sizing: border-box;
border: 4px solid #28a745;
}
.bar {
width: 100%;
height: 16px;
display: grid;
align-items: center;
}
.bar-eform {
width: 80%;
}
.bar-verification {
width: 20%;
}
.bar-bg {
height: 4px;
background-color: #ecedee;
position: relative;
}
.bar-arrow {
position: absolute;
top: 0;
left: 0;
height: 4px;
background-color: #28a745;
}
.page-indicator {
color: #28a745;
font-size: 14px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="page">
<div class="container">
<h3>{{encourageText}}</h3>
<div class="progress-bar">
<div class="point">
<div :class="checkEFormProgress">
</div>
<p><strong>Account</strong></p>
</div>
<div class="bar bar-eform">
<div class="bar-bg">
<div class="bar-arrow" v-bind:style="eformProgressWidth"></div>
</div>
</div>
<div class="point">
<div :class="checkVerificationProgress">
</div>
<p><strong>Verification</strong></p>
</div>
<div class="bar bar-verification">
<div class="bar-bg">
<div class="bar-arrow" v-bind:style="verificationProgressWidth"></div>
</div>
</div>
<div class="point">
<div :class="checkReviewProgress">
</div>
<p><strong>Review</strong></p>
</div>
</div>
</div>
<div class="page-indicator">
<strong>{{currentStepNumber}}/{{totalStepNumber}}</strong>
</div>
</div> | {
"domain": "codereview.stackexchange",
"id": 42920,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "javascript, css, comparative-review, vue.js",
"url": null
} |
javascript, css, comparative-review, vue.js
Answer: It appears that the second version pulls the states out into an enum-like object. This does make it simpler to work with in the methods for the computed properties. Bear in mind that while stateProgress and stateProgressClassName are declared with const so they cannot be re-assigned, it is possible to assign properties on them. If that should be prevented then use Object.freeze().
The method getProgressClassName() could just verify that the value in progressState exists in stateProgress (using Object.values()) and if so, return "step-indicator-" + stateProgress. However, it appears that those calls names are redundant also. Let's look at the styles for those classes:
.step-indicator-not-started {
width: 15px;
height: 15px;
border-radius: 100px;
background: #ecedee;
box-sizing: border-box;
border: none;
}
.step-indicator-progressing {
width: 15px;
height: 15px;
border-radius: 100px;
background: #ecedee;
box-sizing: border-box;
border: 4px solid #28a745;
}
.step-indicator-done {
width: 15px;
height: 15px;
border-radius: 100px;
background: #28a745;
box-sizing: border-box;
border: 4px solid #28a745;
}
All three of those have four styles in common: width, height, border-radius and box-sizing.
One could abstract those styles into a separate ruleset for a new class .step-indicator that has those common styles:
.step-indicator {
width: 15px;
height: 15px;
border-radius: 100px;
box-sizing: border-box;
}
.not-started {
background: #ecedee;
border: none;
}
.progressing {
background: #ecedee;
border: 4px solid #28a745;
}
.done {
background: #28a745;
border: 4px solid #28a745;
}
In order to use those, the step-indicator class can be separated from the three classes, which allows those associated computed properties to be eliminated, along with stateProgressClassName and the method getProgressClassName.
For instance: | {
"domain": "codereview.stackexchange",
"id": 42920,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "javascript, css, comparative-review, vue.js",
"url": null
} |
javascript, css, comparative-review, vue.js
<div :class="checkEFormProgress">
Can be updated to the following array syntax:
<div :class="[eFormProgress, 'step-indicator']">
Also there is some redundancy in those last two computed properties:
eformProgressWidth() {
return this.eformCurrentStepNumber > 100
? { width: "100%" }
: { width: this.eformCurrentStepNumber + "%" };
},
verificationProgressWidth() {
return this.verifcationCurrentStepNumber >= 100
? { width: "100%" }
: { width: this.verifcationCurrentStepNumber + "%" };
}
The ternary operators could be moved inside the object:
eformProgressWidth() {
return {
width: this.eformCurrentStepNumber > 100
? "100%"
: this.eformCurrentStepNumber + "%"
};
},
verificationProgressWidth() {
return {
width: this.verifcationCurrentStepNumber >= 100
? "100%"
: this.verifcationCurrentStepNumber + "%"
};
}
The Math.min() function can help simplify these methods to a single line each:
eformProgressWidth() {
return { width: Math.min(this.eformCurrentStepNumber, 100) + "%" };
},
verificationProgressWidth() {
return { width: Math.min(this.verifcationCurrentStepNumber, 100) + "%" };
}
These suggestions can lead to greatly reduced code.
const stateProgress = {
NOTSTARTED: "not-started",
PROGRESSING: "progressing",
DONE: "done"
}; | {
"domain": "codereview.stackexchange",
"id": 42920,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "javascript, css, comparative-review, vue.js",
"url": null
} |
javascript, css, comparative-review, vue.js
new Vue({
el: "#page",
data: {
currentStepNumber: 2,
totalEformStepNumber: 9,
totalVerificationStepNumber: 2,
totalReviewStepNumber: 1,
eFormProgress: stateProgress.NOTSTARTED,
verificationProgress: stateProgress.NOTSTARTED,
reviewProgress: stateProgress.NOTSTARTED,
encourageText: "Let's Start"
},
computed: {
totalStepNumber() {
return (
this.totalEformStepNumber +
this.totalVerificationStepNumber +
this.totalReviewStepNumber
);
},
eformCurrentStepNumber() {
if (this.currentStepNumber <= 0) {
this.eFormProgress = stateProgress.NOTSTARTED;
} else if (this.currentStepNumber < this.totalEformStepNumber) {
this.eFormProgress = stateProgress.PROGRESSING;
} else if (this.currentStepNumber >= this.totalEformStepNumber) {
this.eFormProgress = stateProgress.DONE;
}
return (this.currentStepNumber / this.totalEformStepNumber) * 100;
},
verifcationCurrentStepNumber() {
//debugger;
if (this.currentStepNumber >= this.totalEformStepNumber) {
if (this.currentStepNumber < this.totalEformStepNumber) {
this.verificationProgress = stateProgress.NOTSTARTED;
} else if (
this.currentStepNumber > this.totalEformStepNumber &&
this.currentStepNumber < this.totalStepNumber
) {
this.verificationProgress = stateProgress.PROGRESSING;
} else if (this.currentStepNumber === this.totalStepNumber) {
this.verificationProgress = stateProgress.DONE;
this.reviewProgress = stateProgress.PROGRESSING;
}
return (
((this.currentStepNumber - this.totalEformStepNumber) /
this.totalVerificationStepNumber) *
100
);
}
return 0;
},
eformProgressWidth() {
return { width: Math.min(this.eformCurrentStepNumber, 100) + "%" };
},
verificationProgressWidth() { | {
"domain": "codereview.stackexchange",
"id": 42920,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "javascript, css, comparative-review, vue.js",
"url": null
} |
javascript, css, comparative-review, vue.js
},
verificationProgressWidth() {
return { width: Math.min(this.verifcationCurrentStepNumber, 100) + "%" };
}
},
created() {}
});
@import url("https://fonts.googleapis.com/css2?family=Roboto&display=swap");
p {
margin: 0;
}
#page {
font-family: Roboto;
width: 100%;
background: #f8f9fa;
display: flex;
flex-direction: column;
align-items: center;
}
.container {
width: 70%;
text-align: center;
}
.progress-bar {
display: flex;
flex-direction: row;
align-items: flex-start;
width: 100%;
}
.point {
width: 38px;
display: flex;
flex-direction: column;
align-items: center;
gap: 8px;
color: #28a745;
}
.step-indicator {
width: 15px;
height: 15px;
border-radius: 100px;
box-sizing: border-box;
}
.not-started {
background: #ecedee;
border: none;
}
.progressing {
background: #ecedee;
border: 4px solid #28a745;
}
.done {
background: #28a745;
border: 4px solid #28a745;
}
.bar {
width: 100%;
height: 16px;
display: grid;
align-items: center;
}
.bar-eform {
width: 80%;
}
.bar-verification {
width: 20%;
}
.bar-bg {
height: 4px;
background-color: #ecedee;
position: relative;
}
.bar-arrow {
position: absolute;
top: 0;
left: 0;
height: 4px;
background-color: #28a745;
}
.page-indicator {
color: #28a745;
font-size: 14px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="page">
<div class="container">
<h3>{{encourageText}}</h3>
<div class="progress-bar">
<div class="point">
<div :class="[eFormProgress, 'step-indicator']">
</div>
<p><strong>Account</strong></p>
</div>
<div class="bar bar-eform">
<div class="bar-bg"> | {
"domain": "codereview.stackexchange",
"id": 42920,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "javascript, css, comparative-review, vue.js",
"url": null
} |
javascript, css, comparative-review, vue.js
</div>
<div class="bar bar-eform">
<div class="bar-bg">
<div class="bar-arrow" v-bind:style="eformProgressWidth"></div>
</div>
</div>
<div class="point">
<div :class="[verificationProgress, 'step-indicator']">
</div>
<p><strong>Verification</strong></p>
</div>
<div class="bar bar-verification">
<div class="bar-bg">
<div class="bar-arrow" v-bind:style="verificationProgressWidth"></div>
</div>
</div>
<div class="point">
<div :class="[reviewProgress, 'step-indicator']">
</div>
<p><strong>Review</strong></p>
</div>
</div>
</div>
<div class="page-indicator">
<strong>{{currentStepNumber}}/{{totalStepNumber}}</strong>
</div>
</div> | {
"domain": "codereview.stackexchange",
"id": 42920,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "javascript, css, comparative-review, vue.js",
"url": null
} |
javascript, react.js, jsx
Title: Theme handler with React
Question: I've just created a theme handler with React.js.
Could my Theme component be polished and improved a bit ?
function Theme() {
const [checkbox, setCheckbox] = React.useState(
JSON.parse(localStorage.getItem("configuration"))?.dark_theme ?? true
);
React.useEffect(() => (
!checkbox
? document.body.setAttribute('data-theme', 'light')
: document.body.removeAttribute('data-theme'),
setToLocalStorage({ dark_theme: checkbox }, "configuration") //memorization
), [checkbox])
return (
<div className="theme">
☀️
<label htmlFor="theme-checkbox">
<input
type="checkbox"
id="theme-checkbox"
defaultChecked={checkbox}
onChange={() => setCheckbox(!checkbox)}
/>
<span className="slidebar"></span>
</label>
</div>
)
}
Thanks for your help
Answer:
Names! Calling a variable that represents whether the theme is dark mode or not checkbox is pretty confusing. Why am I setting a local storage value to checkbox? It took me a moment to unwind that.
The comma operator inside the useEffect seems odd to me, but maybe that's how it's being done these days. I'd probably just braces around the function body and use regular JS statements.
The line setToLocalStorage({ dark_theme: checkbox }, "configuration") will work fine for now, but as soon as you introduce more configurations it will (mysteriously) wipe out all the other ones every time this checkbox is changed. | {
"domain": "codereview.stackexchange",
"id": 42921,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "javascript, react.js, jsx",
"url": null
} |
python, csv
Title: Take every second row in CSV file, and put it next to the previous row
Question: I have a csv file
1;(same.)
2;Type...
3; (who are you?)
4; I am a talker whom the world has not yet seen. And you?
5; (leave.)
6;Connect to the Internet - I'll leave...
7; (I would like to.)
8;He would like to! And you're a no-brainer guy!
The objective was to make it look like
row1 Question - '(same.)' - answer- 'Type...'
row2 Question - '(who are you?)' - answer- 'I am a talker whom the world has not yet seen. And you?
I am just learning, so it was hard for me.
The feedback is much appreciated, how it can be done easier.
final code
list1=[]
list2=[]
with open('answers.csv',mode='r', newline='') as f:
reader = csv.reader(f, delimiter=';')
for line in reader:
num = int(line[0])
if num % 2:
list1.append(line)
if not num % 2:
list2.append(line)
# print(list1)
# print(list2)
for i,m in zip(list1,list2):
print(f'Question {i[1]}, Answer {m[1]}')
Answer: Since you know it will be every other line and start with a Q, I would use Slicing with step parameter, that way you get every n'th item [::n].
Starting at 1 [1::] for the first list, starting at item 2 [2::] in the second list.
with open('answers.csv',mode='r', newline='') as f:
reader = csv.reader(f, delimiter=';')
for i, m in zip(reader[1::2], reader[2::2]):
print(f'Question {i[1]}, Answer {m[1]}')
Hope this helps :) | {
"domain": "codereview.stackexchange",
"id": 42922,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, csv",
"url": null
} |
java, android
Title: Simple calculator app made in Android Studio (Java)
Question: I'm a college student in my first year of my bachelor in IT. I recently decided to try some app development with Android Studio and Java. For my first project, I made a basic calculator app.
Here you can see how it looks:
The calculator app:
can take multiple digits and floating point numbers as input
has operator precendence
can add, substract, divide and mutiply
My main idea was to have an ArrayList in wich every number and every operator gets stored.
Then for the calculation, I searched the ArrayList for the operator and took the numbers that are to left and to the right of it, and replaced those with the answer of those.
Here is the code of my mainActivity.java:
package com.example.calculatormk2;
public class MainActivity extends AppCompatActivity {
private ArrayList input = new ArrayList();
private StringBuilder number = new StringBuilder();
private boolean calculationDone = false;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void onNumberClick(View v) {
number.append(getBtnTxt(v));
updateView(v);
}
public void onOperatorClick(View v) {
addNumberToInput(number);
addOperatorToInput(v);
updateView(v);
}
public void onEqualsClick(View v) {
addNumberToInput(number);
calculate(input);
clearInput();
}
public void calculate(ArrayList i) {
while (i.contains("x") || i.contains("÷")) {
int indexOperatorTimes = i.indexOf("x");
int indexOperatorDivideBy = i.indexOf("÷");
int indexOperatorMain; | {
"domain": "codereview.stackexchange",
"id": 42923,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "java, android",
"url": null
} |
java, android
if (indexOperatorTimes < indexOperatorDivideBy && indexOperatorTimes != -1) {
indexOperatorMain = indexOperatorTimes;
} else {
indexOperatorMain = indexOperatorDivideBy;
}
if (indexOperatorDivideBy == -1) {
indexOperatorMain = indexOperatorTimes;
}
double firstNumber;
double secondNumber;
String operator = i.get(indexOperatorMain).toString();
double answer;
if (i.get(indexOperatorMain - 1) instanceof Integer) {
firstNumber = (int) i.get(indexOperatorMain - 1);
} else {
firstNumber = (double) i.get(indexOperatorMain - 1);
}
if (i.get(indexOperatorMain + 1) instanceof Integer) {
secondNumber = (int) i.get(indexOperatorMain + 1);
} else {
secondNumber = (double) i.get(indexOperatorMain + 1);
}
if (operator.equals("x")) {
answer = firstNumber * secondNumber;
} else {
answer = firstNumber / secondNumber;
}
i.remove(indexOperatorMain - 1);
i.remove(indexOperatorMain - 1);
i.remove(indexOperatorMain - 1);
i.add(indexOperatorMain - 1, answer);
System.out.println(i);
}
while (i.contains("+") || i.contains("-")) {
int indexOperator1 = i.indexOf("+");
int indexOperator2 = i.indexOf("-");
int indexOperatorDef;
if (indexOperator1 < indexOperator2 && indexOperator1 != -1) {
indexOperatorDef = indexOperator1;
} else {
indexOperatorDef = indexOperator2;
}
if (indexOperator2 == -1) {
indexOperatorDef = indexOperator1;
} | {
"domain": "codereview.stackexchange",
"id": 42923,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "java, android",
"url": null
} |
java, android
double firstNumber;
double secondNumber;
String operator = i.get(indexOperatorDef).toString();
double answer;
if (i.get(indexOperatorDef - 1) instanceof Integer) {
firstNumber = (int) i.get(indexOperatorDef - 1);
} else {
firstNumber = (double) i.get(indexOperatorDef - 1);
}
if (i.get(indexOperatorDef + 1) instanceof Integer) {
secondNumber = (int) i.get(indexOperatorDef + 1);
} else {
secondNumber = (double) i.get(indexOperatorDef + 1);
}
if (operator.equals("+")) {
answer = firstNumber + secondNumber;
} else {
answer = firstNumber - secondNumber;
}
i.remove(indexOperatorDef - 1);
i.remove(indexOperatorDef - 1);
i.remove(indexOperatorDef - 1);
i.add(indexOperatorDef - 1, answer);
}
calculationDone = true;
TextView t = findViewById(R.id.mainOutput);
String s = i.get(0).toString();
t.setText(s);
}
public void addOperatorToInput(View v) {
input.add(getBtnTxt(v));
}
public void addNumberToInput(StringBuilder s) {
if (s.toString().contains(".")) {
input.add(Double.parseDouble(s.toString()));
} else {
input.add(Integer.parseInt(s.toString()));
}
clearNumber();
}
public String getBtnTxt(View v) {
return ((Button) v).getText().toString();
}
public void clearNumber() {
number.delete(0, number.length());
}
public void clearInput() {
input.clear();
} | {
"domain": "codereview.stackexchange",
"id": 42923,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "java, android",
"url": null
} |
java, android
public void clearInput() {
input.clear();
}
@SuppressLint("SetTextI18n")
public void updateView(View v) {
TextView mainOutput = findViewById(R.id.mainOutput);
if (calculationDone) {
mainOutput.setText("");
calculationDone = false;
}
mainOutput.setText(mainOutput.getText() + getBtnTxt(v));
}
}
In total it took me about 10 hours to make this and I'm pretty happy with it (because I didn't expect to get it to even work) even though there is a lot of double code. There is also a lot of code which only exists to cast the numbers to the right datatype. I realised late when working on the app that the get() function of an ArrayList returns the item as an object and it gave a lot of trouble retrieving something out of it. Looking back, I probably should have done this differently but I went into this project without a proper plan and just winged it.
I really would appreciate some feedback. You can be honest about it, even if it's garbage.
If, by any chance, anyone wants to take a look at the full project. Here is the GitHub page:
https://github.com/PhilipNousPXL/Calculator-mk2.git
Answer: nice to see some android code here - thanks for sharing
violation of Single Responsibility Principle (SRP)
you MainActivity is responsible to build up the GUI and is also responsible for being a calculator! That is too much responsibility for your Activity.
Solution
create a Class Calculator and that is responsible for taking the input and returning a result.
violation of Integration Operation Segregation Principle (IOSP)
this is the reason why your calculate method is so messy (sorry, no offense, really!)
IOSP calls for a clear separation:
Either a method contains exclusively logic, meaning transformations, control structures or API invocations. Then it’s called an Operation.
Or a method does not contain any logic but exclusively calls other methods within its code basis. Then it’s called Integration. | {
"domain": "codereview.stackexchange",
"id": 42923,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "java, android",
"url": null
} |
java, android
Solution
create a integration method that handles the logical program flow, create several operation methods that do the bit shuffling!
example for an integration method (this is just a method stub):
public void calculate(ArrayList i) {
handleMultiplier(i);
handleAdditions(i);
}
example for an operation method (this is just an example, not real code!!!):
public double getLeftOperand(...){
if (i.get(indexOperatorDef - 1) instanceof Integer) {
return (int) i.get(indexOperatorDef - 1);
} else {
return (double) i.get(indexOperatorDef - 1);
}
}
uncecessarily complex code
it is overkill to parse the arguments to either double or int Keep It Simple Stupid... keep all your input in String and just parse ONLY to double (see getLeftOperand() up above)!
pseudo concurrency
You make your Button unclickable while the calculator is doing some cpu-intensive Task. Either make a real Async-Task (see Handler.post(Runnable)) and make some real separation from your your GUI-Thread.
Or just leave it be and skip the enabling/disabling (that's fine for me)
Open Question
what happens, if you push + twice? that case is not handled properly, you cannot even remove your accidently pushed input. (yes - that also counts for the other arithmetic operations)
Naming
well, thats just me being picky, but one-letter-variables (i, v, etc) are no more used today since very IDE provides code completion!
Android Activity Life Cycle
have a look at the Android Activity Life Cycle and take a thought on what happens to the input, if your Activity is unplanned closed? Your Input will be wiped. But you have left open the requirements for that, so feel free to just look a bit deeper into android and take that point for further projects :-) | {
"domain": "codereview.stackexchange",
"id": 42923,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "java, android",
"url": null
} |
javascript, php, jquery, html, ajax
Title: Upgrade security and code quality of a website contact form
Question: I have a simple website contact form created back in 2017.
The form was developed using PHP, PHPMailer, jQuery, HTML and CSS.
I would like to make sure the code is up to modern standards and secure.
I would also like to switch from PHP to AJAX for success and error messaging (in order to avoid a page refresh). But that matter is probably out of scope here so I'll leave it out of the question.
Here's a detailed breakdown:
(1) The form sends messages from site users to site managers.
(2) It uses HTML for structure and CSS for presentation.
(3) User input is sent via SMTP using PHPMailer.
(4) A textarea box, with a character counter, is provided for users to submit their message.
(5) If the character count is exceeded, a jQuery script prevents the form from being submitted.
(6) Google reCAPTCHA is installed to reduce spam.
(7) HTML and standard browser functions are used for user input validation on the client-side.
(8) PHP functions are used for user input validation and sanitization on the server-side.
(9) PHP handles success and error messaging to the user.
The form works fine, as far as I can tell.
I'm looking for some guidance here:
The SMTP/PHPMailer set-up requires a username and password embedded in the code. Is there a more secure way?
Any suggestions for improving the overall quality and efficiency of this code?
Thank you.
HTML, CSS & jQuery
// text area character counter
// displays total characters allowed
// displays warning at defined count (currently 150)
// disables submit button when < 0
// max characters that can be input set by maxlength attribute in HTML
(function($) {
$.fn.charCount = function(submit, options){
this.submit = submit; | {
"domain": "codereview.stackexchange",
"id": 42924,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "javascript, php, jquery, html, ajax",
"url": null
} |
javascript, php, jquery, html, ajax
$.fn.charCount = function(submit, options){
this.submit = submit;
// default configuration properties
var defaults = {
allowed: 1250,
warning: 150,
css: 'counter',
counterElement: 'span',
cssWarning: 'warning',
cssExceeded: 'exceeded',
counterText: ''
};
var options = $.extend(defaults, options);
function calculate(obj,submit){
submit.attr("disabled", "disabled");
var count = $(obj).val().length;
var available = options.allowed - count;
if(available <= options.warning && available >= 0){
$(obj).next().addClass(options.cssWarning);
} else {
$(obj).next().removeClass(options.cssWarning);
}
if(available < 0){
$(obj).next().addClass(options.cssExceeded);
} else {
$(obj).next().removeClass(options.cssExceeded);
submit.removeAttr("disabled");
}
$(obj).next().html(options.counterText + available);
};
this.each(function() {
$(this).after('<'+ options.counterElement +' class="' + options.css + '">'+ options.counterText +'</'+ options.counterElement +'>');
calculate(this, submit);
$(this).keyup(function(){calculate(this,submit)});
$(this).change(function(){calculate(this,submit)});
});
};
})(jQuery); | {
"domain": "codereview.stackexchange",
"id": 42924,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "javascript, php, jquery, html, ajax",
"url": null
} |
javascript, php, jquery, html, ajax
};
})(jQuery);
$(document).ready(function(){
$("#comments").charCount($("#submit"));
});
#contact-form {
display: flex;
flex-direction: column;
width: 50%;
font: 1rem/1.5 arial, helvetica, sans-serif;
margin: 0 auto 1em !important;
}
#contact-form > div {
display: flex;
flex-direction: column;
margin-bottom: 10px;
}
#contact-form > div:not(.send-fail-notice):not(#counter-container) {
width: 70%;
}
#contact-form > .ad2 { align-self: flex-start; }
/* label formatting */
#contact-form > div > label {
margin-bottom: 2px;
}
/* asterisk formatting */
#contact-form > div > label > span {
color: #f00;
font-size: 1.5em;
line-height: 1;
}
/* input field formatting */
#contact-form input,
#contact-form textarea {
border: 1px solid #ccc;
background: #fcfcfc;
padding: 2px 5px;
resize: none;
font-family: arial, helvetica, sans-serif;
}
#contact-form input:focus,
#contact-form textarea:focus {
border: 1px solid #777;
}
/* textarea and character counter */
#contact-form > #counter-container { }
#contact-form > #counter-container > .counter {
font-size: 1.5em;
color: #ccc;
}
#contact-form > #counter-container .warning {
color: orange;
}
#contact-form > #counter-container .warning::after {
content: " approaching limit";
font-size: 1em;
}
#contact-form > #counter-container .exceeded {
color: red;
}
#contact-form > #counter-container .exceeded::after {
content: " form won't submit";
font-size: 1em;
}
/* submit button formatting */
#contact-form > button {
align-self: flex-start;
padding: 5px 15px;
cursor: pointer;
border: 1px solid #ccc;
background-color: #f1f1f1;
background-image: linear-gradient(#f1f1f1, #fafafa);
}
#contact-form > button:hover {
background-image: linear-gradient(#e1e1e1, #eaeaea);
} | {
"domain": "codereview.stackexchange",
"id": 42924,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "javascript, php, jquery, html, ajax",
"url": null
} |
javascript, php, jquery, html, ajax
#contact-form > button:hover {
background-image: linear-gradient(#e1e1e1, #eaeaea);
}
/* form errors */
.send-fail-notice {
flex-direction: row !important;
align-items: center;
padding: 15px;
background-color: #ffc;
border: 2px solid red;
}
.send-fail-notice > span {
color: #e13a3e;
font-weight: bold;
margin-left: 10px;
}
<form method="post" id="contact-form">
<?php echo $send_fail_one ?>
<?php echo $send_fail_two ?>
<div>
<label for="name">Name <span>*</span></label>
<input type="text" name="name" id="name" maxlength="75" value="<?php echo $name ?>" required>
</div>
<div>
<label for="email">E-mail <span>*</span></label>
<input type="email" name="email" id="email" maxlength="75" value="<?php echo $email ?>" required>
</div>
<div id="subject-line">
<label for="subject">Subject</label>
<input type="text" name="subject" id="subject" maxlength="75" value="<?php echo $subject ?>">
</div>
<div id="counter-container">
<label for="comments">Message <span>*</span></label>
<textarea name="comments" id="comments" maxlength="1500" cols="25" rows="5" required><?php echo $comments ?></textarea>
</div>
<div class="g-recaptcha" data-sitekey="6LdruToUAAAAAO4EZua5CV6_jREeCpv8knqklYa9" style="width: auto;"></div>
<button type="submit" name="submit" id="submit">Send Message</button>
</form>
PHP
// CONTACT FORM PROCESSING SCRIPT
// set default values (prevents undefined variable error)
$send_fail_one = null;
$send_fail_two = null;
$name = null;
$email = null;
$subject = null;
$comments = null;
// Load PHPMailer (v 6.5.3 02/02/2022)
// Import PHPMailer classes into the global namespace
// These must be at the top of your script, not inside a function
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\Exception;
if ($_SERVER["REQUEST_METHOD"] == "POST") { | {
"domain": "codereview.stackexchange",
"id": 42924,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "javascript, php, jquery, html, ajax",
"url": null
} |
javascript, php, jquery, html, ajax
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// Load PHPMailer
require 'PHPMailer/src/Exception.php';
require 'PHPMailer/src/PHPMailer.php';
require 'PHPMailer/src/SMTP.php';
// Create new PHPMailer instance; passing `true` enables exceptions
$mail = new PHPMailer(true);
$mail->CharSet = "UTF-8";
// SMTP Debugging
//SMTP::DEBUG_OFF = off (for production use)
//SMTP::DEBUG_CLIENT = client messages
//SMTP::DEBUG_SERVER = client and server messages
$mail->SMTPDebug = SMTP::DEBUG_SERVER;
$mail->Debugoutput = 'html';
// SMTP settings
$mail->isSMTP();
$mail->Host = 'smtp.gmail.com';
$mail->SMTPAuth = true;
$mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS;
$mail->Port = 465;
$mail->Username = 'demo-purposes@yahoo.com';
$mail->Password = 'FakePasswordForDemoPurposes';
$mail->setFrom('demo-purposes@yahoo.com');
$mail->addAddress('demo-purposes@yahoo.com');
$mail->isHTML(true);
// Sanitize & Validate Input
// Trim all $_POST values
/* Using FILTER_SANITIZE_SPECIAL_CHARS as opposed to FILTER_SANITIZE_STRING because:
* (1) FILTER_SANITIZE_SPECIAL_CHARS will disarm code but still display it.
* (2) FILTER_SANITIZE_STRING removes all code, leaving no trace, and all code input is lost (e.g., anything with brackets is lost).
* Hence, with (1) we can identify users trying to submit code.
* Exception: textarea field ('comments') uses FILTER_SANITIZE_STRING because otherwise nl2br (keep line breaks) doesn't work. */
$name = trim(filter_input(INPUT_POST, 'name', FILTER_SANITIZE_SPECIAL_CHARS));
$email = filter_input(INPUT_POST, 'email', FILTER_SANITIZE_EMAIL);
$subject = trim(filter_input(INPUT_POST, 'subject', FILTER_SANITIZE_SPECIAL_CHARS));
$comments = nl2br(filter_input(INPUT_POST, 'comments', FILTER_SANITIZE_STRING)); | {
"domain": "codereview.stackexchange",
"id": 42924,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "javascript, php, jquery, html, ajax",
"url": null
} |
javascript, php, jquery, html, ajax
// Email Body
$message = <<<HTML
<br>
<table style="border: 1px solid #e1e1e1; background-color: #fafafa; margin: 0 auto; width: 75%; padding: 10px 20px;">
<tr><td style="padding: 10px 0;"><b>NAME</b></td></tr>
<tr><td style="border-bottom: 1px solid #e1e1e1; padding-bottom: 15px;">$name</td></tr>
<tr><td style="padding: 10px 0;"><b>E-MAIL</b></td></tr>
<tr><td style="border-bottom: 1px solid #e1e1e1; padding-bottom: 15px;">$email</td></tr>
<tr><td style="padding: 10px 0;"><b>SUBJECT</b></td></tr>
<tr><td style="border-bottom: 1px solid #e1e1e1; padding-bottom: 15px;">$subject</td></tr>
<tr><td style="padding: 10px 0;"><b>MESSAGE</b></td></tr>
<tr><td style="padding-bottom: 15px;">$comments<td></tr>
</table>
HTML;
$mail->Subject = 'Message Received =?utf-8?B?4oCT?= Website Contact Form';
$mail->Body = $message;
// verify recaptcha response
$url = "https://www.google.com/recaptcha/api/siteverify";
$privatekey = "xxx";
$response = file_get_contents($url."?secret=".$privatekey."&response=".$_POST['g-recaptcha-response']."&remoteip=".$_SERVER['REMOTE_ADDR']);
$data = json_decode($response);
// if recaptcha verification is a success...
if(isset($data->success) AND $data->success==true) {
// ... and if phpmailer does not send (for whatever reason, such as a wrong SMTP password)...
if (!$mail->send()) { | {
"domain": "codereview.stackexchange",
"id": 42924,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "javascript, php, jquery, html, ajax",
"url": null
} |
javascript, php, jquery, html, ajax
// then show this error message:
$send_fail_one = <<<ERROR
<div class="send-fail-notice">
<img src="images/warning-sign.gif" height="44" width="50" alt="error sign">
<span>ERROR. Message not sent.<br>Please try again or contact us at <i><u>bireg</u></i> <i><u>at</u></i> <i><u>outlook</u></i> <i><u>dot</u></i> <i><u>com</u></i>.</span>
</div>
ERROR;
} else {
// ...otherwise delivery is successful and page re-directs to thank you / confirmation page
header('Location: https://www.yahoo.com');
}
} else {
// if re-captcha verification fails, show this error message:
$send_fail_two = <<<ERROR
<div class="send-fail-notice">
<img src="images/warning-sign.gif" height="44" width="50" alt="error sign">
<span>ERROR. Message not sent.<br>Please check the anti-spam box.</span>
</div>
ERROR;
}
} | {
"domain": "codereview.stackexchange",
"id": 42924,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "javascript, php, jquery, html, ajax",
"url": null
} |
javascript, php, jquery, html, ajax
Answer: Contact forms don't have to be a security risk, but it all depends on what you do with the submitted data. There are basically two types of security you need to keep in mind:
1. The server
You don't store anything in a database, or sent the e-mails yourself. This takes away one of the biggest threats to your server. You've left out a lot of code, so it is still possible you do store the data, but clearly you don't want this to be discussed here.
2. The visitor
Users run a much bigger risk with this contact form. Apart from their comment, they have to supply their name and email address. Why exactly?
Any smart user would, of course, not use their own name and e-mail address. Any email address will do. So, why do ask for it?
You could make supplying a name and email address optional.
You are also using Google's hidden reCAPTCHA, which hands over a lot of user data to Google.
Read: Google reCAPTCHA and the GDPR: a possible conflict?
If the reCAPTCHA misses any of that information Google has a second chance by peeking in the mails you so kindly send via their mail server. You don't leave your visitors any choice, if they want to comment they could as well be sending their comments straight to Google.
Why would this be a problem? Google stored this data in the USA. And the US government likes big data. They use it. It's easy. Edward Snowden showed us how. Foreigners have even less protection under US law.
Also Read: Exclusive: Government Secretly Orders Google To Identify Anyone Who Searched A Sexual Assault Victim’s Name, Address Or Telephone Number.
Google is one of the major reasons there's no privacy on the internet, and they actively work, along with Facebook, to keep it that way. They pursue legitimate business interests, but the result is quite damaging.
Most people, including me, too often ignore this obvious problem. We concentrate on all the technical issues, but there's a whole other side to this story. | {
"domain": "codereview.stackexchange",
"id": 42924,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "javascript, php, jquery, html, ajax",
"url": null
} |
python, networking, status-monitoring
Title: Online check with retry logic and anti-flapping
Question: I've got a network device that doesn't hold its WiFi connection brilliantly and occasionally drops off the network completely. Although there are dedicated network monitoring tools out there, I thought it would be a nice exercise to write a small monitoring script in Python.
I want to check the status of the device once per minute with an ICMP echo. Because the network connection is a little unreliable, I'll ignore short drop-outs and so will try up to three times to get a positive response.
Additionally, because the device can sometimes reboot, I want to ignore outages of up to two or three minutes. Once the device has missed three checks, I'll send a message to myself saying it's offline. Similarly, once it has been back online for three checks I'll send a message saying it's back online.
The following code is a test of the logic I came up with; I've applied this to the actual script and it does seem to do the job. However, it seems clunky and I'm sure there's some clever Pythonic way of doing things that I haven't thought of. Note that I'm posting this rather than the full script since this can be executed standalone and doesn't have any real network dependencies.
How can I improve this code so that it's more compact and Pythonic? Thanks!
"""Test ping logic"""
import time
def ping_device(iter_count):
"""Fake ping device function"""
# Pretend that this function tries up to three times to get a good ping response :)
if iter_count == 5:
response = False
elif 11 <= iter_count <= 14:
response = False
else:
response = True
return response
def main():
"""Main functions"""
previous_status = True
current_status_count = 0
adjusted_status = True
previous_adjusted = True
iteration_counter = 0
while True:
iteration_counter += 1
print(f"Pinging iteration {iteration_counter}... ", end="") | {
"domain": "codereview.stackexchange",
"id": 42925,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, networking, status-monitoring",
"url": null
} |
python, networking, status-monitoring
status = ping_device(iteration_counter)
if status:
print("OK")
else:
print("FAIL")
if status != previous_status:
current_status_count = 0
previous_status = status
else:
current_status_count += 1
if current_status_count > 2:
adjusted_status = status
if adjusted_status != previous_adjusted:
previous_adjusted = adjusted_status
if status:
print("***** Device is online *****")
else:
print("!!!!! Device is offline !!!!!")
print(f"---> Current status count is {current_status_count}")
time.sleep(1)
if __name__ == "__main__":
main()
In the actual monitoring script, the ping/retry logic looks like this:
for attempt in range(RETRIES + 1):
ping_response = ping(MONITOR_HOST)
if status is None:
if ping_response:
status = True
previous_status = True
adjusted_status = True
previous_adjusted = True
send_telegram("Current status is online.")
break
else:
status = False
previous_status = False
adjusted_status = False
previous_adjusted = False
send_telegram("Current status is offline.")
else:
if ping_response:
status = True
break
else:
status = False
As well as doing the retries, this handles sending an initial message telling me if the device is online or offline when monitoring is started (status is None on start). Note that I use 'attempt' rather than '_' in the loop as I do log the attempt number. | {
"domain": "codereview.stackexchange",
"id": 42925,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, networking, status-monitoring",
"url": null
} |
python, networking, status-monitoring
Answer: If, as you say in your comments, everything is more or less a single main() function, I would start by splitting things up to make reasonning about each part (and their testing) simpler.
So I would start by the basis that you want to continuously "connect" to your device. For now it's only pingable, but if you are ever offered a REST API or any kind of endpoint, switching will be easy:
def connect(host):
while True:
yield ping(host)
Using a generator here is a simple way of building the retry logic without having to worry about its inner mechanisms:
def retry(generator, max_attempts=5):
for attempt, status in enumerate(generator, start=1):
if status or attempt >= max_attempts:
break
return status
You can have your anti-flapping logic in a dedicated class:
class StabilizedStatus:
def __init__(self, status, flapping_threshold=3):
self._previous_adjusted = self._adjusted_status = self._status = status
self._status_count = 0
self._threshold = flapping_threshold
def __bool__(self):
return bool(self._status)
@property
def stabilized(self):
if self._adjusted_status != self._previous_adjusted:
self._previous_adjusted = self._adjusted_status
return False
return True
@stabilized.setter
def stabilized(self, value):
if value == self._status:
self._status_count += 1
else:
self._status_count = 0
self._status = value
if self._status_count >= self._threshold:
self._adjusted_status = self._status
And lastly you can tie everything together in your main:
import time
from itertools import count
def main():
check_connection = connect(MONITOR_HOST)
status = StabilizedStatus(next(check_connection))
send_telegram("Current status is " + "online" if status else "offline") | {
"domain": "codereview.stackexchange",
"id": 42925,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, networking, status-monitoring",
"url": null
} |
python, networking, status-monitoring
for iteration in count(start=1):
print(f"Pinging {iteration=}... ", end="")
status.stabilized = retry(check_connection, RETRIES + 1)
print("OK" if status else "FAIL")
if not status.stabilized:
if status:
print("***** Device is online *****")
else:
print("!!!!! Device is offline !!!!!")
time.sleep(1)
And your testing code can now be:
def connect(host):
yield from [True] * 4 # Start with 4 good pings
yield from [False] * (RETRIES + 1) # Then a bad one
yield from [True] * 5 # Then 5 good ones
yield from [False] * (RETRIES + 1) * 4 # Then 4 failures
yield from itertools.repeat(True) # Then everything good | {
"domain": "codereview.stackexchange",
"id": 42925,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, networking, status-monitoring",
"url": null
} |
python, performance, beginner, python-3.x, object-oriented
Title: Matchsticks game in Python
Question: I made the following game in Python applying object oriented programming and I would like to know if there is something to improve.
PS: My native language is Spanish, if you see something wrong written in the code let me know.
The 23 matchsticks game is played between 2 participants.
It consists of placing 23 matchsticks on the table and each player can remove
1, 2 or 3 matchsticks per turn.
The player who removes the last matchstick loses and is eliminated.
Make a program that allows two participants to play the 23 matchsticks game.
Example of execution:
Start the game
||||| ||||| ||||| ||||| |||
Player 1 remove: 3
||||| ||||| ||||| |||||
Player 2 remove: 3
||||| ||||| ||||| ||
Player 1 remove: 3
||||| ||||| ||||
Player 2 remove: 1
||||| ||||| |||
Player 1 remove: 3
||||| |||||
Player 2 remove: 3
||||| ||
Player 1 remove: 2
|||||
Player 2 remove: 1
||||
Player 1 remove: 3
|
Player 2 is eliminated.
class MatchsticksGame:
matchsticks = 23
def __is_valid_input(self, player):
return 1 <= player <= 3
def __show_matchsticks(self):
return '||||| '*(self.matchsticks//5) + '|'*(self.matchsticks%5)
def __game_finish(self):
return self.matchsticks <= 0
def play(self):
player2 = False
print('Game starts')
print(self.__show_matchsticks())
while True:
try:
player = int(input(f'The player {player2+1} remove: '))
if not self.__is_valid_input(player):
print('You can delete only between 1 and 3 matchsticks.')
continue
self.matchsticks -= player
print(self.__show_matchsticks())
if self.__game_finish():
print(f'The player {player2+1} is eliminated.')
break | {
"domain": "codereview.stackexchange",
"id": 42926,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, performance, beginner, python-3.x, object-oriented",
"url": null
} |
python, performance, beginner, python-3.x, object-oriented
player2 = not player2
except:
print('You can only enter numeric values.')
if __name__ == '__main__':
game = MatchsticksGame()
game.play()
Answer: Types
Consider: player2 = False, player2 = not player2, and f'...{player2+1}...' Is player2 a boolean value that you can toggle between True and False or is it an numerical variable you can add 1 to? It shouldn't be both.
Using a player_number variable, initialized to 1, and then flipping it between 1 and 2 would be clearer. You can accomplish the flipping with a little bit of math: player_number = 3 - player_number. This is much less tricky than True+1 == 2!
Double underscore
Prefixing members with a double underscore has a special meaning. It is meant to help avoid name clashes between “private” attributes of base and derived classes. See the Reserved classes of identifiers for details. Since you are not using derived classes here, there is no need to use a double underscore prefix.
Variable naming
Reading return 1 <= player <= 3, it looks like you've a game that uses between 1 and 3 players. You are not validating the player; you've validating a number of match sticks to remove. Name the appropriately, such as number_to_remove.
Class Variables -vs- Instance Variables
What is matchsticks? Is it a class variable or an instance variable? Answer: they (plural) are both!
That is a somewhat confusing answer, but you've got a somewhat confusing situation here.
>>> game = MatchsticksGame()
>>> MatchsticksGame.matchsticks
23
>>> game.matchsticks
23
Both MatchsticksGame.matchsticks and game.matchsticks have the same value. Let's change one:
>>> MatchsticksGame.matchsticks -= 3
>>> MatchsticksGame.matchsticks
20
game.matchsticks
20
We changed one, and the other changed. They are the same variable!?
>>> game.matchsticks -= 3
>>> game.matchsticks
17
>>> MatchsticksGame.matchsticks
20 | {
"domain": "codereview.stackexchange",
"id": 42926,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, performance, beginner, python-3.x, object-oriented",
"url": null
} |
python, performance, beginner, python-3.x, object-oriented
Nope!
What's going on? Initially, there is just the class variable MatchsticksGame.matchsticks with the value 23. When you reference game.matchsticks, it looks up the member in the game instance, can't find it, so looks up the member in the MatchsticksGame class. When you set/change the member value, with game.matchsticks -= 3 or self.matchsticks -= player, it fetches the value from the class, subtracts the indicated amount, and stores the value, creating the member of the instance object!
While this seems to work OK here, it fails in an unexpected way when you have a mutable object like a set or a dictionary.
Change this:
class MatchsticksGame:
matchsticks = 23
...
to something like this:
class MatchsticksGame:
INITIAL_MATCHSTICKS = 23
def __init__(self):
self.matchsticks = MatchsticksGame.INITIAL_MATCHSTICKS
...
Object Oriented Programming
You haven't really got object oriented programming here. You have an object with one data member (matchsticks) for state, and one method (play). True, you have 3 other helper methods, but they are pretty trivial -- you could easily substitute them into the play function without any loss of readability. In fact, the entire code could be converted almost unchanged into a single function without classes:
def play_matchsticks():
def is_valid_input(num_to_remove):
return 1 <= num_to_remove <= 3
def show_matchsticks(matchsticks):
return '||||| ' * (matchsticks // 5) + '|' * (matchsticks % 5)
def game_finished(matchsticks):
return matchsticks <= 0
matchsticks = 23
player = 2
print('Game starts')
print(show_matchsticks(matchsticks)) | {
"domain": "codereview.stackexchange",
"id": 42926,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, performance, beginner, python-3.x, object-oriented",
"url": null
} |
python, performance, beginner, python-3.x, object-oriented
print('Game starts')
print(show_matchsticks(matchsticks))
while not game_finished(matchsticks):
player = 3 - player
while True:
try:
matchsticks_to_remove = int(input(f'The player {player} remove: '))
if is_valid_input(matchsticks_to_remove):
break
print('You can delete only between 1 and 3 matchsticks.')
except:
print('You can only enter numeric values.')
matchsticks -= matchsticks_to_remove
print(show_matchsticks(matchsticks))
print(f'The player {player} is eliminated.')
if __name__ == '__main__':
play_matchsticks()
The game itself actually has more state. It has a player which flips back and forth between two values, but the game instance doesn't store that; it is hidden as a local variable inside the play method.
If you wanted to really make this object oriented, you could have a game object initialized with two player objects. The game object would alternate asking each player object for and reporting the results. The player objects would themselves have the input() statement in a loop with try/except to ensure valid input is given. The game object would have a loop until the game was finished.
Something like the following:
class Player:
def __init__(self, player_name):
self.name = player_name
def get_move(self) -> int:
while True:
try:
matchsticks_to_remove = int(input(f'Player {self.name} removes matchsticks: '))
if 1 <= matchsticks_to_remove <= 3:
return matches_to_remove
...
except ValueError:
...
class MatchsticksGame:
def __init__(self, player1, player2, initial_matchsticks=23):
self.players = [player1, player2]
self.turn = 0
self.matchsticks = initial_matchsticks | {
"domain": "codereview.stackexchange",
"id": 42926,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, performance, beginner, python-3.x, object-oriented",
"url": null
} |
python, performance, beginner, python-3.x, object-oriented
def _current_player(self) -> Player:
return self.players[self.turn % 2]
def _show_matchsticks(self) -> None:
...
def _play_turn(self) -> None:
player = self._current_player()
matchsticks_to_remove = player.get_move()
...
self.turn += 1
def play(self) -> None:
while self.matchsticks > 0:
self._play_turn()
...
if __name__ == '__main__':
p1 = Player("Alice")
p2 = Player("Bob")
game = MatchsticksGame(p1, p2)
game.play() | {
"domain": "codereview.stackexchange",
"id": 42926,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, performance, beginner, python-3.x, object-oriented",
"url": null
} |
beginner, c, array, reinventing-the-wheel
Title: Another generic dynamic arrays in C
Question: Wrote this (and others not here) as an exercise to explore how generics could be implemented in C.
Question -- if I were to support out-of-band error setting, how would that look like for dynarray_len()? There is no wrong value to return and requiring the user to check the error after every call seems cumbersome; I don't see any other way around though.
// generic_dynarray.h
#ifndef GENERIC_DYNARRAY_H
#define GENERIC_DYNARRAY_H
#include <stdbool.h>
typedef struct dynarray_T dynarray_T;
// dynarray_new returns a new, initialised dynarray_T.
dynarray_T *dynarray_new(size_t data_size);
// dynarray_destroy frees da.
void dynarray_destroy(dynarray_T *da);
// dynarray_init initialises or clears da.
void dynarray_init(dynarray_T *da, size_t data_size);
// dynarray_get returns the data at index i of da, otherwise NULL incase
// of out-of-bounds i.
void *dynarray_get(dynarray_T *da, size_t i);
// dynarray_set sets the value of index i of da to data. Returns true if
// operation succeeded, false otherwise.
bool dynarray_set(dynarray_T *da, size_t i, void *data);
// dynarray_append appends data to da.
void dynarray_append(dynarray_T *da, void *data);
// dynarray_pop pops and returns the value of da at it's last index.
void *dynarray_pop(dynarray_T *da);
// dynarray_len returns the length of da.
size_t dynarray_len(dynarray_T *da);
#endif
// generic_dynarray.c
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>
#include "generic_dynarray.h"
#define DYNARRAY_MIN_CAP 10
#define DYNARRAY_CAP_GROWTH_RATE 2
#define DYNARRAY_CAP_SHRINK_RATE 0.25 // 1/4
struct dynarray_T {
void *buf; // The buffer array holding the data
size_t cap, len; // The capacity and length of the dynarray
size_t data_size; // The size of the value stored in buf
}; | {
"domain": "codereview.stackexchange",
"id": 42927,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "beginner, c, array, reinventing-the-wheel",
"url": null
} |
beginner, c, array, reinventing-the-wheel
static void valid_dynarray(dynarray_T *da, const char *func) {
if (!da) {
fprintf(stderr, "%s: dynarray_T should not be NULL", func);
exit(1);
}
}
dynarray_T *dynarray_new(size_t data_size) {
dynarray_T *da = malloc(sizeof(*da));
if (!da) {
fprintf(stderr, "%s: memory allocation for da failed\n", __func__);
exit(1);
}
// For realloc in dynarray_init() to work like malloc
da->buf = NULL;
dynarray_init(da, data_size);
return da;
}
void dynarray_destroy(dynarray_T *da) {
valid_dynarray(da, __func__);
free(da->buf);
free(da);
}
// dynarray_resize resizes da->buf to capacity da->cap by reallocing.
static void dynarray_resize(dynarray_T *da, const char *func) {
da->buf = realloc(da->buf, da->data_size * da->cap);
if (!da->buf) {
fprintf(stderr, "%s: memory allocation for da->buf failed\n", func);
exit(1);
}
}
void dynarray_init(dynarray_T *da, size_t data_size) {
valid_dynarray(da, __func__);
da->cap = DYNARRAY_MIN_CAP;
da->len = 0;
da->data_size = data_size;
dynarray_resize(da, __func__);
}
void *dynarray_get(dynarray_T *da, size_t i) {
valid_dynarray(da, __func__);
if (i >= da->len) {
fprintf(stderr, "%s: i %lu must be less than %lu\n",
__func__, i, da->len);
return NULL;
}
return da->buf + i*da->data_size;
}
bool dynarray_set(dynarray_T *da, size_t i, void *data) {
valid_dynarray(da, __func__);
if (i >= da->len) {
fprintf(stderr, "%s: i %lu must be less than %lu\n",
__func__, i, da->len);
return false;
}
memcpy(da->buf + i*da->data_size, data, da->data_size);
return true;
}
void dynarray_append(dynarray_T *da, void *data) {
valid_dynarray(da, __func__);
if (da->cap == da->len+1) {
da->cap = DYNARRAY_CAP_GROWTH_RATE * da->cap;
dynarray_resize(da, __func__);
}
dynarray_set(da, da->len++, data);
} | {
"domain": "codereview.stackexchange",
"id": 42927,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "beginner, c, array, reinventing-the-wheel",
"url": null
} |
beginner, c, array, reinventing-the-wheel
void *dynarray_pop(dynarray_T *da) {
valid_dynarray(da, __func__);
if (da->len == DYNARRAY_CAP_SHRINK_RATE * da->cap) {
da->cap = DYNARRAY_CAP_SHRINK_RATE * da->cap;
dynarray_resize(da, __func__);
}
void *ret = dynarray_get(da, da->len-1);
da->len--;
return ret;
}
size_t dynarray_len(dynarray_T *da) {
valid_dynarray(da, __func__);
return da->len;
}
And a simple test driver,
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "generic_dynarray.h"
int main(int argc, char *argv[]) {
if (argc < 2) {
fprintf(stderr, "expect at least one argument\n");
exit(1);
}
dynarray_T *da_strs = dynarray_new(sizeof(char *));
for (size_t i = 0; i < argc; i++) {
dynarray_append(da_strs, argv[i]);
}
printf("da.len = %lu\n", dynarray_len(da_strs));
for (size_t i = 0; i < dynarray_len(da_strs); i++) {
printf("da_strs[%lu] = %s; ", i, (char *)dynarray_get(da_strs, i));
}
puts("");
size_t len = dynarray_len(da_strs);
for (size_t i = 0; i < len; i++) {
printf("da_strs[%lu] = %s; ", len-i-1, (char *)dynarray_pop(da_strs));
printf("da.len = %lu\n", dynarray_len(da_strs));
}
dynarray_destroy(da_strs);
return 0;
}
Answer: You have a bug here:
da->buf = realloc(da->buf, da->data_size * da->cap);
When realloc() returns a null pointer, we overwrite da->buf with that, losing our pointer to the memory block (i.e. a leak). We should use a temporary pointer:
void *newmem = realloc(da->buf, da->data_size * da->cap);
if (!newmem) {
/* handle error */
} else {
da->buf = newmem;
} | {
"domain": "codereview.stackexchange",
"id": 42927,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "beginner, c, array, reinventing-the-wheel",
"url": null
} |
beginner, c, array, reinventing-the-wheel
In this particular case, the harm is small, because we call exit() in the failure case, so the only evidence is when we run under Valgrind or similar.
But a real library should not unilaterally exit the program - we should return an error indication to the caller, which is in a better position to decide what to do (perhaps try a different operation, or squeeze a cache and try again, or report the error in a GUI rather than on stderr).
You'll find that DYNARRAY_CAP_GROWTH_RATE==2 is a bit high for good performance. Try a value near to 1.5 instead (but make sure you round upwards!). | {
"domain": "codereview.stackexchange",
"id": 42927,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "beginner, c, array, reinventing-the-wheel",
"url": null
} |
c#, object-oriented, design-patterns
Title: Finding and changing filenames of different media files (photos, videos)
Question: My tool should eventually change all media files' names to one qualified format yyyymmdd_hhmmss [optional desc].xxx:
If it's an image, the date is taken from "Date Taken" property of the file.
If it's a video it should already have that format otherwise it's renamed to literrally YYYYMMDD_HHMMSS.MP4
If it's a video file and has a metadata file, then the "Date Taken" is taken from that metadata file.
I chose a specific design to implement my task. I tried to implement in such way so I could later write unit tests (I know that I should have started with the unit tests first) and use Dependency injection. Each type of media file implements a ExtractQualifiedName method which is responsible to extract the DateTaken and then it's used to rename the file. I also created Loaders that load specific media files. At first it seemed like this is the right approach since files have common functionality and I used factories to create the file types, but as I added another type CameraVideoFile I could not use factory anymore in corresponding CameraVideoFilesLoader loader and it seems that the CameraVideoFile does not have much common with the rest files, for example this file will always come in non-qualified format and therefore should not inherit from MediaFile.
Can someone tell me if my design has correct direction?
I included as much code as I could omitting irrelevant parats
public class Program
{
public static void Main(string[] args)
{
var op = ArgumentParser.Parse(args);
if(op.Action == "photo-convert")
ConvertPhotoNames(...)
else if(op.Action == "video-convert")
ConvertVideoNames(...)
else if(op.Action == "modify-video-date")
ModifyVideoDate(...)
...
} | {
"domain": "codereview.stackexchange",
"id": 42928,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, object-oriented, design-patterns",
"url": null
} |
c#, object-oriented, design-patterns
private static void ConvertPhotoNames(DirectoryInfo sourceDir)
{
var filesLoader = new PhotoFilesLoader();
// responsible to generate a name in case such file exists (e.g. adding (0))
var fileNameGenerator = new UniqueFileNameGenerator();
var fileNameHandler = new MediaFileNameHandler(filesLoader, fileNameGenerator);
fileNameHandler.ConvertName(sourceDir);
}
private static void ConvertCameraVideoNames(DirectoryInfo sourceDir)
{
var filesLoader = new CameraVideoFilesLoader();
// responsible to generate a name in case such file exist (e.g. adding (0))
var fileNameGenerator = new UniqueFileNameGenerator();
var fileNameHandler = new MediaFileNameHandler(filesLoader, fileNameGenerator);
fileNameHandler.ConvertName(sourceDir);
}
private static void ConvertVideoNames(DirectoryInfo sourceDir)
{
var filesLoader = new VideoFilesLoader();
// responsible to generate a name in case such file exist (e.g. adding (0))
var fileNameGenerator = new UniqueFileNameGenerator();
var fileNameHandler = new MediaFileNameHandler(filesLoader, fileNameGenerator);
fileNameHandler.ConvertName(sourceDir);
}
}
public class MediaFileNameHandler : IMediaFileNameHandler
{
public void ConvertName(DirectoryInfo sourceDir)
{
foreach (var file in _filesLoader.GetFiles(sourceDir))
{
if (!file.Name.IsQualifiedName)
{
if (file.ExtractQualifiedName())
{
var newFileInfo = _fileNameGenerator.GenerateName(file);
file.Rename(newFileInfo.FullName);
}
}
}
}
}
public class QualifiedNameInfo
{
public bool IsQualifiedName { get; private set; }
public DateTime DateTaken { get; set; }
}
public abstract class MediaFile
{
public QualifiedNameInfo Name { get; private set; } | {
"domain": "codereview.stackexchange",
"id": 42928,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, object-oriented, design-patterns",
"url": null
} |
c#, object-oriented, design-patterns
public abstract class MediaFile
{
public QualifiedNameInfo Name { get; private set; }
public abstract bool ExtractQualifiedName();
public MediaFile(string filePath)
{
Name = new QualifiedNameInfo(filePath);
}
}
public class PhotoFile : MediaFile
{
public override bool ExtractQualifiedName()
{
// get DateTaken from file's DateTaken property
// Name.DateTaken = ...
}
}
public class VideoFile : MediaFile
{
public override bool ExtractQualifiedName()
{
// the file should already be in correct format
throw new NotImplementedException();
}
}
public class CameraVideoFile : MediaFile
{
public CameraVideoFile(string metaFile, FileInfo videoFile) {...}
public override bool ExtractQualifiedName()
{
// get DateTaken from meta file
// Name.DateTaken = ...
}
}
public interface IMediaFilesLoader
{
IEnumerable<MediaFile> GetFiles(DirectoryInfo dir);
}
public class PhotoFilesLoader : IMediaFilesLoader
{
public IEnumerable<MediaFile> GetFiles(DirectoryInfo dir)
{
var factory = new MediaFileFactory();
var files = dir.EnumerateFiles()
.Where(f => f.Extension.IsImageExtension())
.Select(f => factory.Create(f.FullName));
return files;
}
}
public class VideoFilesLoader : IMediaFilesLoader
{
public IEnumerable<MediaFile> GetFiles(DirectoryInfo dir)
{
var factory = new MediaFileFactory();
var files = dir.EnumerateFiles()
.Where(f => f.Extension.IsVideoExtension())
.Select(f => factory.Create(f.FullName));
return files;
}
} | {
"domain": "codereview.stackexchange",
"id": 42928,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, object-oriented, design-patterns",
"url": null
} |
c#, object-oriented, design-patterns
public class CameraVideoFilesLoader : IMediaFilesLoader
{
public IEnumerable<MediaFile> GetFiles(DirectoryInfo dir)
{
// [C0045M01.XML, C0045.MP4] - first 5 letters of meta filename is the filename of the video
foreach (var metaFile in dir.EnumerateFiles(".xml"))
{
var mp4Filename = metaFile.Name.Substring(0, 5);
var mp4File = new FileInfo(metaFile.DirectoryName + "\\" + mp4Filename + ".mp4");
yield return new CameraVideoFile(metaFile, mp4File);
}
}
}
```
Answer: Program
ConvertXYZ
If you look at the definitions of these three methods then you can easily spot that the only difference is the IMediaFilesLoader instance
So, you can have a single Convert method which can anticipate two parameters
private static void Convert(DirectoryInfo sourceDir, IMediaFilesLoader filesLoader)
=> new MediaFileNameHandler(filesLoader, new UniqueFileNameGenerator()).ConvertName(sourceDir);
You did not share with us the source code of the UniqueFileNameGenerator so I can't be sure but my gut feeling says that you can have a single instance and reuse it multiple times
private static readonly UniqueFileNameGenerator fileNameGenerator = new();
private static void Convert(DirectoryInfo sourceDir, IMediaFilesLoader filesLoader)
=> new MediaFileNameHandler(filesLoader, fileNameGenerator).ConvertName(sourceDir);
Main
With above Convert method you can rewrite your if - else if - else if statement
IMediaFilesLoader filesLoader = op.Action switch
{
"photo-convert" => new PhotoFilesLoader(),
"video-convert" => new CameraVideoFilesLoader(),
"modify-video-date" => new VideoFilesLoader(),
_ => null
};
if(filesLoader == default)
{
Console.WriteLine("Specified action is unknown");
Environment.Exit(-1);
return;
}
Convert(dirInfo, filesLoader);
Depending on the command line parameter you instantiate the appropriate IMediaFilesLoader implementation | {
"domain": "codereview.stackexchange",
"id": 42928,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, object-oriented, design-patterns",
"url": null
} |
c#, object-oriented, design-patterns
If the specified argument is not matching with any of the predefined values then you can exit early and gracefully
If everything is fine then you can call the Convert with the two parameters
MediaFileNameHandler
ConvertName
The two if statements can be combined into a single
You can take advantage of LINQ and transform that single if statement into a Where filter
var toBeRenamedFiles = _filesLoader.GetFiles(sourceDir)
.Where(file => !file.Name.IsQualifiedName && file.ExtractQualifiedName());
foreach (var file in toBeRenamedFiles)
file.Rename(_fileNameGenerator.GenerateName(file).FullName);
With this modification we could get rid of two levels of indentation
Now the core logic is not surrounded with guard expressions
QualifiedNameInfo and MediaFile
Your code will not compile since the QualifiedNameInfo class does not have a constructor which anticipates a parameter
Anyway, I still don't understand how would you want to map a string to a bool and a DateTime
PhotoFilesLoader
GetFiles
I suppose that MediaFileFactory is stateless so it can be created once and used many times
If that's true than you can use expression bodied method feature here
public IEnumerable<MediaFile> GetFiles(DirectoryInfo dir)
=> dir.EnumerateFiles()
.Where(file => file.Extension.IsImageExtension())
.Select(file => factory.Create(file.FullName));
Basically the same can be applied for VideoFilesLoader as well since the only difference is the IsXYZExtension call
CameraVideoFilesLoader
GetFiles
Other implementations of the IMediaFilesLoader seemed really generic
But this looks really specialized
I'm not a huge fan of magic strings, but if you really need that then please prefer to create a dedicated constant for that with a meaningful name
const int CommonPartLength = 5;
Instead of using string concatenation for file path please prefer Path.Combine method | {
"domain": "codereview.stackexchange",
"id": 42928,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, object-oriented, design-patterns",
"url": null
} |
c#, object-oriented, design-patterns
Instead of using string concatenation for file path please prefer Path.Combine method
var mp4FileName = metaFile.Name.Substring(0, CommonPartLength);
var mp4FilePath = Path.Combine(metaFile.DirectoryName + $"{mp4FileName}.mp4");
var mp4FileInfo = new FileInfo(mp4FilePath); | {
"domain": "codereview.stackexchange",
"id": 42928,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, object-oriented, design-patterns",
"url": null
} |
c, event-handling, winapi
Title: A C WinAPI program for showing the color of the screen pixel pointed to by mouse cursor with clipboard support
Question: (See the follow-up question.)
I have this program that shows a small window and that window shows a rectangle whose color is the same as the color of the pixel under the mouse cursor. Note that it will show the color of the mouse cursor pixel even outside of its native window. As additional fun, I have coded the clipboard support: when the user presses Ctrl+C, the RGB value of the current color will be copied to the clipboard. All works fine, but when I try to resize the window, it lags.
What do you think?
#ifndef UNICODE
#define UNICODE
#endif
#include <windows.h>
#include <stdio.h>
const int WIDTH = 300;
const int HEIGHT = 200;
const int TEXT_LINE_HEIGHT = 30;
LRESULT CALLBACK WindowProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam);
LRESULT CALLBACK LowLevelMouseProc(int nCode, WPARAM wParam, LPARAM lParam);
VOID WINAPI CopyToClipboard(HWND hwnd);
HWND hwnd;
BOOL ctrlKeyDown = FALSE;
POINT prevPoint;
int WINAPI wWinMain(HINSTANCE hInstance,
HINSTANCE hPrevInstance,
PWSTR pCmdLine,
int nCmdShow) {
prevPoint.x = -1;
prevPoint.y = -1;
const wchar_t CLASS_NAME[] = L"GrabPixlMainWndw";
WNDCLASSEX wc = {};
wc.cbSize = sizeof(wc);
wc.lpfnWndProc = WindowProc;
wc.hInstance = hInstance;
wc.lpszClassName = CLASS_NAME;
RegisterClassEx(&wc);
int screenWidth = GetSystemMetrics(SM_CXFULLSCREEN);
int screenHeight = GetSystemMetrics(SM_CYFULLSCREEN);
hwnd = CreateWindowEx(
0,
CLASS_NAME,
L"GrabPixel 1.6",
WS_OVERLAPPEDWINDOW,
(screenWidth - WIDTH) / 2,
(screenHeight - HEIGHT) / 2,
WIDTH,
HEIGHT,
NULL,
NULL,
hInstance,
NULL);
if (hwnd == NULL) {
return 0;
} | {
"domain": "codereview.stackexchange",
"id": 42929,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c, event-handling, winapi",
"url": null
} |
c, event-handling, winapi
if (hwnd == NULL) {
return 0;
}
HHOOK mouseHook =
SetWindowsHookExA(
WH_MOUSE_LL,
LowLevelMouseProc,
hInstance,
0);
ShowWindow(hwnd, nCmdShow);
UpdateWindow(hwnd);
MSG msg = {};
while (GetMessage(&msg, NULL, 0, 0)) {
TranslateMessage(&msg);
DispatchMessage(&msg);
}
return 0;
}
LRESULT CALLBACK WindowProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam) {
switch (uMsg) {
case WM_DESTROY:
PostQuitMessage(0);
return 0;
case WM_KEYDOWN:
if (wParam == VK_CONTROL) {
ctrlKeyDown = TRUE;
} else if (wParam == 0x43) {
if (ctrlKeyDown) {
CopyToClipboard(hwnd);
}
}
break;
case WM_KEYUP:
if (wParam == VK_CONTROL) {
ctrlKeyDown = FALSE;
}
break;
case WM_PAINT: {
PAINTSTRUCT ps;
RECT rect;
HFONT hFont;
wchar_t buffer[10];
HDC hdc = BeginPaint(hwnd, &ps);
COLORREF color = (COLORREF)wParam;
HBRUSH brush = CreateSolidBrush(color);
GetClientRect(hwnd, &rect);
rect.bottom -= TEXT_LINE_HEIGHT;
// Draw the color rectangle:
hdc = GetDC(hwnd);
FillRect(hdc, &rect, brush);
DeleteObject(brush);
// Draw the RGB rectangle:
brush = CreateSolidBrush(RGB(255, 255, 255));
rect.top = rect.bottom;
rect.bottom += TEXT_LINE_HEIGHT;
FillRect(hdc, &rect, brush);
DeleteObject(brush);
// Print the RGB value of the current pixel:
wsprintf(buffer,
L"#%02x%02x%02x",
GetRValue(color),
GetGValue(color),
GetBValue(color)); | {
"domain": "codereview.stackexchange",
"id": 42929,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c, event-handling, winapi",
"url": null
} |
c, event-handling, winapi
hFont = CreateFont(30,
16,
0,
0,
FW_BOLD,
FALSE,
FALSE,
FALSE,
ANSI_CHARSET,
OUT_DEFAULT_PRECIS,
CLIP_DEFAULT_PRECIS,
ANTIALIASED_QUALITY,
FF_MODERN,
L"Monospaced");
SetTextColor(hdc, RGB(0, 0, 0));
SelectObject(hdc, hFont);
TextOut(hdc,
5,
rect.bottom - TEXT_LINE_HEIGHT,
buffer,
7);
ReleaseDC(hwnd, hdc);
return 0;
}
}
return DefWindowProc(hwnd, uMsg, wParam, lParam);
}
LRESULT CALLBACK LowLevelMouseProc(int nCode, WPARAM wParam, LPARAM lParam) {
if (wParam == WM_MOUSEMOVE) {
POINT p;
if (GetCursorPos(&p)) {
if (p.x == prevPoint.x && p.y == prevPoint.y) {
// No new pixel:
return 0;
}
prevPoint.x = p.x;
prevPoint.y = p.y;
HDC hdc = GetDC(NULL);
if (hdc != NULL) {
COLORREF color = GetPixel(hdc, p.x, p.y);
PostMessage(hwnd, WM_PAINT, color, color);
}
}
}
return 0;
}
VOID WINAPI CopyToClipboard(HWND hwnd) {
HGLOBAL hglbCopy;
LPSTR lpstrCopy;
if (!OpenClipboard(GetDesktopWindow())) {
return;
}
EmptyClipboard();
POINT point;
if (GetCursorPos(&point)) {
int x = point.x;
int y = point.y;
COLORREF color = GetPixel(GetDC(NULL), x, y);
int r = GetRValue(color);
int g = GetGValue(color);
int b = GetBValue(color);
char buffer[10];
sprintf_s(buffer, "#%02x%02x%02x", r, g, b);
HGLOBAL hGlobal = GlobalAlloc(GMEM_MOVEABLE, 10);
if (!hGlobal) {
CloseClipboard();
return;
} | {
"domain": "codereview.stackexchange",
"id": 42929,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c, event-handling, winapi",
"url": null
} |
c, event-handling, winapi
if (!hGlobal) {
CloseClipboard();
return;
}
memcpy(GlobalLock(hGlobal), buffer, 10);
GlobalUnlock(hGlobal);
SetClipboardData(CF_TEXT, hGlobal);
CloseClipboard();
GlobalFree(hGlobal);
}
}
```
Answer:
COLORREF color = GetPixel(GetDC(NULL), x, y); <- resource leak
Each call to GetDC should be cleaned up by ReleaseDC, otherwise we get GDI resource leak. You can monitor this GDI resource leak in Windows Task Manager (under "Details" tab, right-click on the list column header, and select to show "GDI objects") See also documentation for GetDC
A call to BeginPaint should be cleaned up with EndPaint (we don't want to call GetDC/ReleaseDC in between)
HDC hdc = BeginPaint(hwnd, &ps);
//use hdc...
EndPaint(hwnd, &ps);
Font created by CreateFont also needs cleanup with DeleteObject. You must also save the old font and restore it (see suggested code).
Use InvalidateRect, instead of PostMessage(main_wnd, WM_PAINT, 0, 0); to update paint. WM_PAINT message is not for sending messages, it is used for processing the message. This, and the resource leaks, are likely the cause of lag in resizing.
Use GetKeyState(VK_CONTROL) to see if control key is pushed.
LowLevelMouseProc should return CallNextHookEx if it does not process the message.
We can also handle WM_SIZE to update the window on resizing.
Error handling for functions such as GetCursorPos is not necessary. This function fails only if the parameter is incorrect, or there is something seriously wrong, in which case the program will crash anyway.
Make sure process is DPI aware, otherwise mouse position will be off, and GetPixel returns the wrong color.
Suggested changes:
#ifndef UNICODE
#define UNICODE
#endif
#include <windows.h>
#include <stdio.h>
HWND main_wnd;
HHOOK mouseHook;
COLORREF color = 0xffffffff;
void CopyToClipboard(HWND hwnd)
{
if (!OpenClipboard(hwnd))
return;
EmptyClipboard(); | {
"domain": "codereview.stackexchange",
"id": 42929,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c, event-handling, winapi",
"url": null
} |
c, event-handling, winapi
int len = 10;
HGLOBAL hMem = GlobalAlloc(GMEM_MOVEABLE, len);
if (!hMem) return;
char* buffer = GlobalLock(hMem);
if (!buffer) return;
sprintf_s(buffer, len, "#%02x%02x%02x",
GetRValue(color), GetGValue(color), GetBValue(color));
GlobalUnlock(buffer);
SetClipboardData(CF_TEXT, hMem);
CloseClipboard();
}
LRESULT CALLBACK WindowProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
switch (uMsg)
{
case WM_PAINT:
{
PAINTSTRUCT ps;
HDC hdc = BeginPaint(hwnd, &ps);
const int TEXT_LINE_HEIGHT = 30;
if ((GetKeyState(VK_LBUTTON) & 0x8000) == 0)//mouse is up
{
POINT pt;
GetCursorPos(&pt);
HDC hdc_desktop = GetDC(0);
COLORREF clr = GetPixel(hdc_desktop, pt.x, pt.y);
ReleaseDC(0, hdc_desktop);
color = clr;
}
RECT rect;
GetClientRect(hwnd, &rect);
rect.bottom -= TEXT_LINE_HEIGHT;
HBRUSH brush = CreateSolidBrush(color);
FillRect(hdc, &rect, brush);
DeleteObject(brush);
// Draw the RGB rectangle:
brush = CreateSolidBrush(RGB(255, 255, 255));
rect.top = rect.bottom;
rect.bottom += TEXT_LINE_HEIGHT;
FillRect(hdc, &rect, brush);
DeleteObject(brush);
wchar_t buffer[20];
wsprintf(buffer, L"#%02x%02x%02x",
GetRValue(color), GetGValue(color), GetBValue(color));
SetTextColor(hdc, RGB(0, 0, 0));
HFONT hFont = CreateFont(30, 0, 0, 0, FW_BOLD, 0, 0, 0,
0, 0, 0, ANTIALIASED_QUALITY, 0, L"Monospaced");
HFONT oldfont = (HFONT)SelectObject(hdc, hFont);
TextOut(hdc, 5, rect.bottom - TEXT_LINE_HEIGHT, buffer, 7);
SelectObject(hdc, oldfont);
DeleteObject(hFont);
EndPaint(hwnd, &ps);
return 0;
} | {
"domain": "codereview.stackexchange",
"id": 42929,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c, event-handling, winapi",
"url": null
} |
c, event-handling, winapi
EndPaint(hwnd, &ps);
return 0;
}
case WM_KEYDOWN:
//Ctrl+C:
if ((GetKeyState(VK_CONTROL) & 0x8000) == 0x8000 && wParam == 'C')
CopyToClipboard(hwnd);
return 0;
case WM_SIZE:
InvalidateRect(hwnd, NULL, FALSE);
return 0;
case WM_DESTROY:
PostQuitMessage(0);
return 0;
}
return DefWindowProc(hwnd, uMsg, wParam, lParam);
}
LRESULT CALLBACK LowLevelMouseProc(int nCode, WPARAM wParam, LPARAM lParam)
{
if (wParam == WM_MOUSEMOVE)
{
int is_mouse_down = (GetKeyState(VK_LBUTTON) & 0x8000) != 0;
if(!is_mouse_down)
InvalidateRect(main_wnd, 0, 0);
}
return CallNextHookEx(mouseHook, nCode, wParam, lParam);
}
int WINAPI wWinMain(HINSTANCE hInstance, HINSTANCE prev, PWSTR cmd, int show)
{
const wchar_t CLASS_NAME[] = L"GrabPixlMainWndw";
WNDCLASSEX wc = { 0 };
wc.cbSize = sizeof(wc);
wc.hCursor = LoadCursor(NULL, IDC_ARROW);
wc.lpfnWndProc = WindowProc;
wc.hInstance = hInstance;
wc.lpszClassName = CLASS_NAME;
RegisterClassEx(&wc);
int screenWidth = GetSystemMetrics(SM_CXFULLSCREEN);
int screenHeight = GetSystemMetrics(SM_CYFULLSCREEN);
const int w = 300;
const int h = 200;
main_wnd = CreateWindowEx(0, CLASS_NAME, L"GrabPixel 1.6",
WS_OVERLAPPEDWINDOW, (screenWidth - w) / 2, (screenHeight - h) / 2,
w, h, NULL, NULL, hInstance, NULL);
ShowWindow(main_wnd, show);
UpdateWindow(main_wnd);
mouseHook = SetWindowsHookEx(WH_MOUSE_LL, LowLevelMouseProc, hInstance, 0);
MSG msg = { 0 };
while (GetMessage(&msg, NULL, 0, 0)) {
TranslateMessage(&msg);
DispatchMessage(&msg);
}
return 0;
} | {
"domain": "codereview.stackexchange",
"id": 42929,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c, event-handling, winapi",
"url": null
} |
c#, .net, database, repository
Title: Disposing the Context in the Repository pattern
Question: I have a question about the Repository pattern:
public abstract class RepositoryBase<T> : IDisposable, IRepository<T> where T : class, IEntity
{
/// <summary>
/// For iterations using LINQ extension methods on the IQueryable and IEnumerable interfaces
/// it is required that the context which was used to make the query was not disposed before the iteration
/// otherwise it will throw an exception
/// </summary>
private Context _context;
protected Context Context
{
get { return _context ?? (_context = new Context()); }
}
public virtual void AddOrUpdate(T entity)
{
var dbSet = Context.Set<T>();
if (dbSet.Contains(entity))
entity.ChangeDateTime = DateTime.Now;
else
entity.AddeDateTime = DateTime.Now;
Context.Set<T>().AddOrUpdate(entity);
Context.SaveChanges();
}
public virtual void Delete(T entity)
{
Context.Set<T>().Remove(entity);
Context.SaveChanges();
}
public void Drop()
{
var dbSet = Context.Set<T>();
foreach (var entity in dbSet)
dbSet.Remove(entity);
Context.SaveChanges();
}
public virtual IQueryable<T> Find(Expression<Func<T, bool>> predicate)
{
return Context.Set<T>().Where(predicate);
}
public IEnumerable<T> GetAll()
{
return Context.Set<T>();
}
public void Dispose()
{
if (_context != null)
{
_context.Dispose();
_context = null;
}
}
} | {
"domain": "codereview.stackexchange",
"id": 42930,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, .net, database, repository",
"url": null
} |
c#, .net, database, repository
Why I am not embracing each method implementation with a using and disposing the Context as soon as the query is done?
Some of my methods, as Find and GetAll return collections. I would want to be able to iterate through them using LINQ, only this is not possible if the Context is disposed, as it would be in the original Repository model.
Is this the best approach to go around this issue?
Answer:
My question is about why I am not embracing each method implementation with a using and disposing the Context as soon as the query is done.
Some of my methods, as Find and GetAll return collections. I would want to be able to iterate through them using LINQ, only this is not possible if the Context is disposed, as it would be in the original Repository model.
A Linq enumerable isn't enumerated when it's created: it's enumerated when you try to work with it.
If we want to dispose the context within each each method, I think you can do that by realizing the data, i.e. by reading it all into a concrete object such List or EnumerableQuery, before you dispose the context ... something like this (untested code ahead):
public IEnumerable<T> GetAll()
{
using (Context context = new Context())
{
IEnumerable<T> enumerable = context.Set<T>();
// enumerate into a List before disposing the context
List<T> list = new List<T>(enumerable);
return list;
}
}
public virtual IQueryable<T> Find(Expression<Func<T, bool>> predicate)
{
using (Context context = new Context())
{
IEnumerable<T> enumerable = context.Set<T>().Where(predicate);
// enumerate into a EnumerableQuery before disposing the context
// see https://stackoverflow.com/a/6765404/49942 for further details
EnumerableQuery<T> queryable = new EnumerableQuery<T>(enumerable);
return queryable;
}
}
Beware that this is expensive if the data set is huge, if you don't actually want all the data you queried. | {
"domain": "codereview.stackexchange",
"id": 42930,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, .net, database, repository",
"url": null
} |
javascript, beginner
Title: How would I put this set of javascript if statements with varying IDs and Values in one smaller statement?
Question: I'm wanting to reduce the amount of code in this set of statements, as it seems quite repetitive:
if ($('#Size').val() === 'extra-cab' && $(this).attr("id") === 'canopy-17x-select') {
$('.rack-kit input[type="checkbox"]:checked').prop('checked', false).trigger('change');
}
if ($('#Size').val() === 'double-cab' && $(this).attr("id") === 'canopy-17x-select') {
$('.rack-kit input[type="checkbox"]:checked').prop('checked', false).trigger('change');
}
if ($('#Size').val() === 'double-cab' && $(this).attr("id") === 'canopy-14x-select') {
$('.rack-kit input[type="checkbox"]:checked').prop('checked', false).trigger('change');
}
There are three statements. The first Size statement has a value of 'extra-cab' and the next two statements have a value of 'double-cab'. The first two statements share the same ID attribute, but the third one is different.
Any suggestions would be appreciated.
Answer: The easiest things for this is to create a method and create parameter for all those different value.
function triggerChange(sizeVal, canopyId){
if ($('#Size').val() === sizeVal && $(this).attr("id") === canopyId) {
$('.rack-kit input[type="checkbox"]:checked').prop('checked', false).trigger('change');
}
}
triggerChange('extra-cab', 'canopy-17x-select');
triggerChange('double-cab', 'canopy-17x-select');
triggerChange('double-cab', 'canopy-14x-select');
You could also use parameter to send some flag for different condition.
function triggerChange(sendTrigger, sizeVal, canopyId){
if (sendTrigger && $('#Size').val() === sizeVal && $(this).attr("id") === canopyId) {
$('.rack-kit input[type="checkbox"]:checked').prop('checked', false).trigger('change');
}
} | {
"domain": "codereview.stackexchange",
"id": 42931,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "javascript, beginner",
"url": null
} |
c#
Title: Extract counter from list of file names, then increment counter starting from highest value from file names
Question: I have a small function that I would like to make cleaner and/or more efficient.
There is a directory that contains files in the format of <name>-<counter>-<datetime>.xml.
When a new file is added to the directory, I have a function that reads the counter part of the file name of every file. Then it increments this value and uses it as the counter for the new file.
The code works as expected and has no bugs that I've found
One thing I'm not sure of, in terms of best practice, is if I should pass the path into the function, then extract the files there, or if I should extract the files in the calling code and pass the list of files to my function.
public int GetCounterValue(string path)
{
var files = Directory.GetFiles(path, "*.xml", SearchOption.TopDirectoryOnly);
// Return 1 for initial value if no files are present in the directory.
if (files.Count() == 0)
return 1;
var counterValues = new List<int>();
foreach (var file in files)
{
// The [1] index is a magic number that corresponds to the placement of the counter value in the file names.
if (int.TryParse(file.Split('-')[1], out var counterValue))
counterValues.Add(counterValue);
}
// Take the value of the highest counter and increment by one for the next item in the sequence.
return counterValues.Max() + 1;
} | {
"domain": "codereview.stackexchange",
"id": 42932,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#",
"url": null
} |
c#
Answer: Passing in the directory or the files I don't feel is a big decision. Just need to pick a direction and go. If passing in an IEnumerable gives just a bit more freedom of where the files resides. Now they are in a local directory but in future maybe in an FTP site or someplace else or could even be split into multiple locations. Again nothing I would worry too much now. If moving from directory to http something is going to have to refactor at some point.
I would change Directory.GetFiles to Directory.EnumerateFiles will not have to wait for entire directory to enumerate before working with the files and should save some memory if the directory contains a lot of files.
Also the wild card for the directory should contain the separator. That way you know you can safely split the file and not get an index out of bound error when looking for array position 2 in the code. Look something like this
const string filePartSeparator = "-";
var fileCounterParts = Directory.EnumerateFiles(path, $"*{filePartSeparator}*{filePartSeparator}*.xml", SearchOption.TopDirectoryOnly)
.Select(file => file.Split(filePartSeparator)) // split into file parts
.Select(fileParts => fileParts[1]);
This will give back an IEnumerable of string that is just the "counter" in the file and because of wild card we will know can safely do fileParts[1].
For finding the max instead of building up a list, again keeping data in memory that doesn't need to be can just keep a running value and increase it if we find a bigger value. Something like
var nextId = 1;
foreach (var fileCounterPart in fileCounterParts)
{
if (int.TryParse(fileCounterPart, out var counterValue) && counterValue >= nextId)
{
nextId = ++counterValue;
}
}
return nextId; | {
"domain": "codereview.stackexchange",
"id": 42932,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#",
"url": null
} |
c#
return nextId;
Now just a general concern is nothing prevents two calls to this method and having both return the same id as a new file hasn't been created yet. It's not very multi thread or process friendly. Could implement some sort of locking but would need to be at a higher level than this code. | {
"domain": "codereview.stackexchange",
"id": 42932,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#",
"url": null
} |
javascript, node.js
Title: REST metadata fields generation
Question: I wrote a code to fetch the data present and store it in Array format but I thing I have wrote code multiple times can It be possible to minimize the code as its too long
let topicsValue = ["requiredType.*", "Entry.*", "token.*", "RestAPI.*"]; | {
"domain": "codereview.stackexchange",
"id": 42933,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "javascript, node.js",
"url": null
} |
javascript, node.js
let Topic = [],
rest = ["required", "unrequired"],
final = ["createInput", "mustPossible", "finalOutput"];
topicsValue.map((data) => {
let requiredType, entries, token, restAPI;
if (data.split(".")[1].includes("*")) {
if (data.split(".")[0].includes("requiredType")) {
for (const value of final) {
requiredType = data
.split(".")[0]
.replace("requiredType", "required_type")
.concat(`.${value}`);
Topic.push(requiredType);
}
}
if (data.split(".")[0].includes("Entry")) {
for (const value of final) {
entries = data
.split(".")[0]
.replace("Entry", "entries")
.concat(`.${value}`);
Topic.push(entries);
}
for (const value of rest) {
entries = data
.split(".")[0]
.replace("Entry", "entries")
.concat(`.${value}`);
Topic.push(entries);
}
}
if (data.split(".")[0].includes("token")) {
for (const value of final) {
token = data
.split(".")[0]
.replace("token", "tokens")
.concat(`.${value}`);
Topic.push(token);
}
for (const value of rest) {
token = data
.split(".")[0]
.replace("token", "tokens")
.concat(`.${value}`);
Topic.push(token);
}
}
if (
data.split(".")[0].includes("RestAPI") &&
!data.split(".")[0].includes("RestAPIAction")
) {
restAPI = data
.split(".")[0]
.replace("RestAPI", "restAPI")
.concat(`.deploy`);
Topic.push(restAPI);
}
} else {
if (data.split(".")[0].includes("requiredType")) {
if (!rest.includes(data.split(".")[1])) {
requiredType = data
.split(".")[0]
.replace("requiredType", "required_type")
.concat(`.${data.split(".")[1]}`);
Topic.push(requiredType);
}
}
if (data.split(".")[0].includes("Entry")) { | {
"domain": "codereview.stackexchange",
"id": 42933,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "javascript, node.js",
"url": null
} |
javascript, node.js
Topic.push(requiredType);
}
}
if (data.split(".")[0].includes("Entry")) {
if (rest.includes(data.split(".")[1])) {
entries = data
.split(".")[0]
.replace("Entry", "entries")
.concat(`.${data.split(".")[1]}`);
Topic.push(entries);
} else {
entries = data
.split(".")[0]
.replace("Entry", "entries")
.concat(`.${data.split(".")[1]}`);
Topic.push(entries);
}
}
if (data.split(".")[0].includes("token")) {
if (rest.includes(data.split(".")[1])) {
token = data
.split(".")[0]
.replace("token", "tokens")
.concat(`.${data.split(".")[1]}`);
Topic.push(token);
} else {
token = data
.split(".")[0]
.replace("token", "tokens")
.concat(`.${data.split(".")[1]}`);
Topic.push(token);
}
}
if (
data.split(".")[0].includes("RestAPI") &&
!data.split(".")[0].includes("RestAPIAction")
) {
restAPI = data
.split(".")[0]
.replace("RestAPI", "restAPI")
.concat(`.deploy`);
Topic.push(restAPI);
}
}
}); | {
"domain": "codereview.stackexchange",
"id": 42933,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "javascript, node.js",
"url": null
} |
javascript, node.js
console.log(Topic);
Is there any possible way I can reduce the code without effecting the output
As the requirement of the code is like if the topicValue contain * or the other value so I wrote this long code and now I am trying to minimize the code so its look short and effective.
Answer: From a short review;
jshint shows zero issues, congratulations ;)
topicsValue should be const
topicsValue could be topicValues
managing entries without a wildcard seems way too complicated
a lot of things are copy-pasted instead of declared once (like the mapping)
a few more things could be const instead of let (rest, final)
Mandatory rewrite;
const topicValues = ['requiredType.*', 'Entry.*', 'token.*', 'RestAPI.*', 'RestAPIAction.Example'];
function createTopics(topicValues){
const basic = ['createInput', 'mustPossible', 'finalOutput'];
const extra = ['required', 'unrequired'];
let topics = [];
const maps = {
requiredType: { to: 'required_type', values: basic },
Entry: { to: 'entries', values: basic.concat(extra) },
token: { to: 'tokens', values: basic.concat(extra) },
RestAPI: { to: 'restAPI', values: ['deploy'] },
}
for(const topicValue of topicValues){
const parts = topicValue.split(".");
const topic = parts[0];
const value = parts[1];
if(value === "*"){
topics = topics.concat(maps[topic].values.map(value=>`${maps[topic].to}.${value}`));
}else{
topics.push(topicValue);
}
}
return topics;
}
console.log(createTopics(topicValues)); | {
"domain": "codereview.stackexchange",
"id": 42933,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "javascript, node.js",
"url": null
} |
python, python-3.x, game, simulation
Title: Plants vs. Zombies simulator
Question: I am making a pvz simulator. We have a game board with 1 = peashooter and 2 = zombie:
[[(1, <__main__.Plant object at 0x0000011F0FDDA4C0>), (2, <__main__.Zombie object at 0x0000011F0F73D100>), 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 0]]
When the peashooter object shoots a pea ten times, the zombie is defeated and disappears. If they are not in the same row or the peashooter is in front of the zombie, the pea has no effect on that particular zombie.
My code:
class Object:
def __init__(self, objtype, row, column, name=None):
self.pos = self.row, self.column = row, column
self.name = name
self.setup = setup
setup[row][column] = (objtype, self)
class Plant(Object):
def __init__(self,row, column, name=None, aoe=1, damage=1):
super().__init__(1, row, column, name)
self.aoe = aoe
self.damage = damage
def shoot(self):
location = self.setup[self.row][self.column]
curr_column = self.column
while True:
try:
if location[0] == 2: # zombie
location[1].hit(self)
return
except IndexError:
pass
try:
location = self.setup[self.row][curr_column]
except IndexError:
return
curr_column += 1
class PlantTypes:
@staticmethod
def peashooter(row, column, name=None):
return Plant(row, column, name)
class Zombie(Object):
def __init__(self, row, column, name=None, health=10):
super().__init__(2, row, column, name)
self.health = health
def hit(self, plant):
self.health -= plant.damage
if self.health <= 0:
setup[self.row][self.column] = 0
class ZombieTypes:
@staticmethod
def basezombie(row, column, name=None):
return Zombie(row, column, name)
setup = [
[0, 0, 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 0]
] | {
"domain": "codereview.stackexchange",
"id": 42934,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, python-3.x, game, simulation",
"url": null
} |
python, python-3.x, game, simulation
setup = [
[0, 0, 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 0]
]
p0 = PlantTypes.peashooter(0, 0)
z0 = ZombieTypes.basezombie(0, 1)
print(setup)
for i in range(10):
p0.shoot()
print(setup)
Any suggestions for readability/performance/other?
Answer: shoot is currently a method on the Plant, but I think this is a mis-allocation of responsibility. The majority of the work in that function is on the grid instead of on the plant. Consider making a grid class, and obligating it with collision work such as shots.
Similarly, having a zombie delete itself from the grid on death (re-death?) is a mis-allocation of responsibility.
The objtype integer is inconvenient to work with and inadequately constrained. Consider just keeping bare references to the object instances instead of type-object tuples in your grid.
Catching IndexError is a code smell and an indication of an incorrect algorithm. This can be avoided with proper iteration.
Your plant and zombie type classes are redundant and can be deleted.
0 as a default entry in your grid doesn't make much sense since you expect all entries to be type-object pairs. A single None would make more sense when the grid is to contain object references only.
Consider adding pretty-print methods to your classes.
Suggested
from numbers import Real
from typing import Optional
class Object:
def __init__(self, row: int, column: int, name: Optional[str] = None) -> None:
self.row, self.column = row, column
self.name = name
class Plant(Object):
def __init__(self, row: int, column: int, name: Optional[str] = None, aoe: Real = 1, damage: Real = 1) -> None:
super().__init__(row, column, name)
self.aoe = aoe
self.damage = damage
def __str__(self) -> str:
return self.name[:3] if self.name else 'pla' | {
"domain": "codereview.stackexchange",
"id": 42934,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, python-3.x, game, simulation",
"url": null
} |
python, python-3.x, game, simulation
def __str__(self) -> str:
return self.name[:3] if self.name else 'pla'
class Zombie(Object):
def __init__(self, row: int, column: int, name: Optional[str] = None, health: Real = 10) -> None:
super().__init__(row, column, name)
self.health = health
def hit(self, damage: Real) -> None:
self.health -= damage
def __str__(self) -> str:
return f'Z{self.health:2d}'
class Grid:
def __init__(self, m: int, n: int) -> None:
self.m, self.n = m, n
self.grid: list[list[Optional[Object]]] = [
[None]*n
for _ in range(m)
]
def add(self, obj: Object) -> None:
self.grid[obj.row][obj.column] = obj
def shoot(self, plant: Plant) -> None:
row = self.grid[plant.row]
for col in range(1+plant.column, self.n):
zombie = row[col]
if isinstance(zombie, Zombie):
zombie.hit(plant.damage)
if zombie.health <= 0:
row[col] = None
break
def describe(self) -> str:
return '\n'.join(
' '.join(
f'{str(o):3s}' if o else ' . '
for o in row
)
for row in self.grid
)
def main() -> None:
grid = Grid(m=3, n=4)
p0 = Plant(row=0, column=0, name='peashooter')
z0 = Zombie(row=0, column=1, name='basezombie')
grid.add(p0)
grid.add(z0)
print(grid.describe())
for _ in range(10):
grid.shoot(p0)
print()
print(grid.describe())
if __name__ == '__main__':
main()
Output
pea Z10 . .
. . . .
. . . .
pea . . .
. . . .
. . . . | {
"domain": "codereview.stackexchange",
"id": 42934,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, python-3.x, game, simulation",
"url": null
} |
strings, parsing, awk
Title: Awk program for extracting unique values from a k1=v1,k2=v2,... list
Question: A single string consisting of comma-separated pairs in the format <key>=<value>, like
ABC=https://host:443/topic1,DEF=https://host:443/topic1,GHI=https://host:443/topic3,JKL=https://host:443/topic3
must be converted to a line containing the unique set (for which the order does not matter) of values, separated by an empty space, i. e.:
https://host:443/topic1 https://host:443/topic3
via an Awk program.
The background idea is to convert one variant of CLI-arguments into another one in a shell script, like:
#!/bin/bash
all_args="ABC=https://host:443/topic1,DEF=https://host1:443/topic1,GHI=https://host:443/topic3,JKL=https://host:443/topic3"
command1 $all_args
command2 $(echo $all_args | awk -f extractor.awk)
The solution:
BEGIN { FS="," }
{
for ( i = 1; i <= NF; i++) {
split($i, arr, "=")
vals[arr[2]] = arr[2]
}
for (v in vals) printf(v " ")
}
Answer: The array values are irrelevant. Instead of
vals[arr[2]] = arr[2]
you could use
vals[arr[2]] = 1
to indicate you're storing flags in vals, and it is the keys that are important later, not the values.
If your input is guaranteed to be "well formed", and you can assume there is exactly one , between each pair, and one = inside each pair, you can separate fields on BOTH the comma and the equals characters. Then you could extract every second field and flag those in your vals set. This eliminates the need for split().
BEGIN { FS="[,=]" }
{
for( i = 2; i <= NF; i += 2) {
vals[$i] = 1
}
for (v in vals) printf(v " ")
} | {
"domain": "codereview.stackexchange",
"id": 42935,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "strings, parsing, awk",
"url": null
} |
algorithm, ruby, stack, balanced-delimiters
Title: Balanced parenthesis in Ruby
Question: I'm solving the "Balanced Parenthesis" problem in Ruby, and I came up with this solution.
def balanced?(string)
return false if string.length.odd?
pairs = { '{' => '}', '[' => ']', '(' => ')' }
string.chars.each_with_object([]) do |bracket, stack|
if pairs.keys.include?(bracket)
stack << bracket
elsif pairs.values.include?(bracket)
return false unless pairs[stack.pop] == bracket
else
return false
end
end
true
end
The first check is for the length of the string: If it's odd, the can't be balanced.
I then iterate over the chars of the string:
If I find an opening bracket, I add it to an array.
If I find a closing bracket, I remove the last element from the array and check if the brackets are a pair.
If I find neither an opening or a closing bracket, the string must be invalid.
Are there any edge cases I'm missing? Also, this doesn't seem efficient: First, there's an added dictionary. Second, there is a linear search on each iteration to check either the keys or the values of the dictionary. There's an \$O(n)\$ on the array resulting from the string, as well, but I'm not sure if we can avoid this.
Answer: To eliminate nested loop you may apply regex checking for invalid symbol from the start -- it would be O(n) + O(n) = O(n):
def balanced? string
return false if string.length.odd?
return false if string =~ /[^\[\]\(\)\{\}]/
pairs = { '{' => '}', '[' => ']', '(' => ')' }
stack = []
string.chars do |bracket|
if expectation = pairs[bracket]
stack << expectation
else
return false unless stack.pop == bracket
end
end
stack.empty?
end | {
"domain": "codereview.stackexchange",
"id": 42936,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "algorithm, ruby, stack, balanced-delimiters",
"url": null
} |
array, swift
Title: Remove duplicates from array of non-equatable objects
Question: I have an array of non-Equatable objects. I want to remove all the duplicates from the array.
class SearchResult { // non-equatable
var index: Int!
var score: Int!
init(_ index: Int, score: Int = 0) {
self.index = index
self.score = score
}
}
var searchResults: [SearchResult] = [SearchResult(0), SearchResult(1), SearchResult(1), SearchResult(2), SearchResult(2)]
searchResults.map { $0.index } gives us: 0, 1, 1, 2, 2
Currently, I do so by mapping the objects' property index, which is equatable, since it's an Int. This way, I can remove the duplicates from the indices array:
let withDupes: [SearchResult] = searchResults
let indices = withDupes.map { $0.index }.removingDuplicates()
For reference, .removingDuplicates() comes from a post on StackOverflow
Note: this is the part I want to be reviewed.
Then, I get the object with the corresponding index by looping through the indices array and add it to the noDupes array.
var noDupes: [SearchResult] = []
indices.forEach { (index) in
guard let notADupe = (withDupes.filter { $0.index == index }).first else { return }
noDupes.append(notADupe)
}
noDupes.map { $0.index } now is: 0, 1, 2
Now, this code works, but it will be executed very often. Since I feel like this is not a very efficient way to remove the duplicates, I fear a performance drop.
How can I improve and / or simplify my code and still successfully remove the duplicates from the array?
Answer: First note that there is no need to make the SearchResult properties (implicitly unwrapped) optionals, as they are always initialized:
class SearchResult { // non-equatable
var index: Int
var score: Int
init(_ index: Int, score: Int = 0) {
self.index = index
self.score = score
}
} | {
"domain": "codereview.stackexchange",
"id": 42937,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "array, swift",
"url": null
} |
array, swift
Your approach is indeed not optimal, after determining a unique set of property
values, the original array must be searched for each value separately. This lookup can be improved slightly by using first(where:)
var noDupes: [SearchResult] = []
indices.forEach { (index) in
guard let notADupe = withDupes.first(where: { $0.index == index }) else { return }
noDupes.append(notADupe)
}
The advantage of first(where:) over filter + first is that it short-circuits and does not create an intermediate array.
But a better and faster solution would be to modify the removingDuplicates()
method so that it compares the array elements according to a given key (which is
then required to be Equatable).
Here is a possible implementation, using the “Smart KeyPath” feature
from Swift 4:
extension Array {
func removingDuplicates<T: Equatable>(byKey key: KeyPath<Element, T>) -> [Element] {
var result = [Element]()
var seen = [T]()
for value in self {
let key = value[keyPath: key]
if !seen.contains(key) {
seen.append(key)
result.append(value)
}
}
return result
}
}
This can then simply be used as
let searchResults: [SearchResult] = [SearchResult(0), SearchResult(1), SearchResult(1), SearchResult(2), SearchResult(2)]
let withoutDuplicates = searchResults.removingDuplicates(byKey: \.index)
It might also be worth to add another specialization for the case that the key is
Hashable (as it is in your example) because then the seen array can be replaced by a set,
which improves the lookup speed from O(N) to O(1):
extension Array {
func removingDuplicates<T: Hashable>(byKey key: KeyPath<Element, T>) -> [Element] {
var result = [Element]()
var seen = Set<T>()
for value in self {
if seen.insert(value[keyPath: key]).inserted {
result.append(value)
}
}
return result
}
} | {
"domain": "codereview.stackexchange",
"id": 42937,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "array, swift",
"url": null
} |
array, swift
Note that if seen.insert(key).inserted does the “test and insert if not present” with a single call.
Another (more flexible) option is to pass a closure to the function which determines
the uniquing key for each element:
extension Array {
func removingDuplicates<T: Hashable>(byKey key: (Element) -> T) -> [Element] {
var result = [Element]()
var seen = Set<T>()
for value in self {
if seen.insert(key(value)).inserted {
result.append(value)
}
}
return result
}
}
Example:
let withoutDuplicates = searchResults.removingDuplicates(byKey: { $0.index }) | {
"domain": "codereview.stackexchange",
"id": 42937,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "array, swift",
"url": null
} |
python, algorithm
Title: Greedy number partitioning algorithm
Question: I have two functions in Python that do the same thing: they partition a set of items of different sizes into a given number of subsets ("bins"), using an algorithm called greedy number partitioning. The algorithm works as follows: it loops over the items from large to small, and puts the next item into a bin that currently contains the smallest total size. The sizes are always positive integers.
Currently, I have two variants of this function. One variant just gets a list of the sizes, and returns a partition of the sizes:
def partition_list(num_of_bins: int, items: list[int]) -> list[list[int]]:
"""
Partition the given items using the greedy number partitioning algorithm.
>>> partition_list(2, [1,2,3,3,5,9,9])
[[9, 5, 2], [9, 3, 3, 1]]
>>> partition_list(3, [1,2,3,3,5,9,9])
[[9, 2], [9, 1], [5, 3, 3]]
"""
bins = [[] for i in range(num_of_bins)]
sums = [0 for i in range(num_of_bins)]
for item in sorted(items, reverse=True):
index_of_least_full_bin = min(
range(num_of_bins), key=lambda i: sums[i]
)
bins[index_of_least_full_bin].append(item)
sums[index_of_least_full_bin] += item
return bins
The other variant gets a dict mapping an item name to its size, and returns a partition of the item names:
def partition_dict(num_of_bins: int, items: dict[str, int]) -> list[list[int]]:
"""
Partition the given items using the greedy number partitioning algorithm. | {
"domain": "codereview.stackexchange",
"id": 42938,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, algorithm",
"url": null
} |
python, algorithm
>>> partition_dict(2, {"a":1, "b":2, "c":3, "d":3, "e":5, "f":9, "g":9})
[['f', 'e', 'b'], ['g', 'c', 'd', 'a']]
>>> partition_dict(3, {"a":1, "b":2, "c":3, "d":3, "e":5, "f":9, "g":9})
[['f', 'b'], ['g', 'a'], ['e', 'c', 'd']]
"""
bins = [[] for i in range(num_of_bins)]
sums = [0 for i in range(num_of_bins)]
pairs_sorted_by_value = sorted(items.items(), key=lambda pair: -pair[1])
for (item, value) in pairs_sorted_by_value:
index_of_least_full_bin = min(
range(num_of_bins), key=lambda i: sums[i]
)
bins[index_of_least_full_bin].append(item)
sums[index_of_least_full_bin] += value
return bins
The algorithm is the same in both cases, so there is a lot of duplicate code. My main goal is to avoid code duplication. How can I write the algorithm once, but still be able to use it in both ways?
One solution I thought of was to write a function that accepts a list of pairs:
def partition_pairs(num_of_bins: int, pairs: list[tuple[str, int]]) -> list[list[int]]:
"""
Partition the given items into bins using the greedy number partitioning algorithm.
>>> partition_pairs(2, [("a",1), ("b",2), ("c",3), ("d",3), ("e",5), ("f",9), ("g",9)])
[['f', 'e', 'b'], ['g', 'c', 'd', 'a']]
>>> partition_pairs(3, [("a",1), ("b",2), ("c",3), ("d",3), ("e",5), ("f",9), ("g",9)])
[['f', 'b'], ['g', 'a'], ['e', 'c', 'd']]
"""
bins = [[] for i in range(num_of_bins)]
sums = [0 for i in range(num_of_bins)]
pairs_sorted_by_value = sorted(pairs, key=lambda pair: -pair[1])
for (item, value) in pairs_sorted_by_value:
index_of_least_full_bin = min(
range(num_of_bins), key=lambda i: sums[i]
)
bins[index_of_least_full_bin].append(item)
sums[index_of_least_full_bin] += value
return bins | {
"domain": "codereview.stackexchange",
"id": 42938,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, algorithm",
"url": null
} |
python, algorithm
And then use it like this:
def partition_list(num_of_bins: int, items: list[int]) -> list[list[int]]:
return partition_pairs(num_of_bins, [(item, item) for item in items])
def partition_dict(num_of_bins: int, items: dict[str, int]) -> list[list[int]]:
return partition_pairs(num_of_bins, items.items())
This solves the code duplication, but it creates a new problem: data duplication. When calling partition_list, the data is duplicated, so that if the input list has 1,000,000 integers, a temporary list with 2,000,000 integers is created.
Is there a way to avoid both code duplication and data duplication?
Answer: The two functions differ mainly in their for-loop lines. Let's start by making
a few cosmetic edits to increase the parallelism: (1) drop the
pairs_sorted_by_value variable; (2) unpack the dict tuple explicitly; and (3)
create a similar unpacking line for the list function.
# partition_list()
for item in sorted(items, reverse=True):
item, value = (item, item)
# partition_dict()
for item in sorted(items.items(), key=lambda pair: -pair[1]):
item, value = item
After those changes, we can clearly see the behavioral differences between
the two functions: they need different sorting logic and different unpacking logic.
Both are easily expressed as lambdas that can be passed to a utility
function that does the actual work. Here's an illustration (minus the
doc-strings and type declarations, purely for brevity here):
def partition_list(num_of_bins, items):
sorter = lambda items: sorted(items, reverse=True)
unpacker = lambda item: (item, item)
return do_partition(num_of_bins, items, sorter, unpacker)
def partition_dict(num_of_bins, items):
sorter = lambda items: sorted(items.items(), key=lambda pair: -pair[1])
unpacker = lambda item: item
return do_partition(num_of_bins, items, sorter, unpacker) | {
"domain": "codereview.stackexchange",
"id": 42938,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, algorithm",
"url": null
} |
python, algorithm
def do_partition(num_of_bins, items, sorter, unpacker):
rng = range(num_of_bins)
bins = [[] for i in rng]
sums = [0 for i in rng]
for item in sorter(items):
item, value = unpacker(item)
# Index of least full bin.
i = min(rng, key = lambda j: sums[j])
bins[i].append(item)
sums[i] += value
return bins
Speaking of brevity, do yourself a favor and drop the onerously long
index_of_least_full_bin variable name. This is a context where
a super-short name (optionally plus a comment) is better, at no loss of readability. In the same spirit, a convenience variable for range(num_of_bins) can further lighten up the code and enhance readability. | {
"domain": "codereview.stackexchange",
"id": 42938,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, algorithm",
"url": null
} |
javascript, algorithm, sorting, unit-testing
Title: Six different, concise (and hopefuly readable), sorting algorithms using ES6+ idioms, with some basic unit testing
Question: I'm practicing js, unit testing, and algorithms, so implementing some of the common sorting algorithms and doing some basic unit testing on them seemed like a good exercise.
I'm also trying to use modern ES6+ features along with longer variable names to make the code more concise, hopefully without sacrificing too much readability. In order to experiment more with this conciseness-readability relationship, I opted for omitting comments altogether.
Please let me know where you think a comment would've made a big difference, and if you see any improvements that can be done to the variable names (along with any observation you have regarding the code in general).
The chosen ones are three from the O(n^2) family, and three from the O(n log n) family:
Bubble Sort
Selection Sort
Insertion Sort
Merge Sort
Heap Sort
Quick Sort
And for unit testing I'm using
Mocha
Chai
Since this project has dependencies and is larger than 100 lines of code, I've created a Github repository for our convenience here. Pull requests welcome!
Here is the code for the sorting algorithms
const bubbleSort = (nums) => {
let sorted = true
for (let loop = 0; loop < nums.length - 1; loop++) {
for (let index = 0; index < nums.length - 1 - loop; index++) {
if (nums[index] > nums[index + 1]) {
[nums[index], nums[index + 1]] = [nums[index + 1], nums[index]]
sorted = false
}
}
if (sorted) break
}
return nums
}
const selectionSort = (nums) => {
for (let pivot = 0; pivot < nums.length - 1; pivot++) {
let min = pivot
for (let swap = pivot + 1; swap < nums.length; swap++) {
if (nums[min] > nums[swap]) {
min = swap
}
}
[nums[pivot], nums[min]] = [nums[min], nums[pivot]]
}
return nums
} | {
"domain": "codereview.stackexchange",
"id": 42939,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "javascript, algorithm, sorting, unit-testing",
"url": null
} |
javascript, algorithm, sorting, unit-testing
[nums[pivot], nums[min]] = [nums[min], nums[pivot]]
}
return nums
}
const insertionSort = (nums) => {
for (let target = 0; target < nums.length; target++) {
let swap = target
while (swap > 0 && nums[swap - 1] > nums[swap]) {
[nums[swap - 1], nums[swap]] = [nums[swap], nums[swap - 1]]
swap--
}
}
return nums
}
const mergeSort = (nums) => {
const merge = (left, right) => {
const merged = []
while (left.length && right.length) {
merged.push(left[0] <= right[0] ? left.shift() : right.shift())
}
return [...merged, ...left, ...right]
}
const splitAndMerge = (array) => {
if (array.length < 2) return array
const mid = array.length / 2
const left = array.slice(0, mid)
const right = array.slice(mid, array.length)
return merge(splitAndMerge(left), splitAndMerge(right))
}
return splitAndMerge(nums)
}
const heapSort = (nums) => {
const heapifySubtree = (size, root) => {
const left = root * 2 + 1
const right = left + 1
let max = root
if (left < size && nums[left] > nums[max]) {
max = left
}
if (right < size && nums[right] > nums[max]) {
max = right
}
if (max !== root) {
[nums[max], nums[root]] = [nums[root], nums[max]]
heapifySubtree(size, max)
}
}
const heapifyArray = () => {
for (let index = Math.floor(nums.length / 2 - 1); index >= 0; index--) {
heapifySubtree(nums.length, index)
}
}
const sort = () => {
heapifyArray()
for (let index = nums.length - 1; index >= 0; index--) {
[nums[0], nums[index]] = [nums[index], nums[0]]
heapifySubtree(index, 0)
}
}
sort()
return nums
}
const quickSort = (nums) => {
if (nums.length < 2) return nums
const pivot = nums[0]
const left = []
const right = []
for (let index = 1; index < nums.length; index++) {
nums[index] < pivot ? left.push(nums[index]) : right.push(nums[index])
} | {
"domain": "codereview.stackexchange",
"id": 42939,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "javascript, algorithm, sorting, unit-testing",
"url": null
} |
javascript, algorithm, sorting, unit-testing
return [...quickSort(left), pivot, ...quickSort(right)]
}
module.exports = {
bubbleSort,
selectionSort,
insertionSort,
mergeSort,
heapSort,
quickSort
}
And here is the code for the unit tests. I'm using Mocha with Chai, but as I understand it, the patterns used are very similar to Jasmine and Jest.
const { expect } = require('chai')
const sorting = require('./sorting-algorithms')
const testSubjects = [
sorting.bubbleSort,
sorting.selectionSort,
sorting.insertionSort,
sorting.mergeSort,
sorting.heapSort,
sorting.quickSort
]
const expectations = (sort) => () => {
expect(sort([])).to.deep.equal([])
expect(sort([7])).to.deep.equal([7])
expect(sort([1, 2, 3, 4])).to.deep.equal([1, 2, 3, 4])
expect(sort([2.3, 1, 0.5, -1.8])).to.deep.equal([-1.8, 0.5, 1, 2.3])
}
const test = (sort) => () =>
it('sorts numeric array', expectations(sort))
const runTestOnSubject = (sort) =>
describe(`Sorting algorithm ${sort.name}`, test(sort))
testSubjects.forEach(runTestOnSubject)
Please share any comment / observation you might have regarding best practices, anti-patterns, efficiency, or style. All code review contexts are very welcome! If you think anything can be improved, in any way, please let me know.
I do have some specific questions you might want to address:
I've used the ternary operator in two occasions. One in mergeSort, and one in quickSort.
merged.push(left[0] <= right[0] ? left.shift() : right.shift()) // mergeSort
nums[index] < pivot ? left.push(nums[index]) : right.push(nums[index]) // quickSort | {
"domain": "codereview.stackexchange",
"id": 42939,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "javascript, algorithm, sorting, unit-testing",
"url": null
} |
javascript, algorithm, sorting, unit-testing
nums[index] < pivot ? left.push(nums[index]) : right.push(nums[index]) // quickSort
Do you think this is hard to understand or follow? Should I've used if else or another pattern to make these more readable? I went for the ternary because I feel like it helps make the code more expressive (say more with less) in these two instances, but if it makes them harder to read it probably isn't worth it.
Did the code suffer too much from the lack of comments? Where do you think a comment would make a big difference?
Do you see variable names that can be improved?
Would you implement any of these algorithms differently, in order to improve the readability or efficiency?
Are the unit tests implemented correctly, and easy to read / follow? Would you have done something differently?
Answer:
insertionSort implementation is suboptimal.
swap > 0 && nums[swap - 1] > nums[swap] does two compares at each iteration (and twice more data moves than necessary). It is possible to get away with only one comparison. Consider
if (nums[0] > nums[swap]) {
// nums[swap] shall land at the beginning of array. We don't care
// about values. Just shift [0, swap) right by one.
temp = nums[swap]
while (swap > 0) {
nums[swap] = nums[swap - 1]
--swap
}
nums[0] = temp
} else {
temp = nums[swap]
// nums[0] is a natural sentinel. Don't bother to test the indices.
while (nums[swap - 1] > temp) {
nums[swap] = nums[swap - 1]
swap--
}
nums[swap] = temp
}
quickSort
The single most significant advantage of a quick sort is that it sorts in-place. The left and right temporaries defeat it. It is not in-place anymore. | {
"domain": "codereview.stackexchange",
"id": 42939,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "javascript, algorithm, sorting, unit-testing",
"url": null
} |
javascript, algorithm, sorting, unit-testing
There are at least two (not so obvious) optimizations.
First, one of the recursive calls is tail-recursive, and can be eliminated. I don't know how good js is in detecting and eliminating tail recursion; anyhow it is a rare case when a programmer may outperform the compiler. Indeed the goal is to minimize the number of recursive calls; we want to recurse only into a smaller partition.
Second, when the partition become small, a cost of recursion overweights its benefits. Consider a cut-off limit k, and don't recurse into a smaller partition. Instead, insertion-sort the array once the recursion phase finishes. Notice that by that time an array is almost sorted: every element is at most k places away from its final destination, so the cost of the insertion-sort phase is \$O(nk)\$. BTW this gives a hint that k shall be in a ballpark of \$\log{n}\$ without hurting a performance. | {
"domain": "codereview.stackexchange",
"id": 42939,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "javascript, algorithm, sorting, unit-testing",
"url": null
} |
javascript, algorithm, node.js
Title: Javascript/Node: Reducing a sorted array of pairs such that the values corresponding to the same key are summed
Question: System/Language: I'm using plain Javascript to write this algorithm. Environment: Node 17.4.0 with a system that has ~7000 MiB of Memory and ~400GB of Storage.
Input Data
An (AoP) Array of Pairs (a Pair is an array of two elements) where the first element of each Pair is a String and the second element is a Number.
The program can ASSUME that the input AoP is sorted in ascending order by the first element of each Pair - the String.
Example of the Input Data
[ ["A", 3], ["A", 2], ["B", 9], ["C", 1], ["C", 2], ["C", 3], ["D", 2], ["E", 0], ["E", 1] ]
Algorithm
Reduce the input AOP such that all Pairs that have the same String element are merged into one pair with the same string. The Number element should be the sum of all Number elements of the Pairs merged.
Example of the Output Data
[ ["A", 5], ["B", 9], ["C", 6], ["D", 2], ["E", 1] ]
Initial Algorithm
I'm more comfortable writing functions in recursive form (coming from a Scheme background) so I quickly came up with the following:
function sumSameKeysSortedRecursive(arr) {
if (arr.length === 0) {
return [];
} else {
let [fst, ...rst] = arr;
let recurAns = sumSameKeysSortedRecursive(rst);
if (recurAns.length === 0) {
return [fst];
} else {
let [f, ...r] = recurAns;
return f[0] === fst[0]
? [[f[0], f[1] + fst[1]], ...r]
: [fst, ...recurAns];
}
}
} | {
"domain": "codereview.stackexchange",
"id": 42940,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "javascript, algorithm, node.js",
"url": null
} |
javascript, algorithm, node.js
However, my input data has 11 million lines and won't scale with the recursive version (even a tail-recursive version won't work on Node). The second version uses loops:
function sumSameKeysSortedLoop(arr) {
let res = [];
let i = 0; // tracks first occurrence a pair with a unique String
let j = 0; // tracks all subsequent occurrences of Pairs with the same String
let len = arr.length;
while (i < len) {
let sum = 0;
let iname = arr[i][0];
let jname = iname;
while (jname === iname) {
sum = sum + arr[j][1];
j++;
if (j === len) { // have reached beyond the array bound
break;
} else {
jname = arr[j][0];
}
}
res.push([iname, sum]);
i = j; // jump over to the new unique element
if (i === len) {
break;
} else {
iname = arr[i][0];
}
}
return res;
}
Possible Improvements?
I think v2 has space for improvement in at least 2 areas:
Readability: In v1, I can read and understand exactly what is happening (can improve it further by adding helper functions), while in v2 a future reader of the code might take more time understanding it. (Could be subjective)
while + break;: Is there an easy way to translate the program such that its functionality stays the same but uses a for-loop instead? Or where it does not use break; (a more general version)? Or where it does not have to keep track of so many variables (i, j, sum, iname, jname)?
Answer: I read your iterative (loop) solution. It's complicated; it's hard to read.
Here's a simplified version of your code.
function merge(aop) {
const sums = [];
if (aop.length === 0) {
return sums;
}
const str = aop[0][0];
let end = sums.push([str, 0]) - 1;
for (const [str, num] of aop) {
if (str === sums[end][0]) {
sums[end][1] += num;
} else {
end = sums.push([str, num]) - 1;
}
}
return sums;
} | {
"domain": "codereview.stackexchange",
"id": 42940,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "javascript, algorithm, node.js",
"url": null
} |
javascript, algorithm, node.js
return sums;
}
const example = [ ["A", 3], ["A", 2], ["B", 9], ["C", 1], ["C", 2], ["C", 3], ["D", 2], ["E", 0], ["E", 1] ];
console.log(merge(example));
[ [ 'A', 8 ], [ 'B', 9 ], [ 'C', 6 ], [ 'D', 2 ], [ 'E', 1 ] ] | {
"domain": "codereview.stackexchange",
"id": 42940,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "javascript, algorithm, node.js",
"url": null
} |
php, strings, regex
Title: Regex to extract portions of string about shipment
Question: The Problem
I'll be extracting up to 4 parts of a String that come from user-input.
All 4 parts need to be in order i.e. (1-4) below in that order
The first capturing group is required and the last few are not.
The named capturing groups are described below
KEY (This can be either CONF|ESD|TRACKING and needs to be followed be either [:;'\s]\*s) -- This group is required
DATA This can be any text except for any of the 2 patterns described below (Should assume multiple whitespace can lead this following KEY
LINE_DATA This is a string in the following kind of format "1,2,3" or "1(2),3(4),5(6)" and should account for spaces in between chars i.e. " 1 ( 2 ) , 3(4 ), 5 6) "
This capture can only come after a match of "L[:';\s]\s*]"...but I don't want to capture this part. I just want to capture the "1(2),3(4)..." part (and exclude any trailing and leading whitespace). LINE_DATA is optional
INITIALS This is the last part of the string and would come before a \s*$. It's a pattern that would be *[a-zA-Z]+ i.e. "*sm", "*jdm", "*pL" should all match. Again...this group can be optional too and I don't want any leading/trailing whitespace.
Note: this is all case-insensitive too.
Examples with expectations
INPUT: "CONF: FEDEX 12345 L: 12(2),2(9),32 *SM"
MATCHES [KEY=>'CONF' , DATA => 'FEDEX 12345', LINE_DATA => '12(2),2(9),32', INITIALS=>'*SM']
INPUT: "ESD: 12/12/92"
MATCHES: [KEY: 'ESD', DATA: '12/12/92']
INPUT: "tRacking' my data L: 1,2,3(4) ";
MATCHES: [KEY=>'tRacking', DATA=>'my data' LINE_DATA: '1,2,3(4)']
My regex is below
/^(?<KEY>CONF|ESD|TRACKING)[:;'\s]\s*(?<DATA>.*?)\s*(?:L[:;'\s]\s*\K(?<LINE_DATA>[\d\s,\(\)]+?))?\s*(?<INITIALS>\*[a-zA-Z]+)?\s*\K$/i
https://regex101.com/r/Sw8UXC/1 is an interactive playground with the regex.
What I'm looking for in review | {
"domain": "codereview.stackexchange",
"id": 42941,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "php, strings, regex",
"url": null
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.