text
stringlengths
1
2.12k
source
dict
python, python-3.x, python-requests, rss science_and_environment Would more UK gas actually bring down prices?: The government is committed to extracting more oil and gas in the North Sea. Climate change risk to coastal castles - English Heritage: Rising sea levels are threatening ancient castles and forts at an accelerating rate, says English Heritage. Climate change: Spike in Amazon emissions linked to law enforcement: Scientists say a huge increase in deforestation in the Amazon is linked to lax law enforcement. Fracking ban lifted, government announces: Scientific review into fracking concludes there is still a limited understanding of impacts. Rural areas hit harder by cost-of-living crisis, study finds: People living in the countryside face higher costs than those in urban areas, a new report finds. Artemis: Nasa's Moon rocket completes fuelling test: The Space Launch System edges closer to a maiden flight after concluding a tanking demonstration. School uniforms in N America linked to PFAS "forever chemicals": A study of school uniforms in the US and Canada shows high levels of chemical substances linked to health issues. Ringed Neptune captured by James Webb telescope: The super space observatory returns spectacular imagery of the Solar System's most distant planet. Prince William 'comforted' by support for his environmental work: He praised the passion of people supporting the Earthshot environmental prize he helped set up. HS2 wins route-length High Court injunction: A judge grants an 'extensive' injunction in order to prevent access without permission to HS2 land or disruption taking place to its construction.
{ "domain": "codereview.stackexchange", "id": 43909, "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, python-requests, rss", "url": null }
python, python-3.x, python-requests, rss politics Kwasi Kwarteng defends massive tax cuts as fair for all: The chancellor has faced criticism for cutting taxes for the wealthy during a cost-of-living crisis. Jeremy Corbyn: Tory economic plan is irresponsible: The former Labour leader says his borrowing would have been for investment not "to pay bankers' bonuses". Now is the time for Starmer to be bold, says union leader: Unite's general secretary predicts senior Labour MPs will soon return to picket lines. Income tax to be cut by 1p from April: The basic rate of income tax will fall by 1p from April with most people paying 19p instead of 20p for each pound. Stamp duty cut in bid to help house buyers: The chancellor says the changes mean 200,000 more house buyers will no longer pay the tax. A not-so-mini-budget: What’s it all about?: The BBC’s Nick Eardley sets out the key headlines from the chancellor’s massive shake-up of the UK’s finances. At a glance: What's in the mini-budget?: Chancellor Kwasi Kwarteng outlines changes to tax, stamp duty and rules for those claiming benefits. Kwasi Kwarteng's mini-budget of tax cuts reward the wealthy, Labour says: Shadow Chancellor Rachel Reeves says the mini-budget is "admission of 12 years of economic failure". Palestinian anger at possible UK Jerusalem embassy move: It comes after the UK PM is said to have told Israel's leader she might relocate it to Jerusalem. Chancellor Kwasi Kwarteng hails 'new era' as he unveils tax cuts: The chancellor announces the biggest tax cuts since 1972 in a significant change of policy.
{ "domain": "codereview.stackexchange", "id": 43909, "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, python-requests, rss", "url": null }
python, python-3.x, python-requests, rss world Ukraine 'referendums': Soldiers go door-to-door for votes in polls: Russia is holding the self-styled referendums in parts of Ukraine it wants to claim control over. Ukraine war: Russia reveals exemptions as men flee call-up: IT workers, bankers and state media reporters will avoid Russia's first draft since World War Two. Iran protests: US to ease internet curbs for Iranians: The move comes after Iran tries to clamp down on internet freedom to stamp out widespread protests. Iran unrest: What's going on with Iran and the internet?: The internet is cutting out and residents are unable to access social media in parts of the country. Magnus Carlsen and Hans Niemann: The cheating row that's blowing up the chess world: Magnus Carlsen's apparent accusation against Hans Niemann is the biggest chess scandal in years. Italian election campaign ends as far right bids for power: Political leaders hold rallies ahead of elections on Sunday that could bring Giorgia Meloni to power. Donors spending millions on Trump's legal battles: The former president's mounting bills are being paid by donors and the Republican party. Goldman Sachs: Sexual assault claims revealed in pay bias suit: Goldman Sachs is accused of "boys' club" culture that discriminated against women. Palestinian anger at possible UK Jerusalem embassy move: It comes after the UK PM is said to have told Israel's leader she might relocate it to Jerusalem. South Korean President Yoon Suk-yeol denies US insult caught on hot mic: Yoon Suk-yeol denies insulting the US Congress after remarks he made were caught on an open mic.
{ "domain": "codereview.stackexchange", "id": 43909, "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, python-requests, rss", "url": null }
python, python-3.x, python-requests, rss health Covid: First rise in infections in UK since July: The largest rise was in secondary school children as the new term started, according to the ONS. Cancer-killing virus shows promise in patients: One man injected with the modified cold sore virus saw his tumour completely disappear. £500m funding to help hospitals discharge patients: The money is part of a package of measures to support NHS and care system this winter, ministers say. Can the NHS learn from Germany’s health system?: Despite public support for the NHS, satisfaction levels have fallen, raising thoughts of reform. Pret a Manger customer had fatal reaction to 'vegan' wrap: Celia Marsh had a severe dairy allergy and ate food labelled as vegan that had traces of milk in it. Many English maternity units not meeting safety standards: More than half of England's maternity units require improvements in safety, BBC analysis finds. BT Group: Hundreds of 999 call handlers to join strikes: Emergency call centre staff will join 40,000 BT workers walking out in October, their union says. NHS waiting list in Wales: Patients turn to surgery abroad: As the waiting list reaches a record 743,000, patients are self-funding treatment in Lithuania. Scotland's A&E waiting times worst on record: Weekly figures show that a record number of A&E patients waited more than four hours. Covid: Oxford oncologist in plea to government over Evusheld: Dr Lennard Lee wants the government to reconsider rolling out Evusheld for people who are immunosuppressed.
{ "domain": "codereview.stackexchange", "id": 43909, "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, python-requests, rss", "url": null }
python, python-3.x, python-requests, rss education Five things to take to university - and one to avoid: Brighten up your accommodation, make friends and save on costs with these handy items. Study finds Cambridge University 'benefited from slavery': A report commissioned by vice-chancellor, Prof Stephen Toope, prompts a raft of recommendations. Cost of living: Students struggling with impact of soaring prices: One student tells the BBC of the isolating effect of running out of cash while studying at university. Free nursery childcare needed as costs rocket, says TUC: Trade union chief Frances O'Grady says soaring nursery fees are causing parents huge stress. Molly Russell's inquest to put focus on big tech: The teenager's inquest begins today and some see it as test of the power of US tech giants. Scotland's largest teachers' union backs strike: EIS members have rejected a 5% pay offer made by local authorities and supported industrial action. School energy support is not enough to solve crisis, Essex head warns: Vic Goddard, the head of four schools in Harlow, Essex, is struggling to sleep due to the situation. Bus catches fire on way to Swavesey Village College: The fire service says "thanks to the fast actions of the driver, the bus was evacuated quickly". Gordonstoun: The Scottish school that educated a king: The decision for the future King Charles to be educated at Gordonstoun was a departure from the royal norm. King Charles III: 'Without Prince's Trust I'd be in prison or dead': The new king set up the charity in 1976 to help young people get jobs, education and training.
{ "domain": "codereview.stackexchange", "id": 43909, "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, python-requests, rss", "url": null }
python, python-3.x, python-requests, rss uk Kwasi Kwarteng defends massive tax cuts as fair for all: The chancellor has faced criticism for cutting taxes for the wealthy during a cost-of-living crisis. Jeremy Corbyn: Tory economic plan is irresponsible: The former Labour leader says his borrowing would have been for investment not "to pay bankers' bonuses". Now is the time for Starmer to be bold, says union leader: Unite's general secretary predicts senior Labour MPs will soon return to picket lines. EuroMillions result: UK ticket-holder wins £171m jackpot: If they are a single player, the win would make them richer than Adele or Ozzy Osbourne. King Charles III's less formal photo as working monarch: He appears in an unconventional official photo which shows him carrying out his head of state duties. Italy 1-0 England: Gareth Southgate's side relegated after Nations League defeat: England are relegated to the Nations League second tier for the first time following defeat by Italy in Milan. Tearful Federer ends career with final match in London: Roger Federer brings the curtain down on his illustrious career by teaming up with fellow great Rafael Nadal on an emotional night in London. Home Secretary Suella Braverman tells police to stop symbolic gestures: The new home secretary writes to police chiefs saying trust has been shattered and calling for change. Laver Cup: Protester sets arm on fire after entering the court: A protester set his arm on fire after running on court and briefly stopping play during the Laver Cup at the O2 Arena in London. Petrol: Supermarkets no longer selling cheapest fuel, RAC says: Some are driving miles searching for cheaper fuel, as research claims small garages are cheaper.
{ "domain": "codereview.stackexchange", "id": 43909, "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, python-requests, rss", "url": null }
python, json, collections Title: Iterating over JSON more effectively Question: Problem: I need to get data from JSON file containing information about "contributors". Each contributor has an atrribute jobs, which is a list of string-like job positions. The program should print five most popular jobs (in the whole dataset) and assign an attribute top_job to each contributor with a job position of his which is the most frequent in the whole dataset. Use of as little extra libraries (excluding json) as possible is needed. I will greatly appreciate if anyone can suggest as to how the program might be improved in terms of efficiency! Thanks in advance! Sample input: [{'username': 'bartonmichelle', ... 'jobs': ['Teacher, special educational needs', 'Water engineer', 'Intelligence analyst', 'Automotive engineer', 'Geoscientist'], 'id': 173012}, {'username': 'ahardin', ... 'jobs': ['Water engineer', 'Private music teacher', 'Administrator', 'Television camera operator'], 'id': 113928}] Sample output: [{'username': 'bartonmichelle', ... 'jobs': ['Teacher, special educational needs', 'Water engineer', 'Intelligence analyst', 'Automotive engineer', 'Geoscientist'], 'id': 173012, 'top_job': 'Water engineer'}, # top job added based on job's frequency {'username': 'ahardin', ... 'jobs': ['Water engineer', 'Private music teacher', 'Administrator', 'Television camera operator'], 'id': 113928, 'top_job': 'Water engineer'}] # top job added based on job's frequency My approach: from collections import Counter jobs = [] with open('contributors_sample.json','r',encoding="utf-8") as f: contributors_file = json.load(f) for contributor in contributors_file: jobs.extend(contributor['jobs']) sorted_jobs = list(map( lambda sorted_arg: sorted_arg[0], sorted( Counter(jobs).items(), key=lambda tupleobj: tupleobj[1], reverse=True ) ))
{ "domain": "codereview.stackexchange", "id": 43910, "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, json, collections", "url": null }
python, json, collections for contributor in contributors_file: contributors_jobs = contributor['jobs'] top_job = contributors_jobs[0] for job in contributors_jobs[1:]: if sorted_jobs.index(job) < sorted_jobs.index(top_job): top_job = job contributor['top_job'] = top_job contributors_file Current execution time: 0.110848s Answer: Much more complicated than it needs to be. You extend a list, then traverse the list to construct a counter, then traverse again to get a sorted sequence, then traverse again to get a list of keys only; this all needs to go away - especially the lambda/map style which is better expressed with comprehensions. Instead, work with your Counter as a first-class citizen. Don't juggle indices. And spend some quality time reading the Counter documentation. Suggested import json from collections import Counter from pprint import pprint with open('contributors_sample.json') as f: contributors_file = json.load(f) jobs = Counter() for contributor in contributors_file: jobs.update(contributor['jobs']) print('Top jobs:', jobs.most_common(5)) for contributor in contributors_file: top_freq, contributor['top_job'] = max( (jobs[job], job) for job in contributor['jobs'] ) pprint(contributors_file) As a more direct and obscure alternative, the top_job assignment can be written as contributor['top_job'] = max( contributor['jobs'], key=jobs.__getitem__, )
{ "domain": "codereview.stackexchange", "id": 43910, "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, json, collections", "url": null }
python, python-3.x Title: Simplify nested list comprehension Question: def parse_names(tex_names: list[str]) -> set[str]: # the list comprehension in question return set(parsed_name for parsed_name in [_parse_name(tex_name) for tex_name in tex_names] if parsed_name) def _parse_name(tex_name: str) -> Optional[str]: tex_regex = re.compile(r"^%? ?([\w() äöüÄÖÜß]+)( \((ab|bis) \d{2}:\d{2} Uhr\))?,") match = tex_regex.match(tex_name) if match: return match.groups()[0] return None with test def test_parse_names(): raw_names = [ "% Valid Name,", " Without percent,", "Without space,", "% Another (valid) name,", "% Max Mustermann (ab 13:00 Uhr),", "% Maxi Mustermann (bis 14:00 Uhr),", "% Mara Musterfrau (von 13:00 Uhr),", # invalid "% Lara Musterfrau von 13:00 Uhr,", # invalid "12345", # invalid "%% some message", # invalid "Missing comma", # invalid ] expected = { "Valid Name", "Without percent", "Without space", "Another (valid) name", "Max Mustermann", "Maxi Mustermann" } actual = parse_names(raw_names) assert actual == expected Is it possible to simplify the list comprehension while maintaining correct typing? E.g. def parse_names(tex_names: list[str]) -> set[str]: return set(_parse_name(tex_name) for tex_name in tex_names if _parse_name(tex_name)) works just fine, but triggers the mypy error error: List comprehension has incompatible type List[Optional[str]]; expected List[str] Answer: Mypy doesn't know that calling _parse_name multiple times will always return the same value if the same value is passed to it. You could try using walrus operator so it uses the value returned specifically for the truthiness check: return set(value for tex_name in tex_names if (value := _parse_name(tex_name)))
{ "domain": "codereview.stackexchange", "id": 43911, "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", "url": null }
python, python-3.x This is also better because it avoids needing to call the function twice. However, since all you're doing is passing each value to a function and checking the returned value's truthiness, you could use map and filter instead: return set(filter(None, map(_parse_name, tex_names)))
{ "domain": "codereview.stackexchange", "id": 43911, "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", "url": null }
python, pyqt Title: Coordinate conversion program using pyqt Question: As an exercise in using PyQt, the Python switch statement and abstract classes, I made a little app to make conversions between geodetic (WGS84) and PSD93 (Oman) and UTM 40N projections (instead of the ubiquitous calculator). The app has a main window and 3 dialog windows; 4 types of conversions (geod_proj), (proj_geod), (proj_proj) and (geod_geod); and input/ out for geodetic coordinates can be either in decimal degrees or DMS. The main and dialog windows designs are made with PyQt designer in XML. Conversions are done in the module convert_tools.py. The main app is given below. I would appreciate a review and feedback. The entire source code is on GitHub. ''' PyQt application for conversion of coordinates for Oman PSD93 projectiom coordinate system (EPSG 3440) @ 2022 howdimain; bruno.vermeulen@hotmail.com ''' import sys from dataclasses import dataclass from abc import ABCMeta, abstractmethod from enum import Enum from pathlib import Path from PyQt5 import uic, QtWidgets from convert_tools import ConvertTools @dataclass class UIInterface: MainWindow: str = 'convert_main.ui' DialogFloatFloat: str = 'convert_dlg_float_float.ui' DialogDMSFloat: str = 'convert_dlg_DMS_float.ui' DialogFloatDMS: str = 'convert_dlg_float_DMS.ui' class ConvertChoice(Enum): wgs84_psd93 = 1 psd93_wgs84 = 2 psd93_utm40 = 3 utm40_psd93 = 4 lon_lat = 5 class FormatChoice(Enum): Degrees = 1 DMS = 2 convert = ConvertTools()
{ "domain": "codereview.stackexchange", "id": 43912, "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, pyqt", "url": null }
python, pyqt class FormatChoice(Enum): Degrees = 1 DMS = 2 convert = ConvertTools() class MainWindow(QtWidgets.QMainWindow): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) uic.loadUi(Path(__file__).parent / getattr(UIInterface, __class__.__name__), self) self.actionQuit.triggered.connect(self.action_quit) self.actionDegrees.triggered.connect(lambda x: self.select_format(FormatChoice.Degrees)) self.actionDMS.triggered.connect(lambda x: self.select_format(FormatChoice.DMS)) self.pb1_wgs84_psd93.clicked.connect(lambda x: self.select_convert(ConvertChoice.wgs84_psd93)) self.pb2_psd93_wgs84.clicked.connect(lambda x: self.select_convert(ConvertChoice.psd93_wgs84)) self.pb3_psd93_utm40.clicked.connect(lambda x: self.select_convert(ConvertChoice.psd93_utm40)) self.pb4_utm40_psd93.clicked.connect(lambda x: self.select_convert(ConvertChoice.utm40_psd93)) self.pb5_lon_lat.clicked.connect(lambda x: self.select_convert(ConvertChoice.lon_lat)) self.dlg_class_proj_proj = DialogFloatFloat self.dlg_class_geog_proj = DialogFloatFloat self.dlg_class_proj_geog = DialogFloatFloat self.dlg_class_geog_geog = DialogFloatDMS def select_format(self, format_choice): match format_choice: case FormatChoice.Degrees: self.actionDegrees.setChecked(True) self.actionDMS.setChecked(False) self.menuFormat.setTitle('Degrees') self.dlg_class_proj_proj = DialogFloatFloat self.dlg_class_geog_proj = DialogFloatFloat self.dlg_class_proj_geog = DialogFloatFloat self.dlg_class_geog_geog = DialogFloatDMS
{ "domain": "codereview.stackexchange", "id": 43912, "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, pyqt", "url": null }
python, pyqt case FormatChoice.DMS: self.actionDegrees.setChecked(False) self.actionDMS.setChecked(True) self.menuFormat.setTitle('DMS') self.dlg_class_proj_proj = DialogFloatFloat self.dlg_class_geog_proj = DialogDMSFloat self.dlg_class_proj_geog = DialogFloatDMS self.dlg_class_geog_geog = DialogDMSFloat case _: assert False, ( f'check {format_choice} in {__class__.__name__} / ' f'{__class__.select_format.__name__}' )
{ "domain": "codereview.stackexchange", "id": 43912, "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, pyqt", "url": null }
python, pyqt def select_convert(self, convert_choice): match convert_choice: case ConvertChoice.wgs84_psd93: dlg = self.dlg_class_geog_proj( self, convert_choice, 'WGS84 to PSD93', 'Longitude', 'Latitude', 'Easting', 'Northing' ) case ConvertChoice.psd93_wgs84: dlg = self.dlg_class_proj_geog( self, convert_choice, 'PSD93 to WGS84', 'Easting', 'Northing', 'Longitude', 'Latitude' ) case ConvertChoice.psd93_utm40: dlg = self.dlg_class_proj_proj( self, convert_choice, 'PSD93 to UTM 40N', 'Easting', 'Northing', 'Easting', 'Northing' ) case ConvertChoice.utm40_psd93: dlg = self.dlg_class_proj_proj( self, convert_choice, 'UTM 40N to PSD93', 'Easting', 'Northing', 'Easting', 'Northing' ) case ConvertChoice.lon_lat: dlg = self.dlg_class_geog_geog( self, convert_choice, 'DMS to Degrees', 'Longitude', 'Latitude', 'Longitude', 'Latitude' ) case _: assert False, ( f'Check {convert_choice} in {__class__.__name__} / ' f'{__class__.select_convert.__name__}' ) dlg.exec_() def action_quit(self): self.close() sys.exit() class QtMixinMeta(type(QtWidgets.QDialog), ABCMeta): pass
{ "domain": "codereview.stackexchange", "id": 43912, "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, pyqt", "url": null }
python, pyqt class QtMixinMeta(type(QtWidgets.QDialog), ABCMeta): pass class DialogMeta(QtWidgets.QDialog, metaclass=QtMixinMeta): def __init__(self, parent, convert_choice, title, input1, input2, output1, output2): super().__init__(parent) uic.loadUi(Path(__file__).parent / getattr(UIInterface, (self.__class__.__name__)), self) self.TitleText.setText(title) self.TextInput_1.setText(input1) self.TextInput_2.setText(input2) self.TextOutput_1.setText(output1) self.TextOutput_2.setText(output2) self.pb_exit.clicked.connect(self.action_exit) self.pb_convert.clicked.connect(lambda x: self.action_convert(convert_choice)) @abstractmethod def action_convert(self, convert_choice): pass def action_exit(self): self.close() class DialogFloatFloat(DialogMeta): def __init__(self, parent, convert_choice, title, input1, input2, output1, output2): super().__init__(parent, convert_choice, title, input1, input2, output1, output2) def action_convert(self, convert_choice): self.lineEditOutput_1.setText('') self.lineEditOutput_2.setText('') try: val1 = float(self.lineEditInput_1.text()) val2 = float(self.lineEditInput_2.text()) except ValueError: return match convert_choice: case ConvertChoice.wgs84_psd93: val1, val2 = convert.wgs84_to_psd93(val1, val2) f_fmt = '.2f' case ConvertChoice.psd93_wgs84: val1, val2 = convert.psd93_to_wgs84(val1, val2) f_fmt = '.6f' case ConvertChoice.psd93_utm40: val1, val2 = convert.psd93_to_utm40n(val1, val2) f_fmt = '.2f' case ConvertChoice.utm40_psd93: val1, val2 = convert.utm40n_to_psd93(val1, val2) f_fmt = '.2f'
{ "domain": "codereview.stackexchange", "id": 43912, "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, pyqt", "url": null }
python, pyqt case _: assert False, f'Check {convert_choice} in {__class__.__name__}' self.lineEditOutput_1.setText(f'{val1:{f_fmt}}') self.lineEditOutput_2.setText(f'{val2:{f_fmt}}') class DialogDMSFloat(DialogMeta): def __init__(self, parent, convert_choice, title, input1, input2, output1, output2): super().__init__(parent, convert_choice, title, input1, input2, output1, output2) def action_convert(self, convert_choice): self.lineEditOutput_1.setText('') self.lineEditOutput_2.setText('') val1 = self.lineEditInput_1.text() val2 = self.lineEditInput_2.text() if self.lineEditInput_2.text() else '0' val3 = self.lineEditInput_3.text() if self.lineEditInput_3.text() else '0' val4 = self.lineEditInput_4.text() val5 = self.lineEditInput_5.text() if self.lineEditInput_5.text() else '0' val6 = self.lineEditInput_6.text() if self.lineEditInput_6.text() else '0' val1 = ''.join([val1, '\u00B0', val2,'\'', val3, '\"', 'E']) val2 = ''.join([val4, '\u00B0', val5,'\'', val6, '\"', 'N']) val1, val2 = convert.convert_dms_to_dec_degree(val1, val2) if val1 == -1 and val2 == -1: return match convert_choice: case ConvertChoice.wgs84_psd93: val1, val2 = convert.wgs84_to_psd93(val1, val2) f_fmt = '.2f' case ConvertChoice.lon_lat: f_fmt = '.6f' case _: assert False, f'Check {convert_choice} in {__class__.__name__}' self.lineEditOutput_1.setText(f'{val1:{f_fmt}}') self.lineEditOutput_2.setText(f'{val2:{f_fmt}}') class DialogFloatDMS(DialogMeta): def __init__(self, parent, convert_choice, title, input1, input2, output1, output2): super().__init__(parent, convert_choice, title, input1, input2, output1, output2)
{ "domain": "codereview.stackexchange", "id": 43912, "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, pyqt", "url": null }
python, pyqt def action_convert(self, convert_choice): self.lineEditOutput_1.setText('') self.lineEditOutput_2.setText('') self.lineEditOutput_3.setText('') self.lineEditOutput_4.setText('') self.lineEditOutput_5.setText('') self.lineEditOutput_6.setText('') self.lineEditOutput_7.setText('') self.lineEditOutput_8.setText('') try: val1 = float(self.lineEditInput_1.text()) val2 = float(self.lineEditInput_2.text()) except ValueError: return match convert_choice: case ConvertChoice.psd93_wgs84: val1, val2 = convert.psd93_to_wgs84(val1, val2) case ConvertChoice.lon_lat: pass case _: assert False, f'Check {convert_choice} in {__class__.__name__}' val1, val2 = convert.convert_dec_degree_to_dms(val1, val2) lon, lat = convert.strip_lon_lat(val1, val2) if lon and lat: self.lineEditOutput_1.setText(f'{float(lon.group(1)):.0f}') self.lineEditOutput_2.setText(f'{float(lon.group(2)):.0f}') self.lineEditOutput_3.setText(f'{float(lon.group(3)):.2f}') self.lineEditOutput_4.setText(f'{lon.group(4)}') self.lineEditOutput_5.setText(f'{float(lat.group(1)):.0f}') self.lineEditOutput_6.setText(f'{float(lat.group(2)):.0f}') self.lineEditOutput_7.setText(f'{float(lat.group(3)):.2f}') self.lineEditOutput_8.setText(f'{lat.group(4)}') def start_app(): app = QtWidgets.QApplication([]) main_window = MainWindow() main_window.show() app.exec_() if __name__ == '__main__': start_app()
{ "domain": "codereview.stackexchange", "id": 43912, "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, pyqt", "url": null }
python, pyqt if __name__ == '__main__': start_app() Answer: The members of UIInterface should all be lower_snake_case, as in main_window. ConvertChoice members can use the auto feature of enum instead of writing out integers. Same for FormatChoice. Isn't getattr(UIInterface, __class__.__name__) just.. the string 'UIInterface'? I think the getattr magic has limited utility. Perhaps the calculation of this path could be moved to a @classmethod on UIInterface. On pb1_wgs84_psd93 etc., rather than lambdas, try setData on the elements for each ConvertChoice and having only one callback. select_format() would be better re-expressed as a dictionary lookup, with all seven of those resulting properties sitting in the dictionary value as a tuple or named tuple. Get rid of your assert False and rely on the indexing operation [] throwing a KeyError if format_choice doesn't make sense. Similar for select_convert. Add PEP484 typehints, especially to things like the signature of DialogFloatFloat.__init__. These join calls: val1 = ''.join([val1, '\u00B0', val2,'\'', val3, '\"', 'E']) val2 = ''.join([val4, '\u00B0', val5,'\'', val6, '\"', 'N']) are better-expressed with string interpolation: val1 = f'{val1}\u00B0{val2}\'{val3}"E'
{ "domain": "codereview.stackexchange", "id": 43912, "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, pyqt", "url": null }
python, linux Title: declarative package manager for Arch Linux Question: pacdef is my declarative package manager for Arch Linux. I have written it since I often found myself discovering a new tool at one of my PCs, using it there for a while, and then missing it when I'm at another PC. So I was looking for a consistent state of software on all my Linux machines. It works like this: In my personal dotfiles repository, I have package files for different use cases, e.g. a file base, for all things that I need unconditionally (editor, kernel, python), a file for all programs that I need for work, etc..., and then a file for each machine (where I have stored, e.g., packages that provide drivers that I only need on one machine). I can pacdef import a file to make pacdef aware of it, then install all packages from it via pacdef sync, remove unmanaged packages via pacdef clean, or review them via pacdef review. More information can be found in the README. Full code here: https://github.com/steven-omaha/pacdef Current HEAD for purposes of this review: 67a9fdb If you run Arch Linux or any of the derivatives, you can install it from the AUR: https://aur.archlinux.org/packages/pacdef Main focus for the review should be the main.py file, which I have pasted below. Of course, all other files can be reviewed as well. Especially, I am interested in: Is there too much overhead? Am I obscuring what's happening somewhere? Are my abstractions appropriate? I recently refactored the main class Pacdef and extracted a couple of functions, since it was doing too much. Would you consider it to be of appropriate scope and size? Code smells I am aware of: There are some tests (like 2 out of 50) I broke during refactoring and are ignored right now since I didn't know yet how to fix those. Those are deactivated. But the program works fine. main.py from __future__ import annotations
{ "domain": "codereview.stackexchange", "id": 43913, "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, linux", "url": null }
python, linux main.py from __future__ import annotations import io import logging import sys from importlib.metadata import version from os import environ from typing import Callable, Optional from .args import Arguments from .aur_helper import AURHelper from .cmd import run from .config import Config from .constants import EXIT_ERROR, EXIT_INTERRUPT, EXIT_SUCCESS, NOTHING_TO_DO, Action from .db import DB from .group import Group from .path import file_exists from .review import Reviewer from .solver import ( calc_packages_to_install, calc_unmanaged_packages, get_groups_matching_arguments, get_managed_packages, ) from .user_input import get_user_confirmation def main(): """Run the main program.""" _setup_logger() args = Arguments() config = Config() helper = AURHelper.from_config(config) db = DB() pacdef = Pacdef(args=args, config=config, aur_helper=helper, db=db) pacdef.run_action_from_arg() def _setup_logger() -> None: """Set up the logger. When the log level is below WARNING (i.e. INFO or DEBUG), the line number of the logging statement is printed as well. """ try: level_name: str = environ["LOGLEVEL"] except KeyError: level_name = "WARNING" level: int = logging.getLevelName(level_name.upper()) if level < logging.WARNING: logging.basicConfig(format="%(levelname)s:%(lineno)d: %(message)s", level=level) else: logging.basicConfig(format="%(levelname)s: %(message)s", level=level) if __name__ == "__main__": try: main() except KeyboardInterrupt: sys.exit(EXIT_INTERRUPT) def _show_version() -> None: """Print version information to STDOUT. The value of `VERSION` is set during compile time by the PKGBUILD using `build()`. """ print(f"pacdef, version: {version('pacdef')}") class Pacdef: """Class representing the main routines of pacdef."""
{ "domain": "codereview.stackexchange", "id": 43913, "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, linux", "url": null }
python, linux class Pacdef: """Class representing the main routines of pacdef.""" def __init__( self, args: Optional[Arguments] = None, config: Optional[Config] = None, aur_helper: Optional[AURHelper] = None, db: Optional[DB] = None, groups: Optional[list[Group]] = None, ): """Save the provided arguments as attributes, or use defaults when none are provided.""" self._conf = config or Config() self._args = args or Arguments() self._aur_helper = aur_helper or AURHelper(self._conf.aur_helper) self._groups: list[Group] = groups or Group.read_groups_from_dir( self._conf.groups_path ) self._db: DB = db or DB() self._sanity_check() @property def _action_map(self) -> dict[Action, Callable[[], None]]: """Return a dict matching all actions to their corresponding Pacdef methods.""" return { Action.clean: self._remove_unmanaged_packages, Action.edit: self._edit_group_file, Action.groups: self._list_groups, Action.import_: self._import_groups, Action.new: self._new_group, Action.remove: self._remove_group, Action.review: self._review, Action.search: self._search_package, Action.show: self._show_group, Action.sync: self._install_packages_from_groups, Action.unmanaged: self._show_unmanaged_packages, Action.version: _show_version, } def _edit_group_file(self) -> None: logging.info("editing group files") groups = get_groups_matching_arguments(self._args, self._groups) if groups is None: logging.error("Could not find a suitable group") sys.exit(EXIT_ERROR) paths = [str(group.path) for group in groups] run([str(self._conf.editor), *paths], check=True)
{ "domain": "codereview.stackexchange", "id": 43913, "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, linux", "url": null }
python, linux def _new_group(self) -> None: if self._args.groups is None: logging.error("Cannot create new group. No name supplied.") exit(EXIT_ERROR) # check if we can create all groups before we actually create them group_names = [g.name for g in self._groups] for group in self._args.groups: if group in group_names: logging.error(f"Cannot create new group '{group}', it already exists.") exit(EXIT_ERROR) for group in self._args.groups: Group.new_file(group, self._conf.groups_path) if self._args.edit_new: self._groups = Group.read_groups_from_dir(self._conf.groups_path) self._edit_group_file() def run_action_from_arg(self) -> None: """Get the function from the provided action arg, execute the function.""" if self._args.action is not None: self._action_map[self._args.action]() def _review(self) -> None: unmanaged = calc_unmanaged_packages( get_managed_packages(self._groups), self._db.get_explicitly_installed_packages(), ) Reviewer(self._groups, unmanaged, self._aur_helper).main() def _remove_unmanaged_packages(self) -> None: """Remove packages not managed by pacdef.
{ "domain": "codereview.stackexchange", "id": 43913, "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, linux", "url": null }
python, linux def _remove_unmanaged_packages(self) -> None: """Remove packages not managed by pacdef. Fetches unmanaged packages, then asks the user to confirm removing the packages. Then removes them using the AUR helper. """ unmanaged_packages = calc_unmanaged_packages( get_managed_packages(self._groups), self._db.get_explicitly_installed_packages(), ) if len(unmanaged_packages) == 0: print(NOTHING_TO_DO) sys.exit(EXIT_SUCCESS) print("Would remove the following packages and their dependencies:") for package in unmanaged_packages: print(f" {package}") try: get_user_confirmation() except io.UnsupportedOperation: pass self._aur_helper.remove(unmanaged_packages) def _list_groups(self): """Print names of the imported groups to STDOUT.""" groups_names = [group.name for group in self._groups] for name in groups_names: print(name) def _import_groups(self) -> None: if self._args.files is None: return for path in self._args.files: link_target = self._conf.groups_path / path.name if file_exists(link_target): logging.warning(f"{path.name} already exists, skipping") else: link_target.symlink_to(path.absolute()) def _remove_group(self) -> None: """Remove the provided groups from the pacdef groups directory. More than one group can be provided. This method is atomic: If not all groups are found, none are removed. """ found_groups = get_groups_matching_arguments(self._args, self._groups) if found_groups is None: logging.error("Could not find a suitable group") sys.exit(EXIT_ERROR) for group in found_groups: group.remove()
{ "domain": "codereview.stackexchange", "id": 43913, "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, linux", "url": null }
python, linux def _search_package(self): """Show imported group which contains `_args.package`. The package name may be a regex. Only one package may be provided in the args. Exits with `EXIT_ERROR` if the package cannot be found. """ if self._args.package is None: logging.error("no search string provided") sys.exit(EXIT_ERROR) matches = [ (group, package) for group in self._groups for package in group if package.matches_regex(self._args.package) ] for group, package in matches: print(f"{group.name}: {package}") if matches: sys.exit(EXIT_SUCCESS) sys.exit(EXIT_ERROR) def _show_group(self) -> None: """Show all packages required by an imported group. More than one group may be provided, which prints the contents of all groups in order. """ found_groups = get_groups_matching_arguments(self._args, self._groups) if found_groups is None: logging.error("Could not find a suitable group") sys.exit(EXIT_ERROR) for group in found_groups: print(group.content) def _install_packages_from_groups(self) -> None: """Install all packages from the imported package groups.""" to_install = calc_packages_to_install( get_managed_packages(self._groups), self._db.get_all_installed_packages() ) if len(to_install) == 0: print(NOTHING_TO_DO) sys.exit(EXIT_SUCCESS) print("Would install the following packages:") for package in to_install: print(f" {package}") try: get_user_confirmation() except io.UnsupportedOperation: pass self._aur_helper.install(to_install)
{ "domain": "codereview.stackexchange", "id": 43913, "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, linux", "url": null }
python, linux def _show_unmanaged_packages(self) -> None: """Print unmanaged packages to STDOUT.""" unmanaged_packages = calc_unmanaged_packages( get_managed_packages(self._groups), self._db.get_explicitly_installed_packages(), ) for package in unmanaged_packages: print(package) def _sanity_check(self) -> None: if self._conf.warn_symlinks: for group in self._groups: if not group.path.is_symlink(): logging.warning(f"group '{group.name}' is not a symlink") Reply to @Reinderien answer Pacdef._action_map must not be cached. It is evaluated exactly once during the runtime of the program. Caching would add overhead without benefits. It also cannot be a class variable AFAIK. If I were to write it like this: class Pacdef: _action_map = { Action.clean: Pacdef._remove_unmanaged_packages, ... } the interpreter cannot figure this out, since the Pacdef class does not exist yet. The only way I found that seemed somewhat idiomatic is making it a property. NOTHING_TO_DO is used 3 times throughout the entire code. I would prefer to keep it that way: If I decide to change the message, I need to only change it in one place. I have pushed some commits that partially implement Reinderien's answer. See here: https://github.com/steven-omaha/pacdef/compare/67a9fdb..6e8d3966bc Answer: Minor: print(f"pacdef, version: {version('pacdef')}") doesn't need formatting, because the default separator for print is a space, thus print('pacdef, version:', version('pacdef'))
{ "domain": "codereview.stackexchange", "id": 43913, "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, linux", "url": null }
python, linux _action_map, as a property, should either be cached or set as a class (i.e. static) variable. In the latter case, the initialisation could be done directly in class scope (not in a method), and the dictionary values would be to non-bound method references instead of bound method references. _new_group calling exit is C-like. Though exit does technically throw an exception, the more idiomatic thing to do here is to throw an exception of your own, for it to be more practically caught by logic above if and when that's called for. Your main already has an except block converting exceptions to exit codes; you can just extend that. group_names should be a set comprehension {} instead of a list comprehension []. NOTHING_TO_DO being saved to a constant is strange. That might be called for if you're doing i18n, but you aren't, so just... write the string literal? This block: if self._args.files is None: return for path in self._args.files: can use a tuple to coalesce and drop the if, as in for path in self._args.files or (): Better yet, change self._args.files to default to that empty tuple instead of None.
{ "domain": "codereview.stackexchange", "id": 43913, "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, linux", "url": null }
python, python-3.x, pygame, snake-game Title: python pygame snake game Question: I used numpy for the O(n) parts, but I didn't add any ability to change grid size because I still wonder if there's a way to make it better than O(n). main.py: import pygame import numpy as np from random import randrange from clickablebox import ClickableBox # values of grid spaces EMPTY = 0 BUG = 1 SNAKE_UP = 2 SNAKE_RIGHT = 3 SNAKE_DOWN = 4 SNAKE_LEFT = 5 GRID_COLORS = ( (200, 200, 200), (65, 163, 23), (255, 243, 128), (255, 243, 128), (255, 243, 128), (255, 243, 128) ) GRID_Y_OFFSET = 20 GRID_X_OFFSET = 20 GRID_HEIGHT = 16 GRID_WIDTH = 16 GRID_SPACE_SIZE = 35 TICKS_BETWEEN_MOVEMENT = 15 # 1 tick is 16 milliseconds
{ "domain": "codereview.stackexchange", "id": 43914, "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, pygame, snake-game", "url": null }
python, python-3.x, pygame, snake-game class Game: def __init__(self): # numpy used instead of list for self.available_bug_spaces because it needs to find and to remove values, which is O(n) self.available_bug_spaces = None self.grid = [] self.tail = (0, 0) self.head = (0, 0) def setup_game(self): # setting up lists self.available_bug_spaces = np.arange(GRID_HEIGHT * GRID_WIDTH, dtype=np.uint64) self.grid.clear() for _ in range(GRID_HEIGHT): self.grid.append([EMPTY] * GRID_WIDTH) # setting initial snake spaces mid_y = GRID_HEIGHT // 2 mid_x = GRID_WIDTH // 2 for x in range(mid_x, mid_x + 5): self.grid[mid_y][x] = SNAKE_LEFT self.available_bug_spaces = np.delete(self.available_bug_spaces, range((mid_y * GRID_WIDTH) + mid_x, (mid_y * GRID_WIDTH) + mid_x + 5)) self.place_bug() self.head = (mid_y, mid_x) self.tail = (mid_y, x) def place_bug(self): # I can't figure out how to make this part better than O(n) if len(self.available_bug_spaces) == 0: return (-1, -1) # player won available_bug_spaces_index = randrange(len(self.available_bug_spaces)) available_bug_spaces_value = self.available_bug_spaces[available_bug_spaces_index] bug_y, bug_x = int(available_bug_spaces_value) // GRID_WIDTH, int(available_bug_spaces_value) % GRID_WIDTH self.available_bug_spaces = np.delete(self.available_bug_spaces, (available_bug_spaces_index,)) self.grid[bug_y][bug_x] = BUG return (bug_y, bug_x) def get_next_coord(self, coord, direction): vertical_change, horizontal_change = ((-1, 0), (0, 1), (1, 0), (0, -1))[direction - SNAKE_UP] return (coord[0] + vertical_change, coord[1] + horizontal_change) def move_forward_no_bug(self, next_head_coord, head_direction):
{ "domain": "codereview.stackexchange", "id": 43914, "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, pygame, snake-game", "url": null }
python, python-3.x, pygame, snake-game def move_forward_no_bug(self, next_head_coord, head_direction): old_tail_coord = self.tail tail_direction = self.grid[self.tail[0]][self.tail[1]] next_tail_coord = self.get_next_coord(self.tail, tail_direction) self.grid[self.tail[0]][self.tail[1]] = 0 self.grid[self.head[0]][self.head[1]] = head_direction self.grid[next_head_coord[0]][next_head_coord[1]] = head_direction # switch out new head position with old tail position # I can't figure out how to make this part better than O(n) self.available_bug_spaces[np.where(self.available_bug_spaces == (next_head_coord[0] * GRID_WIDTH) + next_head_coord[1])[0][0]] = (self.tail[0] * GRID_WIDTH) + self.tail[1] self.head = next_head_coord self.tail = next_tail_coord return self.head, old_tail_coord def move_forward_eat_bug(self, next_head_coord, head_direction): self.grid[self.head[0]][self.head[1]] = head_direction self.grid[next_head_coord[0]][next_head_coord[1]] = head_direction bug_coord = self.place_bug() self.head = next_head_coord return self.head, bug_coord
{ "domain": "codereview.stackexchange", "id": 43914, "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, pygame, snake-game", "url": null }
python, python-3.x, pygame, snake-game class GUI: def __init__(self): self.win = pygame.display.set_mode((1200, 700)) self.font = pygame.font.Font(pygame.font.get_default_font(), 30) self.start_button = ClickableBox(self.win, self.font, "start", (1105, 515), (1090, 480), (100, 100)) self.quit_button = ClickableBox(self.win, self.font, "quit", (1110, 625), (1090, 590), (100, 100)) self.start_button.draw() self.quit_button.draw() self.menu_drawn = True def toggle_menu_screen(self): self.set_message("") if self.menu_drawn: # this means the menu is currently drawn self.start_button.undraw() self.menu_drawn = False else: pygame.draw.rect(self.win, (0, 0, 0), (GRID_X_OFFSET, GRID_Y_OFFSET, GRID_SPACE_SIZE * GRID_WIDTH, GRID_SPACE_SIZE * GRID_HEIGHT)) # undrawing grid self.start_button.draw() self.menu_drawn = True def set_message(self, message): pygame.draw.rect(self.win, (0, 0, 0), (150, 600, 940, 100)) text_surface = self.font.render(message, True, (50, 50, 50)) self.win.blit(text_surface, (150, 650)) def draw_grid(self, grid): for y in range(GRID_HEIGHT): for x in range(GRID_WIDTH): pygame.draw.rect(self.win, GRID_COLORS[grid[y][x]], (GRID_X_OFFSET + (x * GRID_SPACE_SIZE), GRID_Y_OFFSET + (y * GRID_SPACE_SIZE), GRID_SPACE_SIZE, GRID_SPACE_SIZE)) def draw_coords(self, grid, coords): for coord in coords: pygame.draw.rect(self.win, GRID_COLORS[grid[coord[0]][coord[1]]], (GRID_X_OFFSET + (coord[1] * GRID_SPACE_SIZE), GRID_Y_OFFSET + (coord[0] * GRID_SPACE_SIZE), GRID_SPACE_SIZE, GRID_SPACE_SIZE))
{ "domain": "codereview.stackexchange", "id": 43914, "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, pygame, snake-game", "url": null }
python, python-3.x, pygame, snake-game def wait_for_unpause(gui): while True: pygame.time.wait(16) pygame.display.update() events = pygame.event.get() for event in events: if event.type == pygame.QUIT: return False, False elif event.type == pygame.MOUSEBUTTONUP and event.button == 1 and gui.quit_button.clicked(pygame.mouse.get_pos()): return False, True elif event.type == pygame.KEYDOWN and event.key == pygame.K_p: return True, True def wait_for_input(gui): while True: pygame.time.wait(16) pygame.display.update() events = pygame.event.get() for event in events: if ( (event.type == pygame.MOUSEBUTTONUP and event.button == 1 and gui.quit_button.clicked(pygame.mouse.get_pos())) or event.type == pygame.KEYDOWN or event.type == pygame.QUIT ): return event.type != pygame.MOUSEBUTTONUP, pygame.MOUSEBUTTONUP != pygame.QUIT
{ "domain": "codereview.stackexchange", "id": 43914, "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, pygame, snake-game", "url": null }
python, python-3.x, pygame, snake-game def play_game(game, gui): gui.set_message("") ticks_since_last_movement = 0 direction = None current_head_direction = game.grid[game.head[0]][game.head[1]] while True: pygame.time.wait(16) pygame.display.update() ticks_since_last_movement += 1 events = pygame.event.get() for event in events: if event.type == pygame.QUIT: return False, False elif event.type == pygame.MOUSEBUTTONUP and event.button == 1 and gui.quit_button.clicked(pygame.mouse.get_pos()): return False, True elif event.type == pygame.KEYDOWN: if (event.key == pygame.K_UP or event.key == pygame.K_w) and current_head_direction != SNAKE_DOWN: direction = SNAKE_UP elif (event.key == pygame.K_RIGHT or event.key == pygame.K_d) and current_head_direction != SNAKE_LEFT: direction = SNAKE_RIGHT elif (event.key == pygame.K_DOWN or event.key == pygame.K_s) and current_head_direction != SNAKE_UP: direction = SNAKE_DOWN elif (event.key == pygame.K_LEFT or event.key == pygame.K_a) and current_head_direction != SNAKE_RIGHT: direction = SNAKE_LEFT elif event.key == pygame.K_p: ticks_since_last_movement = 0 gui.set_message("paused") keep_playing, keep_running = wait_for_unpause(gui) if not keep_playing or not keep_running: return keep_playing, keep_running gui.set_message("") if direction is not None or ticks_since_last_movement == TICKS_BETWEEN_MOVEMENT: if direction is None: direction = game.grid[game.head[0]][game.head[1]] ticks_since_last_movement = 0 next_head_y, next_head_x = game.get_next_coord(game.head, direction)
{ "domain": "codereview.stackexchange", "id": 43914, "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, pygame, snake-game", "url": null }
python, python-3.x, pygame, snake-game next_head_y, next_head_x = game.get_next_coord(game.head, direction) if not 0 <= next_head_y < GRID_HEIGHT or not 0 <= next_head_x < GRID_WIDTH or SNAKE_UP <= game.grid[next_head_y][next_head_x] <= SNAKE_LEFT: gui.set_message("you lose, press any key to reset") return wait_for_input(gui) if game.grid[next_head_y][next_head_x] == EMPTY: head, old_tail = game.move_forward_no_bug((next_head_y, next_head_x), direction) gui.draw_coords(game.grid, (head, old_tail)) else: head, bug_coord = game.move_forward_eat_bug((next_head_y, next_head_x), direction) if bug_coord == (-1, -1): gui.set_message("you win, press any key to reset") return wait_for_input(gui) gui.draw_coords(game.grid, (head, bug_coord)) current_head_direction = game.grid[game.head[0]][game.head[1]] direction = None
{ "domain": "codereview.stackexchange", "id": 43914, "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, pygame, snake-game", "url": null }
python, python-3.x, pygame, snake-game def main(): pygame.init() pygame.display.set_caption("snake game") game = Game() gui = GUI() keep_running = True while keep_running: pygame.time.wait(16) pygame.display.update() events = pygame.event.get() for event in events: if event.type == pygame.QUIT: keep_running = False elif event.type == pygame.MOUSEBUTTONUP and event.button == 1: if gui.quit_button.clicked(pygame.mouse.get_pos()): keep_running = False elif gui.start_button.clicked(pygame.mouse.get_pos()): gui.toggle_menu_screen() keep_playing = True while keep_playing: game.setup_game() gui.set_message("press any key to start") gui.draw_grid(game.grid) pygame.display.update() keep_playing, keep_running = wait_for_input(gui) if keep_playing: keep_playing, keep_running = play_game(game, gui) gui.toggle_menu_screen() pygame.quit() if __name__ == "__main__": main() clickablebox.py (TextEntryBox not used in this): import pygame
{ "domain": "codereview.stackexchange", "id": 43914, "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, pygame, snake-game", "url": null }
python, python-3.x, pygame, snake-game clickablebox.py (TextEntryBox not used in this): import pygame class ClickableBox: def __init__(self, win, font, text, text_location, box_location, dimensions): self.font = font self.text = text self.text_location = text_location self.box_location = box_location self.dimensions = dimensions self.win = win self.box = None def draw(self, color=(150, 150, 150)): self.box = pygame.draw.rect(self.win, color, (*self.box_location, *self.dimensions)) text_surface = self.font.render(self.text, True, (50, 50, 50)) self.win.blit(text_surface, self.text_location) def undraw(self): pygame.draw.rect(self.win, (0, 0, 0), (*self.box_location, *self.dimensions)) self.box = None def clicked(self, coords): return self.box is not None and self.box.collidepoint(coords) class TextEntryBox(ClickableBox): def __init__(self, win, font, text, text_location, box_location, dimensions, typing_location, max_text): super().__init__(win, font, text, text_location, box_location, dimensions) self.typing_location = typing_location self.max_text = max_text self.box_text = "" def draw(self, text, color=(150, 150, 150)): super().draw(color) text = str(text)[:self.max_text] typing_surface = self.font.render(text, True, (70, 70, 70)) self.win.blit(typing_surface, self.typing_location) self.box_text = text def undraw(self): upper_left_undraw_box = (self.box_location[0], self.text_location[1]) undraw_box_dimensions = (self.dimensions[0], self.dimensions[1] + (self.box_location[1] - self.text_location[1])) pygame.draw.rect(self.win, (0, 0, 0), (*upper_left_undraw_box, *undraw_box_dimensions)) self.box = None
{ "domain": "codereview.stackexchange", "id": 43914, "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, pygame, snake-game", "url": null }
python, python-3.x, pygame, snake-game Answer: Notice that, directly after construction, Game is unusable and requires a call to setup_game. You also have one Game instance that's reused via multiple setup_game calls that each trample the contents of the class. To fix these issues, and to deter harmful state mutation, on the inside of your main() loop just construct a game instance each time. Merge your setup code into the constructor. Add PEP484 type hints to your function signatures. I can't figure out how to make this part better than O(n) The O(n) comes from your np.delete. I'm not convinced that there's a very good role for Numpy in this application, especially for available_bug_spaces. The first instinct is to use a built-in set to represent your available_bug_spaces; this will have amortised O(1) membership test, insertion and deletion. But this comes with an asterisk: if you try to random.sample() on the set, this is now deprecated; if you try it now you will see something like DeprecationWarning: Sampling from a set deprecated since Python 3.9 and will be removed in a subsequent version. Read e.g. random.choice from set? and its links. Since your grid is only 16x16, efficiency is not that big a deal, so it's almost certainly not worth implementing an exotic data structure for this purpose. You could do worse than to Use a built-in set of available coordinates When moving normally, all operations will be O(1) amortised When placing a new bug, cast to a tuple to random.choice() on it; this will be O(n) but is relatively rare so it makes sense to eat the cost here
{ "domain": "codereview.stackexchange", "id": 43914, "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, pygame, snake-game", "url": null }
python, python-3.x, numpy, audio, scipy Title: Python decibel meter-accurate? Question: import os, errno import pyaudio from scipy.signal import lfilter import numpy from tkinter import * from tkinter.ttk import * from tk_tools import * from tkinter import messagebox root=Tk() root.title('Decibel Meter') root.grid() gaugedb = RotaryScale(root, max_value=120.0, unit=' dBA') gaugedb.grid(column=1, row=1) led = Led(root, size=50) led.grid(column=3, row=1) led.to_red(on=False) Label(root, text='Too Loud').grid(column=3, row=0) Label(root, text='Max').grid(column=2, row=0) Label(root, text='Calibration (dB)').grid(column=4, row=0) maxdb_display=SevenSegmentDigits(root, digits=3, digit_color='#00ff00', background='black') maxdb_display.grid(column=2, row=1) CHUNKS = [4096, 9600] CHUNK = CHUNKS[1] FORMAT = pyaudio.paInt16 CHANNEL = 1 RATES = [44300, 48000] RATE = RATES[1] offset=StringVar() offset.set('0') spinbox=Spinbox(root, from_=-20, to=20, textvariable=offset, state='readonly') spinbox.grid(column=4, row=1) appclosed=False from scipy.signal import bilinear def close(): global appclosed root.destroy() appclosed=True stream.stop_stream() stream.close() pa.terminate() def A_weighting(fs): f1 = 20.598997 f2 = 107.65265 f3 = 737.86223 f4 = 12194.217 A1000 = 1.9997
{ "domain": "codereview.stackexchange", "id": 43915, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, python-3.x, numpy, audio, scipy", "url": null }
python, python-3.x, numpy, audio, scipy NUMs = [(2*numpy.pi * f4)**2 * (10**(A1000/20)), 0, 0, 0, 0] DENs = numpy.polymul([1, 4*numpy.pi * f4, (2*numpy.pi * f4)**2], [1, 4*numpy.pi * f1, (2*numpy.pi * f1)**2]) DENs = numpy.polymul(numpy.polymul(DENs, [1, 2*numpy.pi * f3]), [1, 2*numpy.pi * f2]) return bilinear(NUMs, DENs, fs) NUMERATOR, DENOMINATOR = A_weighting(RATE) def rms_flat(a): return numpy.sqrt(numpy.mean(numpy.absolute(a)**2)) pa = pyaudio.PyAudio() stream = pa.open(format = FORMAT, channels = CHANNEL, rate = RATE, input = True, frames_per_buffer = CHUNK) def update_max_if_new_is_larger_than_max(new, max): if new > max: return new else: return max def listen(old=0, error_count=0, min_decibel=100, max_decibel=0): global appclosed while True: try: try: block = stream.read(CHUNK) except IOError as e: if not appclosed: error_count += 1 messagebox.showerror("Error, ", " (%d) Error recording: %s" % (error_count, e)) else: decoded_block = numpy.fromstring(block, numpy.int16) y = lfilter(NUMERATOR, DENOMINATOR, decoded_block) new_decibel = 20*numpy.log10(rms_flat(y))+int(offset.get()) old = new_decibel gaugedb.set_value(float('{:.2f}'.format(new_decibel))) max_decibel = update_max_if_new_is_larger_than_max(new_decibel, max_decibel) maxdb_display.set_value(str(int(float(str(max_decibel))))) if new_decibel>85: led.to_red(on=True) else: led.to_red(on=False) root.update() except TclError: break root.protocol('WM_DELETE_WINDOW', close) listen() Is this an accurate dBA meter? My code works fine, but I want to check if it actually mirrors the ambient sound level from the microphone.
{ "domain": "codereview.stackexchange", "id": 43915, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, python-3.x, numpy, audio, scipy", "url": null }
python, python-3.x, numpy, audio, scipy Answer: Indent your code with a PEP8-compliant IDE or linter; it's a perfect mess right now. Move your global code into functions and maybe classes. There are two good use cases for classes here - one for a GUI and one for an audio processor. offset must not be a StringVar, but instead an IntVar - among other reasons this will obviate the cast in int(offset.get()). Do not leave it nameless and do not leave it orphaned; its parent needs to be the root object. Move your import of bilinear up to join your other imports. Your imports should avoid import *; that makes a vast swamp out of the global namespace and it doesn't need to be like that. Traditionally numpy is aliased to np. Consider writing a context manager to close off your audio stream. numpy.absolute(a)**2 is just a**2, right? Delete update_max_if_new_is_larger_than_max. This is just a call to the built-in max(). Rather than if new_decibel>85: led.to_red(on=True) else: led.to_red(on=False) just move the boolean expression to the argument of a single call and delete the if. Add PEP484 typehints. Convert your lists in A_weighting into immutable tuples. Listen to the warnings being told to you: your use of np.fromstring needs to be replaced with np.frombuffer. str(int(float(str(max_decibel)))) is just... majestic. Use a formatting string instead. As @Seb comments, 44300 should almost certainly be 44100. polymul is deprecated. Use Polynomial instead. An equivalent to rms_flat is the more integrated and maybe faster np.linalg.norm(a) / np.sqrt(len(a)) which, based on the linalg source, further reduces to a self-dot-product: np.sqrt(a.dot(a) / len(a)) Suggested import tkinter as tk import numpy as np import pyaudio import tk_tools from numpy.polynomial import Polynomial from scipy.signal import bilinear, lfilter CHUNKS = [4096, 9600] CHUNK = CHUNKS[1] FORMAT = pyaudio.paInt16 CHANNEL = 1 RATES = [44100, 48000] RATE = RATES[1]
{ "domain": "codereview.stackexchange", "id": 43915, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, python-3.x, numpy, audio, scipy", "url": null }
python, python-3.x, numpy, audio, scipy def A_weighting(fs: float) -> tuple[np.ndarray, np.ndarray]: f1 = 20.598997 f2 = 107.65265 f3 = 737.86223 f4 = 12194.217 a1000 = 1.9997 nums = Polynomial(((2*np.pi * f4)**2 * 10**(a1000 / 20), 0,0,0,0)) dens = ( Polynomial((1, 4*np.pi * f4, (2*np.pi * f4)**2)) * Polynomial((1, 4*np.pi * f1, (2*np.pi * f1)**2)) * Polynomial((1, 2*np.pi * f3)) * Polynomial((1, 2*np.pi * f2)) ) return bilinear(nums.coef, dens.coef, fs) def rms_flat(a: np.ndarray) -> float: return np.sqrt(a.dot(a) / len(a)) class Meter: def __init__(self) -> None: self.pa = pyaudio.PyAudio() self.stream = self.pa.open( format=FORMAT, channels=CHANNEL, rate=RATE, input=True, frames_per_buffer=CHUNK, ) self.numerator, self.denominator = A_weighting(RATE) self.max_decibel = 0 def __enter__(self) -> 'Meter': return self def __exit__(self, exc_type, exc_val, exc_tb) -> None: self.stream.stop_stream() self.stream.close() self.pa.terminate() def listen(self, offset: int) -> float: block = self.stream.read(CHUNK) decoded_block = np.frombuffer(block, dtype=np.int16) y = lfilter(self.numerator, self.denominator, decoded_block) new_decibel = 20*np.log10(rms_flat(y)) + offset self.max_decibel = max(self.max_decibel, new_decibel) return new_decibel class GUI: def __init__(self, meter: Meter) -> None: self.meter = meter self.root = root = tk.Tk() root.title('Decibel Meter') root.grid() root.protocol('WM_DELETE_WINDOW', self.close) self.app_closed = False self.gaugedb = tk_tools.RotaryScale(root, max_value=120, unit=' dBA') self.gaugedb.grid(column=1, row=1) self.led = tk_tools.Led(root, size=50) self.led.grid(column=3, row=1) self.led.to_red(on=False)
{ "domain": "codereview.stackexchange", "id": 43915, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, python-3.x, numpy, audio, scipy", "url": null }
python, python-3.x, numpy, audio, scipy tk.Label(root, text='Too Loud').grid(column=3, row=0) tk.Label(root, text='Max').grid(column=2, row=0) tk.Label(root, text='Calibration (dB)').grid(column=4, row=0) self.maxdb_display = tk_tools.SevenSegmentDigits(root, digits=3, digit_color='#00ff00', background='black') self.maxdb_display.grid(column=2, row=1) self.offset = tk.IntVar(root, value=0, name='offset') spinbox = tk.Spinbox(root, from_=-20, to=20, textvariable=self.offset, state='readonly') spinbox.grid(column=4, row=1) def close(self) -> None: self.app_closed = True def run(self) -> None: while not self.app_closed: new_decibel = self.meter.listen(self.offset.get()) self.update(new_decibel, self.meter.max_decibel) self.root.update() def update(self, new_decibel: float, max_decibel: float) -> None: self.gaugedb.set_value(np.around(new_decibel, 1)) self.maxdb_display.set_value(f'{max_decibel:.1f}') self.led.to_red(on=new_decibel > 85) def main() -> None: with Meter() as meter: gui = GUI(meter) gui.run() if __name__ == '__main__': main() Output Layout Your layout needs a little love. Since the gauge text is at the bottom, why not put all labels at the bottom? Add some padding for legibility's sake, and add some resize sanity. Unfortunately, in addition to missing variable support, tk_tools widgets seem to have a broken layout behaviour because they ignore sticky resize requests; but oh well: import tkinter as tk import numpy as np import pyaudio import tk_tools from numpy.polynomial import Polynomial from scipy.signal import bilinear, lfilter CHUNKS = [4096, 9600] CHUNK = CHUNKS[1] FORMAT = pyaudio.paInt16 CHANNEL = 1 RATES = [44100, 48000] RATE = RATES[1] def A_weighting(fs: float) -> tuple[np.ndarray, np.ndarray]: f1 = 20.598997 f2 = 107.65265 f3 = 737.86223 f4 = 12194.217 a1000 = 1.9997
{ "domain": "codereview.stackexchange", "id": 43915, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, python-3.x, numpy, audio, scipy", "url": null }
python, python-3.x, numpy, audio, scipy nums = Polynomial(((2*np.pi * f4)**2 * 10**(a1000 / 20), 0,0,0,0)) dens = ( Polynomial((1, 4*np.pi * f4, (2*np.pi * f4)**2)) * Polynomial((1, 4*np.pi * f1, (2*np.pi * f1)**2)) * Polynomial((1, 2*np.pi * f3)) * Polynomial((1, 2*np.pi * f2)) ) return bilinear(nums.coef, dens.coef, fs) def rms_flat(a: np.ndarray) -> float: return np.sqrt(a.dot(a) / len(a)) class Meter: def __init__(self) -> None: self.pa = pyaudio.PyAudio() self.stream = self.pa.open( format=FORMAT, channels=CHANNEL, rate=RATE, input=True, frames_per_buffer=CHUNK, ) self.numerator, self.denominator = A_weighting(RATE) self.max_decibel = 0 def __enter__(self) -> 'Meter': return self def __exit__(self, exc_type, exc_val, exc_tb) -> None: self.stream.stop_stream() self.stream.close() self.pa.terminate() def listen(self, offset: int) -> float: block = self.stream.read(CHUNK) decoded_block = np.frombuffer(block, dtype=np.int16) y = lfilter(self.numerator, self.denominator, decoded_block) new_decibel = 20*np.log10(rms_flat(y)) + offset self.max_decibel = max(self.max_decibel, new_decibel) return new_decibel class GUI: def __init__(self, meter: Meter) -> None: self.meter = meter self.root = root = tk.Tk() root.title('Decibel Meter') root.grid() root.grid_rowconfigure(index=0, weight=1) root.grid_rowconfigure(index=1, weight=1) root.grid_columnconfigure(index=0, weight=1) root.grid_columnconfigure(index=3, weight=1) root.protocol('WM_DELETE_WINDOW', self.close) self.app_closed = False
{ "domain": "codereview.stackexchange", "id": 43915, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, python-3.x, numpy, audio, scipy", "url": null }
python, python-3.x, numpy, audio, scipy self.gaugedb = tk_tools.RotaryScale(root, max_value=120, unit=' dBA') # This control does not respect resizing via tk.NSEW. self.gaugedb.grid(row=0, column=0, rowspan=2, sticky=tk.E) self.maxdb_display = tk_tools.SevenSegmentDigits(root, digits=3, digit_color='#00ff00', background='black') self.maxdb_display.grid(row=0, column=1, sticky=tk.S, padx=5) tk.Label(root, text='Max').grid(row=1, column=1, sticky=tk.N, padx=5) self.led = tk_tools.Led(root, size=50) self.led.to_red(on=False) self.led.grid(row=0, column=2, sticky=tk.S, padx=5) tk.Label(root, text='Too Loud').grid(row=1, column=2, sticky=tk.N, padx=5) self.offset = tk.IntVar(root, value=0, name='offset') spinbox = tk.Spinbox(root, from_=-20, to=20, textvariable=self.offset, state='readonly', width=12) spinbox.grid(row=0, column=3, sticky=tk.SW, padx=5) tk.Label(root, text='Calibration (dB)').grid(row=1, column=3, sticky=tk.NW, padx=5) def close(self) -> None: self.app_closed = True def run(self) -> None: while not self.app_closed: new_decibel = self.meter.listen(self.offset.get()) self.update(new_decibel, self.meter.max_decibel) self.root.update() def update(self, new_decibel: float, max_decibel: float) -> None: self.gaugedb.set_value(np.around(new_decibel, 1)) self.maxdb_display.set_value(f'{max_decibel:.1f}') self.led.to_red(on=new_decibel > 85) def main() -> None: with Meter() as meter: gui = GUI(meter) gui.run() if __name__ == '__main__': main()
{ "domain": "codereview.stackexchange", "id": 43915, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, python-3.x, numpy, audio, scipy", "url": null }
python, beginner, python-3.x, tic-tac-toe Title: Tic-Tac-Toe Code Question: I'm a beginner in Python programming, been doing it for only a few weeks and I decided to make a tic-tac-toe game in the Python interpreter. I'm looking for feedback on the program and any way I can improve it and shorten it and point out inefficiencies/errors since I've done everything I can to get rid of all errors I could think of. I would appreciate if it was advice useful to my level and not all about high-level Python code, though I wouldn't mind some of it if its a very useful concept to use in this program and others. Here's the code: print("Welcome to the game of tic-tac-toe, you know how to play, so go on and have fun!") print("Just know that the positions to input are of the form: ") print("| 1 | 2 | 3 |") print("| 4 | 5 | 6 |") print("| 7 | 8 | 9 |") p1, p2, p3, p4, p5, p6, p7, p8, p9 = " ", " ", " ", " ", " ", " ", " ", " ", " " # p stands #for "position", so p1 means position 1, p2 means #position 2 etc. game_playout = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i'] # the letters are placeholders #until the real game starts, after which each letter #will be chronologically replaced with a #0 or a 1, 0 representing 'o' and 1 representing 'x' won = 0 count = 0 x_pos = None o_pos = None used_positions = [ ] def win_check(): if game_playout[0] == game_playout[1] == game_playout[2]: return 1 elif game_playout[3] == game_playout[4] == game_playout[5]: return 1 elif game_playout[6] == game_playout[7] == game_playout[8]: return 1 elif game_playout[0] == game_playout[3] == game_playout[6]: return 1 elif game_playout[0] == game_playout[4] == game_playout[8]: return 1 elif game_playout[1] == game_playout[4] == game_playout[7]: return 1 elif game_playout[2] == game_playout[5] == game_playout[8]: return 1 elif game_playout[2] == game_playout[4] == game_playout[6]: return 1
{ "domain": "codereview.stackexchange", "id": 43916, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, beginner, python-3.x, tic-tac-toe", "url": null }
python, beginner, python-3.x, tic-tac-toe def layout_changer(): global p1, p2, p3, p4, p5, p6, p7, p8, p9 if x_pos == 1: p1 = "x" elif x_pos == 2: p2 = "x" elif x_pos == 3: p3 = "x" elif x_pos == 4: p4 = "x" elif x_pos == 5: p5 = "x" elif x_pos == 6: p6 = "x" elif x_pos == 7: p7 = "x" elif x_pos == 8: p8 = "x" elif x_pos == 9: p9 = "x" if o_pos == 1: p1 = "o" elif o_pos == 2: p2 = "o" elif o_pos == 3: p3 = "o" elif o_pos == 4: p4 = "o" elif o_pos == 5: p5 = "o" elif o_pos == 6: p6 = "o" elif o_pos == 7: p7 = "o" elif o_pos == 8: p8 = "o" elif o_pos == 9: p9 = "o" while won != 1: x_pos = input("Choose your position to place x (1 to 9) ") while not x_pos.isnumeric(): print("Error! Looks like you've haven't entered a number, please try again!") x_pos = input("Choose your position to place x (1 to 9) ") x_pos = int(x_pos) while x_pos not in [1, 2, 3, 4, 5, 6, 7, 8, 9] or x_pos in used_positions: print(f"| {p1} | {p2} | {p3} |") print(f"| {p4} | {p5} | {p6} |") print(f"| {p7} | {p8} | {p9} |") print("Invalid position! Please try another value:") x_pos = int(input("Choose your position to place x (1 to 9) ")) used_positions.append(x_pos) count += 1 game_playout.pop(x_pos - 1) game_playout.insert(x_pos - 1, 1) # We replace the (x_pos-1)th index element in game_playout with 1,where 1 indicates an 'x' layout_changer() print(f"| {p1} | {p2} | {p3} |") print(f"| {p4} | {p5} | {p6} |") print(f"| {p7} | {p8} | {p9} |")
{ "domain": "codereview.stackexchange", "id": 43916, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, beginner, python-3.x, tic-tac-toe", "url": null }
python, beginner, python-3.x, tic-tac-toe won = win_check() if won == 1: print("x has won! Congratulations!") print() print("Thank you for playing the game! Hope you enjoyed!") quit() elif count >= 9: print() print("Draw!") print("Thank you for playing the game! Hope you enjoyed!") quit() o_pos = input("Choose your position to place o (1 to 9) ") while not o_pos.isnumeric(): print("Error! Looks like you've haven't entered a number, please try again!") o_pos = input("Choose your position to place o (1 to 9) ") o_pos = int(o_pos) while o_pos not in [1, 2, 3, 4, 5, 6, 7, 8, 9] or o_pos in used_positions: print(f"| {p1} | {p2} | {p3} |") print(f"| {p4} | {p5} | {p6} |") print(f"| {p7} | {p8} | {p9} |") print("Invalid position! Please try another value:") o_pos = int(input("Choose your position to place o (1 to 9) ")) used_positions.append(o_pos) count += 1 game_playout.pop(o_pos - 1) game_playout.insert(o_pos - 1, 0) # We replace the (o_pos-1)th index element in game_playout with 0,where 0 indicates an 'o' layout_changer() print(f"| {p1} | {p2} | {p3} |") print(f"| {p4} | {p5} | {p6} |") print(f"| {p7} | {p8} | {p9} |") won = win_check() if won == 1: print("o has won! Congratulations!") print() print("Thank you for playing the game! Hope you enjoyed!") Answer: Where to start… tuple assignment p1, p2, p3, p4, p5, p6, p7, p8, p9 = " ", " ", " ", " ", " ", " ", " ", " ", " " Is that the correct number of " "? Did you count? Of course you did, and yes it is the correct number since tuple assignment will generate an exception if a mismatch occurs. But, you don’t need to type, or count; just use tuple multiplication/replication: p1, p2, p3, p4, p5, p6, p7, p8, p9 = (" ",) * 9
{ "domain": "codereview.stackexchange", "id": 43916, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, beginner, python-3.x, tic-tac-toe", "url": null }
python, beginner, python-3.x, tic-tac-toe pop/insert This code is very obtuse and obfuscated: game_playout.pop(x_pos - 1) game_playout.insert(x_pos - 1, 1) # We replace the (x_pos-1)th index element in game_playout with 1,where 1 indicates an 'x' You are popping (removing) an element, and then inserting a new element at the same position. A lot of busy work moving elements backwards in the list for the pop, and then moving them forward again during the insert. Instead, you could simply write: game_playout[x_pos - 1] = 1 # Replace the (x_pos-1)th element with 1, indicating an 'x' WET -vs- DRY Why do you Write Everything Twice (WET)? Don’t Repeat Yourself (DRY)! You have this code several times: print(f"| {p1} | {p2} | {p3} |") print(f"| {p4} | {p5} | {p6} |") print(f"| {p7} | {p8} | {p9} |")
{ "domain": "codereview.stackexchange", "id": 43916, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, beginner, python-3.x, tic-tac-toe", "url": null }
python, beginner, python-3.x, tic-tac-toe You should move it into a function. You’ve demonstrated you know how to use them already. Return Type Consistency win_check() will return either an integer 1, or it doesn’t return anything at all, so it implicitly returns None. That makes it hard to reason about. You can’t say it returns an int, nor can you say it returns a bool. In the code which calls win_check(), you've ended up with if won == 1, and while won != 1 which are opaque conditions. What does won == 1 mean? Would won == 2 mean player 2 has won? Is won == 0 a draw game, or game not over yet? It isn't obvious. In actuality, won == 0 before the first move is made, and suddenly becomes won == None afterwards, until someone wins. Very confusing. The function should return a boolean True or False. Instead of return 1, use return True. At the end, add an explicit return False. Lists -vs- Sets You have the list used_positions recording which moves have been made, and append moves to it, and test pos in used_positions to ensure moves aren’t repeated. The correct data structure to use for this would be a set. used_positions = set() ... while ... or x_pos in used_positions: ... used_position.add(x_pos) ... Using sets reduces the search time of x_pos in used_positions to \$O(1)\$ … effectively constant time, instead of the \$O(N)\$ time of searching a list. But … Three Different versions of the Same Thing You have game_playout representing the played positions for determining a win condition. You have used_positions for recording which moves have been played, to prevent repeats, and p1, p2, … p9 for displaying which positions have been played by which player. These are all the same thing! Or they should be! Consider: grid = [" "] * 9
{ "domain": "codereview.stackexchange", "id": 43916, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, beginner, python-3.x, tic-tac-toe", "url": null }
python, beginner, python-3.x, tic-tac-toe That creates a list of length 9, with each element containing a space. Perfect for displaying the tic-tac-toe grid: def print_grid(): print(f"| {grid[0]} | {grid[1]} | {grid[2]} |") print(f"| {grid[3]} | {grid[4]} | {grid[5]} |") print(f"| {grid[6]} | {grid[7]} | {grid[8]} |") Or slightly more compactly, as: def print_grid(): print(("| {} | {} | {} |\n" "| {} | {} | {} |\n" "| {} | {} | {} |").format(*grid)) Note: There are no commas between the above strings, so Python automatically concatenates them into one long string containing 9 {} format codes. The *grid explodes the elements of the grid list into individual arguments for the .format() function. As moves are made, the grid can be filled in with x and o values: grid[x_pos - 1] = 'x' ... grid[o_pos - 1] = 'o' … which eliminates the ugly mess called layout_changer(). The used_positions check becomes simply testing if the spot is not “empty”: while ... or grid[x_pos - 1] != " ": ... Finally, win_check() needs to be fixed so it doesn’t declare 3 spaces in a row as a winning combination: def win_check(): if grid[0] == grid[1] == grid[2] != ' ': return True elif grid[3] == grid[4] == grid[5] != ' ': return True … return False Draw You determine a draw by maintaining a count and checking if it reaches 9. This can again be another variant of the grid. The game is a draw if nobody won and no valid moves remain. No valid moves remain means grid contains no empty cells. elif " " not in grid: # draw game
{ "domain": "codereview.stackexchange", "id": 43916, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, beginner, python-3.x, tic-tac-toe", "url": null }
python, beginner, python-3.x, tic-tac-toe No more counting required. Don’t quit! Avoid quit(). Never ever call it, as it exits the Python interpreter. This makes testing nigh impossible, since tests are usually written in Python, and don’t get a chance to declare pass or failure if the Python interpreter vanishes before they can determine the pass/fail state! Instead, move the mainline code into a function, and simple return from the function instead of calling quit(). X/O The X player and O player code is virtually identical. Different variables are used (x_pos -vs- o_pos) but these could be replaced with just pos eliminating that difference. Then the only difference is the message printed, and the code that is assigned to the given position. If the code is the same, it too can be moved into a function. def player_move(symbol): pos = input(f"Choose your position to place {symbol} (1 to 9) ") while not pos.isnumeric(): print("Error! Looks like you've haven't entered a number, please try again!") pos = input(f"Choose your position to place {symbol} (1 to 9) ") pos = int(pos) while pos not in [1, 2, 3, 4, 5, 6, 7, 8, 9] or grid[pos - 1] != " ": print_grid() print("Invalid position! Please try another value:") pos = int(input(f"Choose your position to place {symbol} (1 to 9) ")) grid[pos - 1] = symbol
{ "domain": "codereview.stackexchange", "id": 43916, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, beginner, python-3.x, tic-tac-toe", "url": null }
python, beginner, python-3.x, tic-tac-toe grid[pos - 1] = symbol Avoid Global variables At this point, it should be obvious the only global variable left is grid. This could simply be passed to the various functions as an argument, eliminating the last global variable. Why are global variables bad? In 150 lines, you have 15 global variables. Which functions can change a global variable? Which functions use global variables? These are hard questions. If you expand your code to 1500 lines, say to add a TkInter GUI interface for your game, are you going to end up with 150 global variables? Now reasoning about which functions use and change which variables becomes even harder. Another question: what variables do you need to reset if you wanted to play a second game? What if you wanted to player against the computer, and you'd like the computer to "think" about playing various moves to try and play smarter. Currently you have to make a tentative move, evaluate it, then "undo" the move to explore another possibility. If you used local variables, you could make a copy of the game state to try out a move, and then discard it; nothing to "undo". Reworked code Here is a reworking of your code, using the above points. The code has gone from 150 lines to 74. I've introduced a few extra concepts for you to study try...except..., import itertools, any(...) and all(...). Hopefully, these are not too far beyond your current level, so you find them understandable. import itertools BLANK = ' ' X = 'x' O = 'o' WINNING_ROWS = ( (0, 1, 2), (3, 4, 5), (6, 7, 8), # rows (0, 3, 6), (1, 4, 7), (2, 5, 8), # columns (0, 4, 8), (2, 4, 6), # diagonals ) def print_grid(grid): print("| {} | {} | {} |\n" "| {} | {} | {} |\n" "| {} | {} | {} |".format(*grid)) def win_check(grid, symbol) -> bool: return any(all(grid[index] == symbol for index in row) for row in WINNING_ROWS)
{ "domain": "codereview.stackexchange", "id": 43916, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, beginner, python-3.x, tic-tac-toe", "url": null }
python, beginner, python-3.x, tic-tac-toe def player_move(grid, symbol): while True: try: pos = input(f"Choose your position to place {symbol} (1 to 9): ") pos = int(pos) - 1 if pos not in range(9): print("Error! Looks like you've entered an invalid position, please try again!") elif grid[pos] != BLANK: print("Error! Looks like you've entered a filled position, please try again!") else: break except ValueError: print("Error! Looks like you've haven't entered a number, please try again!") grid[pos] = symbol print_grid(grid) def game(): grid = [BLANK] * 9 print_grid(grid) symbols = itertools.cycle((X, O)) while any(cell == BLANK for cell in grid): symbol = next(symbols) player_move(grid, symbol) if win_check(grid, symbol): print(f"{symbol} has won! Congratulations!") break else: print("Draw!") print() print("Thank you for playing the game! Hope you enjoyed!") def main(): print("Welcome to the game of tic-tac-toe, you know how to play, so go on and have fun!") print("Just know that the positions to input are of the form: ") print("| 1 | 2 | 3 |") print("| 4 | 5 | 6 |") print("| 7 | 8 | 9 |") print() game() if __name__ == '__main__': main()
{ "domain": "codereview.stackexchange", "id": 43916, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, beginner, python-3.x, tic-tac-toe", "url": null }
c#, asp.net-core, asp.net-web-api, .net-core, asp.net-core-webapi Title: Export and import work items from Azure DevOps Question: I'm working on an application that exports and imports work items from Azure DevOps. To import work items into Azure DevOps, I have written the following code. Would you be able to review and make suggestions? I'm unsure whether I've used the Async-Await pattern correctly. namespace Export_Import_AzureDevOps.Factory { public class ImportFactory : IImportFactory { private ConcurrentDictionary<int, int> idMapper = new ConcurrentDictionary<int, int>(); private readonly ILogger<ImportFactory> _logger; private readonly Devops _devopsConfiguration; private readonly IImportService<WorkItemCore> _importWorkItemService; private readonly IImportService<SprintCore> _importSprintService; public ImportFactory(ILogger<ImportFactory> logger, IConfiguration configuration, IImportService<SprintCore> importSprintService, IImportService<WorkItemCore> importWorkItemService) { _logger = logger; _devopsConfiguration = configuration.GetSection(nameof(Devops)).Get<Devops>(); _importSprintService = importSprintService; _importWorkItemService = importWorkItemService; } private void PublishSprints(string id) { var sprintPublishURL = $"{_devopsConfiguration.Target.ProjectId}/{_devopsConfiguration.Target.TargetTeamId}/_apis/work/teamsettings/iterations?api-version={_devopsConfiguration.APIVersion}"; var jsonPublishSprintString = $@"{{""id"":""{id}""}}"; HttpContent publishSprintContent = new StringContent(jsonPublishSprintString, Encoding.UTF8, "application/json"); _importSprintService.Post(sprintPublishURL, publishSprintContent).ConfigureAwait(false); }
{ "domain": "codereview.stackexchange", "id": 43917, "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#, asp.net-core, asp.net-web-api, .net-core, asp.net-core-webapi", "url": null }
c#, asp.net-core, asp.net-web-api, .net-core, asp.net-core-webapi private Task CreateSprints(Sprints sprints) { var sprintCreationURL = $"{_devopsConfiguration.Target.ProjectId}/_apis/wit/classificationNodes/Iterations?api-version={_devopsConfiguration.APIVersion}"; foreach (Sprint sprint in sprints.value) { var jsonString = JsonConvert.SerializeObject(sprint); HttpContent content = new StringContent(jsonString, Encoding.UTF8, "application/json"); var result = _importWorkItemService.Post(sprintCreationURL, content).Result; PublishSprints(result.identifier); } return Task.CompletedTask; } private int GetCurrentIdEquivalentId(int oldId) { return idMapper[oldId]; } private void TryAddIdMapper(int oldId, int newId) { if (!idMapper.ContainsKey(oldId)) { idMapper.TryAdd(oldId, newId); } } private int FindParentId(WorkItemDetails workItemDetails) { var parentId = 0; if (workItemDetails.relations != null) { var parentRelation = workItemDetails.relations.Where(relation => relation.attributes.name.Equals("Parent")).FirstOrDefault(); if (parentRelation != null) { parentId = Int32.Parse(parentRelation.url.Split("/")[parentRelation.url.Split("/").Length - 1]); } } return parentId; } private void CreateWorkItem(string url, WorkItem workItem) { List<WorkItemOperation> operations = new List<WorkItemOperation>(); var parentId = FindParentId(workItem.details);
{ "domain": "codereview.stackexchange", "id": 43917, "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#, asp.net-core, asp.net-web-api, .net-core, asp.net-core-webapi", "url": null }
c#, asp.net-core, asp.net-web-api, .net-core, asp.net-core-webapi operations.Add( new WorkItemOperation() { path = "/fields/System.Title", value = workItem.details.fields.Title ?? string.Empty } ); operations.Add( new WorkItemOperation() { path = "/fields/System.Description", value = workItem.details.fields.Description ?? string.Empty } ); operations.Add( new WorkItemOperation() { path = "/fields/Microsoft.VSTS.Common.AcceptanceCriteria", value = workItem.details.fields.AcceptanceCriteria ?? string.Empty } ); operations.Add( new WorkItemOperation() { path = "/fields/System.IterationPath", value = workItem.details.fields.IterationPath.Replace(_devopsConfiguration.Source.ProjectName, _devopsConfiguration.Target.ProjectName) } ); if (parentId != 0) { operations.Add( new WorkItemOperation() { path = "/relations/-", value = new Relationship() { url = $"{_devopsConfiguration.Target.DevOpsOrgURL}{_devopsConfiguration.Target.ProjectId}/_apis/wit/workitems/{GetCurrentIdEquivalentId(parentId)}", attributes = new RelationshipAttribute() } } ); }
{ "domain": "codereview.stackexchange", "id": 43917, "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#, asp.net-core, asp.net-web-api, .net-core, asp.net-core-webapi", "url": null }
c#, asp.net-core, asp.net-web-api, .net-core, asp.net-core-webapi var jsonString = JsonConvert.SerializeObject(operations); HttpContent content = new StringContent(jsonString, Encoding.UTF8, "application/json-patch+json"); var result = _importWorkItemService.Post(url, content).Result; TryAddIdMapper(workItem.id, result.id); } private Task CreateWorkItems(Dictionary<string, WorkItemQueryResult> workItemCollection) { foreach (var workItemCategory in workItemCollection.Keys) { var url = $"{_devopsConfiguration.Target.ProjectId}/_apis/wit/workitems/%24{workItemCategory}?api-version={_devopsConfiguration.APIVersion}"; foreach (var workItem in workItemCollection[workItemCategory].workItems) { CreateWorkItem(url, workItem); } } return Task.CompletedTask; } public async Task<Board> Import(IFormFile file) { string fileContent = null; using (var reader = new StreamReader(file.OpenReadStream())) { fileContent = reader.ReadToEnd(); } var board = JsonConvert.DeserializeObject<Board>(fileContent); await CreateSprints(board.sprints); await CreateWorkItems(board.workItemCollection); return board; } } } Answer: Url handling Rather than recreating some URLs over and over again you can define them only once and use them multiple times: ... private readonly string _versionQueryString; private readonly string _sprintCreationURL; private readonly string _sprintPublishURL; private const string WorkItemPathPrefix = "/fields/"; public ImportFactory(...) { ...
{ "domain": "codereview.stackexchange", "id": 43917, "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#, asp.net-core, asp.net-web-api, .net-core, asp.net-core-webapi", "url": null }
c#, asp.net-core, asp.net-web-api, .net-core, asp.net-core-webapi public ImportFactory(...) { ... _versionQueryString = $"?api-version={_devopsConfiguration.APIVersion}"; _sprintCreationURL = $"{_devopsConfiguration.Target.ProjectId}/_apis/wit/classificationNodes/Iterations{_versionQueryString}"; _sprintPublishURL = $"{_devopsConfiguration.Target.ProjectId}/{_devopsConfiguration.Target.TargetTeamId}/_apis/work/teamsettings/iterations{_versionQueryString}"; } public methods It is a good practice to start with your public methods after the constructors continue with private/protected methods that are used inside the public methods finish with the helper methods that are used inside the non public facing methods //Ctor public ImportFactory(...) //Public public async Task<Board> Import(IFormFile file) //Private/Protected private async Task CreateSprints(Sprints sprints) private async Task CreateWorkItems(Dictionary<string, WorkItemQueryResult> workItems) private async Task CreateWorkItem(string categoryURL, WorkItem workItem) //Helpers private int FindParentId(WorkItemDetails details) private HttpContent GetJsonContent(object data, string mimeType = "application/json") Import method You can use the using declaration since C# 8 to simplify your code You can also use the ReadToEndAsync method of the StreamReader to take advantage of non-blocking I/O public async Task<Board> Import(IFormFile file) { using var reader = new StreamReader(file.OpenReadStream()); string fileContent = await reader.ReadToEndAsync(); var board = JsonConvert.DeserializeObject<Board>(fileContent); await CreateSprints(board.sprints); await CreateWorkItems(board.workItemCollection); return board; } CreateSprints method There is no need for the PublishSprints method, since the whole can be simplified to a single line await _importSprintService.Post(_sprintPublishURL, GetJsonContent(new { id = result.identifier }));
{ "domain": "codereview.stackexchange", "id": 43917, "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#, asp.net-core, asp.net-web-api, .net-core, asp.net-core-webapi", "url": null }
c#, asp.net-core, asp.net-web-api, .net-core, asp.net-core-webapi await _importSprintService.Post(_sprintPublishURL, GetJsonContent(new { id = result.identifier })); Since the Post is an async method you should await it The GetJsonContent helper method looks like this private HttpContent GetJsonContent(object data, string mediaType = "application/json") { var jsonString = JsonConvert.SerializeObject(data); return new StringContent(jsonString, Encoding.UTF8, mediaType); } After all of these modifications the CreateSprints looks like this private async Task CreateSprints(Sprints sprints) { foreach (Sprint sprint in sprints.value) { var result = await _importWorkItemService.Post(_sprintCreationURL, GetJsonContent(sprint)); await _importSprintService.Post(_sprintPublishURL, GetJsonContent(new { id = result.identifier })); } } I'm not sure whether this _importWorkItemService.Post(_sprintCreationURL, GetJsonContent(sprint) should be called on _importWorkItemService or on _importSprintService Without knowing the actual implementation I can't tell but it is likely a bug in your code CreateWorkItems method Since CreateWorkItem should be an async method (see next section) that's why this should be async as well I've renamed your workItemCollection to workItems since you had a sprints parameter in CreateSprints private async Task CreateWorkItems(Dictionary<string, WorkItemQueryResult> workItems) { foreach (var workItemCategory in workItems.Keys) { var categoryURL = $"{_devopsConfiguration.Target.ProjectId}/_apis/wit/workitems/%24{workItemCategory}{_versionQueryString}"; foreach (var workItem in workItems[workItemCategory].workItems) { await CreateWorkItem(categoryURL, workItem); } } } CreateWorkItem method The GetCurrentIdEquivalentId and TryAddIdMapper can be inlined since they are not complex and they are used only inside the CreateWorkItem method once You can use the collection initializer to populate your operations List
{ "domain": "codereview.stackexchange", "id": 43917, "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#, asp.net-core, asp.net-web-api, .net-core, asp.net-core-webapi", "url": null }
c#, asp.net-core, asp.net-web-api, .net-core, asp.net-core-webapi var operations = new List<WorkItemOperation> { new WorkItemOperation() { path = $"{WorkItemPathPrefix}System.Title", value = workItem.details.fields.Title ?? "" }, new WorkItemOperation() { path = $"{WorkItemPathPrefix}System.Description", value = workItem.details.fields.Description ?? "" }, new WorkItemOperation() { path = $"{WorkItemPathPrefix}Microsoft.VSTS.Common.AcceptanceCriteria", value = workItem.details.fields.AcceptanceCriteria ?? "" }, new WorkItemOperation() { path = $"{WorkItemPathPrefix}System.IterationPath", value = workItem.details.fields.IterationPath.Replace(_devopsConfiguration.Source.ProjectName, _devopsConfiguration.Target.ProjectName) } }; Please prefer await over .Result await _importWorkItemService.Post(categoryURL, GetJsonContent(operations, "application/json-patch+json")); FindParentId method This can be simplified by using the ?. and ?: operators private int FindParentId(WorkItemDetails details) { var parentRelation = details.relations?.Where(relation => relation.attributes.name.Equals("Parent")).FirstOrDefault(); return parentRelation == null ? 0 : int.Parse(parentRelation.url.Split("/")[parentRelation.url.Split("/").Length - 1]); } Please note that the int.Parse is error-prone, please prefer int.TryParse instead For the sake of completeness here is the full code after refactoring class ImportFactory : IImportFactory { private ConcurrentDictionary<int, int> idMapper = new ConcurrentDictionary<int, int>(); private readonly ILogger<ImportFactory> _logger; private readonly Devops _devopsConfiguration; private readonly IImportService<WorkItemCore> _importWorkItemService; private readonly IImportService<SprintCore> _importSprintService;
{ "domain": "codereview.stackexchange", "id": 43917, "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#, asp.net-core, asp.net-web-api, .net-core, asp.net-core-webapi", "url": null }
c#, asp.net-core, asp.net-web-api, .net-core, asp.net-core-webapi private readonly string _versionQueryString; private readonly string _sprintCreationURL; private readonly string _sprintPublishURL; private readonly string _projectId; private const string WorkItemPathPrefix = "/fields/"; public ImportFactory(ILogger<ImportFactory> logger, IConfiguration configuration, IImportService<SprintCore> importSprintService, IImportService<WorkItemCore> importWorkItemService) { _logger = logger; _devopsConfiguration = configuration.GetSection(nameof(Devops)).Get<Devops>(); _importSprintService = importSprintService; _importWorkItemService = importWorkItemService; _versionQueryString = $"?api-version={_devopsConfiguration.APIVersion}"; _projectId = _devopsConfiguration.Target.ProjectId; _sprintCreationURL = $"{_projectId}/_apis/wit/classificationNodes/Iterations{_versionQueryString}"; _sprintPublishURL = $"{_projectId}/{_devopsConfiguration.Target.TargetTeamId}/_apis/work/teamsettings/iterations{_versionQueryString}"; } public async Task<Board> Import(IFormFile file) { using var reader = new StreamReader(file.OpenReadStream()); string fileContent = await reader.ReadToEndAsync(); var board = JsonConvert.DeserializeObject<Board>(fileContent); await CreateSprints(board.sprints); await CreateWorkItems(board.workItemCollection); return board; } private async Task CreateSprints(Sprints sprints) { foreach (Sprint sprint in sprints.value) { var result = await _importWorkItemService.Post(_sprintCreationURL, GetJsonContent(sprint)); await _importSprintService.Post(_sprintPublishURL, GetJsonContent(new { id = result.identifier })); } }
{ "domain": "codereview.stackexchange", "id": 43917, "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#, asp.net-core, asp.net-web-api, .net-core, asp.net-core-webapi", "url": null }
c#, asp.net-core, asp.net-web-api, .net-core, asp.net-core-webapi private async Task CreateWorkItems(Dictionary<string, WorkItemQueryResult> workItems) { foreach (var workItemCategory in workItems.Keys) { var categoryURL = $"{_projectId}/_apis/wit/workitems/%24{workItemCategory}{_versionQueryString}"; foreach (var workItem in workItems[workItemCategory].workItems) { await CreateWorkItem(categoryURL, workItem); } } } private async Task CreateWorkItem(string categoryURL, WorkItem workItem) { var operations = new List<WorkItemOperation> { new WorkItemOperation() { path = $"{WorkItemPathPrefix}System.Title", value = workItem.details.fields.Title ?? "" }, new WorkItemOperation() { path = $"{WorkItemPathPrefix}System.Description", value = workItem.details.fields.Description ?? "" }, new WorkItemOperation() { path = $"{WorkItemPathPrefix}Microsoft.VSTS.Common.AcceptanceCriteria", value = workItem.details.fields.AcceptanceCriteria ?? "" }, new WorkItemOperation() { path = $"{WorkItemPathPrefix}System.IterationPath", value = workItem.details.fields.IterationPath.Replace(_devopsConfiguration.Source.ProjectName, _devopsConfiguration.Target.ProjectName) } }; var parentId = FindParentId(workItem.details); if (parentId != 0) { operations.Add(new WorkItemOperation() { path = "/relations/-", value = new Relationship() { url = $"{_devopsConfiguration.Target.DevOpsOrgURL}{_projectId}/_apis/wit/workitems/{idMapper[parentId]}", attributes = new RelationshipAttribute() } }); }
{ "domain": "codereview.stackexchange", "id": 43917, "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#, asp.net-core, asp.net-web-api, .net-core, asp.net-core-webapi", "url": null }
c#, asp.net-core, asp.net-web-api, .net-core, asp.net-core-webapi var result = await _importWorkItemService.Post(categoryURL, GetJsonContent(operations, "application/json-patch+json")); if (!idMapper.ContainsKey(workItem.id)) { idMapper.TryAdd(workItem.id, result.id); } } private int FindParentId(WorkItemDetails details) { var parentRelation = details.relations?.Where(relation => relation.attributes.name.Equals("Parent")).FirstOrDefault(); return parentRelation == null ? 0 : int.Parse(parentRelation.url.Split("/")[parentRelation.url.Split("/").Length - 1]); } private HttpContent GetJsonContent(object data, string mediaType = "application/json") { var jsonString = JsonConvert.SerializeObject(data); return new StringContent(jsonString, Encoding.UTF8, mediaType); } }
{ "domain": "codereview.stackexchange", "id": 43917, "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#, asp.net-core, asp.net-web-api, .net-core, asp.net-core-webapi", "url": null }
c++, game, tic-tac-toe Title: OOP Tic Tac Toe Console C++ Program Question: Board.h #pragma once #include <vector> #include <iostream> namespace Logs { inline void announce_winner(char winner) { std::cout << "Game Over! " << winner << " wins the game\n"; } inline void draw() { std::cout << "Game Over! .. Draw\n"; } inline void already_chosen() { std::cout << "The cell is already chosen, please try again.\n"; } inline void prompt_to_play() { std::cout << "Please enter a number between 1 and 9 inclusive that is not chosen\n"; } inline void invalid_cell() { std::cout << "Invalid choice. "; prompt_to_play(); } inline void current_turn(char player_symbol) { std::cout << "It's " << player_symbol << " turn\n"; } inline void another_game() { std::cout << "Do you want to play another game? Y - N\n"; } }; class Board { private: size_t width, height; // number of Xs minus number of Os, if +3 X wins, -3 O wins std::vector<short> difference_row; std::vector<short> difference_col; std::vector<short> difference_diagonal; unsigned moves; std::vector<std::vector<char>> board; char player_symbol; public: Board(); bool is_full(); void make_move(); void draw(); void reset(); size_t get_width(); size_t get_height(); bool is_game_over(); void increase_moves(); bool is_valid_move(int row, int col); void update_cell(int row, int col); void toggle_player(); bool any_winner(); char get_symbol() { return player_symbol; } }; Board.cpp #include "Board.h" Board::Board() { Board::reset(); } void Board::make_move() { draw(); Logs::current_turn(player_symbol); Logs::prompt_to_play(); int choice; std::cin >> choice;
{ "domain": "codereview.stackexchange", "id": 43918, "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++, game, tic-tac-toe", "url": null }
c++, game, tic-tac-toe int row_index = (choice - 1) / height; int col_index = (choice - 1) % width; if (is_valid_move(row_index, col_index)) { update_cell(row_index, col_index); increase_moves(); if (is_game_over()) { draw(); if (any_winner()) { Logs::announce_winner(player_symbol); } else { Logs::draw(); } Logs::another_game(); std::string res; std::cin >> res; if (tolower(res[0]) == 'y') { reset(); make_move(); } else { exit(0); } } } else { Logs::invalid_cell(); } make_move(); } bool Board::is_full() { return moves == width * height; } void Board::draw() { for (const auto &row : board) { for (const auto &cell : row) { std::cout << cell << " "; } std::cout << std::endl; } } void Board::reset() { width = 3; height = 3; board.assign(height, std::vector<char>(width)); char current = '1'; for (auto &row : board) { for (auto &cell : row) { cell = current++; } } difference_row = std::vector<short>(3); difference_col = std::vector<short>(3); difference_diagonal = std::vector<short>(2); moves = 0; player_symbol = 'X'; } size_t Board::get_height() { return height; } size_t Board::get_width() { return width; } bool Board::is_game_over() { return Board::any_winner() || Board::is_full(); } void Board::increase_moves() { moves++; // don't toggle player unless game is over, this will help us to announce // winner if (!is_game_over()) { toggle_player(); } } bool Board::is_valid_move(int row, int col) { return !(row < 0 || row >= height || col < 0 || col >= width || board[row][col] == 'X' || board[row][col] == 'O'); }
{ "domain": "codereview.stackexchange", "id": 43918, "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++, game, tic-tac-toe", "url": null }
c++, game, tic-tac-toe void Board::update_cell(int row, int col) { board[row][col] = player_symbol; int add = (player_symbol == 'X' ? +1 : -1); difference_row[row] += add; difference_col[col] += add; if (row == col) { difference_diagonal[0] += add; } if (row + col == height - 1) { difference_diagonal[1] += add; } } void Board::toggle_player() { player_symbol = (player_symbol == 'X' ? 'O' : 'X'); } bool Board::any_winner() { for (int i = 0; i < 3; i++) { if (i < 2 && abs(difference_diagonal[i]) == 3) { return true; } if (abs(difference_row[i]) == 3 || abs(difference_col[i] == 3)) { return true; } } return false; } TicTacToe.h #pragma once #include "Board.h" class TicTacToe { private: Board board; public: TicTacToe(); void start(); }; TicTacToe.cpp #include "TicTacToe.h" TicTacToe::TicTacToe() { board = Board(); } void TicTacToe::start() { while (true) { board.make_move(); if (board.any_winner()) { Logs::announce_winner(board.get_symbol()); } else if (board.is_full()) { Logs::draw(); } } } main.cpp #include "TicTacToe.h" int main() { TicTacToe tic; tic.start(); } I've tried my best to code a multiplayer tic tac toe console program. Here's what I've written. Please, I need a code review, if there's any modifications, advices, etc. to make the code better.
{ "domain": "codereview.stackexchange", "id": 43918, "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++, game, tic-tac-toe", "url": null }
c++, game, tic-tac-toe Answer: General Observations It is very nice to see a program without using namespace std;. The implementation in main.c is good, nice and short., however, it may be too short. It might be better to have a try{} catch(CONDITION) {} that returns the proper exit status rather than having a call to exit() in void Board::make_move(). The recursive nature of make_move() for a new game may also be a problem. This recursion indicates that the objects could be partitioned better. There are 2 functions get_width() and get_height() in the Board class that aren't used. this indicates that they aren't needed and should not have been implemented. If they are needed, they are simple enough that they can be implemented in Board.h rather than Board.cpp. It isn't clear why logging was created as a name space rather than a class. What is clear is that logging should have its own header file, keep every piece of the program as simple as possible. When you compile C or C++ it is best to use the -Wall switch to provide warning for code that could possibly fail. The following line in Board.cpp generates a warning with my compiler: int row_index = (choice - 1) / height;
{ "domain": "codereview.stackexchange", "id": 43918, "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++, game, tic-tac-toe", "url": null }
c++, game, tic-tac-toe because height is defined as size_t and row_index is defined as int. It is best to define all variables used as indexes as size_t. The error message indicates that there might be loss of data due to the difference in size between size_t and int. Since the parameters row and col are used as indexes in bool is_valid_move(int row, int col); and void update_cell(int row, int col); they should be declared as size_t rather than int as well. Use of the inline Keyword In the Logs namespace every function is defined with the inline keyword. The inline keyword is depreciated, and is only a recommendation to the compiler that may be ignored. Optimizing compilers will perform inlining of function based on multiple factors with or without the inline keyword. There is really no reason to use this keyword anymore. Magic Numbers There are Magic Numbers in Board.cpp function (3 and 2), it might be better to create symbolic constants for them to make the code more readable and easier to maintain. These numbers may be used in many places and being able to change them by editing only one line makes maintenance easier. Numeric constants in code are sometimes referred to as Magic Numbers, because there is no obvious meaning for them. There is a discussion of this on stackoverflow. constexpr size_t BOARD_SIZE = 3; ... void Board::reset() { width = BOARD_SIZE; height = BOARD_SIZE; board.assign(height, std::vector<char>(width)); char current = '1'; for (auto& row : board) { for (auto& cell : row) { cell = current++; } } difference_row = std::vector<short>(BOARD_SIZE); difference_col = std::vector<short>(BOARD_SIZE); difference_diagonal = std::vector<short>(2); moves = 0; player_symbol = 'X'; } ...
{ "domain": "codereview.stackexchange", "id": 43918, "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++, game, tic-tac-toe", "url": null }
c++, game, tic-tac-toe ... bool Board::any_winner() { for (int i = 0; i < BOARD_SIZE; i++) { if (i < 2 && abs(difference_diagonal[i]) == BOARD_SIZE) { return true; } if (abs(difference_row[i]) == BOARD_SIZE || abs(difference_col[i] == BOARD_SIZE)) { return true; } } return false; } Object Oriented Design I am including this to help you learn more about object oriented design. I think you may also want to learn about design patterns. SOLID is 5 object orieneted design principles. SOLID is a mnemonic acronym for five design principles intended to make software designs more understandable, flexible and maintainable. This will help you design your objects and classes better. The Single Responsibility Principle - A class should only have a single responsibility, that is, only changes to one part of the software's specification should be able to affect the specification of the class. The Open–closed Principle - states software entities (classes, modules, functions, etc.) should be open for extension, but closed for modification. The Liskov Substitution Principle - Objects in a program should be replaceable with instances of their subtypes without altering the correctness of that program. The Interface segregation principle - states that no client should be forced to depend on methods it does not use. The Dependency Inversion Principle - is a specific form of decoupling software modules. When following this principle, the conventional dependency relationships established from high-level, policy-setting modules to low-level, dependency modules are reversed, thus rendering high-level modules independent of the low-level module implementation details.
{ "domain": "codereview.stackexchange", "id": 43918, "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++, game, tic-tac-toe", "url": null }
php, pdo Title: Can I use PDO transaction in this way? Question: So I want to use PDO transaction in PHP OOP where in the class are multiple insert/update queries. If I create a new methods in Class like beginTransaction(), commit(), rollback() and I use them afterwards in my code is it okay? Here is one example: class TestClass { private $pdo; public function __construct($db) { $this->pdo = $db->DB_CONN(); } public function beginTransaction() { return $this->pdo->beginTransaction(); } public function commit() { return $this->pdo->commit(); } public function rollback() { return $this->pdo->rollback(); } public function insert_one() { $stmt = $this->pdo->prepare("INSERT INTO mytable (id,name,text) VALUES (:id, :name, :text)"); $stmt->execute([":id" => "146", ":name" => "Test Name", ":text" => "Test MSG"]); } public function insert_two() { $stmt = $this->pdo->prepare("INSERT INTO mytable (id,name,text) VALUES (:id, :name, :text)"); $stmt->execute([":id" => "145", ":name" => "TEST NAME 2", ":text" => "TEST MSG 2"]); } } $dataBase = new DataBase; $testClass = new TestClass($dataBase); try { $testClass->beginTransaction(); $testClass->insert_two(); $testClass->insert_one(); $testClass->commit(); } catch (PDOException $e) { die("rolling back.." . $e); $testClass->rollBack(); } Its working fine, but I'm not sure if this is a good way to implement it.. Thank you!
{ "domain": "codereview.stackexchange", "id": 43919, "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, pdo", "url": null }
php, pdo Its working fine, but I'm not sure if this is a good way to implement it.. Thank you! Answer: Yes, it should work but it's not a good way to implement it. Confusion Why did you create all these methods in the first place? Why don't you use $this->pdo->beginTransaction() right away? What is the reason? Separation of concerns and Code reuse But even if you want to create such methods, it just unnatural to have them in the TestClass. Given there will be TestClass2, you're going to write all these methods again, seriously? Naturally, all those should go into the Database class. Besides, Your TestClass should only contain the code related to Test. While all this transaction business is related to the database. Database connection Calling $db->DB_CONN() in the constructor just makes no sense. What if you will have to instantiate two classes? It will create two database connections? What if it will be a hundred? The connection has to be made elsewhere and TestClass should consume an already created $pdo instance. Error handling There must be no die() on error in any code ever. Your code should allow to handle the error gracefully. Therefore it must be throw $e; instead of die. Exception handling You should catch all exceptions. For the transaction, it doesn't matter, whether it was a PDOException or whatever else error that interrupted the code execution. Logical inconsistency What's the point in calling $testClass->rollBack() when your script already died? Encapsulation Why you're writing all this payload in the open? Why not to create a method that encapsulates it? Naming According to the standard, there must be no method names like insert_two() or DB_CONN() The code So a better version could be like class TestClass { private $pdo; public function __construct($pdo) { $this->pdo = $pdo; }
{ "domain": "codereview.stackexchange", "id": 43919, "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, pdo", "url": null }
php, pdo public function insertOne() { $sql = "INSERT INTO mytable (id,name,text) VALUES (:id, :name, :text)"; $stmt = $this->pdo->prepare($sql); $stmt->execute([":id" => "146", ":name" => "Test Name", ":text" => "Test MSG"]); } public function insertTwo() { $sql = "INSERT INTO mytable (id,name,text) VALUES (:id, :name, :text)"; $stmt = $this->pdo->prepare($sql); $stmt->execute([":id" => "145", ":name" => "TEST NAME 2", ":text" => "TEST MSG 2"]); } public function insertAll() { try { $this->pdo->beginTransaction(); $this->insertTwo(); $this->insertOne(); $this->pdo->commit(); } catch (Throwable $e) { $this->pdo->rollBack(); throw $e; } } } $dataBase = new PDO(...); $testClass = new TestClass($dataBase); $testClass->insertAll(); Code formatting See, my code example doesn't trigger the horizontal scrolling, making it much easier to read. And it's not a trifle matter. We are writing a code for the programmer. And it must be always comfortable to read.
{ "domain": "codereview.stackexchange", "id": 43919, "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, pdo", "url": null }
python, python-3.x, hash-map, json Title: Implementation of JSON schem parser to extract some attributes Question: I have three different types of schema possibilities as below: obj_1 = { 'title': 'deposit-test-schema', 'type': 'object', 'properties': { 'title': {'type': 'string', 'x-cap-permission': {"users": ['test@test.com']}}, 'date': {'type': 'string', 'x-cap-permission': {"users": ['test_user@test.com']}}, 'test': { 'type': 'array', 'items': { 'properties': { 'title': {'type': 'string', 'x-cap-permission': {"users": ['test@test.com']}}, 'date': {'type': 'string', 'x-cap-permission': {"users": ['test_user@test.com']}} }, "type": "object" }, } }, } obj_2 = { 'title': 'deposit-test-schema-one', 'type': 'array', 'items': { 'properties': { 'title': {'type': 'string', 'x-cap-permission': {"users": ['test@test.com']}}, 'date': {'type': 'string', 'x-cap-permission': {"users": ['test_user@test.com']}} }, "type": "object" }, } obj_3 = { 'title': 'deposit-test-schema-two', 'type': 'string', 'x-cap-permission': {"users": ['test_user@test.com']} } I want the output to be the nested structure with x-cap-fields. The expected output is: { "title":{ "users":[ "test@test.com" ] }, "date":{ "users":[ "test_user@test.com" ] }, "test.items.properties.title":{ "users":[ "test@test.com" ] }, "test.items.properties.date":{ "users":[ "test_user@test.com" ] { "items.title":{ "users":[ "test@test.com" ] }, "items.date":{ "users":[ "test_user@test.com" ] } } {'.': {'users': ['test_user@test.com']}}
{ "domain": "codereview.stackexchange", "id": 43920, "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, hash-map, json", "url": null }
python, python-3.x, hash-map, json {'.': {'users': ['test_user@test.com']}} I have implemented the following solution to have the expected output: def parse_schema_permission_info(schema): x_cap_fields = {} def extract_permission_field(field, parent_field): for field, value in field.items(): if field == 'x-cap-permission': x_cap_fields.update({parent_field: value}) if isinstance(value, dict): key = parent_field + '.' + field if value.get('x-cap-permission'): x_cap_fields.update( {key: value.get('x-cap-permission')} ) extract_permission_field(value, key) schema_type = schema.get("type") pre_field = '' if schema_type == 'object': schema = schema.get('properties', {}) elif schema_type == 'array': schema = schema.get('items',{}).get('properties', {}) pre_field = 'items' elif schema_type == 'string': extract_permission_field(schema, '.') print(x_cap_fields) return for field in schema: p_field = pre_field + '.' + field if pre_field else field extract_permission_field(schema.get(field), p_field) print(x_cap_fields) What can be improved here to have the same expected output from the above method?
{ "domain": "codereview.stackexchange", "id": 43920, "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, hash-map, json", "url": null }
python, python-3.x, hash-map, json What can be improved here to have the same expected output from the above method? Answer: First I will say, the fact that you're doing any of this raises just all of the red flags. This code and the data it consumes and outputs have all of the hallmarks of poorly-structured data lasagna. Better-structured code would have intermediate models with well-defined types and fields. Also, a better architecture would know which of the three formats it's consuming based on context, and more narrowly tailor a separate schema transformation to each case. But anyway: This is a recursive implementation, and Python sucks at recursion. For untrusted data, it would be trivially easy to construct a stack bomb and crash your program. You have good test cases! You should convert them into unit tests. Add PEP484 type hints. Notice that you've duplicated this logic: if field == 'x-cap-permission': once for the current node and once for the child node. Just do it once. You abuse update(). When there's only one key to update, just [] = assign it. Extract extract_permission_field away from being nested, and convert it from a mutator of x_cap_fields into a function that has no side effects and yields an iterator of key-value pairs. Consider using the new match/case syntax for your schema_type check. pre_field can be simplified by using the literal items., and unconditionally pre-pending. Suggested This is certainly only a half-measure and doesn't address broader architectural problems, but it's better than nothing: from typing import Any, Iterator def extract_permission_field(node: dict[str, Any], parent_field: str) -> Iterator[tuple[str, Any]]: for field, value in node.items(): if field == 'x-cap-permission': yield parent_field, value if isinstance(value, dict): yield from extract_permission_field(value, parent_field + '.' + field)
{ "domain": "codereview.stackexchange", "id": 43920, "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, hash-map, json", "url": null }
python, python-3.x, hash-map, json def parse_schema_permission_info(schema: dict[str, Any]) -> dict[str, Any]: match schema.get('type'): case 'string': return dict(extract_permission_field(schema, '.')) case 'object': schema = schema.get('properties', {}) pre_field = '' case 'array': schema = schema.get('items', {}).get('properties', {}) pre_field = 'items.' case _: raise ValueError('Bad schema type') x_cap_fields = {} for field, value in schema.items(): x_cap_fields.update(extract_permission_field(value, pre_field + field)) return x_cap_fields def test() -> None: obj_1 = { 'type': 'object', 'title': 'deposit-test-schema', 'properties': { 'title': {'type': 'string', 'x-cap-permission': {'users': ['test@test.com']}}, 'date': {'type': 'string', 'x-cap-permission': {'users': ['test_user@test.com']}}, 'test': { 'type': 'array', 'items': { 'type': 'object', 'properties': { 'title': {'type': 'string', 'x-cap-permission': {'users': ['test@test.com']}}, 'date': {'type': 'string', 'x-cap-permission': {'users': ['test_user@test.com']}}, }, }, }, }, } actual = parse_schema_permission_info(obj_1) expected = { 'title': {'users': ['test@test.com']}, 'date': {'users': ['test_user@test.com']}, 'test.items.properties.title': {'users': ['test@test.com']}, 'test.items.properties.date': {'users': ['test_user@test.com']}, } assert actual == expected
{ "domain": "codereview.stackexchange", "id": 43920, "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, hash-map, json", "url": null }
python, python-3.x, hash-map, json obj_2 = { 'type': 'array', 'title': 'deposit-test-schema-one', 'items': { 'type': 'object', 'properties': { 'title': {'type': 'string', 'x-cap-permission': {'users': ['test@test.com']}}, 'date': {'type': 'string', 'x-cap-permission': {'users': ['test_user@test.com']}}, }, }, } actual = parse_schema_permission_info(obj_2) expected = { 'items.title': {'users': ['test@test.com']}, 'items.date': {'users': ['test_user@test.com']}, } assert actual == expected obj_3 = { 'type': 'string', 'title': 'deposit-test-schema-two', 'x-cap-permission': {'users': ['test_user@test.com']}, } actual = parse_schema_permission_info(obj_3) expected = {'.': {'users': ['test_user@test.com']}} assert actual == expected if __name__ == '__main__': test()
{ "domain": "codereview.stackexchange", "id": 43920, "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, hash-map, json", "url": null }
javascript, strings Title: Coderbyte: String Reduction Question: From Coderbyte: Have the function StringReduction(str) take the str parameter being passed and return the smallest number you can get through the following reduction method. The method is: Only the letters a, b, and c will be given in str and you must take two different adjacent characters and replace it with the third. For example "ac" can be replaced with "b" but "aa" cannot be replaced with anything. This method is done repeatedly until the string cannot be further reduced, and the length of the resulting string is to be outputted. For example: if str is "cab", "ca" can be reduced to "b" and you get "bb" (you can also reduce it to "cc"). The reduction is done so the output should be 2. If str is "bcab", "bc" reduces to "a", so you have "aab", then "ab" reduces to "c", and the final string "ac" is reduced to "b" so the output should be 1. Source ( passed all validations ): var replacements = { "ab" : "c", "ac" : "b", "bc" : "a", "ba" : "c", "ca" : "b", "cb" : "a" }; function StringReduction(s) { var original, key; while( s != original ) { original = s; for( key in replacements ) s = s.replace( key , replacements[key] ); } return s.length; } // keep this function call here // to see how to enter arguments in JavaScript scroll down StringReduction(readline()); The funny part of this challenge is that you write against time, so the first version was a terrible, recursive approach. Since then I rewrote it a few times before posting to CR, thinking each time mistakenly that it was perfect, at this point I would like to get your feedback on it. Answer: A few minor notes: Have the function StringReduction(str) strictly speaking, the parameter name is different: function StringReduction(s) :-) var original, key; I'd put the variable declarations to separate lines. From Code Complete 2nd Edition, p759:
{ "domain": "codereview.stackexchange", "id": 43921, "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, strings", "url": null }
javascript, strings I'd put the variable declarations to separate lines. From Code Complete 2nd Edition, p759: With statements on their own lines, the code reads from top to bottom, instead of top to bottom and left to right. When you’re looking for a specific line of code, your eye should be able to follow the left margin of the code. It shouldn’t have to dip into each and every line just because a single line might contain two statements. It could prevent some diff/merge conflicts (you modify the first variable, a coworker the second one at the same time). key could be declared inside the while loop. JavaScript variables declare outside or inside loop? Effective Java, Second Edition, Item 45: Minimize the scope of local variables As @konijn pointed out in his comment, that may confuse maintainers. Anyway, extracting it out into a separate function solves the issue (#6). The name original could be lastString or lastValue since it's not the original string, it's the result of the last loop. Indentation is not consistent. Most of the places it's two spaces but the while loop is only one space indented, the body of the for loop has three spaces. I'd extract out the for loop to a string translate(string, replacements) function for better readability.
{ "domain": "codereview.stackexchange", "id": 43921, "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, strings", "url": null }
rust Title: Rust language solution to old "Perl Quiz of the Week" #21 Question: I'm particularly concerned here that I'm copying more often than I need to, and that's slowing things down; obviously, given the algorithm/approach, I need to do some copying, but I don't want to be doing more than necessary. Code also available at https://gist.github.com/fizbin/905a219af86adb95a6e7fd4bd26a507e /* * This program solves the puzzle * https://perl.plover.com/qotw/e/021 * * (In case that link goes away, a brief summary of the problem * is to consider the free non-abelian group with 26 generators * 'a' through 'z', under the equivalence relation that any two * words found in the dictionary that are anagrams of each other * are equivalent. Now determine which letters commute with which * other letters, and specifically which letters are in the center.) * * It does so by reading the dictionary to determine all anagram * pairs and then applying two strategies over and over again * to ever known pair of equivalent strings, manipulating the * set of everything known until it can't any further at which * point it prints out a table of the letters which are known * to commute and the list of other equivalences that are known * and not derivable from the commutativity table. * * It's a bit surprising that this relatively simple approach * suffices to wring every piece of information out of the * Web2 word list, but it does. Presumably, more advanced reasoning * strategies could be required for different dictionaries; however, * the list of "Leftover facts" printed at the end should be * enough to know whether this simple approach was enough for a given * dictionary. */ use std::{ cell::Cell, collections::{HashMap, HashSet}, fs::File, io::{prelude::*, BufReader}, path::Path, }; #[derive(Hash, Eq, PartialEq, Debug)] struct Fact { lhs: String, rhs: String, }
{ "domain": "codereview.stackexchange", "id": 43922, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "rust", "url": null }
rust #[derive(Hash, Eq, PartialEq, Debug)] struct Fact { lhs: String, rhs: String, } impl Fact { // store facts sorted, so that we know that // abcd=bcda is the same fact as bcda=abcd fn new(lhs: &str, rhs: &str) -> Fact { if lhs <= rhs { Fact { lhs: lhs.to_string(), rhs: rhs.to_string(), } } else { Fact { lhs: rhs.to_string(), rhs: lhs.to_string(), } } } } struct WorldState { // In a WorldState, we store single-letter-commutes facts (e.g. on=no) in 'single_commutes' // and only use 'facts' for facts about longer strings single_commutes: HashMap<char, HashSet<char>>, facts: HashSet<Fact>, } impl WorldState { fn new() -> WorldState { WorldState { single_commutes: HashMap::new(), facts: HashSet::new(), } } fn new_with_singles(single_commutes: &HashMap<char, HashSet<char>>) -> WorldState { let mut singles = HashMap::new(); for (c, nbhs) in single_commutes { singles.insert(*c, nbhs.clone()); } WorldState { single_commutes: singles, facts: HashSet::new(), } }
{ "domain": "codereview.stackexchange", "id": 43922, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "rust", "url": null }
rust fn add_fact(&mut self, lhs: &str, rhs: &str) { if lhs.ne(rhs) { match lhs.len() { 0 => (), 1 => (), 2 => { self.single_commutes .entry(lhs.chars().next().unwrap()) .or_default() .insert(rhs.chars().next().unwrap()); self.single_commutes .entry(rhs.chars().next().unwrap()) .or_default() .insert(lhs.chars().next().unwrap()); } _ => { self.facts.insert(Fact::new(lhs, rhs)); } } } } } fn reduce(state: WorldState) -> (WorldState, bool) { // Take each fact and remove common characters from front/back of both sides let mut retval = WorldState::new_with_singles(&state.single_commutes); let mut found_something = false; for fact in state.facts { let lhsbytes = fact.lhs.as_bytes(); let rhsbytes = fact.rhs.as_bytes(); let mut i1: usize = 0; let mut i2 = fact.rhs.len(); while i1 + 1 < i2 && lhsbytes[i1] == rhsbytes[i1] { i1 += 1; found_something = true; } while i2 > i1 + 1 && lhsbytes[i2 - 1] == rhsbytes[i2 - 1] { i2 -= 1; found_something = true; } retval.add_fact(&fact.lhs[i1..i2], &fact.rhs[i1..i2]) } (retval, found_something) }
{ "domain": "codereview.stackexchange", "id": 43922, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "rust", "url": null }
rust retval.add_fact(&fact.lhs[i1..i2], &fact.rhs[i1..i2]) } (retval, found_something) } fn scramble(state: WorldState) -> (WorldState, bool) { // adjust WorldState facts by moving stuff to the front or the back as may // help with a later reduce operation let mut retval = WorldState::new_with_singles(&state.single_commutes); let mut found_something = false; for fact in state.facts { let ourletters: HashSet<char> = fact.lhs.chars().collect(); let mut lhscopy: Vec<char> = fact.lhs.chars().collect(); let mut rhscopy: Vec<char> = fact.rhs.chars().collect(); let mut local_found: bool = false;
{ "domain": "codereview.stackexchange", "id": 43922, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "rust", "url": null }
rust for c in ourletters { // So for each letter, we see whether we can move the letter all // the way to the left, or all the way to the right, based on the // letters that we know commute. We only move a letter if we can // move it all the way left/right on both lhs & rhs of the fact. if state.single_commutes.contains_key(&c) { let commutes_with = &state.single_commutes[&c]; let can_swap = Cell::new(true); let finder = |c2: &char| { if c == *c2 { true } else { if !commutes_with.contains(c2) { can_swap.replace(false); } false } }; // Can we move c all the way left? let idx1: Option<usize> = lhscopy.iter().position(finder); let idx2: Option<usize> = rhscopy.iter().position(finder); if can_swap.get() { match (idx1, idx2) { (Some(i1), Some(i2)) => { local_found = true; // vec[0], vec[1], .. vec[i1-1], vec[i1] -> vec[i1], vec[0], vec[1], .. vec[i1-1] for i in (0..i1).rev() { lhscopy.swap(i, i + 1); } for i in (0..i2).rev() { rhscopy.swap(i, i + 1); } } (_, _) => (), // shouldn't happen } } else { // Can we move c all the way right? can_swap.replace(true); let ridx1: Option<usize> = lhscopy.iter().rposition(finder);
{ "domain": "codereview.stackexchange", "id": 43922, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "rust", "url": null }
rust let ridx1: Option<usize> = lhscopy.iter().rposition(finder); let ridx2: Option<usize> = rhscopy.iter().rposition(finder); if can_swap.get() { match (ridx1, ridx2) { (Some(i1), Some(i2)) => { local_found = true; // vec[i1], ..., vec[len()-1] -> vec[i1+1], ..., vec[len()-1], vec[i1] for i in i1..(lhscopy.len() - 1) { lhscopy.swap(i, i + 1); } for i in i2..(rhscopy.len() - 1) { rhscopy.swap(i, i + 1); } } (_, _) => (), // shouldn't happen } } } } } if local_found { let lhsnew: String = lhscopy.into_iter().collect(); let rhsnew: String = rhscopy.into_iter().collect(); retval.add_fact(lhsnew.as_str(), rhsnew.as_str()); found_something = true; } else { retval.add_fact(fact.lhs.as_str(), fact.rhs.as_str()) } } (retval, found_something) }
{ "domain": "codereview.stackexchange", "id": 43922, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "rust", "url": null }
rust fn lines_from_file(filename: impl AsRef<Path>) -> Vec<String> { let file = File::open(filename).expect("no such file"); let buf = BufReader::new(file); buf.lines() .map(|l| l.expect("Could not parse line")) // Comment out the next line to limit us to only words that are already all lowercase // (i.e. disallow use of proper nouns) .map(|s| s.to_ascii_lowercase()) .filter(|w| w.chars().all(|f| f.is_lowercase())) .collect() } fn make_initial_facts(wordlist: &[String]) -> Vec<Fact> { let mut anamap: HashMap<String, Vec<&str>> = HashMap::new(); for word in wordlist { let mut cvec: Vec<char> = word.chars().collect(); cvec.sort(); let sorted: String = cvec.into_iter().collect(); anamap.entry(sorted).or_default().push(word.as_str()); } let mut result = Vec::new(); for value in anamap.values() { if value.len() > 1 { for n in 1..value.len() { result.push(Fact::new(value[n - 1], value[n])); } } } result } fn main() { let mut state = WorldState::new(); { // Web2 is from https://perl.plover.com/qotw/words/Web2.gz let lines = lines_from_file("Web2"); for fact in make_initial_facts(lines.as_slice()) { state.add_fact(fact.lhs.as_str(), fact.rhs.as_str()); } } let mut working = true; while working { //println!("Interesting fact size: {}", state.facts.len()); (state, _) = scramble(state); (state, working) = reduce(state); }
{ "domain": "codereview.stackexchange", "id": 43922, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "rust", "url": null }
rust println!("Commute summary:"); println!(" abcdefghijklmnopqrstuvwxyz"); let empty: HashSet<char> = HashSet::new(); for a in 'a'..='z' { print!("{}:", a); let commset = state.single_commutes.get(&a).unwrap_or(&empty); let mut in_center = true; for b in 'a'..='z' { if a == b { print!("\\"); } else if commset.contains(&b) { print!("#"); } else { print!(" "); in_center = false; } } if in_center { print!(" (*)"); } println!(); } println!(); println!("Leftover facts:"); for fact in state.facts { println!(" {}={}", fact.lhs, fact.rhs); } } ``` Answer: The code looks pretty good overall. I'm not going to comment on the algorithm, mainly because I don't entirely understand the problem. Still, there are some issues here, and the biggest one is something that I often do as well. Don't take inputs by reference if you are just going to clone them You do this all over the place in the code, with the worst offender being WorldState::new_with_singles, where you perform the clone manually, rather than just calling .clone(). While doing this does make the code more general, it also causes a sneaky performance hit, especially if the caller already has an owned value they no longer need. The fix varies on a per-method basis- new_with_singles should probably just take in an owned HashMap, but Fact::new and WorldState::add_fact should probably take in an impl Into<String>. scramble and reduce should be methods It's a bit awkward to use them as free functions, especially when they are just performing a transformation on WorldState instances. Rewriting them to have the signatures impl WorldState{ fn scramble(&mut self) -> bool; fn reduce(&mut self) -> bool; }
{ "domain": "codereview.stackexchange", "id": 43922, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "rust", "url": null }
rust would be ideal. Rewrite reduce to use Iterators Always prefer to use iterators instead of indexing, especially when dealing with strings. They are faster, less brittle, and in this case, won't try to split strings in the middle of multibyte characters. fn reduce(state: WorldState) -> (WorldState, bool) { // Take each fact and remove common characters from front/back of both sides let mut retval = WorldState::new_with_singles(&state.single_commutes); let mut found_something = false; for fact in state.facts { let mut lhs = fact.lhs.chars(); let mut rhs = fact.rhs.chars(); //fun fact: the bitwise operators work on bools //There aren't too many uses for it, but it does occasionally come in handy found_something |= lhs .by_ref() .zip(rhs.by_ref()) .take_while(|(l, r)| l == r) .last() .is_some(); found_something |= lhs .by_ref() .rev() .zip(rhs.by_ref().rev()) .take_while(|(l, r)| l == r) .last() .is_some(); retval.add_fact(lhs.as_str(), rhs.as_str()) } (retval, found_something) } Fair warning, I did not test this beyond compiling it, so verifying that it does what I think it does is left as an exercise to the reader. Use Cell::set instead of Cell::replace Fairly self-explanatory, but in the scramble function, you call the Cell::replace method which returns the old value, and then immediately discard it, which is the entire point of Cell::set. Handle unreachable states In a couple of places, you have match statements that look like this: match (idx1, idx2) { (Some(i1), Some(i2)) => { /* elided for brevity */ } (_, _) => (), // shouldn't happen }
{ "domain": "codereview.stackexchange", "id": 43922, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "rust", "url": null }
rust Don't explicitly do nothing in an unreachable state. When it comes to unreachable states, explicitly crashing the program is usually the best (with the unreachable macro), especially since rustc is usually pretty good about optimizing out paths that truly are unreachable**. Also, you're using a match statement with only one pattern, which is also bad, and brings me to my next point. Use Clippy Rust ships with the clippy linter* which contains a bunch of useful lints that don't make sense to have in the compiler itself. I'll let what I got from clippy speak for itself: warning: you seem to be trying to use `match` for destructuring a single pattern. Consider using `if let` --> src/main.rs:168:21 | 168 | / match (idx1, idx2) { 169 | | (Some(i1), Some(i2)) => { 170 | | local_found = true; 171 | | // vec[0], vec[1], .. vec[i1-1], vec[i1] -> vec[i1], vec[0], vec[1], .. vec[i1-1] ... | 179 | | (_, _) => (), // shouldn't happen 180 | | } | |_____________________^ | = note: `#[warn(clippy::single_match)]` on by default = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#single_match help: try this | 168 ~ if let (Some(i1), Some(i2)) = (idx1, idx2) { 169 + local_found = true; 170 + // vec[0], vec[1], .. vec[i1-1], vec[i1] -> vec[i1], vec[0], vec[1], .. vec[i1-1] 171 + for i in (0..i1).rev() { 172 + lhscopy.swap(i, i + 1); 173 + } 174 + for i in (0..i2).rev() { 175 + rhscopy.swap(i, i + 1); 176 + } 177 + } |
{ "domain": "codereview.stackexchange", "id": 43922, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "rust", "url": null }
rust warning: you seem to be trying to use `match` for destructuring a single pattern. Consider using `if let` --> src/main.rs:187:25 | 187 | / match (ridx1, ridx2) { 188 | | (Some(i1), Some(i2)) => { 189 | | local_found = true; 190 | | // vec[i1], ..., vec[len()-1] -> vec[i1+1], ..., vec[len()-1], vec[i1] ... | 198 | | (_, _) => (), // shouldn't happen 199 | | } | |_________________________^ | = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#single_match help: try this | 187 ~ if let (Some(i1), Some(i2)) = (ridx1, ridx2) { 188 + local_found = true; 189 + // vec[i1], ..., vec[len()-1] -> vec[i1+1], ..., vec[len()-1], vec[i1] 190 + for i in i1..(lhscopy.len() - 1) { 191 + lhscopy.swap(i, i + 1); 192 + } 193 + for i in i2..(rhscopy.len() - 1) { 194 + rhscopy.swap(i, i + 1); 195 + } 196 + }
{ "domain": "codereview.stackexchange", "id": 43922, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "rust", "url": null }
rust Use a bunch of line comments instead of a block comment I know this probably seems weird, but for comments, the rust community has decided to prefer a bunch of line comments rather than a single block comment when multiline comments are called for. Purely a stylistic thing, but your block comment doesn't match up with the community's style. Needless block in main function fn main() { let mut state = WorldState::new(); { // Web2 is from https://perl.plover.com/qotw/words/Web2.gz let lines = lines_from_file("Web2"); for fact in make_initial_facts(lines.as_slice()) { state.add_fact(fact.lhs.as_str(), fact.rhs.as_str()); } } // other stuff... }
{ "domain": "codereview.stackexchange", "id": 43922, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "rust", "url": null }
rust There is no reason for that extra block, it should be removed. On performance You mentioned that you were concerned about performance. The first step is to make sure you're running an optimized build. There's a reason why every StackOverflow question involving rust and performance has a comment to the effect of "Did you build it the --release flag?". Also, fair warning, the advice I'm about to give is based on what I think might be slowing down the program. If you want to get serious about improving performance, use cargo flamegraph or something and figure out what's actually slowing your code down, and go from there. The default hasher is slow Rust's default Hashmap and Hashset use a hashdos resistant hash function with mediocre but consistent performance. While this is fine for most use cases, when you are doing lots of hashing of small and reasonably trusted input it's fine to swap in a faster hash function such as the Fowler-Noll-Vo or potentially even swapping out the HashMaps entirely for BtreeMaps instead and seeing how it performs. Lots of Small strings and needless copies Obviously, copies of large heap-based data structures and creating boatloads of small strings are fairly expensive operations. I've mentioned above how smarter function definitions can help prevent needless copies. Additionally, it may be worth creating an interner of some form or storing sufficiently small strings inline tinyvec style. Just using a Vec<char> as a string might yield some performance gains as well, since you convert to and from it regularly. Final notes Your code looks pretty good overall. I'd love to dig into it a little bit deeper, but again, I don't understand the task or algorithm well enough to do so. Make sure you pay attention to Unicode- rust is Unicode aware by default, and you should be too. Your code would almost certainly panic if someone decided to, say, pass in a Chinese dictionary instead of an English one.
{ "domain": "codereview.stackexchange", "id": 43922, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "rust", "url": null }
rust *Typically invoked with cargo clippy. If it's not installed on your local machine, install it via rustup component add clippy **If rustc doesn't optimize out an unreachable path, and you're really sure it can't be reached, std::hint::unreachable_unchecked is always an option.
{ "domain": "codereview.stackexchange", "id": 43922, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "rust", "url": null }
java, algorithm, array, comparative-review Title: Selection algorithms (order statistic) in Java: linear time vs. sorting selector vs. Quickselect Question: This post is about computing order statistics: given an array \$A\$ (not necessarily sorted), find the \$k\$th smallest array component. The entire repository is here. com.github.coderodde.algo.selection.Selector.java: package com.github.coderodde.algo.selection; /** * This interface defines the API for the selection algorithms. * * @author Rodion "rodde" Efremov * @param <E> the array component type. * @version 1.6 (Sep 25, 2022) * @since 1.6 (Sep 25, 2022) */ public sealed interface Selector<E extends Comparable<? super E>> permits LinearTimeSelector, SortingSelector, RandomizedSelector { E select(E[] array, int k); E select(E[] array, int k, int fromIndex, int toIndex); } com.github.coderodde.algo.selection.LinearTimeSelector.java: package com.github.coderodde.algo.selection; import static com.github.coderodde.algo.selection.Support.checkArray; import static com.github.coderodde.algo.selection.Support.checkK; import static com.github.coderodde.algo.selection.Support.checkRangeIndices; import java.util.Arrays; /** * This class provides a method for {@code k}th order statistics in worst case * linear time. * * @author Rodion "rodde" Efremov * @param <E> the element type. * @version 1.6 (Feb 18, 2022) * @since 1.6 (Feb 18, 2022) */ public final class LinearTimeSelector<E extends Comparable<? super E>> implements Selector<E> { private static final int GROUP_LENGTH = 5; /** * {@inheritDoc } */ @Override public E select(E[] array, int k, int fromIndex, int toIndex) { checkArray(array); checkK(array.length, k); checkRangeIndices(fromIndex, toIndex); return selectImpl(array, k, fromIndex, toIndex); }
{ "domain": "codereview.stackexchange", "id": 43923, "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, algorithm, array, comparative-review", "url": null }
java, algorithm, array, comparative-review /** * {@inheritDoc } */ @Override public E select(E[] array, int k) { checkArray(array); return select(array, k, 0, array.length); } private static <E extends Comparable<? super E>> E selectImpl(E[] array, int index, int fromIndex, int toIndex) { E[] medians = getGroupMedians(array, fromIndex, toIndex); E pivot; if (medians.length <= 5) { pivot = medians[medians.length / 2]; } else { pivot = selectImpl(medians, medians.length / 2, 0, medians.length); } int leftArrayLength = 0; int rightArrayLength = 0; for (int i = fromIndex; i < toIndex; i++) { E datum = array[i]; if (datum.compareTo(pivot) < 0) { leftArrayLength++; } else if (datum.compareTo(pivot) > 0) { rightArrayLength++; } } E[] leftArray = Arrays.copyOf(array, leftArrayLength); E[] rightArray = Arrays.copyOf(array, rightArrayLength); for (int i = fromIndex, outputIndex = 0; i < toIndex; i++) { E datum = array[i]; if (datum.compareTo(pivot) < 0) { leftArray[outputIndex++] = datum; } } for (int i = fromIndex, outputIndex = 0; i < toIndex; i++) { E datum = array[i]; if (datum.compareTo(pivot) > 0) { rightArray[outputIndex++] = datum; } } int k = leftArrayLength; if (index < k) { return selectImpl(leftArray, index, 0, leftArrayLength); } else if (index > k) { return selectImpl(rightArray, index - k - 1, 0, rightArrayLength); } else { return pivot; } }
{ "domain": "codereview.stackexchange", "id": 43923, "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, algorithm, array, comparative-review", "url": null }
java, algorithm, array, comparative-review private static <E extends Comparable<? super E>> E[] getGroupMedians(E[] array, int fromIndex, int toIndex) { int arrayLength = toIndex - fromIndex; int numberOfGroups = arrayLength / 5 + (arrayLength % 5 != 0 ? 1 : 0); E[] outputArray = Arrays.copyOfRange(array, 0, numberOfGroups); int groupStartIndex = fromIndex; int outputArrayIndex = 0; for (int groupIndex = 0; groupIndex < numberOfGroups; groupIndex++) { int groupEndIndex = Math.min(groupStartIndex + GROUP_LENGTH, toIndex); Arrays.sort(array, groupStartIndex, groupEndIndex); int groupLength = groupEndIndex - groupStartIndex; int medianIndex = (groupLength - 1) / 2; outputArray[outputArrayIndex++] = array[groupStartIndex + medianIndex]; groupStartIndex = groupEndIndex; } return outputArray; } } com.github.coderodde.algo.selection.RandomizedSelector.java: package com.github.coderodde.algo.selection; import static com.github.coderodde.algo.selection.Support.checkArray; import static com.github.coderodde.algo.selection.Support.checkK; import static com.github.coderodde.algo.selection.Support.checkRangeIndices; import java.util.Random; /** * This class implements a randomized selector relying on the ideas of * quicksort. * * @param <E> the array component type. Must be {@link Comparable}. * @author Rodion "rodde" Efremov * @version 1.6 (Sep 26, 2022) * @since 1.6 (Sep 26, 2022) */ public final class RandomizedSelector<E extends Comparable<? super E>> implements Selector<E> { @Override public E select(E[] array, int k) { checkArray(array); return select(array, k, 0, array.length); }
{ "domain": "codereview.stackexchange", "id": 43923, "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, algorithm, array, comparative-review", "url": null }
java, algorithm, array, comparative-review @Override public E select(E[] array, int index, int fromIndex, int toIndex) { checkArray(array); checkRangeIndices(fromIndex, toIndex); checkK(toIndex - fromIndex, index); Random random = new Random(); return selectImpl(array, index, fromIndex, toIndex, random); } private E selectImpl(E[] array, int index, int fromIndex, int toIndex, Random random) { int rangeLength = toIndex - fromIndex; if (rangeLength < 1) { throw new IllegalArgumentException( "The requested range is non-existent, length = " + rangeLength); } if (rangeLength == 1) { return array[fromIndex]; } int q = randomizedPartition(array, fromIndex, toIndex, random); int k = q - fromIndex; if (index == k) { return array[q]; } else if (index < k) { return selectImpl(array, index, fromIndex, q, random); } else { return selectImpl(array, index - k, q, toIndex, random); } } private static <E extends Comparable<? super E>> int randomizedPartition(E[] array, int fromIndex, int toIndex, Random random) { int i = fromIndex + random.nextInt(toIndex - fromIndex); swap(array, i, toIndex - 1); return partition(array, fromIndex, toIndex); } static <E extends Comparable<? super E>> int partition(E[] array, int fromIndex, int toIndex) { E x = array[toIndex - 1]; int i = fromIndex - 1; for (int j = fromIndex; j < toIndex - 1; j++) { if (array[j].compareTo(x) <= 0) { swap(array, ++i, j); } }
{ "domain": "codereview.stackexchange", "id": 43923, "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, algorithm, array, comparative-review", "url": null }
java, algorithm, array, comparative-review swap(array, i + 1, toIndex - 1); return i + 1; } private static <E> void swap(E[] array, int index1, int index2) { E tmp = array[index1]; array[index1] = array[index2]; array[index2] = tmp; } } com.github.coderodde.algo.selection.SortingSelector.java: package com.github.coderodde.algo.selection; import static com.github.coderodde.algo.selection.Support.checkArray; import static com.github.coderodde.algo.selection.Support.checkK; import static com.github.coderodde.algo.selection.Support.checkRangeIndices; import java.util.Arrays; /** * * @author Rodion "rodde" Efremov * @param <E> the array component type. * @version 1.6 (Sep 25, 2022) * @since 1.6 (Sep 25, 2022) */ public final class SortingSelector<E extends Comparable<? super E>> implements Selector<E> { @Override public E select(E[] array, int k, int fromIndex, int toIndex) { checkArray(array); checkRangeIndices(fromIndex, toIndex); checkK(toIndex - fromIndex, k); Arrays.sort(array, fromIndex, toIndex); return array[k + fromIndex]; } @Override public E select(E[] array, int k) { checkArray(array); return select(array, k, 0, array.length); } } com.github.coderodde.algo.selection.Support.java: package com.github.coderodde.algo.selection; import java.util.ArrayList; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Objects; import java.util.Random; import java.util.Set; /** * This class provides common methods for dealing with the order statistics * algorithms. * * @author Rodion "rodde" Efremov * @version 1.6 (Feb 14, 2022; Love Edition) * @since 1.6 (Feb 14, 2022; Love Edition) */ public final class Support {
{ "domain": "codereview.stackexchange", "id": 43923, "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, algorithm, array, comparative-review", "url": null }
java, algorithm, array, comparative-review public static <E> void checkArrayContainsNoDuplicatesElements(E[] array, int fromIndex, int toIndex) { Set<E> filter = new HashSet<>(); for (E element : array) { if (filter.contains(element)) { throw new IllegalArgumentException( "The element [" + element + "] is duplicated."); } filter.add(element); } } public static <E> void checkArrayContainsNoDuplicatesElements(E[] array) { checkArrayContainsNoDuplicatesElements(array, 0, array.length); } public static Integer[] getArray(Random random, int length, int minimumValue, int maximumValue) { Set<Integer> filter = new HashSet<>(); while (filter.size() < length) { int datum = minimumValue + random.nextInt(maximumValue - minimumValue + 1); filter.add(datum); } List<Integer> ints = new ArrayList<>(filter); Collections.<Integer>shuffle(ints, random); return ints.toArray(new Integer[length]); } static <E> void swap(E[] array, int index1, int index2) { E tmp = array[index1]; array[index1] = array[index2]; array[index2] = tmp; } static <E> void checkArray(E[] array) { Objects.requireNonNull(array, "The input array is null."); if (array.length == 0) { throw new IllegalArgumentException("The input array is empty."); } } static void checkK(int rangeLength, int k) { if (k < 0) { throw new IllegalArgumentException("'k' is negative: " + k); }
{ "domain": "codereview.stackexchange", "id": 43923, "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, algorithm, array, comparative-review", "url": null }
java, algorithm, array, comparative-review if (k >= rangeLength) { throw new IllegalArgumentException( "'k' is too large: " + k + "Must be at most " + (rangeLength - 1) + "."); } } static void checkRangeIndices(int fromIndex, int toIndex) { if (fromIndex < 0) { throw new IllegalArgumentException( "frontIndex is negative: " + fromIndex + ". Must be at least 0."); } if (toIndex < 0) { throw new IllegalArgumentException( "toIndex is negative: " + toIndex + ". Must be at least 0."); } if (fromIndex > toIndex) { throw new IllegalArgumentException( "fromIndex(" + fromIndex + ") > toIndex(" + toIndex + ")"); } } } com.github.coderodde.algo.selection.AbstractSelectorTest.java: package com.github.coderodde.algo.selection; import static com.github.coderodde.algo.selection.Support.getArray; import java.util.Random; import static org.junit.Assert.assertEquals; import org.junit.Before; import org.junit.Test; public abstract class AbstractSelectorTest { private static final int MAXIMUM_ARRAY_CAPACITY = 10_011; private static final int MINIMUM_ARRAY_CAPACITY = 5_317; private static final int MINIMUM_INT = -100_000; private static final int MAXIMUM_INT = 100_000; private Integer[] array ; private final Selector<Integer> selector; public AbstractSelectorTest(Selector<Integer> selector) { this.selector = selector; } @Before public void methodInit() { this.array = new Integer[]{ 4, 1, 5, 2, 3 }; } @Test public void testSelect1() { assertEquals(Integer.valueOf(1), selector.select(array, 0)); }
{ "domain": "codereview.stackexchange", "id": 43923, "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, algorithm, array, comparative-review", "url": null }
java, algorithm, array, comparative-review @Test public void testSelect2() { assertEquals(Integer.valueOf(2), selector.select(array, 1)); } @Test public void testSelect3() { assertEquals(Integer.valueOf(3), selector.select(array, 2)); } @Test public void testSelect4() { assertEquals(Integer.valueOf(4), selector.select(array, 3)); } @Test public void testSelect5() { assertEquals(Integer.valueOf(5), selector.select(array, 4)); } @Test public void testSelect13() { Integer[] array = new Integer[13]; for (int i = 0; i < array.length; i++) { array[i] = i; } for (int i = 0; i < array.length; i++) { assertEquals((Integer) i, selector.select(array, i)); } } @Test public void bruteForceTest() { Random random = new Random(1L); int length = MINIMUM_ARRAY_CAPACITY + random.nextInt( MAXIMUM_ARRAY_CAPACITY - MINIMUM_ARRAY_CAPACITY + 1); int index1 = random.nextInt(length); int index2 = random.nextInt(length); int fromIndex = Math.min(index1, index2); int toIndex = Math.max(index1, index2); Integer[] array1 = getArray(random, length, MINIMUM_INT, MAXIMUM_INT); Support.checkArrayContainsNoDuplicatesElements(array1); Integer[] array2 = array1.clone(); Selector<Integer> sortingSelector = new SortingSelector<>(); Selector<Integer> linearTimeSelector = new LinearTimeSelector(); for (int i = fromIndex, k = 0; i < toIndex; i++, k++) { Integer int1 = sortingSelector.select( array1, k, fromIndex, toIndex);
{ "domain": "codereview.stackexchange", "id": 43923, "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, algorithm, array, comparative-review", "url": null }