body
stringlengths 25
86.7k
| comments
list | answers
list | meta_data
dict | question_id
stringlengths 1
6
|
|---|---|---|---|---|
<p>I currently have a singleton that holds the translation objects in my app. View controllers can subscribe to its delegate so they can update their views if new translation objects have been added. This is what the class looks like</p>
<pre><code>class TranslationItems {
var delegate: TranslationItemsDelegate?
static let shared = TranslationItems()
private var set = Set<Translation>()
// Public API
public func add(object: Translation) {
set.insert(object)
delegate?.newItemAdded()
}
public func remove(object: Translation) {
set.remove(object)
delegate?.someItemDeleted()
}
public func getAll() -> [Translation] {
return Array(set)
}
}
protocol TranslationItemsDelegate {
func newItemAdded()
func someItemDeleted()
}
</code></pre>
<p>View controllers can use it like this:</p>
<pre><code>// Add or remove objects
TranslationItems.shared.add(object: translation)
// Subscribe for notifications
TranslationItems.shared.delegate = self
</code></pre>
<p>Does this singleton class look ok or could it be improved?</p>
|
[] |
[
{
"body": "<p>The problem I see there is that when a new view controller subscribes, the previous one stops receiving notifications. There reason is because delegation is a one to one relationship.</p>\n\n<p>\"View controllers can subscribe to its delegate\" That is wrong, it should be something like: \"A view controller can subscribe to its delegate\"</p>\n\n<p>If that is what you want, then it is OK.</p>\n\n<p>On the other hand, if you want to have several view controllers listening for those events, you need a 1 to many relationship. You can use NoticationCenter, KVO, Observables (RxSwift or Combine), or create your own solution, like:</p>\n\n<p>addObserver removeObserver an array to save these observers (that conform to a protocol) and when triggering the event, just use observers.forEach { $0.sendEvent... }</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-15T13:45:36.220",
"Id": "242343",
"ParentId": "242342",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "242343",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-15T13:31:22.063",
"Id": "242342",
"Score": "1",
"Tags": [
"swift"
],
"Title": "Singleton that holds the app's data"
}
|
242342
|
<p>I want to upload files from my Javascript client to my WebAPI.
With this I want to have a progress bar. My Idea was to cut the files up in chunks and then stream them via SingalR since we are using SingalR anyway. </p>
<p>This is my code:</p>
<p>API:</p>
<pre><code>public async Task UploadStream(IAsyncEnumerable<string> stream)
{
string buffer = "";
await foreach (var item in stream)
{
buffer += item;
}
Console.WriteLine(buffer);
}
</code></pre>
<p>Javascript:</p>
<pre><code>let base64 = data;
let chunks = base64.match(/.{1,25000}/g);
const subject = new signalR.Subject();
hub.getConnection().send("UploadStream", subject);
chunks.forEach((chunk: string) => {
subject.next(chunk);
});
subject.complete();
</code></pre>
<p>Now, this works, and it takes about 0.3 seconds to upload a 2.8MB image on localhost. But, my question is: Is this a good or bad practice? Or is it better to upload files as a multipart request?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-16T07:47:25.307",
"Id": "475658",
"Score": "1",
"body": "Please don't reinvent multipart file upload."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-16T14:04:34.233",
"Id": "475691",
"Score": "0",
"body": "Could you elaborate on why this would be bad? I am still learning, so I would highly appreciate it!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-16T16:18:50.843",
"Id": "475713",
"Score": "0",
"body": "SignalR is a wrapper over sockets. It falls back to WebSocket, long pooling and etc based on browser compatibility. It meant to be used for messages, not large files. Multipart file upload was designed for large files. Sending files over SignalR is an anti-pattern."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-16T19:19:19.577",
"Id": "475744",
"Score": "1",
"body": "Okay, I understand. Thanks."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-15T14:48:20.507",
"Id": "242344",
"Score": "2",
"Tags": [
"c#",
"asp.net-core",
"signalr"
],
"Title": "Uploading files through streaming with SignalR"
}
|
242344
|
<p>This component is meant to take in an array of available options and provide the user an easy way to choose multiple options and filter on the available options. Each time the selected options are changed/updated, those options are console logged.</p>
<p>I'm hoping that someone could provide any criticism on my current code. I want to make sure that the code is as simple and clean as it could be, while keeping all logic outside of the JSX. Photo of component at bottom of post.
If you notice any complexities that could be replaced with some alternative design, i'd be interested to know.</p>
<pre><code>import React, { useState, useEffect } from 'react';
import { Icon, MyInput } from '@mylib/library';
import './MultiSelection.scss';
export default function MultiSelection({
initialOptions=['A', 'B', 'C', 'D', 'Aaron', 'Britney', 'Carter'],
componentLabel='Select Contract Types',
availableLabel='Available Types',
selectedLabel='Selected Types',
filterLabel='Filter available Types',
showFilter=true,
}) {
const [options, setOptions] = useState([]);
const [availableOptions, setAvailableOptions] = useState([]);
const [selectedOptions, setSelectedOptions] = useState([]);
const [availableFilterValue, setAvailableFilterValue] = useState('');
// Convert options into a manageable structure
// on initial render
useEffect(() => {
let tempOptions = [];
initialOptions.forEach(option => tempOptions.push({'text': option, 'isAvailable': true, 'shouldShow': true}));
setOptions(tempOptions);
}, []);
// Separates options into a available and selected array
// in order to keep logic out of the JSX
useEffect(() => {
console.log('Build available and selected options');
const availableOptionsText = [];
const selectedOptionsText = [];
const available = options.filter(option => option.isAvailable && option.shouldShow);
const selected = options.filter(option => !option.isAvailable);
available.forEach(option => availableOptionsText.push(option.text));
selected.forEach(option => selectedOptionsText.push(option.text));
setAvailableOptions(availableOptionsText);
setSelectedOptions(selectedOptionsText);
}, [options]);
const updateStateOfOption = clickedOption => {
const tempOptions = [...options];
tempOptions.forEach(option => {
if(option.text === clickedOption){
option.isAvailable = !tempOptions.find(option => option.text === clickedOption).isAvailable
}
});
setOptions(tempOptions);
}
const handleFilterOnChange = e => {
console.log('Hit handleFilterOnChange');
setAvailableFilterValue(e.target.value);
}
const handleFilterOnBlur = e => {
console.log('Hit handleFilterOnBlur');
setAvailableFilterValue(e.target.value);
}
// Modify which options' shouldShow property depending on filter
// Only the available options will care about the shouldShow property
useEffect(() => {
const tempOptions = [...options];
tempOptions.forEach(option => {
if(availableFilterValue === ''){
option.shouldShow = true;
} else {
if(!option.text.toLowerCase().startsWith(availableFilterValue.toLocaleLowerCase())){
option.shouldShow = false;
} else {
option.shouldShow = true;
}
}
});
if(tempOptions.length !== 0){
setOptions(tempOptions);
}
}, [availableFilterValue]);
const row = (text, key, isAvailableColumn) => {
return(
<div key={`${isAvailableColumn ? 'available' : 'selected'}-button-row-${key}`} className='button-row-container' onClick={() => updateStateOfOption(text)}>
<Icon id='add' iconClass={`${isAvailableColumn ? 'icon-add' : 'icon-trashcan'}`}/>
<div>{text}</div>
</div>
)
}
return(
<div className='multi-selection'>
<label className='dropdown__floatingLabel multi-selection-label'>{componentLabel}</label>
{showFilter &&
<div className='-row page-row'>
<div className='col col-xs-6 col-sm-6 col-md-6 col-lg-6'>
<MyInput
name='availableTypesFilter'
id='availableTypesFilter'
autofocus={false}
fieldValue={availableFilterValue ? availableFilterValue : ''}
errorMessage={''}
label={filterLabel}
allowAutoComplete={false}
changed={handleFilterOnChange}
onBlur={handleFilterOnBlur}
/>
</div>
</div>
}
<div className={`label-container-${showFilter ? 'with-filter' : 'without-filter'}`}>
<p className='dropdown__floatingLabel'>{availableLabel}</p>
<p className='dropdown__floatingLabel'>{selectedLabel}</p>
</div>
<div className='options-container'>
<div className='available-options'>
{availableOptions.map((option, key) => row(option, key, true))}
</div>
<div className='selected-options'>
{selectedOptions.map((option, key) => row(option, key, false))}
</div>
</div>
</div>
)
}
</code></pre>
<p><a href="https://i.stack.imgur.com/vMgv1.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/vMgv1.png" alt="Multi selection component with filter"></a></p>
|
[] |
[
{
"body": "<p>There are a few places in the code where you have an array and you want to construct another array from it. Rather than <code>forEach</code> followed by <code>push</code>, it's more appropriate to use <code>Array.prototype.map</code> to transform one array into another. For example:</p>\n\n<pre><code>useEffect(() => {\n let tempOptions = [];\n initialOptions.forEach(option => tempOptions.push({ 'text': option, 'isAvailable': true, 'shouldShow': true }));\n setOptions(tempOptions);\n}, []);\n</code></pre>\n\n<p>can turn into</p>\n\n<pre><code>useEffect(() => {\n const newOptions = initialOptions.map(text => ({ text, isAvailable: true, shouldShow: true }));\n setOptions(newOptions);\n}, []);\n</code></pre>\n\n<p>As you can see above, properties that are valid identifiers don't need to be quoted (and probably shouldn't, to cut down on noise), and by planning ahead with variable names, you can sometimes use shorthand properties rather than having to list both the key and its value. In addition, you should <a href=\"https://softwareengineering.stackexchange.com/q/278652\">always use <code>const</code></a> to declare variables when possible - don't use <code>let</code> unless you wish to warn the reader of the code that you may have to reassign the variable later.</p>\n\n<p>You can use <code>.map</code> in the second <code>useEffect</code> call too, to great effect:</p>\n\n<pre><code>useEffect(() => {\n console.log('Build available and selected options');\n const optionToText = option => option.text;\n const availableOptionsText = options\n .filter(option => option.isAvailable && option.shouldShow)\n .map(optionToText);\n const selectedOptionsText = options\n .filter(option => !option.isAvailable)\n .map(optionToText);\n\n setAvailableOptions(availableOptionsText);\n setSelectedOptions(selectedOptionsText);\n}, [options]);\n</code></pre>\n\n<p>In <code>updateStateOfOption</code>, you are <em>mutating</em> the <code>isAvailable</code> property of one of the <code>options</code> array objects:</p>\n\n<pre><code>const updateStateOfOption = clickedOption => {\n const tempOptions = [...options];\n tempOptions.forEach(option => {\n if (option.text === clickedOption) {\n option.isAvailable = !tempOptions.find(option => option.text === clickedOption).isAvailable\n }\n });\n setOptions(tempOptions);\n}\n</code></pre>\n\n<p>Spreading an array only creates a shallow copy - each element in the original array is still a reference to one of the elements in the new array, so mutating an element in the new array changes an element in the old array too. Since this is React, such mutation should be avoided. Instead, use <code>findIndex</code> to find the index of the matching option, then create a new array by spreading the parts of the array <em>before</em> the option, then declaring a new (modified) object, then spreading the parts of the array <em>after</em> the option:</p>\n\n<pre><code>const updateStateOfOption = clickedOption => {\n const clickedIndex = options.findIndex(option => option.text === clickedOption);\n const newOptions = [\n ...options.slice(0, clickedIndex),\n { ...options[clickedIndex], isAvailable: !options[clickedIndex].isAvailable },\n ...options.slice(clickedIndex + 1),\n ];\n setOptions(newOptions);\n}\n</code></pre>\n\n<p>You have the same issue in the next <code>useEffect</code> too. This time, you can change every element of the array by using <code>.map</code> and spreading the previous option into an object, then assigning the new <code>shouldShow</code> property:</p>\n\n<pre><code>useEffect(() => {\n const newOptions = options.map(option => ({\n ...option,\n shouldShow: availableFilterValue === '' || option.text.toLowerCase().startsWith(availableFilterValue.toLocaleLowerCase())\n }));\n if (newOptions.length !== 0) {\n setOptions(newOptions);\n }\n}, [availableFilterValue]);\n</code></pre>\n\n<p>You can use <code>||</code> instead of the conditional operator here, if you want:</p>\n\n<pre><code>fieldValue={availableFilterValue ? availableFilterValue : ''}\n</code></pre>\n\n<p>can be</p>\n\n<pre><code>fieldValue={availableFilterValue || ''}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-15T17:22:15.493",
"Id": "242355",
"ParentId": "242345",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "242355",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-15T15:03:55.363",
"Id": "242345",
"Score": "2",
"Tags": [
"javascript",
"react.js"
],
"Title": "Multi Selection Component with Filter (React + Hooks)"
}
|
242345
|
<p>I'm writing an assistant for the tabletop RPG Pathfinder in Java. I intend to use the MVVM pattern using JavaFX, possibly through mvvmFX. Before I go into the V-VM phase, I have built a first iteration of the model, and would like some comments on it. The full code is on <a href="https://github.com/AnabVangun/CARP/tree/952a21a69bb959a21801665e10cbd576ed29cb9f" rel="nofollow noreferrer">GitHub</a>, I only include in this question the relevant classes. I have three main questions but I accept all feedback, especially on comments and package names if they do not follow standard conventions.</p>
<p><strong>Question 1: Can global parameters be accessed to build a view, or does it break the pattern?</strong></p>
<p>In my case, I have six abilities, defined in the <code>AbilityName</code> enum: Strength, Dexterity, etc. I will have six labels in the character sheet to display them to the user. Can I define my abilities in a <code>service</code> package accessed by both the model and the view?</p>
<p>CreatureParameters.java, where I define the enum, follows. Should it be located in a <code>model</code> package and, if so, am I doomed to have some weird code clumsily duplicating it to bind data to the corresponding labels?</p>
<pre><code>package service.parameters;
/**
* Non-instanciable container for the global parameters of the system relative
* to the creatures.
* These are not made to be tweaked but only to be shared between the layers
* of the program.
*/
public class CreatureParameters {
/**
* Names of the six abilities.
*/
public static enum AbilityName{
STRENGTH,
DEXTERITY,
CONSTITUTION,
INTELLIGENCE,
WISDOM,
CHARISMA;
}
private CreatureParameters() {};
}
</code></pre>
<p><strong>Question 2: Are my exceptions sane, or I am doing something wrong?</strong></p>
<p>In the model, when the input for a method call is invalid, I throw an exception. The classes defining the abilities may throw several such exceptions, and I am not sure I am defining them correctly and discriminating them enough.</p>
<p>Value.java, the building block which I will use to store most numerical values and handle bonuses in the future :</p>
<pre><code>package model.values;
/**
* Container for the base numerical unit of measurement. A Value contains a
* base value that may be modified by different instances of {@link Bonus}.
*/
public class Value {
private int value;
/**
* Initialises a simple Value object.
* @param value to store in the object.
*/
public Value(int value) {
this.value = value;
}
/**
* @return the total value of the object.
*/
public int getValue() {
return this.value;
}
}
</code></pre>
<p>AbilityScore.java, where I define a generic ability score interface (I use an interface to let the <code>AbilityScores</code> class handle input validation):</p>
<pre><code>package model.values;
/**
* Read-only container for one of the six ability scores of a creature:
* Strength, Dexterity, Constitution, Intelligence, Wisdom, Charisma.
*/
public interface AbilityScore {
/**
* @return the modifier of the ability score.
*/
public int getModifier();
/**
* Computes the modifier associated with a given value for an ability
* score.
* @param value to take into account.
* @return the modifier associated with the given value.
*/
public static int computeModifier(int value) {
return value/2 - 5;
}
/**
* @return the value of the ability score, taking all bonuses into account.
*/
public int getValue();
}
</code></pre>
<p>ValueParameters.java, where I define the min and max acceptable values for abilities and dice (the Roll class is left out because I do not use it yet).</p>
<pre><code>package service.parameters;
/**
* Non-instanciable container for the global parameters of the system relative
* to the values.
* These are not made to be tweaked but only to be shared between the layers
* of the program.
*/
public final class ValueParameters {
/**Prevents the class from being instantiated.*/
private ValueParameters() {}
/**Private parameter to set a maximum for the input values.*/
private static final int MAX_INT_VALUE = 999;
/**Minimum valid value for an ability score. Must be 0.*/
public static final int MIN_ABILITY_SCORE = 0;
/**Maximum valid value for an ability score. Must be at least 40.*/
public static final int MAX_ABILITY_SCORE = MAX_INT_VALUE;
/**Minimum valid number of dice in a roll. Must be 1.*/
public static final int MIN_NUMBER_OF_DICE = 1;
/**Minimum valid number of sides for a die. Must be at most 4.*/
public static final int MIN_NUMBER_OF_SIDES = 2;
/**Maximum valid number of dice in a roll. Must be at least 10.*/
public static final int MAX_NUMBER_OF_DICE = MAX_INT_VALUE;
/**Maximum valid number of sides for a dice. Must be at least 100.*/
public static final int MAX_NUMBER_OF_SIDES = MAX_INT_VALUE;
}
</code></pre>
<p>Part of the AbilityScores.java file (I made a read-only and a read-write versions of the interface to make sure that only the creature with the ability scores can modify them; any other object must contend with a read-only version and ask the creature to modify them. The read-only version is left out as it is not that relevant to the question):</p>
<pre><code>package model.creatures;
import java.util.AbstractMap;
import java.util.Collections;
import java.util.EnumMap;
import java.util.EnumSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import model.exceptions.IllegalAbilityScoreException;
import model.values.AbilityScore;
import model.values.Value;
import service.parameters.CreatureParameters.AbilityName;
import service.parameters.ValueParameters;
/**
* Set of the six abilities of any creature.
*/
public interface AbilityScores extends Iterable<Map.Entry<AbilityName, AbilityScore>>{
/**
* Public unmodifiable reference to the subset of abilities that all
* creatures must have. The other abilities are optional, some creatures
* may not have them.
*/
public final static Set<AbilityName> MANDATORY_ABILITIES = Collections.unmodifiableSet(EnumSet.of(
AbilityName.DEXTERITY, AbilityName.WISDOM, AbilityName.CHARISMA));
/**
* Returns the modifier associated with the given ability.
* @param ability
* @return an integer which may be positive or negative depending on the
* value of the ability, or zero if the ability is not defined.
*/
public int getModifier(AbilityName ability);
/**
* Returns specified the {@link model.values.AbilityScore}. May return
* {@link null} if the ability is not defined for the creature.
* @param ability
* @return an {@link AbilityScore} object or {@link null}.
*/
public AbilityScore getScore(AbilityName ability);
/**
* Checks that the input is valid to build an AbilityScore.
* @param values the input to check.
* @param fail if true, raise an {@link IllegalAbilityScoreException}
* instead of returning false.
* @return true if all mandatory abilities are present, and all present
* abilities have valid values.
*/
public static boolean isValidAbilityScoreInput(Map<AbilityName, Integer> values, boolean fail) {
//Reject null input
if(values == null) {
if(fail) {
throw new IllegalAbilityScoreException(IllegalAbilityScoreException.Cause.NULL);
}
return false;
}
//Check if all mandatory abilities are present
if(!MANDATORY_ABILITIES.containsAll(values.keySet())) {
//If not, find the missing one and throw an exception
for(AbilityName ability: MANDATORY_ABILITIES) {
if (!values.containsKey(ability)) {
if(fail) {
throw new IllegalAbilityScoreException(ability.toString(), values.keySet().toString());
}
return false;
}
}
}
//Verify that all model.values are valid
for(Entry<AbilityName, Integer> entry : values.entrySet()) {
if(entry.getValue() < ValueParameters.MIN_ABILITY_SCORE
|| entry.getValue() > ValueParameters.MAX_ABILITY_SCORE) {
if(fail) {
throw new IllegalAbilityScoreException(entry.getKey().toString(), entry.getValue());
}
return false;
}
}
return true;
}
/**
* Initialises an {@link AbilityScores} object with model.values for at least
* some of the abilities.
* @param model.values must contain the mandatory abilities: DEXTERITY,
* WISDOM, and CHARISMA. May also contain the optional abilities.
* @throws {@link model.exceptions.IllegalAbilityScoreException} if a mandatory
* ability is missing or if a value is invalid.
*/
public static AbilityScores create(Map<AbilityName, Integer> values) {
return new RWAbilityScores(values);
}
}
/**
* Read-write implementation of the {@link AbilityScores} interface.
* This class offers additional methods to increment abilities or add bonuses.
* Classes using a {@link RWAbilityScores} attribute should never expose it
* directly but only expose its {@link ROAbilityScores} counterpart.
*/
class RWAbilityScores implements AbilityScores{
/**
* Map of the scores associated with the abilities.
*/
private EnumMap<AbilityName, AbilityScoreType> abilities;
/**
* Initialises an {@link AbilityScores} object with model.values for at least
* some of the abilities.
* @param model.values must contain the mandatory abilities: DEXTERITY,
* WISDOM, and CHARISMA. May also contain the optional abilities.
* @throws {@link model.exceptions.IllegalAbilityScoreException} if a mandatory
* ability is missing or if a value is invalid.
*/
public RWAbilityScores(Map<AbilityName, Integer> values) {
//Validate input
AbilityScores.isValidAbilityScoreInput(values, true);
this.abilities = new EnumMap<AbilityName, AbilityScoreType>(AbilityName.class);
for(Entry<AbilityName, Integer> entry : values.entrySet()) {
this.abilities.put(entry.getKey(), new AbilityScoreType(entry.getValue()));
}
}
/**
* Initialises a {@link RWAbilityScores} object by making a deep-copy of
* the input {@link AbilityScores} object.
* @param abilities object to copy.
*/
public RWAbilityScores(AbilityScores abilities) {
//Reject null input
if(abilities == null) {
throw new IllegalAbilityScoreException(IllegalAbilityScoreException.Cause.NULL);
}
this.abilities = new EnumMap<AbilityName, AbilityScoreType>(AbilityName.class);
for(Map.Entry<AbilityName, AbilityScore> entry : abilities) {
if(entry.getValue() != null) {
this.abilities.put(entry.getKey(), new AbilityScoreType(entry.getValue()));
}
}
}
@Override
public int getModifier(AbilityName ability) {
return abilities.getOrDefault(ability, AbilityScoreType.UNDEFINED).getModifier();
}
@Override
public AbilityScore getScore(AbilityName ability) {
return abilities.get(ability);
}
/**
* @return a read-only object encapsulating this one.
*/
//This method is commented because I left out the ROAbilityScores class.
//public AbilityScores getROAbilityScores() {
// return new ROAbilityScores(this);
//}
/**
* Implementation of the {@link AbilityScore} interface based on the
* {@link Value} class. It adds mutability to the interface, which must be
* managed by the {@link AbilityScores} container.
*/
private static class AbilityScoreType extends Value implements AbilityScore{
final static AbilityScoreType UNDEFINED = new AbilityScoreType(ValueParameters.MIN_ABILITY_SCORE) {
@Override
public int getModifier() {
return 0;
}
@Override
public int getValue() {
throw new IllegalAbilityScoreException(IllegalAbilityScoreException.Cause.UNDEFINED);
}
};
/**
* Basic constructor directly derived from {@link Value#Value(int)}.
* @param value
*/
AbilityScoreType(int value) {
super(value);
}
/**
* Makes a deep copy of the input {@link AbilityScore} object.
* @param value to copy.
*/
AbilityScoreType(AbilityScore value){
super(value.getValue());
}
@Override
public int getModifier() {
return AbilityScore.computeModifier(this.getValue());
}
}
@Override
public Iterator<Map.Entry<AbilityName, AbilityScore>> iterator() {
return new Iterator<Map.Entry<AbilityName, AbilityScore>>(){
//Build atop an iterator for the names
Iterator<AbilityName> nameIterator = EnumSet.allOf(AbilityName.class).iterator();
@Override
public boolean hasNext() {
return nameIterator.hasNext();
}
@Override
public Entry<AbilityName, AbilityScore> next() {
AbilityName name = nameIterator.next();
return new AbstractMap.SimpleImmutableEntry<AbilityName, AbilityScore>(name, getScore(name));
}
};
};
}
</code></pre>
<p>And finally, the IllegalAbilityScoreException.java :</p>
<pre><code>package model.exceptions;
/**
* Exception raised when an object tries to create an illegal
* {@link model.values.AbilityScore} or {@link model.creatures.AbilityScores}.
*/
public class IllegalAbilityScoreException extends RuntimeException {
private static final long serialVersionUID = 6846962934628169718L;
public static enum Cause{
NULL,
UNDEFINED
}
/**
* Initialises an {@link IllegalAbilityScoreException} for when an illegal
* value is given to the constructor.
* @param ability name of the ability with an illegal value.
* @param value value in the illegal call to the AbilityScore
* constructor.
*/
public IllegalAbilityScoreException(String ability, int value){
super("An ability score must be positive or null, received " + value
+ "for ability " + ability + ".");
}
/**
* Initialises an {@link IllegalAbilityScoreException} for when a required
* ability is not initialised.
* @param missingAbility
* @param listOfAbilities
*/
public IllegalAbilityScoreException(String missingAbility, String listOfAbilities) {
super("Ability score " + missingAbility
+ " must be defined, received no value for it in map with "
+ listOfAbilities + ".");
}
/**
* Initialises an {@link IllegalAbilityScoreException} for when an illegal
* call to {@link model.values.Value#getValue()} is performed on the UNDEFINED
* AbilityScore or when an {@link model.creatures.AbilityScores} object is
* initialised with a null input.
*/
public IllegalAbilityScoreException(Cause type) {
super(pickMessage(type));
}
/**
* Picks the message to set in the
* {@link IllegalAbilityScoreException#IllegalAbilityScoreException(Cause)}
* constructor.
* @param cause of the issue raising the exception
* @return the adequate message for the given situation
*/
static private String pickMessage(Cause cause) {
String message;
switch(cause) {
case NULL:
message = "Tried to create an AbilityScores object with a null input";
break;
case UNDEFINED:
message = "Tried to call getValue() on the UNDEFINED AbilityScore.";
break;
default:
message = "An unknown error has occurred";
}
return message;
}
}
</code></pre>
<p><strong>Question 3: is it reasonnable to unit-test the parameters to make sure that they are not set to a value that will break stuff?</strong>
Some parameters must be exactly or above some values. This is written in a specific comment for each value, but to add one more safety net, I have written simple unit tests to check these conditions. Can I?</p>
<p>For example, I have a ValueParametersTest.java file which includes the following code to check the conditions of the ValueParameters class defined in <strong>question 2</strong>:</p>
<pre><code>package service.parameters;
import static org.junit.Assert.*;
import org.junit.Test;
public class ValueParametersTest {
/**
* Checks that the ability score parameters have reasonable values.
*/
@Test
public void testAbilityScoreParameters() {
assertEquals("MIN_ABILITY_SCORE must be 0.", 0, ValueParameters.MIN_ABILITY_SCORE);
assertTrue("MAX_ABILITY_SCORE must be at least 40.", ValueParameters.MAX_ABILITY_SCORE > 40);
}
/**
* Checks that the roll parameters have reasonable values.
*/
@Test
public void testRollParameters() {
assertEquals("MIN_NUMBER_OF_DICE must be 1.", 1, ValueParameters.MIN_NUMBER_OF_DICE);
assertTrue("MIN_NUMBER_OF_SIDES must be at least 1.", ValueParameters.MIN_NUMBER_OF_SIDES >= 1);
assertTrue("MIN_NUMBER_OF_SIDES must be at most 4.", ValueParameters.MIN_NUMBER_OF_SIDES <= 4);
assertTrue("MAX_NUMBER_OF_DICE must be at least 10.", ValueParameters.MAX_NUMBER_OF_DICE >= 10);
assertTrue("MAX_NUMBER_OF_SIDES must be at least 100.", ValueParameters.MAX_NUMBER_OF_SIDES >= 100);
}
}
</code></pre>
|
[] |
[
{
"body": "<blockquote>\n <p>Question 1: Can global parameters be accessed to build a view, or does it break the pattern?</p>\n</blockquote>\n\n<p>I understand your question as:<br>\n<em>Should parameters controlling the view itself be part of the model layer?</em> </p>\n\n<p>My answer to that would be: yes.</p>\n\n<blockquote>\n <p>Question 2: Are my exceptions sane, or I am doing something wrong?</p>\n</blockquote>\n\n<p>The questions are: </p>\n\n<ul>\n<li><p>does the caller need to destinguish between different of your exceptions (for other reason then showing the right error message)? </p>\n\n<p>If not you don't need custom exceptions at all.</p></li>\n<li><p>does the caller need to destinguish between your exceptions and prefefines system Exceptions like i.e. <code>NullPointerException</code> (for other reason then showing the right error message)? </p>\n\n<p>If you answered the previous question with \"yes\" and this with \"no\" a single custom exception may be enough.</p></li>\n</ul>\n\n<blockquote>\n <p>Question 3: is it reasonnable to unit-test the parameters to make sure that they are not set to a value that will break stuff?</p>\n</blockquote>\n\n<p>Unittest verify any <strong>behavior</strong> that is important for your <em>business logic</em>. This means, you don't test <em>data</em> like \"parameters\". </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-24T08:51:38.417",
"Id": "476605",
"Score": "0",
"body": "Thanks! So, I should get rid of my XXXParametersTest class and possibly some of my exceptions if I don't intend on catching them specifically to respond to them, is that right?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-24T10:02:09.357",
"Id": "476609",
"Score": "0",
"body": "@Anab there usually is no \"right or wrong\" ;o) But yes, that is **my** suggestion."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-23T12:29:58.970",
"Id": "242795",
"ParentId": "242351",
"Score": "1"
}
},
{
"body": "<p>You've got some answers to your initial questions, which you seem to be happy with, so I'm not going to address them. There are some things that I noticed about your code, however which I think are worth mentioning.</p>\n<h1>Tests</h1>\n<ul>\n<li><strong>Naming</strong> Consider losing 'test' from the front of your test names. All the methods are annotated and in test class. Having the word test at the front of the method name just adds noise. Consider instead adding some indicator as to what it is you're testing for / the expected value. <code>maxAbilityScore_aboveLowerBound</code>. This will make it easier possible at a glance to see what the test is validating. It doesn't make a lot of difference on these tests, however larger tests (which you have in your github) will be clearer.</li>\n<li><strong>Size</strong> Tests should be aimed at testing one thing. How small 'one thing' is, can be open to interpretation. I tend to come down on the side of smaller is better, because if something breaks it's usually pretty clear what / why. <code>testRollParameters</code> is really testing the number of sides on the die and also the number of dice to roll. These seem like two separate things, so I'd probably break the test up. This might be too small for some people, however if I look at your github, the <code>testGetModifier</code> method contains 4 asserts, with two of them inside a <code>for</code> loop, wrapped in a <code>while</code> loop. This feels like it's testing too much and the intention of the test is lost. Things like parameterised tests and good naming can help maintain the intention if you need to the same test for a different set of inputs.</li>\n</ul>\n<h1>Magic Numbers</h1>\n<p>Consider</p>\n<pre><code>public static int computeModifier(int value) {\n return value/2 - 5;\n}\n</code></pre>\n<p>It may be that 2 and 5 make perfect sense to you, or it may be that they are based on some formula from a book, in which case having them as actual numbers might make sense. However, I'm left wondering why 5, why not 4 or 6. If a constant would make sense here, consider using it to make the calculation clearer.</p>\n<h1>Fail flag / YAGNI</h1>\n<p>The way you're using a parameter to determine failure behaviour adds unnecessary complexity to your <code>isValidAbilityScoreInput</code> method. Every time you encounter an error condition you have <code>if(fail) throw... else return false</code>. This makes the intention of the code harder to follow. Personally, I would rather see two functions <code>isValidAbilityScoreInput</code>, which returns <code>true/false</code> and <code>validateAbilityScoreInput</code>, which throws an exception if it's invalid. This makes it clearer to the caller what behaviour to expect and simplifies the method implementation. This might seem like it's duplicating code, however you could implement it in a way to reduce this duplication. Also, as it stands your code base only ever calls the method with <code>fail</code> set to <code>true</code>, so you only really need the 'throws exception' version currently. Worry about the non-throwing version at the point that you actually need it...</p>\n<h1>There can be only one...or can there?</h1>\n<p>The way you're validating abilities will only flag up the first failing item. Consider:</p>\n<pre><code>for (Entry<AbilityName, Integer> entry : values.entrySet()) {\n if (entry.getValue() < ValueParameters.MIN_ABILITY_SCORE\n || entry.getValue() > ValueParameters.MAX_ABILITY_SCORE) {\n throw new IllegalAbilityScoreException(entry.getKey().toString(), entry.getValue());\n }\n}\n</code></pre>\n<p>The check stops as soon as there is an entry that is invalid. You have a similar approach when checking for mandatory values. This might be acceptable / desired behaviour, however consider if it's worth collecting a list of failing abilities so that they can all be put into the exception.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-17T19:09:12.257",
"Id": "479132",
"Score": "0",
"body": "Thanks for your review! Your first two points are interesting and will go in my todo list. I think I have already addressed the last two. In commit [6193](https://github.com/AnabVangun/CARP/blob/619302f8be7fec503cc1a1c0318434cc349d1737/src/main/java/model/creatures/AbilityScores.java), the `AbilityScores` interface contains a method with signature `public static Map<AbilityName, InvalidityCode> checkAbilityScoresValidity(Map<AbilityName, Integer> values)` instead of the previous `isValidAbilityScoreInput`. What do you think? I'll check for other places where the points apply."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-18T08:54:07.647",
"Id": "479185",
"Score": "0",
"body": "@Anab If you need the error information, it seems like an improvement. However, consider the value of your comments. If the comment simply states what the code does 'reject null input', you probably don't need it. They can easily become out of date when you don't update them as you change the code '//If not, find the missing one and throw an exception'..."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-17T11:15:11.087",
"Id": "244032",
"ParentId": "242351",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "242795",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-15T16:20:08.253",
"Id": "242351",
"Score": "4",
"Tags": [
"java",
"unit-testing",
"mvvm",
"exception"
],
"Title": "Sanity check a simple RPG character"
}
|
242351
|
<p>I designed a simple timeout thrower for a bluetooth protocol I am writing. If the packet is not received in a certain amount of time, then timeout is thrown. I made it to be as plug and play as possible.</p>
<p>timeout.hpp: </p>
<pre><code>#ifndef __timeout_h__
#define __timeout_h__
#include <thread>
struct Timeoutthread{
private:
int sleep;
public:
Timeoutthread(int seconds);
void time(bool* alert);
};
class Timeout{
private:
int sleep;
bool alert;
public:
Timeout(int seconds);
bool timeout();
};
#endif
</code></pre>
<p>timeout.cpp:</p>
<pre><code>#include "timeout.hpp"
Timeout::Timeout(int seconds){
sleep = seconds;
Timeoutthread timeoutthread(sleep);
std::thread timeout(&Timeoutthread::time,timeoutthread,&alert);
timeout.detach();
}
bool Timeout::timeout(){
return alert;
}
Timeoutthread::Timeoutthread(int seconds){
sleep = seconds;
}
void Timeoutthread::time(bool* alert){
std::this_thread::sleep_for (std::chrono::seconds(sleep));
*alert = true;
}
</code></pre>
<p>simple implementation:</p>
<pre><code>#include <iostream>
#include "timeout.hpp"
int main(){
std::string message = "";
Timeout timeout(10);
while(message == ""){
message = readBLE();
if(timeout.timeout() == true)
message = "timed out";
}
std::cout<<message<<std::endl;
return 0;
}
</code></pre>
<p>The loop waits for a bluetooth message, but if no message is received in 10 seconds, then a timeout is thrown. </p>
<p>Is this an efficient way to do it. I want to make sure that I am not wasting any resources.</p>
<p><strong>EDIT:</strong></p>
<p>There seems to be some confusion on the <code>readBLE()</code> part. There is a lot more code associated with this part but it does not act like <code>std::cin</code> where it is waiting for a user input. Whenever <code>readBLE()</code> is called, if there was no message received, then it would just return an empty string. Sorry for the confusion.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-15T17:13:52.853",
"Id": "475595",
"Score": "0",
"body": "Do you mean to say your `(read from bluetooth)` returns in at most ten seconds?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-15T19:06:09.290",
"Id": "475598",
"Score": "0",
"body": "@bipll at most it will take 10 seconds before the loop ends with a timeout."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-15T19:10:30.187",
"Id": "475599",
"Score": "0",
"body": "Why don't you just store time data when you begin reading and compare it after each failed attempt? It's wasteful to create a thread to deal with it. Not to mention that you have data racing issues."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-15T19:23:23.810",
"Id": "475601",
"Score": "0",
"body": "@ALX23z using the system time sounds logical and simple. When I was researching timeouts, I didn’t find any examples of someone using system times, they would all use some sort of multi threading, so I feel like there could be some advantage to it over just system time."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-16T07:10:06.513",
"Id": "475655",
"Score": "0",
"body": "@AubreyChampagne this is how it is normally implemented. Also not system time (as it can be adjusted) instead stick to a monotonous clock like `steady_clock`. Don't trust some weird sources of info."
}
] |
[
{
"body": "<h1>The <code>Timeout</code> class doesn't solve the problem you have</h1>\n\n<p>If you write:</p>\n\n<pre><code>message = (read from bluetooth);\nif(timeout.timeout() == true)\n message = \"timed out\";\n</code></pre>\n\n<p>Then it will first wait for the message to be read from Bluetooth, which might take more than 10 seconds, and then once you have the message, it will check whether more than 10 seconds have passed since the start, and if so it will discard the message you got. The fact that the timer is run in its own thread does not magically make <code>(read from bluetooth)</code> exit after the timer expires.</p>\n\n<p>What you instead have to do is run the <code>(read from bluetooth)</code> command in a thread, and wait at most 10 seconds for that to complete. With C++11, you can do this very easily with <a href=\"https://en.cppreference.com/w/cpp/thread/async\" rel=\"nofollow noreferrer\"><code>std::async()</code></a>:</p>\n\n<pre><code>#include <future>\n#include <chrono>\n\n...\n\nauto future = std::async(std::launch::async, [] {\n return (read from bluetooth);\n});\n\nauto status = future.wait_for(std::chrono::seconds(10));\n\nif (status == std::future_status::ready)\n message = future.get();\nelse\n message = \"timed out\";\n</code></pre>\n\n<p>The problem however is that if there is a timeout, the thread running the Bluetooth read command is still running. When exiting the scope, the destructor of <code>future</code> will block until the thread finishes execution. So this kind of approach has a limited use.</p>\n\n<p>The best solution would be to find some wait to make <code>(read from bluetooth)</code> itself give up after 10 seconds, or have some way to cause it to stop waiting for data.</p>\n\n<h1>Identifiers with double underscores are reserved</h1>\n\n<p>You should not use identifiers that start with underscores, or contain double underscores, as they are <a href=\"https://en.cppreference.com/w/cpp/language/identifiers\" rel=\"nofollow noreferrer\">reserved</a>, and might be used by the compiler and/or the standard library. This even applies to macros, so instead of:</p>\n\n<pre><code>#ifndef __timeout_h__\n#define __timeout_h__\n</code></pre>\n\n<p>Write:</p>\n\n<pre><code>#ifndef timeout_h\n#define timeout_h\n</code></pre>\n\n<p>Or use the following pragma that most compilers understand, and that ensure that a header file is only read once:</p>\n\n<pre><code>#pragma once\n</code></pre>\n\n<h1>Store durations as <code>std::chrono::duration</code></h1>\n\n<p>Avoid storing timeouts as <code>int</code>, this limits the resolution. Instead, consider using <code>std::chrono::duration</code> to store the timeout period.</p>\n\n<h1>Make member functions <code>const</code> where appropriate</h1>\n\n<p>If a member function doesn't modify any member variables, mark it as <code>const</code>, like so:</p>\n\n<pre><code>class Timeout {\n ...\n bool timeout() const;\n}\n</code></pre>\n\n<h1>Ensure variables are properly initialized</h1>\n\n<p>You never initialize <code>alert</code> to <code>false</code>, so a call to <code>timeout()</code> might return an uninitialized value.</p>\n\n<h1>Use <a href=\"https://en.cppreference.com/w/cpp/atomic/atomic\" rel=\"nofollow noreferrer\"><code>std::atomic<></code></a> variables when communicating between threads</h1>\n\n<p>If you write:</p>\n\n<pre><code>Timeout timeout(10);\n// do something\nif (timeout.timeout())\n ...\n</code></pre>\n\n<p>Then the compiler might know that <code>alert</code> is set to <code>false</code> in the first line, and if it can prove that <code>do something</code> never touches the variable <code>timeout</code>, then it can assume in the third line that <code>alert</code> will always be <code>false</code>. To ensure the compiler does not make such assumptions when threads are involved, you have to tell it that it should atomically read and write this flag.</p>\n\n<h1>Do you need a separate thread at all?</h1>\n\n<p>The only thing your <code>Timeoutthread</code> does is sleep for a certain amount of time, then set a variable. You know that the threads sets that variable a given number of seconds after it starts. So instead of using a thread, you can just store the current time when an instance of <code>Timeout</code> is created in a separate member variable, and in <code>timeout()</code> just check the difference between the current time now and the time stored in that member variable.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-15T20:36:49.647",
"Id": "475610",
"Score": "0",
"body": "@MartinYork Oops, you're right. I updated the answer."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-15T21:46:15.867",
"Id": "475615",
"Score": "0",
"body": "It seems like comparing the time is the way to go, but I'm still trying to figure out why most forums suggest using another thread that just sleeps."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-16T10:59:14.343",
"Id": "475675",
"Score": "0",
"body": "Op says his `(read from bluetooth)` returns in at most ten seconds so your concern no. 1 is irrelevant."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-15T19:48:30.697",
"Id": "242364",
"ParentId": "242352",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "242364",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-15T16:36:01.203",
"Id": "242352",
"Score": "3",
"Tags": [
"c++",
"multithreading",
"timeout",
"protocols"
],
"Title": "Timeout thrower using multithreading"
}
|
242352
|
<p>I've created my first gem in Profitwell API wrapper <a href="https://github.com/eebasadre20/profitwell" rel="nofollow noreferrer">https://github.com/eebasadre20/profitwell</a>. I love to get some feedback, comment, or suggestion on the code structure, method implementations, and so on.</p>
<p>I am more concerned in my code structure like how I structured to handle the module and class, the request-response handling, error handling, and parameters handling.</p>
<p>Here is one of the examples of my resource:</p>
<pre><code>module Profitwell
class Plans
include Client
def all
request(
"get",
resource_path("plans")
)
end
def find(plan_id)
request(
"get",
resource_path("plans/#{plan_id}")
)
end
def create(params = {})
request(
"post",
resource_path("plans"),
options: params
)
end
def update(plan_id, params = {})
request(
"put",
resource_path("plans/#{plan_id}"),
options: params
)
end
end
end
</code></pre>
<p>I would be very pleased if you give me some feedback regarding the code structure and implementation - <a href="https://github.com/eebasadre20/profitwell" rel="nofollow noreferrer">Profitwell API Wrapper</a></p>
<p>Everyone is welcome to share your idea and contribute to this simple project.</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-15T17:07:49.523",
"Id": "242354",
"Score": "2",
"Tags": [
"ruby",
"api"
],
"Title": "Profitwell API wrapper build as Ruby gem"
}
|
242354
|
<p>My mentor says to reproduce the system() function of Linux exactly as given in the man pages. I have written the below code. Could someone review this code and provide me any suggestions for improvising. I am a beginner. Thanks :).</p>
<pre><code> #include<stdio.h>
#include<unistd.h>
#include<sys/types.h>
#include<sys/wait.h>
#include<error.h>
int my_system(const char *command);
int my_system(const char *command)
{
int ret = 0;
ret = execl("/bin/sh", "sh", "-c", command, (char *)NULL);
if (ret == -1)
error(1, 0, "error occcured in the execl() system call\n");
}
int main(int argc, char *argv[])
{
pid_t pid;
int ret;
int wstatus;
if (argc > 2)
error(1, 0, "Too many arguments\n");
pid = fork();
if (pid == -1) {
error(1, 0, "error in creating the sub-process\n");
} else if (pid == 0) {
ret = my_system(argv[1]);
} else {
wait(NULL);
}
return 0;
}
<span class="math-container">```</span>
</code></pre>
|
[] |
[
{
"body": "<h1>Enable compiler warnings and fix all of them</h1>\n\n<p>I immediately see that your function <code>my_system()</code>, which should return an <code>int</code>, does not contain a <code>return</code> statement. That means the return value is undefined. If you enable compiler warnings, the compiler will complain about such mistakes.</p>\n\n<h1>Don't add unnecessary forward declarations</h1>\n\n<p>Why add a forward declaration of <code>my_system()</code> right before the actual implementation? This is an unnecessary repetition of code. It's best to always try to not repeat yourself.</p>\n\n<h1>Read the man page again and pay attention to the details</h1>\n\n<p>You implemented the call to <code>execl()</code> exactly as written in the man page, but that is only the easy part. You have to ensure that the return value and the behavior in the presence of errors is exactly as the man page describes.</p>\n\n<p>In particular, <code>system()</code> does not call <code>error()</code> when there is an error, instead the return value and the value of <code>errno</code> is used to convey the type of error that has occurred.</p>\n\n<h1>Create a test suite before making any changes to <code>my_system()</code></h1>\n\n<p>You could change <code>my_system()</code> right now to fix any immediately obvious errors, but the temptation is very high that afterwards you consider the implementation to be complete. Instead, try to create a test suite first that calls <code>my_system()</code> in different ways to ensure that its behavior matches that given in the man page.\nAlso, instead of making assumptions of what the required behavior is, in this case you can just check what the actual <code>system()</code> function does.</p>\n\n<p>So such a test suite could look like:</p>\n\n<pre><code>#include <assert.h>\n...\nconst char *commands[] = {\n \"/bin/true\",\n \"/bin/false\",\n // add more commands here\n \"\",\n NULL,\n};\n\nfor (int i = 0; ; i++) {\n int my_ret = my_system(commands[i]);\n int my_errno = errno;\n int ret = system(commands[i]);\n assert(my_ret == ret);\n if (ret == -1)\n assert(my_errno == errno);\n\n if(!commands[i])\n break;\n}\n<span class=\"math-container\">```</span>\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-15T19:00:23.363",
"Id": "242361",
"ParentId": "242356",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "242361",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-15T17:48:59.643",
"Id": "242356",
"Score": "2",
"Tags": [
"c",
"linux",
"unix"
],
"Title": "Reproduce the system() function of linux"
}
|
242356
|
<p>Here's my attempt at trying to understand <code>synchronized()</code> blocks using an Object lock, using <code>wait()</code> and <code>notify()</code>:</p>
<pre class="lang-java prettyprint-override"><code>
import java.util.Scanner;
public class SyncTest {
private Scanner scanner;
private Object lock;
private volatile String string;
public SyncTest() {
scanner = new Scanner(System.in);
lock = new Object();
string = "";
}
public void start() {
//This thread will wait until the other thread notifies it.
Thread t1 = new Thread(new Runnable() {
@Override
public void run() {
while (true) {
synchronized (lock) {
try {
lock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("String changed.");
}
}
});
t1.start();
//This thread will notify Thread 1 if a condition is met.
Thread t2 = new Thread(new Runnable() {
@Override
public void run() {
while (true) {
if (!string.isEmpty()) {
synchronized (lock) {
lock.notify();
}
string = "";
}
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
});
t2.start();
//This is just a dummy thread to modify the string data.
Thread t3 = new Thread(new Runnable() {
@Override
public void run() {
while (true) {
string = scanner.nextLine();
}
}
});
t3.start();
}
public static void main(String[] args) {
new SyncTest().start();
}
}
</code></pre>
<p>Couple questions:</p>
<ol>
<li><p>Is there any better way of achieving such functionality?</p></li>
<li><p>Is this how listeners work? How are they so efficient at listening to events? I mean, if I don't add the 200ms delay in <code>t2</code> execution, the thread will consume a lot of processing power, so, how can I create a listener behavior?</p></li>
</ol>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-15T23:12:36.220",
"Id": "475622",
"Score": "1",
"body": "As for #2: Beware that a listener is nothing more than an object instance that has one or more methods that get called by the object instance that it has been passed to. In principle, a listener does not have to do any multithreading: the code that is run by the listener is generally run in the thread of the method that calls it. And for #1, yes, we use `java.util.concurrent`. If you're doing locking yourself, you're likely reinventing some threaded wheel."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-15T23:31:15.983",
"Id": "475623",
"Score": "0",
"body": "@MaartenBodewes, so, for example, what's the best way of constantly checking if a variable \"changes\" to trigger some kind of action?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-16T00:07:01.573",
"Id": "475627",
"Score": "0",
"body": "What you're probably looking for is a \"Monitor\". Although `java.util.concurrent` doesn't have a `Monitor` class it does have, for instance, `ReentrantLock`, see [here](https://dzone.com/articles/java-concurrency-%E2%80%93-part-5) for a (seemingly good) explanation."
}
] |
[
{
"body": "<p>It does look sound to me with one exception that you need to be aware of, as far as I can see:</p>\n<pre class=\"lang-java prettyprint-override\"><code>if (!string.isEmpty()) {\n synchronized (lock) {\n lock.notify();\n }\n string = "";\n}\n</code></pre>\n<p>The moment you set <code>string</code> to a new value, the first thread might not have visited the variable at this point. You can see that when outputting <code>string</code> in both threads. This is only important if thread #1 is going to do processing on the value.</p>\n<p>Additionally, because of the <code>Thread.sleep(200);</code> you might miss input lines because <code>string</code> value might have changed an unidentified number of times during this period.</p>\n<hr />\n<blockquote>\n<p>I mean, if I don't add the 200ms delay in t2 execution, the thread will consume a lot of processing power, so, how can I create a listener behavior?</p>\n</blockquote>\n<p>The same way you did between #2 and #1, <code>notify</code> #2 from #3.</p>\n<hr />\n<p>To fix these issues, you want to use something like a <code>BlockingQueue</code>. Thread #3 pushes the line to the <code>Queue</code>, thread #2 dequeues the next value and notifies #1. Or, #2 pushes it to a second <code>Queue</code> for #1.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-16T18:42:45.353",
"Id": "242416",
"ParentId": "242357",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "242416",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-15T18:09:40.480",
"Id": "242357",
"Score": "2",
"Tags": [
"java",
"multithreading"
],
"Title": "Example using Object lock synchronized blocks"
}
|
242357
|
<p>This code is meant to retry the db operation when a DB connection breaks: OperationalError.</p>
<p>A transaction can fail for example when a db is being restarted and a commit fails. Or when a network error causes error in the DB transaction. (Variables-Names have been adjusted for demo).</p>
<p>My current method forcefully closes the current connection and re-establishes connections. Could there be a better way of doing this?</p>
<pre><code>import psycopg2
from configs import mydb
class DBConnection:
"""connect to db to get data"""
def __init__(self):
self.establish_connections()
def establish_connections(self):
# connect to the database
self.connection = psycopg2.connect(
application_name="all_data",
dbname=mydb.dbname,
user=mydb.user,
password=mydb.password,
host=mydb.host,
)
self.connection.autocommit = True
self.cursor = self.connection.cursor()
print("Connected to DBConnection")
def record_data(self, results):
sql_command = f"""INSERT INTO
msg_results(results)
VALUES ('{results}');"""
try:
self.cursor.execute(sql_command)
except psycopg2.OperationalError:
print("psycopg2.OperationalError: record_data")
# close old connection
try:
self.connection.close()
except:
print("Exception: in record_data while trying to close existing connection")
#restart connection
self.establish_connections()
# TRY THE TRANSACTION AGAIN
self.record_data(results)
# another error occurred, this has failed, go home
except Exception as e:
print("CALCResultsConnection.record_data", str(e))
<span class="math-container">```</span>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-16T07:27:26.627",
"Id": "475657",
"Score": "2",
"body": "Look into tenacity or retrying libraries (or other Open source libraries), which can ease out your retry logics for any domain. If you want me to give detailed example with your code as example, let me know, I will leave an answer"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-16T10:53:41.170",
"Id": "475674",
"Score": "0",
"body": "Thanks @kushj. Yes please, I kindly request for a detailed answer"
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-15T18:47:46.040",
"Id": "242359",
"Score": "2",
"Tags": [
"python",
"python-3.x",
"database",
"postgresql"
],
"Title": "Handling failures in DB transactions"
}
|
242359
|
<p>More than once I claimed that using binary search doesn't improve performance of the insertion sort. For example, see <a href="https://codereview.stackexchange.com/a/242155/40480">answer here</a> and <a href="https://codereview.stackexchange.com/a/241402/40480">comments here</a>). Now I have time to substantiate my claim.</p>
<p>The only practical application of the insertion sort, where we actually do care about performance, is sorting <em>almost sorted</em> data; that is such data where each element is within a fixed distance from its final destination. Only this scenario is benchmarked.</p>
<p>First, the implementations of insertion sorts (<code>insertion_sort.h</code>)</p>
<pre><code>#include <algorithm>
template<typename It>
void straight_insertion_sort(It first, It last) {
for (auto cur = first + 1; cur < last; ++cur) {
auto val = *cur;
auto it = cur;
if (val < *first) {
for (it = cur; it > first; --it) {
*it = *(it - 1);
}
} else {
for (it = cur; val < *(it - 1); --it) {
*it = *(it - 1);
}
}
*it = val;
}
}
template<typename It>
void binary_insertion_sort(It first, It last) {
for (auto cur = first + 1; cur < last; ++cur) {
auto val = *cur;
auto insertion_point = std::lower_bound(first, cur - 1, *cur);
std:: copy_backward(insertion_point, cur - 1, cur);
*insertion_point = val;
}
}
</code></pre>
<p>The benchmarks shall run against an almost sorted data. This is how the testcases are prepared. (<code>incomplete_qsort.h</code>, the code is adapted from <a href="https://en.cppreference.com/w/cpp/algorithm/partition" rel="nofollow noreferrer">std::partition</a>) example; cutoff is added to make the array <em>almost sorted</em>. After a call to <code>incomplete_qsort</code> every element is at most <code>cutoff</code> away from where it is supposed to be. NB: this is not really for a review, but only for completeness.</p>
<p>Note: I need <a href="/questions/tagged/c%2b%2b14" class="post-tag" title="show questions tagged 'c++14'" rel="tag">c++14</a> here. <a href="/questions/tagged/c%2b%2b11" class="post-tag" title="show questions tagged 'c++11'" rel="tag">c++11</a> does not allow <code>auto</code> as an argument to <code>lambda</code>.</p>
<pre><code>#include <algorithm>
template<typename It>
void incomplete_qsort(It first, It last, size_t cutoff) {
if (std::distance(first, last) < cutoff) {
return;
}
auto pivot = *first;
auto mid1 = std::partition(first, last,
[pivot](const auto& em) {return em < pivot; });
auto mid2 = std::partition(mid1, last,
[pivot](const auto& em) {return !(pivot < em); });
incomplete_qsort(first, mid1, cutoff);
incomplete_qsort(mid2, last, cutoff);
}
</code></pre>
<p>This is the driver (<code>benchmark.cpp</code>):</p>
<pre><code>#include "incomplete_qsort.h"
#include "insertion_sort.h"
#include <chrono>
#include <iostream>
#include <iomanip>
#include <iostream>
#include <numeric>
#include <random>
#include <vector>
using iter = std::vector<int>::iterator;
using sorter = void (*)(iter, iter);
double run_benchmark(std::vector<int>& data, sorter s) {
auto start = std::chrono::system_clock::now();
s(data.begin(), data.end());
auto end = std::chrono::system_clock::now();
std::chrono::duration<double> diff = end - start;
return diff.count();
}
int main(int argc, char ** argv)
{
std::random_device rd;
std::mt19937 g(rd());
for (int i = 12; i < 25; i++) {
auto size = 1 << i;
std::vector<int> data1(size);
std::vector<int> data2(size);
std::iota(data1.begin(), data1.end(), 0);
std::shuffle(data1.begin(), data1.end(), g);
incomplete_qsort(data1.begin(), data1.end(), 16);
std::copy(data1.begin(), data1.end(), data2.begin());
double duration1 = run_benchmark(data1, straight_insertion_sort);
double duration2 = run_benchmark(data2, binary_insertion_sort);
std::cout << std::setw(8) << size << ": "
<< std::setw(8) << duration1
<< std::setw(8) << duration2
<< " (" << duration2 / duration1 << ")"
<< '\n';
}
}
</code></pre>
<p>And finally the results, compiled with <code>-O3</code>:</p>
<pre><code> 4096: 5.2e-05 0.000158 (3.03846)
8192: 9.1e-05 0.000269 (2.95604)
16384: 0.000161 0.000494 (3.06832)
32768: 0.000275 0.000968 (3.52)
65536: 0.000555 0.001823 (3.28468)
131072: 0.001171 0.003686 (3.14774)
262144: 0.002084 0.007765 (3.72601)
524288: 0.004457 0.015087 (3.38501)
1048576: 0.008304 0.030951 (3.72724)
2097152: 0.017204 0.063931 (3.71605)
4194304: 0.033697 0.132659 (3.93682)
8388608: 0.06833 0.277166 (4.05629)
16777216: 0.136164 0.569059 (4.17922)
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-16T11:11:34.430",
"Id": "475676",
"Score": "0",
"body": "Sorry, but is there a specific question here, i.e., what in particular are you looking for in an answer?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-16T15:44:37.957",
"Id": "475705",
"Score": "1",
"body": "@Juho According to the chapter of this exchange, any facet of the code presented is a fair game for a reviewer. I am interested in everything people may come up with. Style, methodology, omissions, outright errors, etc."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-16T15:55:38.250",
"Id": "475706",
"Score": "0",
"body": "Ok, thanks for the clarification!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-16T17:49:46.857",
"Id": "475731",
"Score": "0",
"body": "Correct me if I'm wrong, but the results seem to indicate that binary search is still an aver of 3 times faster than insertion sort."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-17T00:18:35.657",
"Id": "475767",
"Score": "0",
"body": "@pacmaninbw Umm... I don't see it. The last column is `binary / straight`."
}
] |
[
{
"body": "<ul>\n<li><p><strong>Naming</strong></p>\n\n<p>As pointed in comments, <code>duration1</code> and <code>duration2</code> are bad names since they lead to a confusion. <code>duration_straight</code> and <code>duration_binary</code> seem to be better choice.</p></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-17T00:46:34.313",
"Id": "242434",
"ParentId": "242365",
"Score": "1"
}
},
{
"body": "<p>Your initial claim sounds about right to me, since for each iteration, checking at most <code>cutoff</code> elements for the <code>insertion_point</code> in the straight version (due to the restriction on the input) should become increasingly faster than checking logarithmic many in the binary version. Of course there is a lot more to consider like <a href=\"https://en.wikipedia.org/wiki/Locality_of_reference\" rel=\"noreferrer\">cache locality</a>, but computational complexity should be the dominating factor in this case. That being said, I see some potential to improve your benchmark.</p>\n\n<h2>Benchmarking</h2>\n\n<h3>Verify that your implementations are correct</h3>\n\n<p>A testsuite would of course be best practice, but the absolute minimum is to make sure that your algorithms return the same result as <code>std::sort</code>. The binary insertion sort you provided has an off-by-one-error, thus rendering your results useless. For the following two lines, the shown fix was to increase all end-iterators by one:</p>\n\n<pre><code>auto insertion_point = std::lower_bound(first, cur, *cur);\nstd::copy_backward(insertion_point, cur, cur + 1);\n</code></pre>\n\n<h3>Choose a suitable baseline</h3>\n\n<p>Without any generally accepted baseline for the runtime of the algorithms, it is hard to argue whether the results are significant in any way. Again, <code>std::sort</code> does the job.</p>\n\n<h3>Test against (somewhat) equally optimized implementations</h3>\n\n<p>I am not an expert in optimization, but managed to shave off about 30% of the runtime of the binary version by adding an early return and using <code>std::upper_bound</code> instead of <code>std::lower_bound</code>, both of which indirectly happen in your straight version:</p>\n\n<pre><code>for (auto cur = first + 1; cur < last; ++cur) {\n if (*(cur - 1) < *cur) { continue; }\n auto val = *cur;\n auto insertion_point = std::upper_bound(first, cur, *cur);\n std::copy_backward(insertion_point, cur, cur + 1);\n *insertion_point = val;\n}\n</code></pre>\n\n<p>The change from <code>std::lower_bound</code> to <code>std::upper_bound</code> does not change much due to the input format, which leads us to the next chapter.</p>\n\n<h3>Use realistic data</h3>\n\n<p>In your benchmark, you simply shuffle the numbers from 0 to n and partially sort them again, which means that there are no duplicates in the input. This is a rather strict constraint and probably allows for even more optimized algorithms (e.g. bucket sort). An input vector where each element is drawn from a chosen probability distribution (and then again partially sorted) should yield more representative results.</p>\n\n<p>Additionally, you should always put some thought into the type of elements you are sorting, e.g. for <code>int</code> copying is fine, but for larger classes the benchmark needs to be adapted towards utilizing <code>std::move</code>.</p>\n\n<h3>Run tests multiple times</h3>\n\n<p>This is especially important for micro optimizations, so small <code>size</code> in our case, and the reason why microbenchmark support libraries like <a href=\"https://github.com/google/benchmark\" rel=\"noreferrer\">google/benchmark</a> exist. If you’re not willing to put up with the hazzle of integrating it in your project, <a href=\"http://quick-bench.com/\" rel=\"noreferrer\">quick-bench.com</a> allows for easy online benchmarking.</p>\n\n<p>I quickly threw together an example using your code and the fixed algorithm, you can find it <a href=\"http://quick-bench.com/VsGg3pkTpteNs--EK19EeZrUyhk\" rel=\"noreferrer\">here</a>.</p>\n\n<h3>Specify your compiler version and hardware</h3>\n\n<p>This is not as relevant for proving a general point, but of course results will differ when using compilers of different development levels (or even using your own homecrafted one). Here, websites like quick-bench come in handy again.</p>\n\n<h2>Code quality</h2>\n\n<h3>Naming</h3>\n\n<p>As mentioned by others, <code>duration1</code> and <code>duration2</code> as well as <code>data1</code> and <code>data2</code> are quite unhelpful. Also, iterators are usually named <code>begin</code> and <code>end</code> instead of <code>first</code> and <code>last</code>. Other than that, your naming is expressive enough.</p>\n\n<h3>Creating the input vector</h3>\n\n<p>You initialize two vectors of the needed size, thus default initializing all the elements. Then you fill the first one and copy the partially sorted result back to the other. Preferably, one would reserve an empty vector and then use a custom function like <code>iota_n</code> (<a href=\"https://stackoverflow.com/questions/11767512/what-would-be-a-good-implementation-of-iota-n-missing-algorithm-from-the-stl\">example</a>) to back-insert all the elements. Once they are shuffled and partially sorted, simply use</p>\n\n<pre><code>auto data_copy = initial_data;\n</code></pre>\n\n<p>instead of calling <code>std::copy</code>.</p>\n\n<p>Also, you included <code><iostream></code> twice.</p>\n\n<h3>Insertion sort</h3>\n\n<p>Whereas binary_insertion_sort is readable and reasonably easy to grasp, it took me a while longer for straight_insertion_sort. The if-case can only occur in the beginning of the range to sort and does nothing but catch an edge-case. It can be simplified to </p>\n\n<pre><code>for (auto cur = first + 1; cur < last; ++cur) {\n if (*cur < *first) {\n std::rotate(first, cur, cur + 1);\n }\n else {\n auto val = *cur;\n auto it = cur;\n for (it = cur; val < *(it - 1); --it) {\n *it = *(it - 1);\n }\n *it = val;\n }\n}\n</code></pre>\n\n<p>, which actually seems to be a bit faster. I tried making the else-case more readable whilst preserving speed by using <code>std::rotate</code> once more, but failed to do so.</p>\n\n<p>For both algorithms, you use <code><</code> to compare iterators, where usually <code>!=</code> is used, see <a href=\"https://stackoverflow.com/questions/6673762/why-is-used-with-iterators-instead-of\">this SO thread</a>. It doesn’t make any difference speedwise.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-17T18:55:56.810",
"Id": "475838",
"Score": "2",
"body": "Welcome to Code Review. This is a very good first contribution!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-17T22:41:56.513",
"Id": "475846",
"Score": "0",
"body": "Great review, thanks."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-17T17:35:56.853",
"Id": "242472",
"ParentId": "242365",
"Score": "8"
}
}
] |
{
"AcceptedAnswerId": "242472",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-15T21:30:24.380",
"Id": "242365",
"Score": "4",
"Tags": [
"c++",
"c++14",
"benchmarking",
"insertion-sort"
],
"Title": "Benchmarking insertion sort"
}
|
242365
|
<pre><code>package labodeva;
import java.util.Scanner;
public class odev5dene {
static int[] quick(int kucuk,int buyuk,int[] arr,int pivot) {
int bos[] = new int[100];
int t=0;
while(kucuk<=buyuk) { // buyuk is big kucuk is small
if(arr[kucuk]<=arr[pivot]) {
kucuk++;
}
else if(arr[buyuk]>arr[pivot]) {
buyuk--;
}
else{
bos[0] = arr[kucuk];
arr[kucuk]=arr[buyuk];
arr[buyuk] = bos[0];
buyuk--;
kucuk++;
}
}
if(kucuk>buyuk) {
bos[0] = arr[pivot];
arr[pivot]=arr[buyuk];
arr[buyuk]=bos[0];
pivot=buyuk; //sil
}
if(pivot-1>0&&pivot+1<arr.length) {
quick(0,pivot-1,arr,0);
quick(pivot+1,arr.length-1,arr,pivot+1);
}
if(pivot+1<arr.length&&pivot-1<0) {
quick(pivot+1,arr.length-1,arr,pivot+1);
}
return arr;
}
public static void main(String[] args) {
int a =0;
Scanner scan = new Scanner(System.in);
System.out.println("Please enter how many value do you want to add the array : ");
a=scan.nextInt();
int k[] =new int[a];
for(int i=0;i<a;i++) {
System.out.println("Please enter your "+(i+1)+".value");
k[i]=scan.nextInt();
}
k=quick(0,a-1,k,0); // it starts 0. element as pivot and goes on and also small and equal number value starts here big number value starts at the end of list
for(int i=0;i<a;i++) {
System.out.println(k[i]);
}
}
}
</code></pre>
<p>i wrote this code and it sorts the given array but i tried to do quicksort is this quicksort i am not sure can you check ?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-16T05:18:14.257",
"Id": "475641",
"Score": "0",
"body": "(I always found it slightly more taxing to follow source code with comments&identifiers in my first language, and keywords in English as compared to sticking to (Pidgin) English.)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-16T05:23:47.743",
"Id": "475642",
"Score": "0",
"body": "I expect a *production strength* quicksort implementation to a) use additional space growing not nearly as fast as the number *n* of items *even worst case* b) not show worst case time for reverse sorted input, let alone sorted one."
}
] |
[
{
"body": "<ol>\n<li>In quicksort, when you are sorting from elements 20 to 40, and the split becomes 30, the recursive calls should be to sort 20 to 29 and 31 to 40. You did 0 to 29 and 31 to max. I suspect this made your code degenerate into an <span class=\"math-container\">\\$O(n^2)\\$</span> sort (but still work).</li>\n<li>In quicksort, you should not pass in a pivot. The function should work that out itself.</li>\n<li>Variable bos is a problem. You only ever use bos[0], so you shouldn't even make an array, just a simple variable.</li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-16T00:03:32.403",
"Id": "242371",
"ParentId": "242368",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-15T23:00:19.497",
"Id": "242368",
"Score": "-1",
"Tags": [
"java",
"beginner",
"algorithm",
"quick-sort"
],
"Title": "Does this code I wrote do what we expect from the quick sort algorithm?"
}
|
242368
|
<p>Goal: apply <code>fn</code> to every element of an arbitrarily nested iterable (tuple, list, dict, np.ndarray), including to iterables. Ex:</p>
<pre class="lang-py prettyprint-override"><code>def fn1(x, key): # ignore `key` for now
return str(x) if not isinstance(x, Iterable) else x
def fn2(x, key):
return x ** 2 if isinstance(x, (int, float, np.generic)) else x
arr = np.random.randint(0, 9, size=(2, 2))
obj = (1, {'a': 3, 'b': 4, 'c': ('5', 6., (7, 8)), 'd': 9}, arr)
deepmap(obj, fn1) == ('1', {'a': '3', 'b': '4', 'c': ('5', '6.0', ('7', '8')), 'd': '9'},
array([[6, 1], [5, 4]]))
deepmap(obj, fn2) == (1, {'a': 9, 'b': 16, 'c': ('5', 36.0, (49, 64)), 'd': 81},
array([[36, 1], [25, 16]]))
</code></pre>
<p><a href="https://codereview.stackexchange.com/questions/241654/deep-len-python"><code>deeplen</code></a> should also be a special case of <code>deepmap</code>, with proper <code>fn</code> (just a demo, don't care for optimizing this):</p>
<pre class="lang-py prettyprint-override"><code>def deeplen(obj):
count = [0]
def fn(x, key):
if not isinstance(x, Iterable) or isinstance(x, str):
count[0] += 1
return x
deepmap(obj, fn)
return count[0]
deeplen(obj) == 12
</code></pre>
<p>My working implementation, along tests, below. Unsure this works without OrderedDict (Python >=3.6 default); it does if key order doesn't change even as values are changed (but no keys inserted/popped). A resolution is appending actual Mapping keys to <code>key</code> instead of their index, but this complicates implementing. (As for why pass <code>key</code> to <code>fn</code>: we can implement e.g. <code>deepequal</code>, comparing <code>obj</code> against another obj; this requires key info. Also <a href="https://repl.it/repls/SilverUnnaturalGigahertz" rel="nofollow noreferrer"><code>deepcopy</code></a>.)</p>
<p>Any improvements? I haven't tested exhaustively - maybe there are objects for which this fails, hence subject to extendability. Performance/readability could be better also.</p>
<hr>
<p><strong>Visualization</strong>: <code>deepmap</code> traverses a nest <em>left-to-right</em>, <em>inward-first</em>: (<a href="https://repl.it/repls/UnhealthyUnrulyEyestrain" rel="nofollow noreferrer">code</a>)</p>
<p><a href="https://i.stack.imgur.com/Y574G.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Y574G.png" alt="enter image description here"></a></p>
<ul>
<li><em>Purple</em>: <code>fn</code> applied to iterable / element</li>
<li><em>Blue</em>: <code>tuple()</code> applied to list</li>
<li><em>Green</em>: <code>list()</code> applied to tuple</li>
<li><em>Grey</em>: iterable exit; dropping <code>key[-1]</code> and decrementing <code>depth</code> - no operation</li>
<li><em>Green + Purple</em>: <code>fn(item)</code> is only assigned to <code>list</code>-cast tuple; no 'intermediate' state</li>
<li><em>Empty</em>: see placement of <code>print</code> in linked code; this is to show effect of list+fn</li>
</ul>
<hr>
<p><strong>Implementation</strong>: <a href="https://repl.it/@OverLordGoldDra/WealthyMoralEngines" rel="nofollow noreferrer">live demo</a></p>
<pre class="lang-py prettyprint-override"><code>from collections.abc import Mapping
def deepmap(obj, fn):
def deepget(obj, key=None, drop_keys=0):
if not key or not obj:
return obj
if drop_keys != 0:
key = key[:-drop_keys]
for k in key:
if isinstance(obj, Mapping):
k = list(obj)[k] # get key by index (OrderedDict, Python >=3.6)
obj = obj[k]
return obj
def dkey(x, k):
return list(x)[k] if isinstance(x, Mapping) else k
def nonempty_iter(item):
# do not enter empty iterable, since nothing to 'iterate' or apply fn to
try:
list(iter(item))
except:
return False
return not isinstance(item, str) and len(item) > 0
def _process_key(obj, key, depth, revert_tuple_keys, recursive=False):
container = deepget(obj, key, 1)
item = deepget(obj, key, 0)
if nonempty_iter(item) and not recursive:
depth += 1
if len(key) == depth:
if key[-1] == len(container) - 1: # iterable end reached
depth -= 1 # exit iterable
key = key[:-1] # drop iterable key
if key in revert_tuple_keys:
supercontainer = deepget(obj, key, 1)
k = dkey(supercontainer, key[-1])
supercontainer[k] = tuple(deepget(obj, key))
revert_tuple_keys.pop(revert_tuple_keys.index(key))
if depth == 0 or len(key) == 0:
key = None # exit flag
else:
# recursively exit iterables, decrementing depth
# and dropping last key with each recursion
key, depth = _process_key(obj, key, depth, revert_tuple_keys,
recursive=True)
else: # iterate next element
key[-1] += 1
elif depth > len(key):
key.append(0) # iterable entry
return key, depth
key = [0]
depth = 1
revert_tuple_keys = []
if not nonempty_iter(obj): # nothing to do here
raise ValueError(f"input must be a non-empty iterable - got: {obj}")
elif isinstance(obj, tuple):
obj = list(obj)
revert_tuple_keys.append(None) # revert to tuple at function exit
while key is not None:
container = deepget(obj, key, 1)
item = deepget(obj, key, 0)
if isinstance(container, tuple):
ls = list(container) # cast to list to enable mutating
ls[key[-1]] = fn(item, key)
supercontainer = deepget(obj, key, 2)
k = dkey(supercontainer, key[-2])
supercontainer[k] = ls
revert_tuple_keys.append(key[:-1]) # revert to tuple at iterable exit
else:
k = dkey(container, key[-1])
container[k] = fn(item, key)
key, depth = _process_key(obj, key, depth, revert_tuple_keys)
if None in revert_tuple_keys:
obj = tuple(obj)
return obj
</code></pre>
<p><strong>Testing</strong>:</p>
<pre class="lang-py prettyprint-override"><code>import numpy as np
from collections.abc import Iterable
from copy import deepcopy
from time import time
from deepmap import deepmap
def fn1(x, key):
return str(x) if not isinstance(x, Iterable) else x
def fn2(x, key):
return x ** 2 if isinstance(x, (int, float, np.generic)) else x
def fn3(x, key):
return str(x)
def make_bigobj():
arrays = [np.random.randn(100, 100), np.random.uniform(30, 40, 10)]
lists = [[1, 2, '3', '4', 5, [6, 7]] * 555, {'a': 1, 'b': arrays[0]}]
dicts = {'x': [1, {2: [3, 4]}, [5, '6', {'7': 8}] * 99] * 55,
'b': [{'a': 5, 'b': 3}] * 333, ('k', 'g'): (5, 9, [1, 2])}
tuples = (1, (2, {3: np.array([4., 5.])}, (6, 7, 8, 9) * 21) * 99,
(10, (11,) * 5) * 666)
return {'arrays': arrays, 'lists': lists,
'dicts': dicts, 'tuples': tuples}
def deeplen(obj):
count = [0]
def fn(x, key):
if not isinstance(x, Iterable) or isinstance(x, str):
count[0] += 1
return x
deepmap(obj, fn)
return count[0]
#### CORRECTNESS ##############################################################
np.random.seed(4)
arr = np.random.randint(0, 9, (2, 2))
obj = (1, {'a': 3, 'b': 4, 'c': ('5', 6., (7, 8)), 'd': 9}, {}, arr)
out1 = deepmap(deepcopy(obj), fn1)
assert str(out1) == ("('1', {'a': '3', 'b': '4', 'c': ('5', '6.0', ('7', '8'))"
", 'd': '9'}, {}, array([[7, 5],\n [1, 8]]))")
out2 = deepmap(deepcopy(obj), fn2)
assert str(out2) == ("(1, {'a': 9, 'b': 16, 'c': ('5', 36.0, (49, 64)), "
"'d': 81}, {}, array([[49, 25],\n [ 1, 64]]))")
out3 = deepmap(deepcopy(obj), fn3)
assert str(out3) == (r"""('1', "{'a': 3, 'b': 4, 'c': ('5', 6.0, (7, 8)), """
r"""'d': 9}", '{}', '[[7 5]\n [1 8]]')""")
try:
deepmap([], fn1)
except ValueError:
pass
except:
print("Failed to catch invalid input")
#### PERFORMANCE ##############################################################
bigobj = make_bigobj()
_bigobj = deepcopy(bigobj)
t0 = time()
assert deeplen(bigobj) == 53676
print("deeplen: {:.3f} sec".format(time() - t0))
assert str(bigobj) == str(_bigobj) # deeplen should not mutate `bigobj`
bigobj = deepcopy(_bigobj)
t0 = time()
deepmap(bigobj, fn1)
print("deepmap-fn1: {:.3f} sec".format(time() - t0))
# deepmap-fn2 takes too long
</code></pre>
<pre><code>deeplen: 0.856 sec
deepmap-fn1: 0.851 sec
</code></pre>
<hr>
<p><strong>Updates</strong>:</p>
<ol>
<li><p><code>deepmap</code> failed with <em>empty iterables</em>, e.g. <code>[]</code>, <code>{}</code> - fixed, tests updated. Also added invalid input handling.</p></li>
<li><p>Improved <code>nonempty_iter</code> to use <a href="https://stackoverflow.com/questions/1952464/in-python-how-do-i-determine-if-an-object-is-iterable#answer-36407550"><code>try-iter</code></a>, and applied it as check on <code>obj</code> at input. Unsure what test to add as my use-case is TensorFlow - a more general suggestion is welcome.</p></li>
<li><p>Improved <code>nonempty_iter</code> again. <code>try-iter</code> is insufficient to determine whether <code>obj</code> is <em>Python-iterable</em>; some objects (e.g. TensorFlow <a href="https://github.com/tensorflow/tensorflow/blob/master/tensorflow/python/framework/ops.py#L266" rel="nofollow noreferrer"><code>Tensor</code></a>) support creating <em>generators</em> but not <em>consuming</em> them without <a href="https://github.com/tensorflow/tensorflow/blob/master/tensorflow/python/ops/map_fn.py#L47" rel="nofollow noreferrer">dedicated methods</a>. It does become a question of what exactly we're mapping and with what methods; in that case, object-specific treatment is required.</p>
<ul>
<li>This can be considered a limitation rather than improvement, as it doesn't allow non-Pythonic iteration (non-indices/hash keys) - but an exception will be thrown unless improvement #2 below is implemented, and it's an unlikely edge case anyway.</li>
</ul></li>
</ol>
<hr>
<p><strong>Possible improvements</strong>:</p>
<ol>
<li><code>fn</code> could also apply to Mappable <code>.keys()</code> instead of <code>.values()</code> only</li>
<li>Only Pythonic iterables are iterated with current implementation (see Update 3). More general access and assignment specifiers can be implemented - but code beyond <code>deepget</code> would require modifying (e.g. <code>supercontainer[k]</code>).</li>
</ol>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-20T02:35:23.900",
"Id": "476071",
"Score": "0",
"body": "`deepmap((1, 2, [3, 4]), fn3)` returns `('1', 2', '[3, 4]')`. I expected `('1', '2', ['3', '4'])`. `deepmap` should apply the function (`fn3`) recursively to all the nested elements (e.g., the 3 and 4) not just to the top level elements (e.g. [3, 4]). Right?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-20T02:42:18.577",
"Id": "476072",
"Score": "0",
"body": "@RootTwo Negative; note the goal statement: \"apply `fn` to every element of an arbitrarily nested iterable (tuple, list, dict, np.ndarray), **including to iterables**\" - so `[3, 4]` is cast to string before it can be iterated; `fn1` yields the behavior you describe. This is intended, as it gives more flexibility to what we can do with `fn`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-20T03:32:33.103",
"Id": "476078",
"Score": "0",
"body": "I guess I don't understand the interface between `deepmap` and the function. How does `deepmap` determine whether to recursively apply a function to an iterable, a la `fn1`, versus to apply the function to the whole iterable, a la `fn3`. Does the recursion occur when the function returns the argument unchanged? In this call, `deepmap((1, 2, [3, 4]), fn3)`, the first argument is an iterable, so `fn3` should be applied to the iterable as a whole and return `\"(1, 2, [3, 4])\"`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-20T04:46:19.387",
"Id": "476081",
"Score": "0",
"body": "@RootTwo Added visual; good last point - the \"whole\" iterable is exempt from `fn`, on logic that it is the \"object\" whose internals we're mapping, and that we can just `fn(obj)` if needed, no `deepmap` necessary."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-15T23:01:55.897",
"Id": "242369",
"Score": "4",
"Tags": [
"python",
"python-3.x",
"iterator"
],
"Title": "Deep map, Python"
}
|
242369
|
<p>Doubts in logic to generate the output file according to the example
I need that even if he reaches the total_min <720 condition he continues to travel the lines. 720 is the total number of minutes before lunch, when reached, it should separate the activities that should be performed after lunch (lunch must be inserted manually).</p>
<ul>
<li>I need to make a system that reads a TXT file (intput.txt).</li>
<li>This file has several lines.</li>
<li>Each line an activity with execution time (30min, 45min, 60min)</li>
<li>Activities should start at 9 am.</li>
<li>Half day (12:00) lunch break</li>
<li>Generate a TXT with organized activities (output.txt)</li>
</ul>
<blockquote>
<p>intput.txt</p>
</blockquote>
<pre><code>Correr 60min
Estudar 30min
Ler 45min
Escrever 60min
Caminhar 45min
Jogar 30min
</code></pre>
<blockquote>
<p>Example how the output.txt file should look</p>
</blockquote>
<pre><code>09:00 Correr 60min
10:00 Estudar 30min
10:30 Ler 45min
11:15 Caminhar 45min
12:00 Almoço 60min
13:00 Jogar
(...)
</code></pre>
<blockquote>
<p>My code:</p>
</blockquote>
<pre><code> public static void main(String[] args) throws IOException {
// TODO code application logic here
ArrayList<String> antes_almoco = new ArrayList<String>();
ArrayList<String> depois_almoco = new ArrayList<String>();
int total_min = 540;
int horas = total_min / 60;
int minutos = total_min % 60;
String trinta = "30min";
String quarentaCinco = "45min";
String sessenta = "60min";
boolean trinta_min = false;
boolean quarentaCinco_min = false;
boolean sessenta_min = false;
String path = "C:\\input.txt";
String outputDir = "C:\\output.txt";
FileReader arq = new FileReader(path);
BufferedReader lerArq = new BufferedReader(arq);
String linha;
//Output
File file2 = new File(outputDir);
FileWriter arq_output = new FileWriter(file2, true);
PrintWriter gravarArq = new PrintWriter(arq_output);
if (!file2.exists()) {
file2.createNewFile();
}
while ((linha = lerArq.readLine()) != null) {
trinta_min = linha.toLowerCase().contains(trinta.toLowerCase());
quarentaCinco_min = linha.toLowerCase().contains(quarentaCinco.toLowerCase());
sessenta_min = linha.toLowerCase().contains(sessenta.toLowerCase());
if (sessenta_min == true) {
total_min += 60;
if (total_min < 720) {
antes_almoco.add(linha);
} else if (total_min > 720) {
depois_almoco.add(linha);
}
}
if (trinta_min == true && total_min < 720) {
total_min += 30;
if (total_min < 720) {
antes_almoco.add(linha);
} else if (total_min > 720) {
depois_almoco.add(linha);
}
}
if (quarentaCinco_min == true && total_min < 720) {
total_min += 45;
if (total_min < 720) {
antes_almoco.add(linha);
} else if (total_min > 720) {
depois_almoco.add(linha);
}
}
if (total_min == 720) {
total_min += 60;
antes_almoco.add("12:00 Almoço");
}
}
for (String cont : antes_almoco) {
System.out.println(cont);
gravarArq.printf("%d:%02d %s \n", horas, minutos, cont);
}
for (String cont : depois_almoco) {
//System.out.println(cont);
gravarArq.printf("%d:%02d %s \n", horas, minutos, cont);
}
lerArq.close();
gravarArq.close();
arq.close();
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-16T04:01:54.960",
"Id": "475636",
"Score": "1",
"body": "Can you clarify the question? Are you just looking for a general code review, or is there a problem?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-16T05:31:36.700",
"Id": "475644",
"Score": "0",
"body": "(`lunch must be inserted manually` I hate the vision of being machine (force) fed.)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-16T05:36:55.463",
"Id": "475645",
"Score": "0",
"body": "(`720 is the total number of minutes` & `start at 9 am. Half day (12:00) lunch break` is that working surprisingly short minutes, or looong hours?)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-16T05:46:26.303",
"Id": "475647",
"Score": "0",
"body": "I see neither `lunch inserted manually` nor `horas` or `minutos` computed/updated: I don't see how this can possibly work: [off topic at CodeReview@SE](https://codereview.stackexchange.com/help/on-topic)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-16T08:01:49.170",
"Id": "475659",
"Score": "0",
"body": "I am looking for a general code review. I have a problem, for me to insert lunch I have the following `if (total_min == 720)`, but it does not insert when the variable `total_min` is passed previously."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-16T15:13:47.287",
"Id": "475702",
"Score": "2",
"body": "720 minutes is 12 hours, not 3 hours. It's 180 minutes from 9 am to 12 noon. An entire conference day is 6 or 7 hours (360 or 420 minutes) at most. @greybeard made a joke, but there's something wrong with your instructions."
}
] |
[
{
"body": "<p>I revised your code and ran some tests. </p>\n\n<p>Here is the input to my last test.</p>\n\n<pre><code>Correr 60min\nEstudar 30min\nLer 45min\nEscrever 60min\nCaminhar 45min\nCutting of steel sheets 60min\nJogar 30min\n</code></pre>\n\n<p>Here is the output from my last test.</p>\n\n<pre><code>09:00 Correr 60min\n10:00 Estudar 30min\n10:30 Ler 45min\n11:15 Escrever 60min\n12:15 Almoço 60min\n01:15 Caminhar 45min\n02:00 Cutting of steel sheets 60min\n03:00 Jogar 30min\n</code></pre>\n\n<p>The first major change I made to your code was to write a method to convert elapsed minutes to time.</p>\n\n<p>I only needed one <code>List</code> to hold the events. Actually, I didn't need the <code>List</code> at all. I could have written the string out as I created it, but I left the <code>List</code> in.</p>\n\n<p>I also simplified the processing of each line. All I need is the number of minutes that the event lasts. This code can handle any number of minutes, not just 30, 45, or 60.</p>\n\n<p>Edited to add: I revised the code to handle an input line with an event that has spaces in the event text.</p>\n\n<pre><code>import java.io.BufferedReader;\nimport java.io.File;\nimport java.io.FileReader;\nimport java.io.FileWriter;\nimport java.io.IOException;\nimport java.io.PrintWriter;\nimport java.util.ArrayList;\nimport java.util.List;\n\npublic class Schedule {\n\n public static void main(String[] args) throws IOException {\n // TODO code application logic here\n\n List<String> events = new ArrayList<>();\n\n String path = \"C:\\\\Eclipse\\\\Eclipse-2020-workspace\\\\\"\n + \"com.ggl.testing\\\\resources\\\\input.txt\";\n String outputDir = \"C:\\\\Eclipse\\\\Eclipse-2020-workspace\\\\\"\n + \"com.ggl.testing\\\\resources\\\\output.txt\";\n\n FileReader arq = new FileReader(path);\n BufferedReader lerArq = new BufferedReader(arq);\n\n // Output\n File file2 = new File(outputDir);\n FileWriter arq_output = new FileWriter(file2, true);\n PrintWriter gravarArq = new PrintWriter(arq_output);\n\n if (!file2.exists()) {\n file2.createNewFile();\n }\n\n int totalMinutes = 0;\n int lunchMinutes = 180;\n boolean beforeLunch = true;\n\n String linha;\n while ((linha = lerArq.readLine()) != null) {\n String[] fields = linha.split(\" \");\n int lastIndex = fields.length - 1;\n int endIndex = fields[lastIndex].lastIndexOf(\"min\");\n int duration = Integer.valueOf(\n fields[lastIndex].substring(0, endIndex));\n\n String output = \"\";\n for (int i = 0; i < fields.length; i++) {\n output += fields[i] + \" \"; \n }\n output = toTime(totalMinutes) + \" \" + output;\n events.add(output.trim());\n\n totalMinutes += duration;\n\n if (beforeLunch && totalMinutes >= lunchMinutes) {\n output = toTime(totalMinutes) + \" Almoço 60min\";\n events.add(output);\n totalMinutes += 60;\n beforeLunch = false;\n }\n }\n\n for (String cont : events) {\n System.out.println(cont);\n gravarArq.println(cont);\n }\n\n lerArq.close();\n gravarArq.close();\n arq.close();\n }\n\n private static String toTime(int minutes) {\n int hours = minutes / 60 + 9;\n hours = hours % 12;\n hours = (hours == 0) ? 12 : hours;\n minutes = minutes % 60;\n return String.format(\"%02d:%02d\", hours, minutes);\n }\n\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-16T16:14:09.053",
"Id": "475709",
"Score": "0",
"body": "Thank you Gilbert! The following error is returning to me:`Exception in thread \"main\" java.lang.StringIndexOutOfBoundsException: String index out of range: -1\n at java.lang.String.substring(String.java:1967)` Is it an error reading the String?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-16T16:16:46.460",
"Id": "475712",
"Score": "0",
"body": "@RonisonMatos: Does the input current line have \"min\" at the end? Is there a space between the name and the duration?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-16T16:26:56.600",
"Id": "475716",
"Score": "0",
"body": "It has \"min\", but the number of characters in the line is greater. Follows current first line. `Cutting of steel sheets 60min`. if I put `Correr 60min` it works"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-16T16:41:28.480",
"Id": "475719",
"Score": "1",
"body": "@RonisonMatos: I wasn't aware that event text could contain spaces. See my revised answer."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-16T16:49:53.800",
"Id": "475721",
"Score": "0",
"body": "Worked perfectly! Thank you!"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-16T16:02:47.893",
"Id": "242407",
"ParentId": "242372",
"Score": "3"
}
},
{
"body": "<pre class=\"lang-java prettyprint-override\"><code>ArrayList<String> antes_almoco = new ArrayList<String>();\nArrayList<String> depois_almoco = new ArrayList<String>();\n</code></pre>\n\n<ol>\n<li>You should use the lowest common denominator that you always need, in this case you should declare the variables as <code>List<String></code>, as you most likely don't need to bind yourself to a specific implementation.</li>\n<li>Java naming conventions are lowerCamelCase for variables.</li>\n</ol>\n\n<hr>\n\n<pre class=\"lang-java prettyprint-override\"><code>int horas = total_min / 60;\n</code></pre>\n\n<p>Not a problem here, but be aware that dividing an integer by an integer will always yield an integer:</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>double value = 5 / 2;\n// value == 2.0\n</code></pre>\n\n<hr>\n\n<pre class=\"lang-java prettyprint-override\"><code>String path = \"C:\\\\input.txt\";\nString outputDir = \"C:\\\\output.txt\";\n</code></pre>\n\n<p>You could make those relative to the jar, so this application would also run on non-Windows systems.</p>\n\n<p>Also, the variable name is wrong, it's not a directory.</p>\n\n<p>Also also, declare variables when they are needed, not all of them on the start of the block. It allows you to limit variables to certain scopes and makes refactoring easier as everything that belongs together is together.</p>\n\n<hr>\n\n<pre class=\"lang-java prettyprint-override\"><code>FileReader arq = new FileReader(path);\n</code></pre>\n\n<p>\"Native\" resources like files, sockets, etc. require a well-defined lifecycle so that they are correctly freed when not needed anymore. You can use the try-with-resources for that or call <code>close</code> on the resources you don't need anymore.</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>FileReader reader = new FileReader(path);\n\n// Application logic.\n\nreader.close();\n</code></pre>\n\n<pre class=\"lang-java prettyprint-override\"><code>try (FileReader reader = new FileReader(path)) {\n // Logic.\n} // close being called automatically when leaving the block.\n</code></pre>\n\n<hr>\n\n<p>There is the <code>java.time</code> API, especially the <code>Duration</code> class which seems to be highly applicable to your use-case.</p>\n\n<p>Now what you could do with this is, to split it into functions and classes. That would be a good exercise. A good start for that would be to extract the representation of a single line to a class, like this:</p>\n\n<pre><code>// All time-classes from java.time.\n\npublic class TimeEntry {\n public TimeEntry(LocalTime startTime, String name, Duration duration);\n public static TimeEntry create(String stringRepresentation);\n @Override\n public String toString();\n // Getters for these values.\n}\n</code></pre>\n\n<p>The <code>create</code> Method is a factory method which parses the string representation as in the file and outputs a valid <code>TimeEntry</code> class or <code>null</code>. The <code>toString</code> returns the string representation as in the file.</p>\n\n<p>That means that your loop can be basically summed up as:</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>for (String line : lines) {\n TimeEntry timeEntry = TimeEntry.create(line);\n\n if (timeEntry != null) {\n doLogicOnIt(timeEntry);\n }\n}\n\n</code></pre>\n\n<p>Also you should separate reading from writing. There are times when you want to do both at the same time, but to exercise separation I'd suggest to read the file in one function that returns a <code>List</code> of <code>TimeEntry</code>s, then there is another function manipulating that list and and a third writing it to a file. That has the upside that you can read and write the files faster, you're not bound to the files as input/output source and you can easier control the lifecycle of the file handles.</p>\n\n<p>Now, there are times when reading everything into memory is inappropriate. That is when you either have a pipe as input, or if the state you're reading from the file is too large to keep in memory. Neither is the case here.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-16T18:24:38.703",
"Id": "242414",
"ParentId": "242372",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "242407",
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-16T03:06:38.857",
"Id": "242372",
"Score": "2",
"Tags": [
"java",
"algorithm",
"object-oriented",
"dynamic-programming",
"topological-sorting"
],
"Title": "(Java) Read .txt and organize activities for hours / minutes"
}
|
242372
|
<p>The powers of 2 are trivial to factor because all powers of 2 have one <strong>1-bit</strong> and the rest <strong>0-bits</strong>. Just iterate minus one 0-bit as follows: 10000,1000,100,10,1. And then convert the binary strings into base-10 and you got the factors for <em>powers of 2</em>.</p>
<p>Example</p>
<pre><code>import operator
from operator import mul
from functools import reduce
import time
print('Find the factors of a power of 2')
print('This input number must be a power of 2')
X = 32
binary = "{0:b}".format(int(X))
l = len(binary)
# Checking if input is power of 2
# All binary strings that are a power of 2 must
# have only ONE 1 bit
if binary.count(str(1)) == 1:
print('yes, this is a power of two')
else:
print('no, this is not a power of 2')
quit()
start = (round(time.time() * 1000000))
count = 0
result = [];
for j in range(0, l):
count = count + 1
# create list of factors called result
result.append(int(binary[0:l-count], 2))
if len(result) == l-1:
# I don't want to forget X itself is a factor
result.append(X)
end = (round(time.time() * 1000000))
break
print(result)
print('Factoring took', end-start, 'microseconds')
</code></pre>
<h2>Output</h2>
<pre class="lang-none prettyprint-override"><code>Find the factors of a power of 2
This input number must be a power of 2
yes, this is a power of two
[16, 8, 4, 2, 1, 32]
Factoring took 0 microseconds
</code></pre>
<h2>Question</h2>
<p>What better names could I use to define my variables, and what could make the program run faster?</p>
<p>Is there a more efficient implementation to decide if a number is a power of 2?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-16T04:13:52.050",
"Id": "475637",
"Score": "0",
"body": "have you considered using `<<` and `>>` ?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-16T04:15:04.227",
"Id": "475638",
"Score": "0",
"body": "@impopularGuy I've been practicing python since August of last year and not exactly sure how to use that. Could you give an example?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-16T04:33:15.540",
"Id": "475639",
"Score": "2",
"body": "[This answer](https://stackoverflow.com/a/600306/8363478) explains beautiful way to check whether a number is power of 2"
}
] |
[
{
"body": "<ol>\n<li>There should be some function definitions. <code>is_power_of_2</code>, <code>powers_of_2_below</code> and a <code>main</code>.</li>\n<li>It's good practice to use an <code>if __name__ == '__main__'</code> guard.</li>\n<li>Please stop putting lots of spaces at the end of lines.</li>\n<li>Many of the imports are not used.</li>\n<li>Always indent with 4 spaces.</li>\n</ol>\n\n<pre class=\"lang-py prettyprint-override\"><code>import time\n\n\ndef is_power_of_2(X):\n binary = \"{0:b}\".format(int(X))\n return binary.count(str(1)) == 1\n\n\ndef powers_of_2_below(X):\n binary = \"{0:b}\".format(int(X))\n l = len(binary)\n count = 0\n result = [];\n for j in range(0, l):\n count = count + 1\n # create list of factors called result\n result.append(int(binary[0:l-count], 2))\n if len(result) == l-1:\n # I don't want to forget X itself is a factor\n result.append(X)\n break\n return result\n\n\ndef main(X):\n print('Find the factors of a power of 2')\n print('This input number must be a power of 2')\n if is_power_of_2(X):\n print('yes, this is a power of two')\n else:\n print('no, this is not a power of 2')\n quit()\n start = (round(time.time() * 1000000))\n result = factors_of_power_of_2(X)\n end = (round(time.time() * 1000000))\n print(result)\n print('Factoring took', end - start, 'microseconds')\n\n\nif __name__ == '__main__':\n main(X)\n</code></pre>\n\n<ol start=\"6\">\n<li>You can now use <code>return</code> rather than <code>quit</code> to exit <code>main</code>.</li>\n<li>The code in <code>is_power_of_2</code> is fine. There are a couple other ways you can implement it but they're all pretty underwhelming.</li>\n<li>By replacing <code>count</code> with <code>(j + 1)</code> we can remove the need for that variable.</li>\n<li>By using <code>j</code> rather than <code>(j + 1)</code> we can remove the need for the <code>if</code> in the for.</li>\n<li>To get <code>l</code> in <code>powers_of_2_below</code> we can use <code>X.bit_length()</code>.</li>\n<li>We can instead use <code>1 << j</code> to build the value from <code>j</code> alone. This however will invert the output.</li>\n</ol>\n\n<pre class=\"lang-py prettyprint-override\"><code>import time\n\n\ndef is_power_of_2(x):\n binary = \"{0:b}\".format(int(x))\n return binary.count(str(1)) == 1\n\n\ndef powers_of_2_below(x):\n result = []\n for j in range(0, x.bit_length()):\n result.append(1 << j)\n return result\n\n\ndef main(x):\n print('Find the factors of a power of 2')\n print('This input number must be a power of 2')\n if is_power_of_2(x):\n print('yes, this is a power of two')\n else:\n print('no, this is not a power of 2')\n return\n start = (round(time.time() * 1000000))\n result = factors_of_power_of_2(x)\n end = (round(time.time() * 1000000))\n print(result)\n print('Factoring took', end - start, 'microseconds')\n\n\nif __name__ == '__main__':\n main(32)\n</code></pre>\n\n<ol start=\"12\">\n<li><p>We can use a list comprehension instead of a for loop in <code>powers_of_2_below</code>.</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>def powers_of_2_below(x):\n return [1 << j for j in range(x.bit_length())]\n</code></pre></li>\n</ol>\n\n<p>Alternate solutions to <code>is_power_of_2</code>:</p>\n\n<ol start=\"13\">\n<li><p>We can use <code>powers_of_2_below</code> with <code>&</code> and <code>any</code>.</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>def is_power_of_2(x):\n x = abs(x)\n if x == 0:\n return False\n return not any(x & i for i in powers_of_2_below(x - 1))\n</code></pre></li>\n<li><p>We can replace the <code>any</code> with just <code>x & x - 1</code>. This is because <span class=\"math-container\">\\$1000 - 1 = 0111\\$</span>. Logically this is doing exactly the same as 13.</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>def is_power_of_2(x):\n x = abs(x)\n if x == 0:\n return False\n return not x & x - 1\n</code></pre></li>\n<li><p>We can instead use <code>x.bit_length()</code> to construct the power of 2 it should be and check they are the same.</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>def is_power_of_2(x):\n if x == 0:\n return False\n return abs(x) == 1 << x.bit_length() - 1\n</code></pre></li>\n</ol>\n\n<p>Overall <code>is_power_of_2</code> just doesn't look nice.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-17T15:38:41.313",
"Id": "242467",
"ParentId": "242373",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-16T04:06:27.290",
"Id": "242373",
"Score": "0",
"Tags": [
"python",
"bitwise",
"math-expression-eval"
],
"Title": "Factoring the powers of 2 in Python"
}
|
242373
|
<p>I am creating a 2D text-based Drawing Application which can draw basic shapes like Line, Rectangle, Triangle, Circle, Oval. The Line can be drawn in eight directions on a 2D plane and can be moved by a user in Left, Right, Up and Down directions. </p>
<p>The Lines(or any other Shape) are contained within a Boundary. Lines(or any other Shape) must respect the boundary and warn the user when he tries to move the Line beyond the Boundary, here's the visual example,</p>
<pre><code>* * * * * * * * * * * * * * * * * * * * * *
* *
* *
* *
* *
* 6 7 8 *
* 6 7 8 *
* 6 7 8 *
* 6 7 8 *
* 6 7 8 *
* 5 5 5 5 5 8 1 1 1 1 1 *
* 4 3 2 *
* 4 3 2 *
* 4 3 2 *
* 4 3 2 *
* 4 3 2 *
* *
* *
* *
* *
* *
* * * * * * * * * * * * * * * * * * * * * *
</code></pre>
<p>In the above diagram, the Boundary is made of <code>*</code> marks and the numbers 1-8 represent each possible line on a 2D plane.</p>
<p>Since there are 8 types of Line and each line can be moved-in 4 possible directions, this is how I am detecting whether the user move was valid or not( Move is valid if the Line moved is within the Boundary).</p>
<p>So let' say the Line was (0,x) which means it grows linearly only on x-coordinate (East Direction Only) and user moved it in Left direction,</p>
<pre><code>//I am repeating below logic for each different type of Line
if( lineYCoordinate == 0 && lineXCoordinate == 1 ){ //Detect what type of line it was
switch( User.Move){ // Detect what move did user made
case LEFT: {
//check if line is overlapping the window
// if overlapping warn user else move the line
}
case RIGHT: {
//check if line is overlapping the window
// if overlapping warn user else move the line
}
case UP: {
//check if line is overlapping the window
// if overlapping warn user else move the line
}
case DOWN: {
//check if line is overlapping the window
// if overlapping warn user else move the line
}
}
}
</code></pre>
<p>So here's the problem, the above entire logic was just for one type of Line. Currently, I am repeating the same logic for other 7 types of Lines too. The logic to determine whether the Line is overlapping with Boundary depends on which type of Line it was and in which direction it was moved. </p>
<p>How can I refactor this logic, so that I can reuse or minimize the multiple switch and if-else constructs?</p>
<p>As advised, this is the method which I want to refactor.</p>
<pre><code>boolean isOverlappingWindow(Window window, Utils.MenuOption option) {
boolean isOverlapping = false;
//rInc & cInc is equivalent as x, y coordinate respectively
if (rInc == 0 && cInc == 1) { //detect line type
switch (option) { //detect user move
case DOWN: {
if ((rb + 2) > window.lastRowForBorder) {
--rb;
}
break;
}
case RIGHT: {
if ((cb + length + 2) > window.lastColumnForBorder) {
--cb;
}
break;
}
case LEFT: {
if (cb < window.firstColumnForBorder) {
++cb;
}
break;
}
case UP: {
if (rb < window.firstRowForBorder) {
++rb;
}
break;
}
}
}
if (rInc == 1 && cInc == 0) {
switch (option) {
case DOWN: {
if ((rb + length + 2) > window.lastRowForBorder) {
--rb;
}
break;
}
case RIGHT: {
if ((cb + 2) > window.lastColumnForBorder) {
--cb;
}
break;
}
case LEFT: {
if (cb < window.firstColumnForBorder) {
++cb;
}
break;
}
case UP: {
if (rb < window.firstRowForBorder) {
++rb;
}
break;
}
}
}
if (rInc == 0 && cInc == -1) {
switch (option) {
case DOWN: {
if ((rb + 2) > window.lastRowForBorder) {
--rb;
}
break;
}
case RIGHT: {
if ((cb + 2) > window.lastColumnForBorder) {
--cb;
}
break;
}
case LEFT: {
if ((Math.abs(length - cb)) < window.firstColumnForBorder) {
++cb;
}
break;
}
case UP: {
if (rb < window.firstRowForBorder) {
++rb;
}
break;
}
}
}
if (rInc == -1 && cInc == 0) {
//same goes here
}
if (rInc == 1 && cInc == 1) {
//same goes here
}
if (rInc == 1 && cInc == -1) {
// same goes here
}
if (rInc == -1 && cInc == -1) {
//same goes here
}
if (rInc == -1 && cInc == 1) {
// same goes here
}
return isOverlapping;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-16T05:51:20.437",
"Id": "475648",
"Score": "0",
"body": "Welcome to CodeReview@SE. Please present [actual code from your project](https://codereview.stackexchange.com/help/on-topic) for review."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-16T08:13:44.393",
"Id": "475661",
"Score": "0",
"body": "@greybeard added the actual code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-16T11:25:28.010",
"Id": "475677",
"Score": "0",
"body": "The method doesn't compile by itself, and the variable names are so cryptic that I can't make heads or tails about what the code is supposed to do. Unless the code compiles, I can't refactor it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-16T14:32:21.810",
"Id": "475698",
"Score": "1",
"body": "While this claims to be object-oriented I don't see any classes in the question. One of the ways to reduce code duplication is to create a base class and inherit the the base class for the common functions. Code design / object design is off-topic for code review where we review code that is working as expected to provide suggestions on how to improve that code. Try https://softwareengineering.stackexchange.com/help/dont-ask or https://stackoverflow.com/help/dont-ask."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-17T08:53:16.630",
"Id": "475788",
"Score": "0",
"body": "`//same goes here` No no, you either post the code and we can help you with a review, or you don't post the code. It looks like you got something going here, but please be complete when posting your code or you're making it needlessly difficult on the reviewers. We don't handle that very well."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-17T09:04:51.147",
"Id": "475790",
"Score": "1",
"body": "@Mast this was my first question, I'll remember all the tips the reviewers have added and will make sure that I don't repeat the same mistakes."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-17T14:53:19.390",
"Id": "475819",
"Score": "0",
"body": "Good! For maximum effect, reading the [FAQ on asking questions](https://codereview.meta.stackexchange.com/q/2436/52915) might help too. Best of luck with your next question."
}
] |
[
{
"body": "<p>One of the great things about working with OOP, is instance methods and polymorphism. </p>\n\n<p>If you add methods in a <code>Line</code> class to perform this logic. Then you hold several instances of the line, and move each with a simple method call. You can also make use of inner properties to make the calculation simpler. </p>\n\n<p>This may not help enough. You said there are 8 <em>types</em> of lines, so I'm assuming there some difference in the logic. In other words, you can make 8 classes which <code>extend Line</code> and customizes the general logic from <code>Line</code> to make the implementation work for the line type.</p>\n\n<p>An example code for the concept:</p>\n\n<pre><code>class Line {\n private double motionSpeed;\n\n public void move(Direction direction) {\n switch(direction) {\n case UP:\n moveBy(0, -motionSpeed);\n break;\n // other cases\n }\n }\n\n // child classes will implement how to actually move\n protected abstract void moveBy(double x, double y);\n}\nclass LineType1 extends Line {\n\n @Override\n protected void moveBy(double x, double y) {\n // actually move\n } \n}\n\nclass UI {\n private Collection<Line> lines;\n\n public void moveLines(Direction direction) {\n for (Line line : lines) {\n line.move(direction);\n } \n }\n}\n<span class=\"math-container\">```</span> \n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-16T15:13:39.550",
"Id": "475701",
"Score": "0",
"body": "To sum it up, I need to **create more Classes** and make use of **polymorphism and dynamic binding** to replace multiple switch and if-else constructs."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-16T16:35:34.693",
"Id": "475718",
"Score": "0",
"body": "Thats the OOP option, yeah. If you already have a list class, then you can just use it."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-16T11:19:20.963",
"Id": "242392",
"ParentId": "242375",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "242392",
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-16T04:59:27.387",
"Id": "242375",
"Score": "1",
"Tags": [
"java",
"object-oriented",
"design-patterns"
],
"Title": "Reusing multiple switch cases and if-else statements"
}
|
242375
|
<p>I first thought of the idea when looking at c style multidimensional arrays and realized that there is not really a modern c++ version of that.other than having an std::array of std::array which is not very convenient, so I decided to essentially make a copy of std::array and modify it so would act like a multidimensional array. here is the code</p>
<p>array.h</p>
<pre><code>#pragma once
#include <cstddef>
#include <utility>
#include <initializer_list>
#include <limits>
#include <cstring>
#include <iostream>
namespace turtle {
template<typename T, typename Dim, bool opt = false>
class array;
template<typename T, template<size_t, size_t...> typename dim,size_t Size, size_t... Sizes, bool opt>
#if __cplusplus > 201709L
requires (Size != 0) && ((Sizes != 0) && ... && true) //prevent any size parameters from being zero
#endif
class array<T,dim<Size,Sizes...>,opt> {
template<typename ... Args>
static constexpr auto multply(const Args& ... args) { return (args * ...); }
constexpr static size_t size_ = multply(Size,Sizes...);
public:
using value_type = T;
using size_type = size_t;
using difference_type = ptrdiff_t;
using pointer = T*;
using const_pointer = const T*;
using reference = T&;
using const_reference = const T&;
using iterator = T*;
using const_iterator = const T*;
template<typename... Args>
array(const Args&... args) {
array_copy(sizeof...(args)-1,args...);
}
array() = default;
~array() = default;
//Element access
constexpr reference at(size_type pos) { return data_[pos]; }
constexpr const_reference at(size_type pos) const { return data_[pos]; }
constexpr decltype(auto) operator[](const size_type& pos) {
if constexpr (sizeof...(Sizes)) {
auto temp = array<T, dim<Sizes...>,true>();
temp.data_ = data_ + multply(pos, Sizes...);
return temp;
}
else {
return data_at(pos);
}
}
constexpr const auto& operator[](const size_type& pos) const { return (*this)[pos]; }
template<typename Index, typename ... Indices>
constexpr reference operator ()(const Index& index, const Indices& ... indices) {
return data_[this->index(index, indices...)];
}
template<typename Index, typename ... Indices>
constexpr const_reference operator()(const Index& index, const Indices& ... indices) const {
return (*this)(index,indices...);
}
template<typename Index, typename ... Indices>
constexpr size_type index(const Index& index, const Indices& ... indices) {
static_assert (sizeof...(Indices) >= sizeof...(Sizes), "not enough parameters");
static_assert (sizeof...(Indices) <= sizeof...(Sizes), "too many parameters");
//x + (y*i) + (z*i*j) + (w*i*j*k) ...
return get_index(std::pair<size_type, size_type>(Size, index), std::pair<size_type, size_type>(Sizes, indices)...);
}
constexpr reference front() { return data_[0]; }
constexpr const_reference front() const { return front(); }
constexpr reference back() { return data_[size_ - 1]; }
constexpr const_reference back() const { return back(); }
constexpr T* data() noexcept { return data_; }
constexpr const T* data() const noexcept { return data(); }
//Iterators
constexpr iterator begin() noexcept { return data_; }
constexpr iterator end() noexcept { return begin() + size_; }
constexpr const_iterator begin() const noexcept { return data_; }
constexpr const_iterator end() const noexcept { return begin() + size_; }
constexpr iterator cbegin() const noexcept { return begin(); }
constexpr iterator cend() const noexcept { return begin() + size_; }
//Capacity
constexpr size_type size() const noexcept { return size_; }
constexpr bool empty() const noexcept { return begin() == end(); }
constexpr size_type max_size() const noexcept { return std::numeric_limits<size_type>::max() / sizeof(T); }
//Operations
constexpr void fill(const T& value) {
std::fill(begin(), end(), value);
}
constexpr void swap(array other) noexcept(noexcept(std::swap(std::declval<value_type&>(), std::declval<value_type&>()))) {
/*from swap_ranges*/
iterator first1 = data();
iterator first2 = other.data();
while (first1 != end()) {
std::swap(*first1, *first2);
++first1; ++first2;
}
}
T data_array[opt ? 1 : size_];
T* data_ = data_array;
private:
//Helper functions
template<typename Index, typename ... Indices>
constexpr size_type get_index(const Index& index, const Indices& ... indices) const {
size_type new_index = index.second;
size_type final_index = 0;
if constexpr (sizeof...(Indices)) {
new_index *= multply(indices.first...);
return get_index(indices...) + new_index;
}
return final_index + new_index;
}
template<typename Arg,typename... Args>
constexpr void array_copy(const size_type& size,const Arg& arg, const Args&... args) {
static_assert(sizeof...(args) < size_, "Too many parameters");
data_[size-sizeof...(args)] = arg;
if constexpr (sizeof...(args) > 0) {
array_copy(size,args...);
}
}
constexpr reference data_at(const size_type& pos) { return data_[pos]; }
};
//Comparisons
template<typename T, template<size_t, size_t...> typename dim, size_t Size, size_t... Sizes>
constexpr inline bool operator==(const array<T,dim<Size,Sizes...>>& one, const array<T,dim<Size,Sizes...>>& two) {
auto first1 = one.begin(), first2 = two.begin();
for (; first1 != one.end(); first1++, first2++) {
if (*first1 != *first2) return false;
}
return true;
}
} //namespace turtle
template<size_t, size_t...>
struct Size;
</code></pre>
<p>here is a test case </p>
<pre><code>
#include <iostream>
#include "array.h"
int main() {
turtle::array<int,Size<10,10,10>> array;
for(int i = 0; i < array.size(); ++i) {
array.at(i) = i;
}
array[9][9][9] = -1;
for(const auto& item : array) {
std::cout << item << '\n';
}
return 0;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-16T21:14:16.830",
"Id": "475749",
"Score": "0",
"body": "Please provide some code test cases that show how to use this library."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-16T21:46:18.080",
"Id": "475758",
"Score": "0",
"body": "Ok I added a test case"
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-16T04:59:50.617",
"Id": "242376",
"Score": "1",
"Tags": [
"c++"
],
"Title": "c++ fixed size multidimensional array"
}
|
242376
|
<h2><strong>Motivation</strong></h2>
<p>In the standard Python library <code>enum</code>, a subclass of <code>Enum</code> would create all its members upon class creation. This can be a huge waste of time and memory, especially if the class contains lots of members but only a fraction of them would ever get called.</p>
<p>As a practice project on metaclasses, I decided to implement a lazy version of <code>Enum</code>. This is not intended to be a full-fledged library, so I didn't implement most of the features in the standard <code>enum</code> library, just some basic functionalities.</p>
<p>In <code>LazyEnum</code>, a member would be created only when we ask to and it would be created only once. For example, let say <code>MyClass</code> is a subclass of <code>LazyEnum</code>. The first time we call <code>MyClass(1)</code> an object of type <code>MyClass</code> is created. Any subsequent call to <code>MyClass(1)</code> simply return the same object. Moreover, I want to put some validation on member creation, say we may only allow <code>n</code> to be a positive integer when calling <code>MyClass(n)</code>.</p>
<p>This idea is inspired by <a href="https://codereview.stackexchange.com/users/88700/ethan-furman">Ethan Furman</a>'s reply to my <a href="https://codereview.stackexchange.com/questions/241884/use-python-enum-to-implement-residue-ring-and-multiplicative-residue-group">previous question</a> here and also a discussion on Udemy with <a href="https://www.udemy.com/user/fredbaptiste/" rel="nofollow noreferrer">Fred Baptiste</a>, who is the instructor of the <a href="https://www.udemy.com/course/python-3-deep-dive-part-1/" rel="nofollow noreferrer">Python 3 Deep Dive</a> series.</p>
<p>Before looking at the code, let me provide an example of how to use <code>LazyEnum</code>.</p>
<h2><strong>Example</strong></h2>
<pre><code>from lazyenum import LazyEnum
class Product(LazyEnum):
def _validate_identifier_value(product_id):
# special method used by metaclass for validation
return isinstance(product_id, int) and (1001 <= product_id <= 9999)
COMPANY_NAME = 'Our Example Company'
def __init__(self, product_id, product_title):
# no need to store 'product_id' as instance attribute
self.product_title = product_title
def __repr__(self):
return f'Product({self.product_id!r}, {self.product_title!r})'
</code></pre>
<p>Remark:</p>
<ol>
<li><code>LazyEnum</code> is created by a private metaclass <code>_LazyEnumMeta</code>.</li>
<li>The first non-self parameter of <code>__init__</code> is automatically grabbed by the metaclass and cached, so we don't need to set it as an instance attribute. If we write <code>self.product_id = product_id</code>, it would raise an error when we try to initialize a new member. This parameter is called the <strong>identifier field</strong> and its value is called the <strong>identifier value</strong>, which uniquely identify each member.</li>
<li>The metaclass would look for a method named <code>_validate_identifier_value</code> and use it for validation. It can be defined as a static method or a class method, but if we define it as a class method, we would need to decorate it with <code>@classmethod</code>. Here we just define it as a static method.</li>
</ol>
<p>Let us see some example outputs. First, we can initialize a member as usual and call it by its identifier value.</p>
<pre><code>>>> prod1 = Product(1001, 'Our Nice First Product')
>>> Product(1001)
Product(1001, 'Our Nice First Product')
>>> prod1 is Product(1001)
True
</code></pre>
<p>We can get the identifier value by using <code>.identifier_field</code> or directly calling the instance attribute (<code>.product_id</code> in this case). The <code>.identifier_field</code> would give us a nametuple called <code>Identifier</code>, whose first entry is the attribute name and the second entry is the value.</p>
<pre><code>>>> prod1.identifier_field
Identifier(field_name='product_id', value=1001)
>>> prod1.product_id
1001
</code></pre>
<p>Error would be raised if we attempt to create a new member with an existing identifier value. Of course, the same thing would happen if we use an invalid identifier value.</p>
<pre><code>>>> Product(1001, 'This Is Still The First Product')
ValueError: Member with identifier value 1001 already exists. Cannont pass additional arguments ('This Is Still The First Product',) or {}.
>>> Product(1, 'Product With Invaild ID')
ValueError: Identifier field 'product_id' has invalid value 1.
</code></pre>
<p>In the regular <code>Enum</code>, you can set aliases to a member. Right now we didn't set any alias, but we can do so using dot notation and see all aliases of a member using <code>.all_aliases</code>. We can also simultaneously create a new member and set an alias to it.</p>
<pre><code>>>> prod1.all_aliases
[]
>>> Product.product_one = prod1
>>> Product.first_product = Product.product_one
>>> prod1.all_aliases
['product_one', 'first_product']
>>>
>>> Product.product_two = Product(1002, 'The Amazing Second Product')
>>> Product.product_two
Product(1002, 'The Amazing Second Product')
>>> Product(1002).all_aliases
['product_two']
</code></pre>
<p>But be careful, we may accidentally overwrite other class attributes.</p>
<pre><code>>>> Product.COMPANY_NAME
'Our Example Company'
>>> Product.COMPANY_NAME = prod1
>>> prod1.all_aliases
['product_one', 'first_product', 'COMPANY_NAME']
>>> Product.COMPANY_NAME
Product(1001, 'Our Nice First Product')
>>>
>>> Product.COMPANY_NAME = 'Our Example Company'
>>> prod1.all_aliases
['product_one', 'first_product']
</code></pre>
<p>We can change instance attributes that are not the identifier field. Attempting to change the identifier field would raise an error.</p>
<pre><code>>>> prod1.product_title = 'First Product With New Name'
>>> prod1
Product(1001, 'First Product With New Name')
>>> prod1.product_id = 2001
AttributeError: can't set attribute
</code></pre>
<p>We can iterate over the class members.</p>
<pre><code>>>> Product(1003, 'Even More Amazing Third Product')
Product(1003, 'Even More Amazing Third Product')
>>> for prod in Product: print(prod)
Product(1001, 'First Product With New Name')
Product(1002, 'The Amazing Second Product')
Product(1003, 'Even More Amazing Third Product')
>>> len(Product)
3
</code></pre>
<p>Finally, the class has properties <code>.identifier_value_map</code> and <code>.alias_to_member_map</code>, which help inspect all members. Note that we didn't set any alias to <code>Product(1003)</code>.</p>
<pre><code>>>> Product.identifier_value_map
mappingproxy({
1001: Product(1001, 'First Product With New Name'),
1002: Product(1002, 'The Amazing Second Product'),
1003: Product(1003, 'Even More Amazing Third Product')
})
>>> Product.alias_to_member_map
mappingproxy(OrderedDict([
('product_one', Product(1001, 'First Product With New Name')),
('first_product', Product(1001, 'First Product With New Name')),
('product_two', Product(1002, 'The Amazing Second Product'))
]))
</code></pre>
<h2><strong>The Code</strong></h2>
<p>Here is the code.</p>
<pre><code># lazyenum.py
from collections import namedtuple, OrderedDict
from types import MappingProxyType
_Identifier = namedtuple('Identifier', 'field_name value')
def _get_identifier_value(self):
# use this function to monkey patch the class
id_map = type(self)._object_id_to_value_map
return id_map[id(self)]
class _LazyEnumMeta(type):
def __new__(mcls, name, bases, attrs):
attrs['_object_id_to_value_map'] = {}
attrs['_identifier_value_map'] = {}
attrs['_alias_to_member_map'] = OrderedDict()
cls = super().__new__(mcls, name, bases, attrs)
# grab the first parameter name from the __init__ method
# then inject it to the class as a read-only property
id_name = cls.__init__.__code__.co_varnames[1]
cls._identifier_field_name = id_name
setattr(cls, id_name, property(_get_identifier_value))
return cls
def __call__(cls, value, *args, **kwargs):
# rely on the class to provide the validation method
if not cls._validate_identifier_value(value):
raise ValueError(f'Identifier field {cls._identifier_field_name!r} '
f'has invalid value {value!r}.')
# create a new memeber iff no existing member has the same identifier value
if value not in cls._identifier_value_map:
new_member = super().__call__(value, *args, **kwargs)
cls._object_id_to_value_map[id(new_member)] = value
cls._identifier_value_map[value] = new_member
elif args or kwargs:
raise ValueError(f'Member with identifier value {value!r} already exists. '
f'Cannont pass additional arguments {args} or {kwargs}.')
return cls._identifier_value_map[value]
def __contains__(cls, other):
return other in cls._identifier_value_map.values()
def __len__(cls):
return len(cls._identifier_value_map)
def __iter__(cls):
yield from cls._identifier_value_map.values()
def __setattr__(cls, attr_name, attr_value):
if attr_name in cls._alias_to_member_map:
del cls._alias_to_member_map[attr_name]
# check if we are setting name to a class member
if attr_value in cls:
cls._alias_to_member_map[attr_name] = attr_value
super().__setattr__(attr_name, attr_value)
def __delattr__(cls, attr_name):
if attr_name in cls._alias_to_member_map:
del cls._alias_to_member_map[attr_name]
super().__delattr__(attr_name)
@property
def identifier_value_map(cls):
return MappingProxyType(cls._identifier_value_map)
@property
def alias_to_member_map(cls):
return MappingProxyType(cls._alias_to_member_map)
class LazyEnum(metaclass=_LazyEnumMeta):
# the first two methods serve as the defaults if a subclass didn't provide them
# to avoid error when _LazyEnumMeta attempts to use those two methods
def _validate_identifier_value(value):
return True
def __init__(self, identifier_value):
pass
@property
def identifier_field(self):
id_name = type(self)._identifier_field_name
return _Identifier(id_name, getattr(self, id_name))
@property
def all_aliases(self):
pairs = type(self)._alias_to_member_map.items()
return [alias for alias, member in pairs if member is self]
</code></pre>
<h2><strong>Questions</strong></h2>
<p>1.</p>
<p>The above code doesn't work well with dataclasses. If we write</p>
<pre><code>from lazyenum import LazyEnum
from dataclasses import dataclass
@dataclass
class Product(LazyEnum):
def _validate_identifier_value(product_id):
return isinstance(product_id, int) and (1001 <= product_id <= 9999)
product_id : int
product_title : str
</code></pre>
<p>then type the following in the console:</p>
<pre><code>>>> prod1 = Product(1001, 'First Product')
>>> prod1.product_id = 2001
>>> Product(2001)
TypeError: __init__() missing 1 required positional argument: 'product_title'
>>> Product(1001)
Product(product_id=2001, product_title='First Product')
</code></pre>
<p>We can change the <code>product_id</code> but the member is still identified by the old value! How can I fix this?</p>
<ol start="2">
<li>Apart from the issue of dataclasses, is there any problem in the above code? Where can I make improvements?</li>
</ol>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-16T07:24:26.920",
"Id": "475656",
"Score": "1",
"body": "I just skimmed over major part of question, so I could be wrong, but you might be interested in Singleton Pattern - and how it can be implemented in Python."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-16T16:14:18.120",
"Id": "475710",
"Score": "0",
"body": "@kushj The class clearly has multiple instances and so the Singleton Pattern doesn't apply here. Additionally the OP is already using caching to only allow one instance per id."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-17T18:41:20.097",
"Id": "475836",
"Score": "1",
"body": "Interestingly enough, I was just considering adding a lazy ability to Enum generation this last week! I don't have enough experience with dataclasses to offer any aid with your question, but I will say that `LazyEnum` is not a great choice of name as your usage does not appear to be enum related (see [Python Enum -- when and where to use?](https://stackoverflow.com/a/22594360/208880)"
}
] |
[
{
"body": "<p>This right here is where I would start asking myself if this is a good idea or if there isn't a better way to achieve this:</p>\n\n<blockquote>\n <p>The first non-self parameter of <code>__init__</code> is automatically grabbed by\n the metaclass and cached, so we don't need to set it as an instance\n attribute. If we write self.product_id = product_id, it would raise an\n error when we try to initialize a new member.</p>\n</blockquote>\n\n<p><strong>This behavior is not obvious and it is not even properly documented, because your class does not have a <code>docstring</code>.</strong></p>\n\n<p>Honestly, I don't quite get your enum story, either. At face value you just have a class that you can inherit from to make your class a singleton class depending on the arguments. For this I might use something like this:</p>\n\n<pre><code>class UniqueInstances:\n \"\"\"Makes sure that each instance exists only once.\n Subclasses must implement __hash__ and __eq__ for this to work.\n Note that new instances are being created,\n but get discarded if they already exist.\n \"\"\"\n __instances = {}\n def __new__(cls, *args, **kwargs):\n self = super().__new__(cls)\n self.__init__(*args, **kwargs)\n return self.__instances.setdefault(self, self)\n\n def __hash__(self):\n raise NotImplementedError\n\n def __eq__(self, other):\n raise NotImplementedError\n\nclass Product(UniqueInstances):\n def __init__(self, product_id, name):\n self.product_id = product_id\n self.name = name\n\n def __hash__(self):\n return self.product_id\n\n def __eq__(self, other):\n return self.product_id == other.product_id\n\np1 = Product(1001, \"Test\")\np2 = Product(1001, \"Foo\")\nprint(p1 is p2, p1.name, p2.name)\n# True Foo Foo\n</code></pre>\n\n<p>This is cheating a bit, because it <em>does</em> create a new instance, but it gets discarded if an equal instance already exists. If this still qualifies as <em>lazy</em>, I'm not sure.</p>\n\n<p>It does however have the advantage that it is more obvious what happens, since you have to define <code>__hash__</code> and <code>__eq__</code> which is used to determine if an instance already exists.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-16T10:20:41.267",
"Id": "475670",
"Score": "0",
"body": "Indeed your approach is much simpler. I didn't think of it. Thank you for the advice."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-16T09:23:15.830",
"Id": "242385",
"ParentId": "242377",
"Score": "4"
}
},
{
"body": "<h1>High-level</h1>\n\n<ol>\n<li><p><code>LazyEnum</code> should be separate from the underlying datatype.\nYou should allow a similar interface like the following:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>@dataclasses.dataclass\nclass Product:\n id: int\n name: str\n\nclass Products(metaclass=LazyEnumMeta, type=Product):\n pass\n\nProducts(1001, 'foo')\n</code></pre>\n\n<p>This can alleviate the following problem. If, however, you still run into this problem, it's because your using <code>Products</code> for something it shouldn't be used for.</p>\n\n<blockquote>\n <p>But be careful, we may accidentally overwrite other class attributes.</p>\n</blockquote></li>\n<li><p>You should allow the enum class to function similarly to how Python's does.</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>class Products(metaclass=LazyEnumMeta, type=Product):\n product_one = first_product = 1001\n product_two = 1002\n</code></pre>\n\n<p>By only using the ID we can allow the the Product to not be constructed yet, but still define the mapping.</p></li>\n<li><p>You should re-decide where the following exception is handled.</p>\n\n<blockquote>\n <p>Member with identifier value {value!r} already exists.</p>\n</blockquote>\n\n<p>If you handle it on <code>Products</code> then you could theoretically allow people to create multiple <code>Product</code>s with different values that aren't in the enum.</p>\n\n<p>If you go Graipher's route then you're locking down <code>Product</code> when you may want to use it in two enums.</p>\n\n<p>It boils down to, where do you want the singleton <code>Product</code>s to be scoped?</p></li>\n<li><p>I'm not a fan of having the <code>__call__</code> function as a <code>__getitem__</code>.</p></li>\n</ol>\n\n<p>Here's a proof of concept for the above suggestions.</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>import dataclasses\nimport inspect\n\n\nclass LazyEnumMeta(type):\n def __new__(mcls, name, bases, attrs, type):\n _attrs = {}\n for key in list(attrs.keys()):\n if not (key.startswith('__') and key.endswith('__')):\n _attrs[key] = attrs.pop(key)\n\n attrs['_type'] = type\n arguments = inspect.signature(type).parameters.values()\n attrs['_id'] = next(iter(arguments)).name\n attrs['_attrs'] = _attrs\n attrs['_items'] = {}\n return super().__new__(mcls, name, bases, attrs)\n\n def __call__(self, *args, **kwargs):\n id = args[0] if args else kwargs[self._id]\n if id in self._items:\n return self._items[id]\n self._items[id] = item = self._type(*args, **kwargs)\n return item\n\n def __getitem__(self, id):\n return self._items[id]\n\n def __getattr__(self, name):\n return self._items[self._attrs[name]]\n\n\n@dataclasses.dataclass\nclass Product:\n id: int\n name: str\n\n\nclass Products(metaclass=LazyEnumMeta, type=Product):\n FIRST = 1001\n\n\nprint(Products(id=1001, name='foo'))\nprint(Products[1001])\nprint(Products.FIRST)\n</code></pre>\n\n<h1>Granular</h1>\n\n<ul>\n<li><p>Many of your names are long and needlessly use Hungarian notation <code>_object_id_to_value_map</code>. This can just be <code>_id_to_value</code> or <code>_by_ids</code>.</p>\n\n<p>You should notice that many of my names above are really short. <code>type</code>, <code>id</code>, <code>attrs</code>, <code>items</code>. You don't need long names, and when you do it's normally a good idea to refactor the code to prevent a god class.</p></li>\n<li><p>I'd much prefer to use <code>inspect</code> than the low level <code>cls.__init__.__code__.co_varnames[1]</code>.</p></li>\n<li><p>Your hanging indents are not 'correct'. You should change:</p>\n\n<blockquote>\n <pre class=\"lang-py prettyprint-override\"><code>raise ValueError(f'Identifier field {cls._identifier_field_name!r} '\n f'has invalid value {value!r}.')\n</code></pre>\n</blockquote>\n\n<p>To:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>raise ValueError(f'Identifier field {cls._identifier_field_name!r} '\n f'has invalid value {value!r}.')\n</code></pre>\n\n<p>Alternately you can change your style and use:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>raise ValueError(\n f'Identifier field {cls._identifier_field_name!r} '\n f'has invalid value {value!r}.'\n)\n</code></pre></li>\n<li><p>I don't really see any gain from using <code>id(new_member)</code>. If anything it makes the code more annoying.</p></li>\n<li>I don't think exposing <code>identifier_value_map</code>, <code>alias_to_member_map</code>, <code>identifier_field</code> or <code>all_aliases</code> publicly are good design choices.</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-16T11:59:03.250",
"Id": "475679",
"Score": "0",
"body": "This is very informative and helpful advice. Thank you very much!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-16T11:25:31.560",
"Id": "242393",
"ParentId": "242377",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "242393",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-16T05:11:17.733",
"Id": "242377",
"Score": "6",
"Tags": [
"python",
"python-3.x",
"object-oriented",
"enum",
"meta-programming"
],
"Title": "LazyEnum with validation"
}
|
242377
|
<p>I wrote a simple Makefile to build <code>.expected</code> files and compare them. It works as expected and I was wondering it would be great if I could get some feedback. More specifically if I followed all conventions and if it can be improved upon. This is my first Makefile.</p>
<pre><code># Relative path
RELATIVE_PATH=..
APSSCHED=$(RELATIVE_PATH)/bin/apssched
EXAMPLES=$(RELATIVE_PATH)/examples
BASE=.:$(RELATIVE_PATH)/base:$(EXAMPLES)
FLAGS=-DCOT
CASES=simple-binding1 simple-binding2 simple-binding3
# Generate output and store it in a file
%.output: $(EXAMPLES)/%.aps
$(APSSCHED) $(FLAGS) -p $(BASE) $(basename $<) > $@
# Copy actual output as expected
%.expected: %.output
cp -f $< $@
# Compare actual output with expected
.PHONY: %.compare
%.compare: %.output
# maybe there is a better way without using basename ...
diff $(basename $@).expected $<
# Generate and verify all outputs
.PHONY: all
all: $(addsuffix .compare,$(CASES))
# Regenerate expected output
.PHONY: build.expected
build.expected: $(addsuffix .expected,$(CASES))
.PHONY: clean.expected
clean.expected:
-rm -f *.expected
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-16T06:07:26.373",
"Id": "475650",
"Score": "1",
"body": "Welcome to CodeReview@SE."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-16T05:50:18.147",
"Id": "242380",
"Score": "1",
"Tags": [
"beginner",
"makefile"
],
"Title": "Basic Makefile to create .expected files"
}
|
242380
|
<p>I am developing applications for android. In my application, the user can add information about his weight and watch the progress of weight change. I decided to add filtering of the elements according to the following criteria: the presence of a comment, the absence of a comment, weight gain, weight reduction. For this, I wrote the WeightFilterUseCase and WeightFilterUseCaseTest classes for testing. Could you talk about the flaws of my code?</p>
<p>WeightFilterUseCase </p>
<pre><code> public class WeightFilterUseCase {
public List<WeightUI> filter(List<WeightUI> weights, WeightFilter weightFilter) {
switch (weightFilter) {
case ShowOnlyHaveComment:
return filterByEmptyComment(weights, true);
case ShowOnlyHaventComment:
return filterByEmptyComment(weights, false);
case ShowOnlyWeightGrowing:
return filterWeightByChange(weights, WeightChange.WeightGrowing);
case ShowOnlyWeightDecreases:
return filterWeightByChange(weights, WeightChange.WeightDecreases);
}
throw new EnumConstantNotPresentException(WeightFilter.class, weightFilter.toString());
}
private List<WeightUI> filterByEmptyComment(List<WeightUI> weights, boolean isEmpty) {
return weights.stream().filter(weight -> weight.getComment().trim().isEmpty() == isEmpty).collect(Collectors.toList());
}
private List<WeightUI> filterWeightByChange(List<WeightUI> weights, WeightChange weightChange) {
return weights.stream().filter(weight -> weight.isWeightGrowing() == weightChange).collect(Collectors.toList());
}
public enum WeightFilter {
ShowOnlyHaveComment,
ShowOnlyHaventComment,
ShowOnlyWeightGrowing,
ShowOnlyWeightDecreases
}
}
</code></pre>
<p>WeightFilterUseCaseTest</p>
<pre><code>public class WeightFilterUseCaseTest {
private List<WeightUI> weights = new ArrayList<>();
private WeightFilterUseCase weightFilterUseCase = new WeightFilterUseCase();
@Before
public void init() {
weights.add(new WeightUI(new Weight(0, 0, 0, "ds", ""), WeightChange.WeightNotChange, 0));
weights.add(new WeightUI(new Weight(0, 0, 0, "", ""), WeightChange.WeightNotChange, 0));
weights.add(new WeightUI(new Weight(0, 0, 0, "ds", ""), WeightChange.WeightGrowing, 0));
weights.add(new WeightUI(new Weight(0, 0, 0, "", ""), WeightChange.WeightDecreases, 0));
}
@Test
public void testFilterOnlyHaveComment() {
List<WeightUI> filterWeights = weightFilterUseCase.filter(weights, WeightFilterUseCase.WeightFilter.ShowOnlyHaveComment);
assert filterWeights.get(0).equals(weights.get(0));
assert filterWeights.get(1).equals(weights.get(2));
assert filterWeights.size() == 2;
}
@Test
public void testFilterOnlyHaventComment() {
List<WeightUI> filterWeights = weightFilterUseCase.filter(weights, WeightFilterUseCase.WeightFilter.ShowOnlyHaventComment);
assert filterWeights.get(0).equals(weights.get(1));
assert filterWeights.get(1).equals(weights.get(3));
assert filterWeights.size() == 2;
}
@Test
public void testFilterOnlyWeightGain() {
List<WeightUI> filterWeights = weightFilterUseCase.filter(weights, WeightFilterUseCase.WeightFilter.ShowOnlyWeightGrowing);
assert filterWeights.get(0).equals(weights.get(2));
assert filterWeights.size() == 1;
}
@Test
public void testFilterOnlyWeightDecreases() {
List<WeightUI> filterWeights = weightFilterUseCase.filter(weights, WeightFilterUseCase.WeightFilter.ShowOnlyWeightDecreases);
assert filterWeights.get(0).equals(weights.get(3));
assert filterWeights.size() == 1;
}
}
</code></pre>
<p>WeightChange</p>
<pre><code>public enum WeightChange {
WeightGrowing(-1),
WeightDecreases(1),
WeightNotChange(0);
int change;
WeightChange(int change) {
this.change = change;
}
public static WeightChange getByChange(int chane) {
for (WeightChange weightChange : values()) {
if (weightChange.change == chane) return weightChange;
}
return WeightNotChange;
}
}
</code></pre>
<p>WeightUI</p>
<pre><code>class WeightUI (baseWeight: Weight): Weight(baseWeight){
var isWeightGrowing:WeightChange = WeightChange.WeightNotChange
var changeWeight: Double = 0.0
var isSelect = false
constructor(weight: Weight,isWeightGrowing : WeightChange,changeWeight:Double) : this(weight){
this.isWeightGrowing = isWeightGrowing
this.changeWeight = changeWeight
this.isSelect = isSelect
}
}
</code></pre>
<p>Weight</p>
<pre><code>@Entity
open class Weight(@PrimaryKey(autoGenerate = true) var id: Long = 0, override var weight: Float = 0.0f,
override var date: Long = 0, var comment: String = "",var userName : String = "") : WeightGraphPoint, Parcelable {
constructor(weight: Weight) : this(weight.id, weight.weight, weight.date, weight.comment,weight.userName)
constructor(weight: Float,date:Long,userName: String) : this(0,weight,date,userName)
constructor(parcel: Parcel) : this(
parcel.readLong(),
parcel.readFloat(),
parcel.readLong(),
parcel.readString() ?: "",
parcel.readString()?: "")
override fun writeToParcel(parcel: Parcel, flags: Int) {
parcel.writeLong(id)
parcel.writeFloat(weight)
parcel.writeLong(date)
parcel.writeString(comment)
parcel.writeString(userName)
}
override fun describeContents(): Int {
return 0
}
companion object CREATOR : Parcelable.Creator<Weight> {
override fun createFromParcel(parcel: Parcel): Weight {
return Weight(parcel)
}
override fun newArray(size: Int): Array<Weight?> {
return arrayOfNulls(size)
}
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other == null) return false
val other = other as Weight
if (weight == other.weight && date == other.date)
return true
return false
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-16T09:20:39.077",
"Id": "475664",
"Score": "0",
"body": "You have written some parts in Java and some parts in Kotlin, why the mix? Why not go Kotlin all the way?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-16T09:36:08.603",
"Id": "475665",
"Score": "0",
"body": "The project was originally written in java, after which I decided to study kotlin and rewrote a part on it."
}
] |
[
{
"body": "<p>I won't necessarily point out flaws, but also suggestions. Of course you don't have to adhere to any of them, just things to help improve your code. I'm not that familiar with Kotlin, so I am likely to miss some stuff in the Kotlin parts.</p>\n\n<h3>WeightFilter</h3>\n\n<p>Although it seems like a basic usage of an <code>enum</code>, there is a way to improve the design.\n<code>Enum</code>s in Java are actually a type of class, and so they can have methods. Instead of using a <code>switch</code> to filter by type, we can implement the logic inside:</p>\n\n<pre><code>public enum WeightFilter {\n ShowOnlyHaveComment {\n @Override\n List<WeightUI> filter(List<WeightUI> data) {\n return data.stream().filter(weight -> weight.getComment().trim().isEmpty()).collect(Collectors.toList());\n }\n },\n ShowOnlyHaventComment {\n //implementation\n }\n // other constants\n ;\n\n abstract List<WeightUI> filter(List<WeightUI> data);\n}\n\npublic List<WeightUI> filter(List<WeightUI> weights, WeightFilter weightFilter) {\n return weightFilter.filter(weights);\n}\n</code></pre>\n\n<p>There are actual several implementation options, like:</p>\n\n<pre><code>public enum WeightFilter {\n ShowOnlyHaveComment {\n @Override\n Predicate<WeightUI> newFilter() {\n return weight -> weight.getComment().trim().isEmpty();\n }\n },\n ShowOnlyHaventComment {\n //implementation\n }\n // other constants\n ;\n\n abstract Predicate<WeightUI> newFilter();\n}\n</code></pre>\n\n<p>Why is this design good? The main advantage is that you can modify the enum without having to worry about the <code>switch</code>. It's not uncommon that programmers forget to update all <code>switch</code> over enum which they modified.</p>\n\n<h3>WeightChange</h3>\n\n<p>We don't really see all the usages of <code>WeightChange</code>, so maybe the can be other comments.</p>\n\n<p><code>getByChange</code> is an example for a common factory method for <code>Enum</code> by a property. However, the implementation has a small problem.</p>\n\n<p>If the value is not found among the constants, it returns a default value. This is likely pretty bad, since the argument is wrong, but the method acts as if everything is fine. So you might miss bugs that are related to that. Instead, a <code>EnumConstantNotPresentException</code> or <code>IllegalArgumentException</code> should be thrown, indicating the \"user\" of this method has provided an invalid argument.</p>\n\n<h3>WeightFilterUseCaseTest</h3>\n\n<p>This is more of a personal approach, so feel free to ignore it.</p>\n\n<p>Tests should generally be completely disconnected from each other, so that they won't have any affect on each other. The sharing of <code>weights</code> and <code>weightFilterUseCase</code> across the instance can lead to an effect among each other, depending on the runner of the tests (which could be changed). I would recommend creating all of those inside each test method as a local variable. It might make the tests longer, but it ensures they are sandboxed. You can use a method to create <code>weights</code> instead of creating each time manually, or switch to JUnit5 and use something like <code>MethodSource</code>.</p>\n\n<p>You might want to become more familiar with assertions from <a href=\"https://www.baeldung.com/junit-assertions\" rel=\"nofollow noreferrer\">JUnit</a> and matchers from <a href=\"https://dzone.com/articles/using-hamcrest-and-junit\" rel=\"nofollow noreferrer\">Hamcrest</a>. They both provide more information on test failures, and allow more complex assertions to be done easily.</p>\n\n<h3>WeightUI</h3>\n\n<p>Not really sure how this is used, since you haven't posted the code for it, however one clear things is that the inheritance of <code>Weight</code> is wrong. Inheritance is used to define type relations, not avoid data duplication, and <code>WeightUI</code> doesn't seem to be a type of <code>Weight</code>.. since <code>Weight</code> is just a container for data about <code>Weight</code>. If anything <code>WeightUI</code> should contain an instance of <code>Weight</code> and use it. </p>\n\n<h3>Weight</h3>\n\n<p>Again not sure how everything is used here, not the full code. </p>\n\n<p><code>date</code> can be an actual date object, like <code>Date</code>, instead of <code>long</code>. This can make it easier to use with some things. Really depends on how you use <code>date</code>. Can easily be converted to epoch time for parceling if needed.</p>\n\n<p>Inside <code>equals</code>, after some basic checks, you immediately convert the object to <code>Weight</code>, without testing if it really is an instance of <code>Weight</code>. Could lead to an exception.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-16T11:02:09.577",
"Id": "242391",
"ParentId": "242382",
"Score": "2"
}
},
{
"body": "<p>I have two considerations ,in your class <code>WeightFilterUseCase</code> you have the following method:</p>\n\n<blockquote>\n<pre><code>public List<WeightUI> filter(List<WeightUI> weights, WeightFilter weightFilter) {\n switch (weightFilter) {\n case ShowOnlyHaveComment:\n return filterByEmptyComment(weights, true);\n case ShowOnlyHaventComment:\n return filterByEmptyComment(weights, false);\n case ShowOnlyWeightGrowing:\n return filterWeightByChange(weights, WeightChange.WeightGrowing);\n case ShowOnlyWeightDecreases:\n return filterWeightByChange(weights, WeightChange.WeightDecreases);\n }\n throw new EnumConstantNotPresentException(WeightFilter.class, weightFilter.toString());\n}\n</code></pre>\n</blockquote>\n\n<p>You can rewrite the first two cases of your switch with just one case in a more compact way:</p>\n\n<pre><code>case ShowOnlyHaveComment: case ShowOnlyHaventComment:\n return filterByEmptyComment(weights, weightFilter == WeightFilter.ShowOnlyHaveComment);\n</code></pre>\n\n<p>Instead of throwing the exception out of the switch you can add the <code>default</code> case and throw there the exception, so your method can be rewritten in this way:</p>\n\n<pre><code>public List<WeightUI> filter(List<WeightUI> weights, WeightFilter weightFilter) {\n switch (weightFilter) {\n case ShowOnlyHaveComment: case ShowOnlyHaventComment:\n return filterByEmptyComment(weights, weightFilter == WeightFilter.ShowOnlyHaveComment);\n case ShowOnlyWeightGrowing:\n return filterWeightByChange(weights, WeightChange.WeightGrowing);\n case ShowOnlyWeightDecreases:\n return filterWeightByChange(weights, WeightChange.WeightDecreases);\n default:\n throw new EnumConstantNotPresentException(WeightFilter.class, weightFilter.toString());\n }\n}\n</code></pre>\n\n<p>I don't know Kotlin, so I cannot help for Kotlin code.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-16T16:02:42.983",
"Id": "242406",
"ParentId": "242382",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "242391",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-16T06:39:28.177",
"Id": "242382",
"Score": "2",
"Tags": [
"java",
"beginner",
"android",
"enum",
"kotlin"
],
"Title": "List Filtering Code"
}
|
242382
|
<p>Currently, I'm working on a legacy application written in .NET that does not contain any unit tests.
This application, when executed produces a very large directory tree with roughly 20.000 files in total in different folders.</p>
<p>The application is currently being used heavily in production thus any mistakes during the refactoring cannot be afforded.</p>
<p>Therefore, I've decided to write a Directory Comparer tool which can compare 2 directories for equality.
This can then be used in an integration test to see if the generated output after the refactoring matches a predefined snapshot.</p>
<p>Below is the code for it.
Any feedback is highly appreciated.</p>
<p><strong>The interfaces</strong></p>
<pre><code>public interface IDirectoryValidator
{
bool Exists(string path);
IEnumerable<string> GetSubDirectories(string path);
}
public interface IFileValidator
{
IEnumerable<string> GetFiles(string path);
IEnumerable<byte> Read(string path);
}
</code></pre>
<p><strong>Interface Implementations</strong></p>
<pre><code>public sealed class DirectoryValidator : IDirectoryValidator
{
public bool Exists(string path)
{
return Directory.Exists(path);
}
public IEnumerable<string> GetSubDirectories(string path)
{
return Directory.GetDirectories(path);
}
}
public sealed class FileValidator : IFileValidator
{
public bool Exists(string path)
{
return File.Exists(path);
}
public IEnumerable<string> GetFiles(string path)
{
return Directory.GetFiles(path);
}
public IEnumerable<byte> Read(string path)
{
return File.ReadAllBytes(path);
}
}
</code></pre>
<p><strong>Validator Entry Point</strong></p>
<pre><code>public sealed class FileSystemEqualityVerifier
{
private readonly FileSystemValidator fileSystemValidator;
public FileSystemEqualityVerifier(FileSystemValidator fileSystemValidator)
{
this.fileSystemValidator = fileSystemValidator;
}
public bool AreEqual(string referencePath, string actualPath)
{
return this.DirectoriesExists(referencePath, actualPath) &&
this.DirectoryContentsEqual(referencePath, actualPath);
}
private static bool LastPathPartsEqual(string referencePath, string actualPath)
{
return Path.GetFileName(referencePath) == Path.GetFileName(actualPath);
}
private bool DirectoriesExists(params string[] paths)
{
return paths.All(path => this.fileSystemValidator.DirectoryExists(path));
}
private bool DirectoryContentsEqual(string referencePath, string actualPath)
{
return this.AmountOfEntriesInDirectoriesEqual(referencePath, actualPath) &&
this.FilesInDirectoriesEqual(referencePath, actualPath) &&
this.SubDirectoriesEqual(referencePath, actualPath);
}
private bool AmountOfEntriesInDirectoriesEqual(string referenceDirectory, string actualDirectory)
{
return this.DirectoriesContainsSameAmountOfDirectories(referenceDirectory, actualDirectory) &&
this.DirectoriesContainsSameAmountOfFiles(referenceDirectory, actualDirectory);
}
private bool DirectoriesContainsSameAmountOfDirectories(string referenceDirectory, string actualDirectory)
{
var referenceSubDirectoriesCount = this.fileSystemValidator.GetDirectories(referenceDirectory).Count();
var actualSubDirectoriesCount = this.fileSystemValidator.GetDirectories(actualDirectory).Count();
return referenceSubDirectoriesCount.Equals(actualSubDirectoriesCount);
}
private bool DirectoriesContainsSameAmountOfFiles(string referenceDirectory, string actualDirectory)
{
var referenceFilesCount = this.fileSystemValidator.GetFiles(referenceDirectory).Count();
var actualFilesCount = this.fileSystemValidator.GetFiles(actualDirectory).Count();
return referenceFilesCount.Equals(actualFilesCount);
}
private bool FilesInDirectoriesEqual(string referencePath, string actualPath)
{
var referenceFilesAsArray = this.fileSystemValidator.GetFiles(referencePath).ToArray();
var actualFilesAsArray = this.fileSystemValidator.GetFiles(actualPath).ToArray();
return referenceFilesAsArray
.Select((value, index) => new { Index = index, Value = value })
.All(element => this.FileEquals(element.Value, actualFilesAsArray[element.Index]));
}
private bool FileEquals(string referencePath, string actualPath)
{
return LastPathPartsEqual(referencePath, actualPath) &&
this.FileContentEquals(referencePath, actualPath);
}
private bool FileContentEquals(string referencePath, string actualPath)
{
var referenceFileContent = this.fileSystemValidator.ReadFile(referencePath);
var actualFileContent = this.fileSystemValidator.ReadFile(actualPath);
return referenceFileContent.SequenceEqual(actualFileContent);
}
private bool SubDirectoriesEqual(string referencePath, string actualPath)
{
var referenceDirectoriesAsArray = this.fileSystemValidator.GetDirectories(referencePath).ToArray();
var actualDirectoriesAsArray = this.fileSystemValidator.GetDirectories(actualPath).ToArray();
return referenceDirectoriesAsArray
.Select((value, index) => new { Index = index, Value = value })
.All(element => this.SubDirectoryContentsEqual(element.Value, actualDirectoriesAsArray[element.Index]));
}
private bool SubDirectoryContentsEqual(string referencePath, string actualPath)
{
var result = this.DirectoryContentsEqual(referencePath, actualPath) &&
LastPathPartsEqual(referencePath, actualPath);
return result;
}
}
</code></pre>
<p>It's covered by unit tests with the code below.</p>
<p><strong>The Models</strong></p>
<pre><code>internal enum EntryType
{
Dir = 1,
File = 2,
}
internal sealed class Entry
{
private readonly string name;
private readonly string? content;
private Entry(string parentPath, string name)
{
this.ParentPath = parentPath;
this.name = name;
this.EntryType = EntryType.Dir;
}
private Entry(string parentPath, string name, string content)
{
this.ParentPath = parentPath;
this.name = name;
this.content = content;
this.EntryType = EntryType.File;
}
internal string ParentPath { get; }
internal string FullPath => this.BuildFullPath();
internal IEnumerable<byte> ContentBytes => Encoding.ASCII.GetBytes(this.content ?? string.Empty);
internal EntryType EntryType { get; }
public static Entry Directory(string parentPath, string name)
{
return new Entry(parentPath, name);
}
public static Entry File(string parentPath, string name, string content)
{
return new Entry(parentPath, name, content);
}
public bool IsOfTypeWithFullPath(string directoryPath, EntryType entryType)
{
return (this.FullPath == directoryPath) && (this.EntryType == entryType);
}
private string BuildFullPath()
{
return string.IsNullOrEmpty(this.ParentPath) ? this.name : this.ParentPath + "/" + this.name;
}
}
</code></pre>
<p><strong>The FileSystem STUB</strong></p>
<pre><code>public sealed class FileSystemStub
{
private readonly Mock<IDirectoryValidator> directoryValidatorMock;
private readonly Mock<IFileValidator> fileValidatorMock;
private readonly IList<Entry> entries;
internal FileSystemStub()
{
this.directoryValidatorMock = new Mock<IDirectoryValidator>();
this.fileValidatorMock = new Mock<IFileValidator>();
this.entries = new List<Entry>();
}
internal IDirectoryValidator DirectoryValidator => this.directoryValidatorMock.Object;
internal IFileValidator FileValidator => this.fileValidatorMock.Object;
internal void AddDirectory(string name)
{
this.AddDirectory(string.Empty, name);
}
internal void AddDirectory(string parentPath, string name)
{
this.entries.Add(Entry.Directory(parentPath, name));
this.ConfigureDirectoryValidatorMock();
}
internal void AddFile(string parentPath, string name, string contentHash)
{
this.entries.Add(Entry.File(parentPath, name, contentHash));
this.ConfigureFileValidatorMock();
}
private void ConfigureDirectoryValidatorMock()
{
this.directoryValidatorMock
.Setup(validator => validator.Exists(It.IsAny<string>()))
.Returns(this.BuildExistsPredicate(EntryType.Dir));
this.directoryValidatorMock
.Setup(validator => validator.GetSubDirectories(It.IsAny<string>()))
.Returns(this.BuildListDirectoryContentsPredicate(EntryType.Dir));
}
private void ConfigureFileValidatorMock()
{
this.fileValidatorMock
.Setup(validator => validator.GetFiles(It.IsAny<string>()))
.Returns(this.BuildListDirectoryContentsPredicate(EntryType.File));
this.fileValidatorMock
.Setup(validator => validator.Read(It.IsAny<string>()))
.Returns(this.GetFileContentsPredicate());
}
private Func<string, bool> BuildExistsPredicate(EntryType entryType)
{
return element => this.entries.Any(entry => entry.IsOfTypeWithFullPath(element, entryType));
}
private Func<string, IEnumerable<string>> BuildListDirectoryContentsPredicate(EntryType entryType)
{
return element => this.entries
.Where(entry => (entry.ParentPath == element) && (entry.EntryType == entryType))
.Select(entry => entry.FullPath);
}
private Func<string, byte[]> GetFileContentsPredicate()
{
return element => this.entries
.Where(entry => (entry.FullPath == element) && (entry.EntryType == EntryType.File))
.SelectMany(entry => entry.ContentBytes)
.ToArray();
}
}
</code></pre>
<p><strong>The actual UT's</strong></p>
<pre><code>public sealed class FileSystemEqualityVerifierUT
{
private readonly FileSystemStub fileSystem;
private readonly FileSystemEqualityVerifier fileSystemEqualityVerifier;
public FileSystemEqualityVerifierUT()
{
this.fileSystem = new FileSystemStub();
this.fileSystemEqualityVerifier = this.CreateFileSystemEqualityVerifier();
}
public static IEnumerable<object[]> UnEqualFileSystems =>
new List<object[]>
{
new object[]
{
new Action<FileSystemStub>(
fileSystem => { }),
},
new object[]
{
new Action<FileSystemStub>(
fileSystem => { fileSystem.AddDirectory("/REF"); }),
},
new object[]
{
new Action<FileSystemStub>(
fileSystem => { fileSystem.AddDirectory("/ACTUAL"); }),
},
new object[]
{
new Action<FileSystemStub>(
fileSystem =>
{
fileSystem.AddDirectory("/REF");
fileSystem.AddDirectory("/REF", "DIR 1");
fileSystem.AddDirectory("/ACTUAL");
fileSystem.AddDirectory("/ACTUAL", "DIR 1");
fileSystem.AddDirectory("/ACTUAL", "DIR 2");
}),
},
new object[]
{
new Action<FileSystemStub>(
fileSystem =>
{
fileSystem.AddDirectory("/REF");
fileSystem.AddFile("/REF", "FILE 1", "FILE 1 DATA");
fileSystem.AddDirectory("/ACTUAL");
fileSystem.AddFile("/ACTUAL", "FILE 1", "FILE 1 DATA");
fileSystem.AddFile("/ACTUAL", "FILE 2", "FILE 2 DATA");
}),
},
new object[]
{
new Action<FileSystemStub>(
fileSystem =>
{
fileSystem.AddDirectory("/REF");
fileSystem.AddFile("/REF", "FILE 1", "FILE 1 DATA");
fileSystem.AddDirectory("/ACTUAL");
fileSystem.AddFile("/ACTUAL", "FILE 1 ALT.", "FILE 1 DATA");
}),
},
new object[]
{
new Action<FileSystemStub>(
fileSystem =>
{
fileSystem.AddDirectory("/REF");
fileSystem.AddFile("/REF", "FILE 1", "FILE 1 DATA");
fileSystem.AddDirectory("/ACTUAL");
fileSystem.AddFile("/ACTUAL", "FILE 1", "FILE 1 DATA ALT.");
}),
},
new object[]
{
new Action<FileSystemStub>(
fileSystem =>
{
fileSystem.AddDirectory("/REF");
fileSystem.AddDirectory("/REF", "DIR 1");
fileSystem.AddDirectory("/REF/DIR 1", "DIR 1.1");
fileSystem.AddDirectory("/ACTUAL");
fileSystem.AddDirectory("/ACTUAL", "DIR 1");
fileSystem.AddDirectory("/ACTUAL/DIR 1", "DIR 1.1");
fileSystem.AddDirectory("/ACTUAL/DIR 1", "DIR 1.2");
}),
},
new object[]
{
new Action<FileSystemStub>(
fileSystem =>
{
fileSystem.AddDirectory("/REF");
fileSystem.AddDirectory("/REF", "DIR 1");
fileSystem.AddFile("/REF/DIR 1", "FILE 1.1", "FILE 1.1 DATA");
fileSystem.AddDirectory("/ACTUAL");
fileSystem.AddDirectory("/ACTUAL", "DIR 1");
fileSystem.AddFile("/ACTUAL/DIR 1", "FILE 1.1", "FILE 1.1 DATA");
fileSystem.AddFile("/ACTUAL/DIR 1", "FILE 1.2", "FILE 1.2 DATA");
}),
},
new object[]
{
new Action<FileSystemStub>(
fileSystem =>
{
fileSystem.AddDirectory("/REF");
fileSystem.AddDirectory("/REF", "DIR 1");
fileSystem.AddFile("/REF/DIR 1", "FILE 1.1", "FILE 1.1 DATA");
fileSystem.AddDirectory("/ACTUAL");
fileSystem.AddDirectory("/ACTUAL", "DIR 1");
fileSystem.AddFile("/ACTUAL/DIR 1", "FILE 1.1 ALT.", "FILE 1.1 DATA");
}),
},
new object[]
{
new Action<FileSystemStub>(
fileSystem =>
{
fileSystem.AddDirectory("/REF");
fileSystem.AddDirectory("/REF", "DIR 1");
fileSystem.AddFile("/REF/DIR 1", "FILE 1.1", "FILE 1.1 DATA");
fileSystem.AddDirectory("/ACTUAL");
fileSystem.AddDirectory("/ACTUAL", "DIR 1");
fileSystem.AddFile("/ACTUAL/DIR 1", "FILE 1.1", "FILE 1.1 DATA ALT.");
}),
},
};
public static IEnumerable<object[]> EqualFileSystems =>
new List<object[]>
{
new object[]
{
new Action<FileSystemStub>(
fileSystem =>
{
fileSystem.AddDirectory("/REF");
fileSystem.AddDirectory("/REF", "DIR 1");
fileSystem.AddDirectory("/ACTUAL");
fileSystem.AddDirectory("/ACTUAL", "DIR 1");
}),
},
new object[]
{
new Action<FileSystemStub>(
fileSystem =>
{
fileSystem.AddDirectory("/REF");
fileSystem.AddFile("/REF", "FILE 1", "FILE 1 DATA");
fileSystem.AddDirectory("/ACTUAL");
fileSystem.AddFile("/ACTUAL", "FILE 1", "FILE 1 DATA");
}),
},
new object[]
{
new Action<FileSystemStub>(
fileSystem =>
{
fileSystem.AddDirectory("/REF");
fileSystem.AddDirectory("/REF", "DIR 1");
fileSystem.AddDirectory("/REF/DIR 1", "DIR 1.1");
fileSystem.AddDirectory("/ACTUAL");
fileSystem.AddDirectory("/ACTUAL", "DIR 1");
fileSystem.AddDirectory("/ACTUAL/DIR 1", "DIR 1.1");
}),
},
new object[]
{
new Action<FileSystemStub>(
fileSystem =>
{
fileSystem.AddDirectory("/REF");
fileSystem.AddDirectory("/REF", "DIR 1");
fileSystem.AddFile("/REF/DIR 1", "FILE 1.1", "FILE 1.1 DATA");
fileSystem.AddDirectory("/ACTUAL");
fileSystem.AddDirectory("/ACTUAL", "DIR 1");
fileSystem.AddFile("/ACTUAL/DIR 1", "FILE 1.1", "FILE 1.1 DATA");
}),
},
};
private IDirectoryValidator DirectoryValidator => this.fileSystem.DirectoryValidator;
private IFileValidator FileValidator => this.fileSystem.FileValidator;
[Theory(DisplayName = "Returns 'FALSE' when the 'Reference' directory is NOT equal to the 'Actual' directory.")]
[MemberData(nameof(UnEqualFileSystems))]
public void GivenUnEqualFileSystemsReturnFalse(Action<FileSystemStub> configureFileSystem)
{
// ARRANGE.
configureFileSystem(this.fileSystem);
// ACT.
var areFileSystemsEqual = this.fileSystemEqualityVerifier.AreEqual("/REF", "/ACTUAL");
// ASSERT.
Assert.False(areFileSystemsEqual);
}
[Theory(DisplayName = "Returns 'TRUE' when the 'Reference' directory is equal to the 'Actual' directory.")]
[MemberData(nameof(EqualFileSystems))]
public void GivenEqualFileSystemsReturnTrue(Action<FileSystemStub> configureFileSystem)
{
// ARRANGE.
configureFileSystem(this.fileSystem);
// ACT.
var areFileSystemsEqual = this.fileSystemEqualityVerifier.AreEqual("/REF", "/ACTUAL");
// ASSERT.
Assert.True(areFileSystemsEqual);
}
private FileSystemEqualityVerifier CreateFileSystemEqualityVerifier()
{
var fileSystemValidator = new FileSystemValidator(this.DirectoryValidator, this.FileValidator);
return new FileSystemEqualityVerifier(fileSystemValidator);
}
}
</code></pre>
<p>Thanks for the feedback in advance.</p>
|
[] |
[
{
"body": "<p>My first feedback about <code>IFileValidator</code> interface would be to have an <code>Exists()</code> method, just like how you're having one in <code>IDirectoryValidator</code> interface. Plus the Validator interfaces are doing much more than validation I feel. For example, it is also trying to get a list of subdirectories and files. It is good if Validators only handle the job of validations and let the classes who implement them handle the other jobs. In fact, you can have one more interface called <code>IValidator</code> like</p>\n\n<pre><code>interface IValidator\n{\n bool Validate();\n}\n\ninterface IDirectoryValidator: IValidator\n{\n\n}\n\ninterface IFileValidator : IValidator\n{\n\n}\n\nclass DirectoryValidator : IDirectoryValidator\n{\n private string mPath;\n\n public DirectoryValidator(string path)\n {\n mPath = path;\n }\n\n public bool Validate()\n {\n // You can have following validations implemented in this class\n // Check if the path is a valid string, if so\n // Check if path exists, if so \n // Check if the directory is accessible and so on...\n\n return false;\n }\n}\n\nclass FileValidator : IFileValidator \n{\n private string mPath;\n\n public FileValidator(string path)\n {\n mPath = path;\n }\n\n public bool Validate()\n {\n // You can have following validations implemented in this class\n // Check if the file path is valid string, if so\n // Check if path exists, if so \n // Check if the file is accessible and so on...\n\n return false;\n }\n}\n</code></pre>\n\n<p>Of course, this is just an idea, on how Validators can just have the validation logic. </p>\n\n<p>Also, I see <code>GetFiles()</code> is being called multiple times like in <code>FilesInDirectoriesEqual()</code> and <code>DirectoriesContainsSameAmountOfFiles()</code> for the same path. It means you're trying to access your drives again and again. If your drives are huge then it might take time to access every folder and file. Hence, to improve it based on your needs you can make it a one-time operation. </p>\n\n<p>Looking at the code I sense you're using just two paths to compare at a time. If it so, you can pass them inside the constructor of the class and run <code>GetFiles()</code> or <code>GetDirectories()</code> and store it in a property. It can significantly improve performance.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-16T09:29:50.040",
"Id": "242386",
"ParentId": "242383",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-16T07:55:32.347",
"Id": "242383",
"Score": "3",
"Tags": [
"c#",
".net",
"file-system"
],
"Title": "Compare 2 directories for equality"
}
|
242383
|
<p>I trying to convert this <strong>C code</strong> for calculating distance from RSSI to <strong>Swift code</strong>. I try to do it by myself, but considering I'm beginner, I need help in how to do it.</p>
<p><strong>Here is C code:</strong></p>
<pre><code>#define QUEUE_SIZE 16
#define INCREASE_INDEX(x) ({x++; if(x >= QUEUE_SIZE) x = 0;})
int rssi_array[QUEUE_SIZE] = {0};
int sort_rssi[QUEUE_SIZE] = {0};
int rssi_index = 0;
static double getDistance(double rssi, int txPower) {
/*
* RSSI = TxPower - 10 * n * lg(d)
* n = 2 (in free space)
*
* d = 10 ^ ((TxPower - RSSI) / (10 * n))
*/
if (rssi == 0) {
return -1.0; // if we cannot determine accuracy, return -1.
}
return pow(10, ((double) txPower - rssi) / (10 * 2));
}
static double calculateAccuracy(double rssi, int txPower) {
if (rssi == 0) {
return -1.0; // if we cannot determine accuracy, return -1.
}
double ratio = rssi * 1.0 / txPower;
if (ratio < 1.0) {
return pow(ratio, 10);
} else {
double accuracy = (0.89976) * pow(ratio, 7.7095) + 0.111;
return accuracy;
}
}
int cmpfunc (const void * a, const void * b) {
return ( *(int*)a - *(int*)b );
}
static double calculate_average() {
double average = 0;
int i = 0;
int drop = 3;
memcpy(sort_rssi, rssi_array, QUEUE_SIZE * sizeof(int));
qsort(sort_rssi, QUEUE_SIZE, sizeof(int), cmpfunc);
for (i = 0; i < QUEUE_SIZE - drop; ++i) {
if(sort_rssi[i + drop] == 0) break;
average += sort_rssi[i];
}
return average / i;
}
// For adding new rssi we can use this code:
rssi_array[rssi_index] = rssi;
INCREASE_INDEX(rssi_index);
double mean_rssi = calculate_average();
</code></pre>
<p>Here is what I managed to do, but I'm not sure if it's good.
<strong>Swift code:</strong></p>
<pre><code>let queueSize = 16
func increaseIndex(_ x: Int) -> Int {
var x = x + 1
if x >= queueSize {
x = 0
}
return x
}
var rssiArray = [0]
var sortRssi = [0]
var rssiIndex = 0
private func getDistance(rssi: Double, txPower: Int) -> Double {
if rssi == 0 {
return -1.0 // if we cannot determine accuracy, return -1.
}
return pow(10, (Double(txPower) - rssi) / (10 * 2))
}
private func calculateAccuracy(rssi: Double, txPower: Int) -> Double {
if rssi == 0 {
return -1.0 // if we cannot determine accuracy, return -1.
}
let ratio = rssi * 1.0 / Double(txPower)
if ratio < 1.0 {
return pow(ratio, 10)
} else {
let accuracy = (0.89976) * pow(ratio, 7.7095) + 0.111
return accuracy
}
}
// This part is probably for comparing results from two functions,
// but I don't get it from where and what
func compareFunction(_ a: UnsafeRawPointer?, _ b: UnsafeRawPointer?) -> Int {
return Int(a ?? 0) - Int(b ?? 0)
}
private func calculateAverage() -> Double {
var average: Double = 0
var i = 0
let drop = 3
memcpy(sortRssi, rssiArray, queueSize * MemoryLayout<Int>.size)
qsort(sortRssi, queueSize, MemoryLayout<Int>.size, cmpfunc)
for i in 0..<queueSize - drop {
if sortRssi[i + drop] == 0 {
break
}
average += Double(sortRssi[i])
}
return average / Double(i)
}
</code></pre>
<p>I know this will be very useful for others. Code help will be much appreciated.</p>
<p><strong>Thank you all in advance!</strong></p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-09T22:48:14.773",
"Id": "499464",
"Score": "0",
"body": "This isn't exactly important enough to be an answer, but one big thing about Swift is that literals are disconnected from types. So, `Double` can be represented with `1`, omitting the `.0` when it's clear that a `Double` goes there (comparing, passing to a function, etc.)."
}
] |
[
{
"body": "<p>A few suggestions:</p>\n\n<ul>\n<li>Don't have everything be part of a class. In Swift, you can have free functions, just like in C. Remove the <code>class AverageRSSI: NSObject { ... }</code>.</li>\n<li>Keep casing consistent. You have <code>calculateAccuracy</code> and <code>calculate_average</code>. The preferred casing in Swift is <code>camelCase</code>.</li>\n<li>It's customary in Swift not to capitalize constant and function names. Everything that's not a class name should be <code>camelCase</code>.</li>\n<li>Have more meaningful names. <code>calculateAccuracy</code> is good, <code>cmpfunc</code> is not. <code>rssi_array</code> could also be <code>rssi_values</code> or simply <code>rssi</code>.</li>\n<li>Make both the function definition and the function call as clear as possible. For example, when you read <code>calculateAccuracy(_ rssi: Double, _ txPower: Int)</code>, it's clear that the first parameter is <code>rssi</code> and the second is <code>txPower</code>, but when you call it as <code>calculateAccuracy(1.0, 2)</code>, it's no longer clear. Keep the parameter names with <code>calculateAccuracy(rssi: Double, txPower: Int)</code> and call it as <code>calculateAccuracy(rssi: 1.0, txPower: 2)</code>.</li>\n<li><code>getDistance</code> and <code>calculateAccuracy</code> return the magic value <code>-1</code> in case of error. In Swift it's better to throw an error detailing what the problem was, instead of returning an invalid value.</li>\n<li>Since <code>rssi_array</code> and <code>sort_rssi</code> are arrays, you don't need to use <code>memcpy</code> to copy the values of one to another, you can simply assign the values with <code>sort_rssi = rssi_array</code>.</li>\n<li>In Swift, you don't need to use the C <code>qsort()</code> function, since any <code>MutableCollection</code> has a <a href=\"https://developer.apple.com/documentation/swift/mutablecollection/2802575-sort\" rel=\"nofollow noreferrer\"><code>sort()</code></a> method.</li>\n<li>Since <code>sort_rssi</code> is only used inside a function, it doesn't need to be file global, it can be a local variable.</li>\n</ul>\n\n<p>You could replace</p>\n\n<pre class=\"lang-c prettyprint-override\"><code>memcpy(sort_rssi, rssi_array, QUEUE_SIZE * sizeof(int));\nqsort(sort_rssi, QUEUE_SIZE, sizeof(int), cmpfunc);\n</code></pre>\n\n<p>with:</p>\n\n<pre class=\"lang-swift prettyprint-override\"><code>var sortedRssi = rssiArray\nsortedRssi.sort(by: >)\n</code></pre>\n\n<p>See:</p>\n\n<ul>\n<li><a href=\"https://swift.org/documentation/api-design-guidelines/\" rel=\"nofollow noreferrer\">Swift API Design Guidelines</a> for a list of Swift coding guidelines.</li>\n<li><a href=\"https://docs.swift.org/swift-book/LanguageGuide/CollectionTypes.html\" rel=\"nofollow noreferrer\">Collection Types</a> for details about collections, including arrays.</li>\n<li><a href=\"https://docs.swift.org/swift-book/LanguageGuide/ErrorHandling.html\" rel=\"nofollow noreferrer\">Error Handling</a> for details about how to create, throw and catch errors.</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-16T10:10:28.687",
"Id": "475667",
"Score": "0",
"body": "Thanks @rid I will correct the code according to your suggestions and update the question. How to deal issue with memcpy and qsort? What is the solution in swift?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-16T10:27:27.643",
"Id": "475672",
"Score": "0",
"body": "@AppleFan, updated answer with some more suggestions, including some related to `memcpy()` and `qsort()`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-16T10:38:57.257",
"Id": "475673",
"Score": "0",
"body": "@AppleFan, updated answer to mention `sort()` that's part of any mutable collection, such as arrays, and added a usage example."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-16T11:37:21.503",
"Id": "475678",
"Score": "0",
"body": "I see that in C using `memcpy`, `QUEUE_SIZE` is used. If I replace `memcpy` with `var sortedRssi = rssiArray`, how come `queueSize` is not used?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-16T12:27:57.583",
"Id": "475681",
"Score": "0",
"body": "@AppleFan My guess would be that you can copy arrays in Swift."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-16T12:32:21.150",
"Id": "475682",
"Score": "0",
"body": "@rid, How I can post new code, so you can check if I did it correctly?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-16T13:15:35.363",
"Id": "475683",
"Score": "0",
"body": "@AppleFan, you could revert this question to the original code, so that the answer makes more sense, then add a new part to the question with the updated code (or even maybe create a new question)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-16T13:18:24.893",
"Id": "475684",
"Score": "1",
"body": "@AppleFan, in C, an \"array\" is just a pointer to a place in memory that contains values one after the other. It doesn't have the concept of size or length. `memcpy()` simply copies bytes from one part of the memory to another, and you need to tell it from where, to where, and how many bytes. In Swift, arrays are objects that contain metadata such as length, so the Swift array has all the knowledge it needs to make a copy of itself to another array."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-09T22:49:48.100",
"Id": "499465",
"Score": "0",
"body": "Also, your two-line sort example can be replaced with [`let sortedRssi = rssiArray.sorted(by: >)`](https://developer.apple.com/documentation/swift/array/2296815-sorted)"
}
],
"meta_data": {
"CommentCount": "9",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-16T10:02:50.773",
"Id": "242388",
"ParentId": "242387",
"Score": "1"
}
},
{
"body": "<p>Since this is a good chunk of my day job, I've got a bit of feedback for you </p>\n<p>Just keep in mind that Swift is a very flexible language! Your translation works, so you can use as much or as little of that as you want, depending on your or your team's preferences.</p>\n<h3>Embrace Immutability</h3>\n<p>C was designed to be sugar atop Assembly, which emulates a Turing machine, so it's very good at mutation. Swift was designed to be algorithmic, declarative, and functional, so it's very good at copying. Because of this, Swift code will work and optimize better if you embrace immutability.</p>\n<p>For example, you already did a little bit of this in <code>increaseIndex(_:)</code> by making it take an input and return an output, rather than mutating some global variable:</p>\n<pre class=\"lang-swift prettyprint-override\"><code>func increaseIndex(_ x: Int) -> Int {\n var x = x + 1\n if x >= queueSize {\n x = 0\n }\n return x\n}\n</code></pre>\n<p>In C, this is good because it works with C's talents of mutating memory. However, this comes at the cost of clarity: If <code>x</code> is a <code>var</code>, where is it mutated? What is its value when it's returned and when might that change? If I want to write more code in this function, how, where, and why should I mutate <code>x</code>? I have to think like a machine, stepping through the code in my head and keeping track of state, just to understand what will be returned.</p>\n<p>Compare that to this version:</p>\n<pre class=\"lang-swift prettyprint-override\"><code>func increaseIndex(_ x: Int) -> Int {\n let x = x + 1\n if x >= queueSize {\n return 0\n }\n return x\n}\n</code></pre>\n<p>Here, we know that <code>x</code> has the same value throughout the function, and will never change, since it's declared as a <code>let</code> constant. We can see at the declaration site that it's always the input plus one. We can also see that there's a branch with a special case, and the only code in there is <code>return 0</code>. So we know that this function can only ever return its input plus one, or zero.</p>\n<p>We can do better, though, if we...</p>\n<h3>Embrace language constructs</h3>\n<p>Taking the same example above, there are a few more approaches that Swift allows. Let's look at this one:</p>\n<pre class=\"lang-swift prettyprint-override\"><code>func increaseIndex(_ x: Int) -> Int {\n let x = x + 1\n guard x < queueSize else {\n return 0\n }\n return x\n}\n</code></pre>\n<p>The <code>guard</code> statement! It works kind of like other languages' <code>unless</code>, except it <strong>must always</strong> leave scope (in this case, <code>return</code>. In loops, <code>continue</code> and <code>break</code> can also work, etc.). This gives us the peace-of-mind that, since we see a <code>guard</code>, absolutely nothing after it will be executed if its condition is false. We also know that maintainers can't mess this up solely by changing the body of the <code>guard</code>, since the compiler enforces that the body must return from this function no matter what.</p>\n<p>This is another approach that's available to us:</p>\n<pre class=\"lang-swift prettyprint-override\"><code>func increaseIndex(_ x: Int) -> Int {\n let x = x + 1\n return x < queueSize\n ? x\n : 0\n}\n</code></pre>\n<p>Ternary operators aren't everyone's cup-of-tea, so I understand if you don't like this approach. Personally, I find it much better because you can see this function has two lines: it declares a constant and then returns. No possibility of it doing anything else, and it's clear that it either returns that constant or zero, depending on the condition we see.</p>\n<p>Here's another place where Swift can help things be clearer:</p>\n<pre class=\"lang-swift prettyprint-override\"><code>private func getDistance(rssi: Double, txPower: Int) -> Double {\n if rssi == 0 {\n return -1.0 // if we cannot determine accuracy, return -1.\n }\n return pow(10, (Double(txPower) - rssi) / (10 * 2))\n}\n</code></pre>\n<p>Your comment there is necessary because you're using a <a href=\"https://en.wikipedia.org/wiki/Magic_number_(programming)\" rel=\"nofollow noreferrer\">magic number</a>. This is unnecessary in Swift, since <code>enum</code>s are very cheap and lightweight, and have <a href=\"https://docs.swift.org/swift-book/LanguageGuide/Enumerations.html#ID148\" rel=\"nofollow noreferrer\">associated values</a>. The Swift compiler's optimizer will take care of erasing the enum's cases where possible, too, so you don't have to worry about (un)boxing. So, this function can be made clearer with an <code>Optional</code> return!</p>\n<pre class=\"lang-swift prettyprint-override\"><code>private func getDistance(rssi: Double, txPower: Int) -> Double? {\n if rssi == 0 {\n return nil\n }\n return pow(10, (Double(txPower) - rssi) / (10 * 2))\n}\n</code></pre>\n<p>And, if you're OK using ternary operators, it can further be simplified to this:</p>\n<pre class=\"lang-swift prettyprint-override\"><code>private func getDistance(rssi: Double, txPower: Int) -> Double? {\n return rssi == 0 \n ? nil\n : pow(10, (Double(txPower) - rssi) / 20)\n}\n</code></pre>\n<h3>Swift separates literals from types</h3>\n<p>In C and its descendents, each primitive has its own literal, and strings exist too. In Swift, literals can represent anything, and default to primitives if no type is specified. In fact, you take advantage of this in a few places already!</p>\n<p>This means that you don't <em>have to</em> write <code>1.0</code> or similar where it's clear a <code>Double</code> is expected; you can simply write <code>1</code>. This makes the language more human. For me, it makes it easier to read too.</p>\n<h3>Lots to learn in <code>calculateAverage()</code></h3>\n<p>Last up, let's look at <code>calculateAverage()</code>. At first glance, I'm not sure what's intended here, nor how it works. There's a lot of internal state and low-level operations, and a recreation of a C-style for-loop. These are big code smells for me, telling me there's stuff to be done here:</p>\n<pre class=\"lang-swift prettyprint-override\"><code>var rssiArray = [0]\nvar sortRssi = [0]\n\nprivate func calculateAverage() -> Double {\n var average: Double = 0\n var i = 0\n let drop = 3\n memcpy(sortRssi, rssiArray, queueSize * MemoryLayout<Int>.size)\n qsort(sortRssi, queueSize, MemoryLayout<Int>.size, cmpfunc)\n for i in 0..<queueSize - drop {\n if sortRssi[i + drop] == 0 {\n break\n }\n average += Double(sortRssi[i])\n }\n return average / Double(i)\n}\n</code></pre>\n<p>First, <a href=\"https://codereview.stackexchange.com/a/242388/30419\">as rid said</a>, the sorting can be simplified greatly by taking advantage of Swift's built-in memory management and standard library functions:</p>\n<pre class=\"lang-swift prettyprint-override\"><code>memcpy(sortRssi, rssiArray, queueSize * MemoryLayout<Int>.size)\nqsort(sortRssi, queueSize, MemoryLayout<Int>.size, cmpfunc)\n\n// becomes:\n\nsortRssi = rssiArray.sorted(by: >)\n</code></pre>\n<p>This also means that <code>compareFunction</code> is unnecessary!</p>\n<p>Next, I see a constant <code>drop = 3</code>. It appears to me you're using this to drop the first 3 values from the array, which can be replaced with the standard library function <a href=\"https://developer.apple.com/documentation/swift/array/1688675-dropfirst\" rel=\"nofollow noreferrer\"><code>dropFirst(_:)</code></a>. This returns a lazily-evaluated sequence, so we'll also have to create an array from that:</p>\n<pre class=\"lang-swift prettyprint-override\"><code>sortRssi = Array(rssiArray.sorted(by: >).dropFirst(3))\nfor i in 0..<sortRssi.count {\n if sortRssi[i] == 0 {\n break\n }\n average += Double(sortRssi[i])\n}\n</code></pre>\n<p>I also notice that you're keeping track of an <code>i</code> variable here, and returning it at the end. This is also unnecessary since now its value will be the same as <code>sortRssi.count</code>, and Swift only allows for-each loops anyway:</p>\n<pre class=\"lang-swift prettyprint-override\"><code>private func calculateAverage() -> Double {\n var average: Double = 0\n sortRssi = Array(rssiArray.sorted(by: >).dropFirst(3))\n for item in sortRssi {\n if item == 0 {\n break\n }\n average += Double(item)\n }\n \n return average / Double(sortRssi.count)\n}\n</code></pre>\n<p>Looking better already! We can further simplify this by taking advantage of the Swift higher-order function <a href=\"https://developer.apple.com/documentation/swift/array/3126956-reduce\" rel=\"nofollow noreferrer\"><code>reduce</code></a>. As the name implies, this reduces a collection of values down to a single value, which is exactly what you want in an averaging function: to reduce an array of numbers to a single number representing the average:</p>\n<pre class=\"lang-swift prettyprint-override\"><code>private func calculateAverage() -> Double {\n sortRssi = Array(rssiArray.sorted(by: >).dropFirst(3))\n let total: Double = sortRssi.reduce(into: 0) { average, item in\n if item == 0 {\n break // !! Doesn't compile!\n }\n average += Double(item)\n }\n \n return total / Double(sortRssi.count)\n}\n</code></pre>\n<p>Oh my! It seems that <code>reduce</code> can't work here because of this special condition of your program! Not to worry, we can take care of that with another standard library function, <a href=\"https://developer.apple.com/documentation/swift/array/2830384-prefix\" rel=\"nofollow noreferrer\"><code>prefix(while:)</code></a>. This lets us take only the first however-many items in the array, so long as they all match a certain condition, just like you're doing here:</p>\n<pre class=\"lang-swift prettyprint-override\"><code>let total: Double = sortRssi\n .prefix(while: { $0 != 0 })\n .reduce(into: 0) { average, item in\n average += Double(item)\n }\n</code></pre>\n<p>As a C dev, I'm sure this is setting off your big-O alarm, since it loops twice! Not to worry, there's this magical little gem: <a href=\"https://developer.apple.com/documentation/swift/array/1689574-lazy\" rel=\"nofollow noreferrer\"><code>.lazy</code></a>. It allows any collection to be lazily-evaluated, so the loop only runs once:</p>\n<pre class=\"lang-swift prettyprint-override\"><code>let total: Double = sortRssi\n .lazy\n .prefix(while: { $0 != 0 })\n .reduce(into: 0) { average, item in\n average += Double(item)\n }\n</code></pre>\n<p>And now since <code>total</code> is created on one line and used once on the next, we don't have to dedicate a line to declaring it, so we can remove it altogether and get this:</p>\n<pre class=\"lang-swift prettyprint-override\"><code>private func calculateAverage() -> Double {\n sortRssi = Array(rssiArray.sorted(by: >).dropFirst(3))\n return sortRssi\n .lazy\n .prefix(while: { $0 != 0 })\n .reduce(into: Double(0)) { average, item in\n average += Double(item)\n }\n / Double(sortRssi.count)\n}\n</code></pre>\n<p>And since we're already in lazy-land, we can restructure this a little more if we want with another standard library function, <a href=\"https://developer.apple.com/documentation/swift/array/3017522-map\" rel=\"nofollow noreferrer\"><code>map</code></a>:</p>\n<pre class=\"lang-swift prettyprint-override\"><code>private func calculateAverage() -> Double {\n sortRssi = Array(rssiArray.sorted(by: >).dropFirst(3))\n return sortRssi\n .lazy\n .prefix(while: { $0 != 0 })\n .map(Double.init)\n .reduce(into: 0) { average, item in\n average += item\n }\n / Double(sortRssi.count)\n}\n</code></pre>\n<p>And now since the body of the <code>reduce</code> only has one function call in it (<code>+=</code>), we can remove the body and replace it with a reference to that function:</p>\n<pre class=\"lang-swift prettyprint-override\"><code>private func calculateAverage() -> Double {\n sortRssi = Array(rssiArray.sorted(by: >).dropFirst(3))\n return sortRssi\n .lazy\n .prefix(while: { $0 != 0 })\n .map(Double.init)\n .reduce(into: 0, +=)\n / Double(sortRssi.count)\n}\n</code></pre>\n<p>This looks much better to me. It is very Swifty! There's no internal state, it's all standard Swift functions,</p>\n<p>If you want, though, it can be made to fit the philosophies of Swift even better by removing it from state and placing it in a type-extension, to make it more reusable in other places:</p>\n<pre class=\"lang-swift prettyprint-override\"><code>private func calculateAverage() -> Double {\n sortRssi = Array(rssiArray.sorted(by: >).dropFirst(3))\n return sortRssi.averaged(while: { $0 != 0 })\n}\n\n\nextension Collection where Element: BinaryInteger {\n func averaged(while allowedPrefixPredicate: (Element) -> Bool) -> Double {\n lazy\n .prefix(while: allowedPrefixPredicate)\n .map(Double.init)\n .reduce(into: 0, +=)\n / Double(count)\n }\n}\n</code></pre>\n<p>There it is. Now, the work we put into creating this averaging function can be reused for any collection containing integers. We use it here on an array of <code>Int</code>s, but later if you want similar behavior, you can use it on a set of <code>UInt8</code>s, etc!</p>\n<h3>Putting it all together</h3>\n<p>Embracing these patterns makes this more reliable. Let's see how it looks after we put all this together in your program:</p>\n<pre class=\"lang-swift prettyprint-override\"><code>let queueSize = 16\nvar rssiArray = [0]\nvar sortRssi = [0]\nvar rssiIndex = 0\n\n\nfunc increaseIndex(_ x: Int) -> Int {\n let x = x + 1\n return x < queueSize\n ? x\n : 0\n}\n\n\nprivate func getDistance(rssi: Double, txPower: Int) -> Double? {\n return rssi == 0\n ? nil\n : pow(10, (Double(txPower) - rssi) / 20)\n}\n\n\nprivate func calculateAccuracy(rssi: Double, txPower: Int) -> Double? {\n guard rssi != 0 else {\n return nil\n }\n let ratio = rssi * (1 / Double(txPower))\n return ratio < 1\n ? pow(ratio, 10)\n : (0.89976) * pow(ratio, 7.7095) + 0.111\n}\n\n\nprivate func calculateAverage() -> Double {\n sortRssi = Array(rssiArray.sorted(by: >).dropFirst(3))\n return sortRssi.averaged(while: { $0 != 0 })\n}\n\n\n\nextension Collection where Element: BinaryInteger {\n func averaged(while allowedPrefixPredicate: (Element) -> Bool) -> Double {\n lazy\n .prefix(while: allowedPrefixPredicate)\n .map(Double.init)\n .reduce(into: 0, +=)\n / Double(count)\n }\n}\n</code></pre>\n<p>This looks good to me. It maintains the original functionality, and embraces Swift as much as it can. I hope it helps!</p>\n<h3>Compare before and after</h3>\n<p>After adjusting for whitespace and comment lines, and tweaking names a bit to be more comparable, here's a diff comparing the original C code to my Swift translation:</p>\n<p><a href=\"https://www.diffchecker.com/muVaLwtG\" rel=\"nofollow noreferrer\">https://www.diffchecker.com/muVaLwtG</a></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-10T16:45:47.397",
"Id": "253314",
"ParentId": "242387",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "242388",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-16T09:33:41.800",
"Id": "242387",
"Score": "2",
"Tags": [
"c",
"swift",
"ios",
"objective-c",
"converting"
],
"Title": "Convert C to Swift"
}
|
242387
|
<h1>Motivation</h1>
<p>I have been trying to work on my first bigger scale Python project, however I am struggling to create pythonic solutions. Instead some of the functions (and especially the naming) I've done so far seems like more of a hacky solution, than a best coding practice. Hope someone can clear up some confusions and lead show me in the right direction. </p>
<h1>Brief Overview</h1>
<p>The script processes Google Spreadsheets by interacting with the Google Docs Sheets API. A class <code>Sheets</code> handles the API calls. The second class <code>CustomSheet</code> handles the application-specific data logic and parsing of the API call responses. At the same time there are 5 different instances of <code>CustomSheet</code> shared amongst different scripts to perform various automation on the data. </p>
<p>Because the Google Docs API is limited too <code>100req/100s</code>, instances are only initialized once. Initially I had the idea of writing a script coordinating the handling of the instances and sub-scripts, however this added a lot of complexity and little benefit. Instead whenever a <code>CustomSheet</code> is initialized, the instance is appended to <code>instances</code> on class-level so scripts can get them autonomously – and of course it also made sense to implement a classmethod that initializes all instances automatically by calling <code>initializeAll</code>, as their initialization requirements are predictable. While it adds a lot of comfort, it seems like a lot of the logic that should be handled on script level is now moved to class level.</p>
<h1>Questions</h1>
<ol>
<li>Is initializing all relevant class instances (<code>initializeAll</code>) ok?</li>
<li>And handling instances using <code>@classmethods</code> (<code>get</code>, <code>getAll</code>)?</li>
<li>Should <code>getCustomSheet</code> be renamed to <code>getSheet</code> which then simply calls <code>super()</code>? But what if the necessity arises to make a raw API call from one of the scripts?</li>
<li>The <code>errorResilience</code> should really be a decorator. However having to work with slices and indices on return values either leaves the choice of passing them to a decorator, e.g. <code>@error_resilience([0]['api_call'])</code> which does not seem possible, or to catch an <code>IndexError</code> within the decorator, but then again the returned value is not available in the decorator context (, is it?)</li>
<li>There are a lot of functions in <code>CustomSheet</code> performing evaluations on instance variables. E.g. <code>Entries</code> are evaluated using <code>CustomSheet</code> instances (<code>searchEntry</code>, <code>filterEntry</code>, <code>conv</code>). An alternative solution could be adding <code>instances</code> for <code>Entry</code> as well and moving the functions there, so the logic of evaluating entries is in the Entry class, however this seems to be unpractical during normal runtime, since <code>Entry</code> would have to be imported in all scripts, instead of just importing <code>CustomSheet</code>. Logic seems scattered amongst multiple classes, but it seems to make sense</li>
<li>Any other general remarks on the code? I feel like I use a lot of <code>for ... in ...:</code> loops. Any feedback is greatly appreciated.</li>
</ol>
<h2>Code</h2>
<h3>modules/Sheets.py</h3>
<pre><code>import requests
import json
from time import sleep
from random import randint
from modules.PositionRange import PositionRange
import logging
logger = logging.getLogger(__name__)
from settings import CLIENT_ID, CLIENT_SECRET, REFRESH_TOKEN, PROXY
class Sheets():
""" Google Docs API Library """
PROXIES = {'http': PROXY, 'https': PROXY}
header = {
'Content-Type': 'application/json; charset=utf-8',
}
spreadsheetId = ''
accessToken = ''
def __init__(self, spreadsheetName):
self.getToken()
self.setSpreadsheet(name=spreadsheetName)
def getToken(self):
""" Gets authentication token from Google Docs API
if no Global API token is set on Class Level yet. """
if not Sheets.accessToken:
self.refreshToken()
else:
self.header.update({'Authorization': f'Bearer {Sheets.accessToken}'})
def refreshToken(self):
refreshGUrl = 'https://www.googleapis.com/oauth2/v4/token'
header = {
'Content-Type': 'application/x-www-form-urlencoded'
}
body = {
'client_id': CLIENT_ID,
'client_secret': CLIENT_SECRET,
'refresh_token': REFRESH_TOKEN,
'grant_type': 'refresh_token'
}
r = requests.post(refreshGUrl, headers=header, data=body, proxies=Sheets.PROXIES)
token = self.errorResilience(r.json(), self.refreshToken, {})['access_token']
Sheets.accessToken = token
self.header.update({'Authorization': f'Bearer {Sheets.accessToken}'})
return token
def setSpreadsheet(self, name=None, spreadsheetId=None):
if(name):
spreadsheetId = self.getSpreadsheet(name)
if(spreadsheetId and self.spreadsheetId != spreadsheetId):
logger.debug(f'Setting spreadsheetId to [{spreadsheetId}]')
self.spreadsheetId = spreadsheetId
spreadsheetInfo = self.getSpreadsheetInfo()
self.spreadsheetName = spreadsheetInfo['properties']['title']
self.sheets = spreadsheetInfo['sheets']
logger.info(f'Selected Spreadsheet: {self.spreadsheetName} [{self.spreadsheetId}]')
else:
logger.debug(f'SpreadsheetId already selected [{spreadsheetId}] or None')
def getSpreadsheet(self, name):
try:
logger.info(f'Trying to resolve spreadsheetId for {name}...')
query = f'name = "{name}"'
driveGUrl='https://www.googleapis.com/drive/v3/files'
params = {'q': query}
r = requests.get(driveGUrl, params=params, headers=self.header, proxies=Sheets.PROXIES)
logger.debug(f'RESPONSE: {r.json()}')
return self.errorResilience(r.json(), self.getSpreadsheet, {'name': name})['files'][0]['id']
except IndexError as e:
logger.error(f'Error during spreadsheetId lookup. File {name} was probably deleted.')
logger.exception(f'[ERROR] getSpreadsheet: {name}')
raise EOFError('File not found.') from None
def getSpreadsheetInfo(self):
logger.info(f'Getting all spreadsheet information [{self.spreadsheetId}]')
sheetGUrl = f'https://sheets.googleapis.com/v4/spreadsheets/{self.spreadsheetId}'
r = requests.get(sheetGUrl, headers=self.header, proxies=Sheets.PROXIES)
sheetData = r.json()
return self.errorResilience(sheetData, self.getSpreadsheetInfo, {})
def getSheet(self, sheetName: str, posRange: PositionRange) -> dict:
""" Gets the content of one specific sheet """
sheetGUrl = f'https://sheets.googleapis.com/v4/spreadsheets/{self.spreadsheetId}'
logger.info(f'Getting sheet content: {sheetName}{posRange} [{self.spreadsheetName} | {self.spreadsheetId}]')
sheetGUrl = f'{sheetGUrl}/values/{requests.utils.quote(sheetName)}{posRange}'
r = requests.get(sheetGUrl, headers=self.header, proxies=Sheets.PROXIES)
sheetData = r.json()
return self.errorResilience(sheetData, self.getSheet, {'sheetName': sheetName, 'posRange': posRange})
def errorResilience(self, sheetData, callingFunc, kwargs):
""" Centralized Error Handling for API Calls. Would ideally
be a decorator, however working with different slices and indices
(e.g. refreshToken) in return values doesn't make this possible(?) """
args = []
if('error' in sheetData.keys()):
code = sheetData['error']['code']
if(code == 401):
logger.error('UNAUTHORIZED. API TOKEN LIKELY EXPIRED...')
self.refreshToken()
sleep(5)
return callingFunc(*args, **kwargs)
elif(code == 403):
logger.error('The request is missing a valid API key.')
self.getToken()
elif(code == 404):
logger.error('FILE NOT FOUND. SPREADSHEETID INVALID')
raise IndexError(f'Spreadsheet does not exist {self.name} [{self.spreadsheetId}]')
elif(code == 429):
tsleep = 100 + randint(10, 50)
logger.error(f'API LIMIT EXCEEDED. AUTO-RECOVERING BY WAITING {tsleep}s...')
sleep(tsleep)
return callingFunc(*args, **kwargs)
elif(code == 400):
logger.error('SPECIFIED SHEET DOES NOT EXIST OR ILLEGAL RANGE.')
raise IndexError(sheetData['error']['message'])
else:
logger.error('AN UNKNOWN ERROR OCCURRED.')
return sheetData
</code></pre>
<h3>modules/CustomSheet.py</h3>
<pre><code>from datetime import datetime
from copy import copy
from dateutil.relativedelta import relativedelta
from time import sleep
from modules.Sheets import Sheets
from modules.Entry import Entry
from modules.Synonyms import Synonyms
from modules.PositionRange import PositionRange
from collections import Counter
import logging
logger = logging.getLogger(__name__)
class CustomSheet(Sheets):
""" Custom class that holds """
MONTHS = ['Error', 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul',
'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
TYP = 'CustomSheet'
POS = PositionRange.from_str('A4:R')
instances = []
def __init__(self, date=datetime.now()):
super(CustomSheet, self).__init__(spreadsheetName=CustomSheet.getCustomSheet(date))
self.datum = date
self.name = self.spreadsheetName
self.sheetData = []
self.updateSynonyms()
self.entries = []
self.name = self.spreadsheetName
CustomSheet.append(self)
def __new__(cls, date=datetime.now()):
name = CustomSheet.getCustomSheet(date)
x = CustomSheet.get(name)
if x:
logger.debug(f'{name} already exists. Returning instance...')
return x
else:
logger.debug(f'{name} does not exist already. Creating new instance')
return super(CustomSheet, cls).__new__(cls)
def __getnewargs__(self):
return self.datum
def __str__(self):
return f'{self.spreadsheetName}'
def __eq__(self, value):
return self.name == value
def __lt__(self, other):
return self.datum < other.datum
def __lt__(self, other):
return self.datum > other.datum
def getCustomSheetSheet(self, sheetName):
sheetData = {}
posRange = self.POS
sheetData[sheetName] = self.getSheet(sheetName=sheetName)
return self.parseCustomSheet(sheetData=sheetData, posRange=posRange)
def getCustomSheets(self):
sheetData = {}
sheets = self.sheets
posRange = self.POS
for sheet in sheets:
sheetName = sheet['properties']['title']
if(sheetName.isdigit()):
sheetData[sheetName] = self.getSheet(posRange=posRange, sheetName=sheetName)
return self.parseCustomSheet(sheetData=sheetData, posRange=posRange)
def parseCustomSheet(self, sheetData, posRange):
""" Creates Entries from Spreadsheet Data; basically a dict
so we don't have to work with lists we get from Google Docs """
logger.debug(f'Parsing (raw data -> Entry) {sheetData}')
length = posRange.column_length()
logger.debug(f'LENGTH: {length}')
appended = []
for sheetName, rows in sheetData.items():
pos = copy(posRange)
pos.decrement_row()
for row in rows['values']:
while(len(row) < length+1):
row.append('')
pos.increment_row()
entry = Entry.from_customsheet(self, sheetName, row, pos)
if not entry.isValid():
logger.debug('NO VALID ENTRY FOR DICT ABOVE')
continue
logger.debug('IS VALID ENTRY')
self.sheetData.append(entry)
appended.append(entry)
return appended
def filter(self, field: str, value: str) -> list:
""" Filters Entries for <field> having a certain <value> """
found = []
if not isinstance(value, CustomSheet):
value = value.strip().upper()
for entry in instance.sheetData:
if(entry.__dict__[field.lower()] == value
and 'SYNC' not in entry.sheet):
found.append(entry)
return found
def hasEntry(self, entry: Entry) -> bool:
return entry in self.sheetData
@staticmethod
def getCustomSheet(date):
""" Function to build spreadsheet names by
internal naming convention. """
name = f'Sheet {CustomSheet.MONTHS[date.month]} {str(date.year)}'
return name
@staticmethod
def getTime(relativeMonth=0, absoluteMonth=0):
""" Helpfunction that helps iterating over months
while automatically decrementing years. """
relativeMonth = int(relativeMonth)
absoluteMonth = int(absoluteMonth)
thisMonth = datetime.today().replace(day=1, hour=4, minute=20, second=0, microsecond=0)
date = thisMonth - relativedelta(months=relativeMonth)
if(absoluteMonth != 0):
date = datetime.today()
while(date.month != absoluteMonth):
date = date - relativedelta(months=1)
return date
@classmethod
def get(cls, value: str):
""" Gets a certain CustomSheet instance by its name """
if(isinstance(value, datetime)):
value = CustomSheet.getCustomSheet(value)
for instance in cls.instances:
if instance.name == value:
return instance
@classmethod
def getAll(cls):
return cls.instances
@classmethod
def append(cls, instance) -> None:
if isinstance(instance, list):
instances = instance
for instance in instances:
CustomSheet.append(instance)
return
assert isinstance(instance, CustomSheet)
if(instance not in cls.instances):
cls.instances.append(instance)
@staticmethod
def initializeAll():
""" Helpfunction that initializes all sheets
of the last four months. """
initialized = []
for i in range(0, 4):
try:
initialize = CustomSheet(CustomSheet.getTime(i))
logger.info(f'Building CustomSheet Cache {initialize.name} [iteration {i+1}/4]')
initialize.getCustomSheets()
logger.debug(f'Sheet data [iteration {i+1}]: {initialize.sheetData}')
initialized.append(initialize)
logger.info(f'###- PASSED CUSTOMSHEET CACHE [iteration {i+1}/4]')
sleep(12)
except EOFError as e:
# Fallback in case a file was deleted on Google Docs
logger.exception(f'Skipping month trying to autorecover [iteration {i+1}/4]')
continue
return initialized
@classmethod
def searchEntry(cls, sentry):
""" Searches a specific Entry in all available instances """
found = []
for instance in cls.instances:
for entry in instance.sheetData:
if(entry == sentry):
found.append(entry)
return found
@classmethod
def filterEntry(cls, field, value):
found = []
for instance in cls.instances:
found.extend(instance.filter(field=field, value=value))
return found
@staticmethod
def conv(*entry_list):
""" Used to combine multiple search criteria using .filter()
Only keeps entries that are available in all lists of <entry_list> """
seen = set()
repeated = set()
for entries in entry_list:
for entry in set(entries):
if entry in seen:
repeated.add(entry)
else:
seen.add(entry)
return list(repeated)
def updateSynonyms(self) -> None:
self.synonyms = []
self.synonyms.extend(Synonyms.update(self))
logger.debug(f'New Synonyms: {self.synonyms}')
@classmethod
def searchSynonyms(cls, xSynonyms: list, typ: str='', name: str='') -> list:
found = []
if isinstance(synonym, str):
synonym = [synonym]
for instance in cls.instances:
for xSynonym in xSynonyms:
for synonym in instance.synonyms:
if(synonym.matches(synonym=xSynonym, typ=typ, name=name)):
found.append(synonym)
logger.debug(f'SYNONYM {xSynonyms} FOUND; {found}')
filtered = Synonyms.filter(found)
logger.info(f'Synonym {xSynonyms} found {filtered}')
return filtered
</code></pre>
<h3>modules/Entry.py</h3>
<pre><code>from datetime import datetime
import logging
logger = logging.getLogger(__name__)
class Entry():
HEADERS = ['Abr', 'Kunde', 'Tätigkeit', 'Techniker', 'AZ Anfang', 'AZ Ende', 'Dauer',
'AZ Abzug', 'Anfahrt', 'AZ Typ', 'Bemerkung', 'Freigegeben', '', '', '', '',
'Wartung Anfang', 'Wartung Ende']
def __init__(self, *args, **kwargs):
"""
**kwargs {
'Datum': datetime.datetime(2020, 2, 6, 0, 0),
'pos': < modules.PositionRange.PositionRange object at 0x1101f41d0 > ,
'Abr': '',
'Kunde': 'Test',
'Tätigkeit': 'Something',
'Techniker': 'T2',
'AZ Anfang': '14:00',
'AZ Ende': '15:30',
'Dauer': '1,50',
'AZ Abzug': '0',
'Anfahrt': '',
'AZ Typ': '4',
'Bemerkung': 'b.A.',
'Freigegeben': 'nein',
'Wartung Anfang': '',
'Wartung Ende': '',
...
}
"""
self.abr = kwargs.get('Abr', '').strip().upper()
self.kunde = kwargs.get('Kunde', '').strip().upper()
self.tätigkeit = kwargs.get('Tätigkeit', '').strip().upper()
self.techniker = kwargs.get('Techniker', '').strip().upper()
self.anfang = kwargs.get('AZ Anfang', '')[0:5].replace('24:', '00:')
self.ende = kwargs.get('AZ Ende', '')[0:5].replace('24:', '00:')
self.dauer = kwargs.get('Dauer', '').strip().upper()
self.abzug = kwargs.get('AZ Abzug', '').strip().upper()
self.anfahrt = kwargs.get('Anfahrt', '').strip().upper()
self.typ = kwargs.get('AZ Typ', '').strip().upper()
self.bemerkung = kwargs.get('Bemerkung', '')
self.freigegeben = kwargs.get('Freigegeben', '')
self.wartunganfang = kwargs.get('Wartung Anfang', '')
self.wartungende = kwargs.get('Wartung Ende', '')
self.datum = kwargs.get('Datum')
self.sheet = kwargs.get('sheet').strip().upper()
self.pos = kwargs.get('pos')
self.ref = kwargs.get('ref')
self.sync = datetime.now()
try:
hanfang, manfang = self.anfang.split(':')
hende, mende = self.ende.split(':')
self.dtanfang = self.datum.replace(hour=int(hanfang), minute=int(manfang))
self.dtende = self.datum.replace(hour=int(hende), minute=int(mende))
except Exception as e:
self.dtanfang = self.datum
self.dtende = self.datum
#logger.debug(f'DT: {self}: {e}')
def __str__(self):
return f'{self.kunde} @ {self.techniker} {self.dauer} {self.datum.strftime("%d/%b")} ({self.sheet}{self.pos}) [{self.ref.name}]'
def __repr__(self):
return str(self.__dict__)
def __hash__(self):
return hash(f'{self.datum}{self.sheet}{self.kunde}{self.tätigkeit}{self.techniker}{self.typ}')
def __eq__(self, other):
try:
if(self.datum == other.datum
and self.kunde == other.kunde
and self.techniker == other.techniker
and self.tätigkeit == other.tätigkeit):
return True
else:
return False
except Exception as e:
logger.exception('You may only compare this to another Eintrag object.')
def __lt__(self, other):
if(self.sheet == other.sheet):
return self.dtanfang < other.dtanfang
else:
return self.sheet < other.sheet
def __le__(self, other):
if(self.sheet == other.sheet):
return self.dtanfang <= other.dtanfang
else:
return self.sheet <= other.sheet
def __ne__(self, other):
return not(self == other)
def __gt__(self, other):
if(self.sheet == other.sheet):
return self.dtanfang > other.dtanfang
else:
return self.sheet > other.sheet
def __ge__(self, other):
if(self.sheet == other.sheet):
return self.dtanfang >= other.dtanfang
else:
return self.sheet >= other.sheet
@classmethod
def from_customsheet(cls, ref, sheetName, sheetRow, posRange):
""" Creates an Entry from a sheetData dict """
logger.debug(f'Creating entry from {sheetRow}')
logger.debug(f'POSRANGE: {posRange}')
date = datetime.strptime(f'{ref.datum.year} '
f'{ref.datum.month} '
f'{sheetName}', '%Y %m %d')
parseDict = {
'Datum': date,
'sheet': sheetName.upper(),
'pos': posRange,
'ref': ref
}
for i in range(0, len(Entry.HEADERS)):
if(Entry.HEADERS[i] != ''):
logger.debug(f'{Entry.HEADERS[i]}: {sheetRow[i]}')
parseDict.update({Entry.HEADERS[i]: sheetRow[i].strip()})
logger.debug(parseDict)
return cls(**parseDict)
def isValid(self):
if(Entry.stripString(self.techniker) != ''
or Entry.stripString(self.kunde) != ''
or Entry.stripString(self.tätigkeit) != ''):
return True
else:
return False
def isComplete(self):
if(Entry.stripString(self.techniker) != ''
and Entry.stripString(self.kunde) != ''
and Entry.stripString(self.tätigkeit) != ''
and Entry.stripString(self.anfang != '')
and Entry.stripString(self.ende != '')):
return True
else:
return False
@staticmethod
def stripString(string):
string = string.strip()
string = string.replace('\\r\\n','')
string = string.replace('\r\n','')
string = string.replace(' ', '')
return string
</code></pre>
<h3>modules/PositionRange.py</h3>
<pre><code>import logging
logger = logging.getLogger(__name__)
class PositionRange():
def __init__(self, p1=None, p2=None):
self.p1 = str(p1).upper().replace('!','') or ''
self.p2 = str(p2).upper() or p1
def __str__(self):
if(self.p1 and self.p2):
return f'!{self.p1}:{self.p2}'
elif(self.p1):
return f'!{self.p1}'
else:
return ''
def __repr__(self):
return f'{self.p1}:{self.p2}'
@classmethod
def from_str(cls, posRange):
""" Class from stringified version e.g. A1:F10 """
try:
p1, p2 = posRange.split(':')
except:
p1 = posRange.split(':')
p2 = p1
return cls(p1, p2)
def p1_column(self):
"""
Gibt den Buchstaben für p1
der aktuellen POSRange zurück
"""
chars = 0
for char in self.p1:
if(char.isalpha()):
chars += 1
return self.p1[0:chars]
def p2_column(self):
"""
Gibt den Buchstaben für p2
der aktuellen POSRange zurück
"""
chars = 0
for char in self.p2:
if(char.isalpha()):
chars += 1
return self.p2[0:chars]
def p1_column_number(self):
"""
Holt den Alphanumerischen Wert für p1, also
den für den Buchstaben den Index
"""
chars = 0
for char in self.p1:
if(char.isalpha()):
chars += 1
x = (chars - 1) * 25
x = x + (ord(self.p1[chars-1].lower()) - 97)
return x
def p2_column_number(self):
"""
Holt den Alphanumerischen Wert für p2, also
den für den Buchstaben den Index
"""
chars = 0
for char in self.p2:
if(char.isalpha()):
chars += 1
x = (chars - 1) * 25
x = x + (ord(self.p2[chars-1].lower()) - 97)
return x
def p1_row(self):
if(len(self.p1) <= 1):
return 1
else:
x = ''
for c in self.p1:
if(c.isdigit()):
x = x + c
return int(x)
def p2_row(self):
if(len(self.p2) <= 1):
return 999999999
else:
x = ''
for c in self.p2:
if(c.isdigit()):
x = x + c
return int(x)
def column_length(self):
"""
Rechnet aus, wie groß Zeilenrange ist, indem
der Abstand zwischen beiden berechnet wird
(bspw. für A4!M => müsste 12 sein)
"""
length = self.p2_column_number() - self.p1_column_number()
return length
def column_index(self, column):
indexLength = self.column_length()
indexStart = self.p1_column_number()
indexFind = (ord(column.lower()) - 97)
index = indexLength - (indexLength - (indexFind - indexStart))
return index
def column_headers(self, row=1):
for char in pos:
if(self.p1[0].isalpha()):
p1 = f'{self.p1[0]}{row}'
if(self.p2[0].isalpha()):
p2 = f'{self.p2[0]}{row}'
return PositionRange(p1, p2)
def increment_row(self):
row = str(self.p1_row() + 1)
self.p1 = self.p1_column() + row
self.p2 = self.p2_column() + row
def decrement_row(self):
row = str(self.p1_row() - 1)
self.p1 = self.p1_column() + row
self.p2 = self.p2_column() + row
</code></pre>
<h3>modules/Synonyms.py</h3>
<pre><code>from collections import Counter
import logging
logger = logging.getLogger(__name__)
class Synonyms():
def __init__(self, *args, **kwargs):
self.synonym = kwargs.get('synonym', '').strip().upper()
self.sheet = kwargs.get('sheet', '').strip().upper()
self.typ = kwargs.get('typ', '').strip().upper()
self.ref = kwargs.get('ref')
def __str__(self):
return f'{self.synonym} ({self.sheet}) [{self.ref.name}]'
def __repr__(self):
return str(self.__dict__)
def __eq__(self, other: str):
if(self.synonym == other.strip().upper()):
return True
else:
return False
def matches(synonym: str, typ: str, name: str) -> bool:
if(self == synonym.upper().strip()):
if(typ and self.typ != typ.upper().strip()):
return False
if(name and self.ref.name.upper().strip() != name.upper().strip()):
return False
return True
else:
return False
@staticmethod
def update(instance) -> None:
logger.info(f'Updating Synonyms for {instance.name}...')
typ = instance.TYP
if(typ == 'CustomSheet'):
return Synonyms.updateCustomSheet(instance)
elif(typ == 'Projektliste'):
return Synonyms.updateOtherCustomSheet(instance)
else:
logger.error(f'Cannot update synonyms. {typ} is unknown instance.')
@staticmethod
def updateCustomSheet(instance) -> None:
synonyms = []
typ = instance.TYP
synonym = {'synonym': instance.name, 'sheet': '', 'ref': instance, 'typ': typ}
synonyms.append(Synonyms(synonym))
synonym = {'synonym': instance.name.replace('Sheet ', ''), 'sheet': '', 'ref': instance, 'typ': typ}
synonyms.append(Synonyms(synonym))
if(instance.datum.month == instance.getTime().month):
synonym = {'synonym': 'CURRENT', 'sheet': '', 'ref': instance, 'typ': typ}
synonyms.append(Synonyms(synonym))
synonym = {'synonym': 'SYNC', 'sheet': 'SYNC', 'ref': instance, 'typ': typ}
synonyms.append(Synonyms(synonym))
synonym = {'synonym': 'PJ-SYNC', 'sheet': 'PJ-SYNC', 'ref': instance, 'typ': typ}
synonyms.append(Synonyms(synonym))
elif(instance.datum.month == instance.getTime(1).month):
synonym = {'synonym': 'PREVIOUS', 'sheet': '', 'ref': instance, 'typ': typ}
synonyms.append(Synonyms(synonym))
for sheet in instance.sheets:
sheetName = sheet['properties']['title']
if(sheetName.isdigit()):
x = instance.datum.replace(day=int(sheetName))
synonym = {'synonym': x.strftime('%d%m%Y'), 'sheet': '', 'name': sheetName, 'typ': typ}
synonyms.append(Synonyms(synonym))
return synonyms
@staticmethod
def filter(synonyms):
""" Filters synonyms list to from .searchSynonyms()
for the Greatest Common Denominator """
greatestCommon = Counter(synonym.ref for synonym in synonyms if synonym.ref)
maxOccurences = 0
for name, occurences in greatestCommon.most_common():
if(occurences == maxOccurences):
raise EOFError(f'Search synonym no max determinable for {greatestCommon}')
elif(occurences > maxOccurences):
maxOccurences = occurences
try:
spreadsheet = greatestCommon.most_common(1)[0][0]
subSearch = [synonym for synonym in synonyms if synonym.ref == spreadsheet]
greatestCommon = Counter(xsearch.sheet for xsearch in subSearch if xsearch.sheet)
sheetName = greatestCommon.most_common(1)[0][0]
# just making sure
result = [x for x in subSearch if x.sheet == sheetName]
logger.debug(f'FILTERED SYNONYM: {result}')
return result[0]
except IndexError as e:
raise EOFError(f'No synonyms specified in {synonyms}') from None
</code></pre>
<hr>
<h3>settings.py</h3>
<pre><code>"""
Dummy account for Stackoverflow with two sheets using
|- https://stackoverflow.com/questions/19766912/how-do-i-authorise-an-app-web-or-installed-without-user-intervention
"""
CLIENT_ID = '255572645365-h0b1joml2eml85045u1htq062scebu4m.apps.googleusercontent.com'
CLIENT_SECRET = 'Mtx71-OaHyfHyZs6zxSFbJHR'
REFRESH_TOKEN = '1//04dwAK3oaiVrmCgYIARAAGAQSNwF-L9IrmzgKSCRRNMTGiPm9Ih-mCtsv5iIlJpPemHeHpoW7CzM85VxlxbobeoaP3j1uXxt5UvY'
PROXY = ''
</code></pre>
<h3>example.py</h3>
<pre><code>import pickle
import os
from time import sleep
from modules.CustomSheet import CustomSheet
from modules.Synonyms import Synonyms
from modules.Entry import Entry
import logging
import logging.handlers
logger = logging.getLogger(__name__)
CACHE_PICKLE = 'GoogleCache.dat'
CACHE_DIR = os.path.realpath(os.path.join(os.getcwd(), os.path.dirname(__file__)))
logging.basicConfig(
format='[%(asctime)s] %(levelname)s [%(name)s.%(funcName)s():%(lineno)d] – %(message)s',
datefmt='%Y/%m/%d %H:%M:%S',
level=logging.DEBUG,
handlers=[
logging.StreamHandler(),
]
)
def saveCache(sheetDataX):
logger.info('Saving cache...')
path = os.path.join(CACHE_DIR, CACHE_PICKLE)
logger.debug(f'Path: {path}')
with open(path, "wb") as f:
pickle.dump(sheetDataX, f, pickle.HIGHEST_PROTOCOL)
sleep(.5)
def loadCache():
logger.info('Loading cache...')
try:
path = os.path.join(CACHE_DIR, CACHE_PICKLE)
with open(path, "rb") as f:
cache = pickle.load(f)
CustomSheet.append(cache)
logger.debug(f'Cache: {cache}')
return cache
except FileNotFoundError as e:
logger.exception('Offline cache store not found. Was probably deleted; recreating completely...')
return buildCache()
def buildCache():
x = CustomSheet.initializeAll()
saveCache(x)
if __name__ == '__main__':
buildCache()
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-16T19:34:33.580",
"Id": "475745",
"Score": "0",
"body": "I created a Google dummy account that can be used to fiddle around with the API straight out of the box! Let me know if you run in any issues & happy about feedback!"
}
] |
[
{
"body": "<p>I have rewritten the code you've provided in <code>sheet.py</code>. Whilst it's pretty much an entire rewrite I believe the problems with the code aren't that drastic.</p>\n\n<ol>\n<li><p>Be more scared of <a href=\"https://en.wikipedia.org/wiki/Side_effect_(computer_science)\" rel=\"nofollow noreferrer\">side effects</a> and partially initialized classes.</p>\n\n<p>I feel 'side effect' is a loaded term. If you look it up then you're bound to find <a href=\"https://en.wikipedia.org/wiki/Functional_programming\" rel=\"nofollow noreferrer\">FP</a> zealots saying it's the spawn of Satan. Whilst OOP lovers will say it's FP scaremongering.</p>\n\n<p>Either way your over-reliance on side effects in your code is making my life harder, as determining the state <code>Sheet</code> is in is much harder. Personally I would remove all, bar one, side effects from <code>Sheet</code>.</p></li>\n<li><p>Don't be scared of making small classes.</p>\n\n<p>I feel the largest problem with the code is the lack of a <code>GoogleSession</code> class that interacts with <a href=\"https://2.python-requests.org/en/master/user/advanced/#session-objects\" rel=\"nofollow noreferrer\"><code>requests.Session</code></a>. We can see this problem manifest in <code>errerResilience</code>.</p>\n\n<blockquote>\n <p>Centralized Error Handling for API Calls. Would ideally\n be a decorator, however working with different slices and indices\n (e.g. refreshToken) in return values doesn't make this possible(?)</p>\n</blockquote>\n\n<p>This is not the best design. Instead if you wrap an immutable <code>requests.Session</code> object in your own <code>GoogleSession</code> then you can build a <code>get</code> method that does this on each request. The benefit of doing it at this level is that you have the raw request and so you can just try over and over until it works. Additionally it looks like you're just calling <code>requests.Session</code>. making the calling code have additional functionality almost seamlessly.</p></li>\n<li><p>The functionality <code>Sheet</code> provides would be better as a library.</p>\n\n<p>By only passing <code>GoogleSession</code> to <code>Sheet</code> and removing all side effects you should notice my plan for <code>Sheet</code> is vastly different to what it is right now. By following both of these all methods will need to be passed the sheet's information as arguments.</p>\n\n<p>This makes the code easier to follow as now there are no strange, and needless, side effects when interacting with <code>Sheet</code>. The code is also now ridiculously short.</p></li>\n<li><p>You should follow <a href=\"https://en.wikipedia.org/wiki/Composition_over_inheritance\" rel=\"nofollow noreferrer\">composition over inheritance</a>.</p>\n\n<p>Whilst I think it's dumb to have COI as a principle, I do however agree that for many programmers it's much easier to get composition right. Good use of inheritance is notoriously hard to teach as many bad guides use shapes as an example.</p>\n\n<p>I should note that the rest of my answer has suggested using composition; <code>Sheet</code> uses <code>GoogleSession</code>, where <code>GoogleSession</code> uses <code>requests.Session</code>. I'm also suggesting <code>CustomSheet</code> use <code>Sheet</code> rather than inherit from it.</p></li>\n</ol>\n\n<p>You have some additional problems:</p>\n\n<ul>\n<li>You have too much logging for my taste. If you just log on each request to debug then you don't really need any more.</li>\n<li>Having <code>logger.error</code> followed by a <code>raise Exception</code> just feels wrong to me. Either the exception will be handled in which case you logging it as an error is erroneous, or the exception won't be handled and you'll get the error and a traceback when the program halts.</li>\n<li>Many of the log messages in <code>errorResilience</code> are juvenile.</li>\n</ul>\n\n<p>Below is the changes I made to <code>sheets.py</code>. Unfortunately I do not have the time to review more than just this file. Please think about editing your code to follow some of the changes I made, and potentially post a follow up question.<br>\n<sub><strong>Note</strong>: Untested</sub></p>\n\n<pre class=\"lang-py prettyprint-override\"><code>import requests\nfrom time import sleep\nfrom random import randint\n\nfrom modules.PositionRange import PositionRange\n\nimport logging\nlogger = logging.getLogger(__name__)\n\nfrom . import settings\n\n\nclass GoogleError(Exception):\n def __init__(self, code, message):\n super().__init__(message)\n self.code = code\n self.message = message\n\n def __repr__(self):\n return f'GoogleError({self.code!r}, {self.message!r})'\n\n def __str__(self):\n return f'[{self.code}] {self.message}'\n\n\nclass GoogleSession:\n def __init__(self, session: requests.Session) -> None:\n self._token = None\n self.session = session\n\n def get(self, *args: Any, **kwargs: Any) -> Any:\n for _ in range(5):\n if self._token is None:\n self.update_token(self.get_oauth_token())\n r = self.session.get(*args, **kwargs)\n data = r.json()\n if 'error' not in data:\n return data\n error = data['error']\n self._handle_error(error['code'], error['message'])\n raise GoogleError(error['code'], error['message'])\n\n def _handle_error(self, code: int, message: str) -> None:\n logger.debug(f'[{code}] {message}')\n if code in (401, 403):\n self.update_token(self.get_oauth_token())\n elif code == 429:\n tsleep = 100 + randint(10, 50)\n logger.warn(f'API limit exceeded. Auto-recovering by waiting {tsleep}s.')\n sleep(tsleep)\n else:\n raise GoogleError(code, message)\n\n def get_oauth_token(self) -> str:\n data = self.get(\n 'https://www.googleapis.com/oauth2/v4/token',\n headers={\n 'Content-Type': 'application/x-www-form-urlencoded'\n },\n data={\n 'client_id': settings.CLIENT_ID,\n 'client_secret': settings.CLIENT_SECRET,\n 'refresh_token': settings.REFRESH_TOKEN,\n 'grant_type': 'refresh_token'\n },\n )\n return data['access_token']\n\n def update_token(self, token: str) -> None:\n self._token = token\n self.session.headers.update({'Authorization': f'Bearer {Sheets.accessToken}'})\n\n\nclass SheetHelper:\n def __init__(self, session: GoogleSession) -> None:\n self.session = session\n\n def get_id(self, name: str) -> str:\n data = self.session.get(\n 'https://www.googleapis.com/drive/v3/files',\n params={'q': f'name = \"{name}\"'},\n )\n return data['files'][0]['id']\n\n def get_info(self, id: str) -> dict:\n return self.session.get(f'https://sheets.googleapis.com/v4/spreadsheets/{id}')\n\n def get_sheet(self, id: str, name: str, range: PositionRange):\n return self.session.get(\n f'https://sheets.googleapis.com/v4/spreadsheets/{id}/values/{requests.utils.quote(name)}{range}'\n )\n\n def get(self, name: str, id: Optional[str] = None):\n if id is None:\n id = self.getSpreadsheet(name)\n\n info = self.get_info(id)\n return (\n id,\n name,\n info['properties']['title'],\n info['sheets'],\n )\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-17T12:09:52.460",
"Id": "475794",
"Score": "0",
"body": "It's genius for how simple it appears while providing a lot of complexity. Thanks for the differentiated feedback; it really helps to see another version of the code! Even though `Sheets` was the only class I was happy with and saw the other classes as more of an issue, your approach just feels *right*. I do have some questions indeed though and hope you can clear them up! Will post in a second comment."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-17T12:12:33.873",
"Id": "475795",
"Score": "0",
"body": "The Google Sheets API also utilizes `POST`, `DELETE` and `PUT` requests. How could they be incorporated without having too much redundant code regarding the token and error handling? Speaking of the `_handle_error`, it appears like the API limit \"auto-recovery\" - by simply recalling the function - is no longer in scope; any reason for that? The application layer could handle it - sure, however I thought it would be smart if I moved as much API-specific complexity as I could to the API-specific class."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-17T12:19:32.403",
"Id": "475796",
"Score": "0",
"body": "`GoogleSession.get` has a loop `for _ in range(5):`, what's its purpose? And finally – by side effects you're referring to the `Sheets.accessToken` variable I assume? I didn't have this initially, however as the number of `CustomSheet` instances grew, every initialization led to a new token and therefore additional stress on the API, which I tried to avoid by all instances sharing the same token in an easily understanable manner. Your solution is much better however by just creating a passable session object."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-17T12:24:33.960",
"Id": "475797",
"Score": "1",
"body": "@schlumpfpirat ① I would implement them without a care for \"too much redundant code\". You should only fix issues you can see, not ones originating from paranoia. (I too had this problem, just let go ;) ② I'm not sure what you mean by this. The API limit auto-recovery is handled by the `for _ in range(5):` loop. ③ This retries the request 5 times before deciding to error, note how 401, 403 and 429 don't raise errors in `_handle_error`. ④ Yes, modifying `Sheets.accessToken` or `self.spreadsheetId` are side effects - they're modifying state rather than returning."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-17T12:24:37.373",
"Id": "475798",
"Score": "0",
"body": "PS: Hey btw, I know your time is limited, but I would really like to learn more and improve. Most of the coding patterns I mainly chose to make my code easily understandable by 3rd parties, going by \"better be a little more explicit than too efficient\", as I find more compact coding can sometimes be hard to read if it's not well done. So in light of all this – could you also consider giving paid reviews or classes?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-17T12:30:36.120",
"Id": "475799",
"Score": "0",
"body": "② ah I see it now, if there's no error the data is simply returned. ④ well going by a composition principle indeed. My initial, inheritance plan was to have the `Sheets` class holding the data representing the `CustomSheet` in Google Docs like the `spreadsheetId`, an `accessToken` to interact with etc, while `CustomSheet` held the actual parsed data. It makes way more sense the way you did it. I initially wanted to make the GoogleDocs a Python library as well, as I think it could be quite handy for people, but was overwhelmed with creating one."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-17T12:38:39.373",
"Id": "475800",
"Score": "0",
"body": "@schlumpfpirat I don't have the skills to be a good teacher. Additionally why pay me when you could post on here for free? :) ② Yeah that code is not the nicest to read. But it gets things done :( ④ I agree and think that's a better solution than having it all in one class."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-17T12:49:26.130",
"Id": "475803",
"Score": "0",
"body": "well because you're good and I'm not sure I can already apply these principles reliably throughout my whole code base, but can understand I cannot expect someone to sink there time into it for free. Besides it's just fair as I mainly want to improve and feel like I need the help of someone in order to progress and go anywhere. :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-17T13:11:05.357",
"Id": "475806",
"Score": "1",
"body": "@schlumpfpirat At programming and reviewing I'm ok, but teaching I'm _really_ bad. On Code Review we have a thing called [an iterative review](https://codereview.meta.stackexchange.com/a/1765), this means it's ok to try and follow my advice to the best of your ability and ask another question! If you get the above working and integrate it into your code I'd be happy to review other parts of your code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-17T13:14:56.003",
"Id": "475808",
"Score": "0",
"body": "alright, I'll be back! :P thanks again until then"
}
],
"meta_data": {
"CommentCount": "10",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-17T01:03:16.447",
"Id": "242437",
"ParentId": "242394",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "242437",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-16T12:39:50.863",
"Id": "242394",
"Score": "3",
"Tags": [
"python",
"python-3.x"
],
"Title": "Python class inheritance - creating pythonic naming, logic and functions"
}
|
242394
|
<p>I'm a newbie PABX tech with a hobby for programming so when I learnt most of the telephone system programming can be completed with scripts I got curious. </p>
<p>With a bit of trial and error to work out the seemingly undocumented syntax of the script I decided once I'd cracked it, to create a spreadsheet where the user enters a list of names in an excel sheet (in column B from row 2) and then clicks a <code>CommandButton</code> to create a script to easily input the name list for the telephone extensions into the system. </p>
<p>I've chosen <code>VBA</code> as my preferred language as </p>
<ol>
<li>I'm most competent in VBA, and</li>
<li>It's common to copy/paste a list from excel already (it's just slightly more tedious that way in my oppinion)</li>
</ol>
<p><strong>I've not had much experience writing to external files (other than other office applications) so I'm looking to see if there are any more efficient ways to achieve this than the way I have with FSOs.</strong></p>
<p>General housekeeping is welcomed too, so any improvements in the way it's written; order of the code, efficiencies elsewhere etc. </p>
<p>The comments are aimed at someone who has very little VBA experience as as far as I know I'm the only person familiar with it in the office. </p>
<pre><code>Public Sub WriteNamesInRangeToPCSFile()
'Description of operations:
'----------------------------------------------------------------------------------------------------------
'
'First the sub finds the last row of column B.
'Then the range containing the extensions and names is created using these variables.
'
'A file system object is created and a new .pcs file is created (represented by variable 'objScriptFile'
'The file path for the .pcs file is defined by the user on Sheet1 in cell C1
'
'The range is put into an array as this is more efficient than reading directly from each cell in the range.
'The output string is built by concatanating itself with each array element contatining a name.
' Each iteration has a carraige return/line feed (chr(9)) at the end of the string so it's written on a new line
'
'The OutputText string is then written to the .pcs file.
'
'==========================================================================================================
'------------ Set variables for our range and dynamically define the range of ext and names --------------=
'==========================================================================================================
Dim PopulatedRangeOfNamesAndExtensions As Range
Dim LastRow As Long
With ThisWorkbook.Sheets("Sheet1")
LastRow = .Cells(Rows.Count, "B").End(xlUp).Row
If LastRow = 1 Then
MsgBox "Please enter at least 1 extension AND name!", vbCritical + vbOKOnly, "No Extension And Name"
Exit Sub
Else
Set PopulatedRangeOfNamesAndExtensions = .Range(Cells(2, "B"), Cells(LastRow, "B"))
End If
End With
'==========================================================================================================
'------------ Create scripting file system object and create .pcs file to user defined path --------------=
'==========================================================================================================
Dim objFSO As Object
Dim objScriptFile As Object
Dim UDFilePath As String
UDFilePath = ThisWorkbook.Sheets("Sheet1").Range("E3").Value
If UDFilePath = "" Then
MsgBox "Please enter a file path in cell E3 to save the script file to.", vbInformation, "Save Location Required"
ThisWorkbook.Sheets("Sheet1").Range("E3").Select
Exit Sub
ElseIf Not Right(UDFilePath, 1) = "\" Then
UDFilePath = UDFilePath & "\" 'Error check to ensure back slash is last character
End If
Set objFSO = CreateObject("Scripting.FileSystemObject")
On Error GoTo PathNotFound
Set objScriptFile = objFSO.CreateTextFile(UDFilePath & "NEC_15-01_Names_Script.pcs", 2)
On Error GoTo 0
'==========================================================================================================
'------------ Build our output string by dumping the data to an array and looping the array --------------=
'==========================================================================================================
Dim OutputText As String
Dim ArrayElementCounter As Long
Dim ArrayForRange As Variant
ArrayForRange = PopulatedRangeOfNamesAndExtensions
For ArrayElementCounter = 0 To (UBound(ArrayForRange) - 1)
If Not ArrayForRange(ArrayElementCounter + 1, 1) = Empty Then 'counter + 1 because counter is zero based and array is 1 based
OutputText = OutputText & "SET" & vbTab & "15-01" & vbTab & "(" & ArrayElementCounter & ",0,00)" & vbTab & vbDoubleQuote & ArrayForRange(ArrayElementCounter + 1, 1) & vbDoubleQuote & vbCrLf
End If
Next ArrayElementCounter
'Write the built output string to the newly created .pcs file.
objScriptFile.Write (OutputText)
Exit Sub 'Exit before error handler is run.
PathNotFound: 'Error handler if non valid file path is used (such as non existent path)
If Err.Number = 76 Then
MsgBox "Run time error (76) has occured." & vbNewLine & vbNewLine & _
"The following path does not exist or is not in a valid format:" & vbNewLine & _
vbDoubleQuote & UDFilePath & vbDoubleQuote & vbNewLine & vbNewLine & _
"Please check the path in cell E3 and try again.", _
vbCritical + vbOKOnly, "Invalid File Path"
Else 'Raise normal error if not due to invalid file path
Err.Raise Err.Number, Err.Source, Err.Description, Err.HelpFile, Err.HelpContext
End If
End Sub
</code></pre>
<p>The scripts are tab-spaced with the syntax:<br>
<code>SET <Memory-Block> (parameters) "Value"</code><br>
Where <code>(Parameters)</code> further breaks down to <code>(<Row>,<Column>,<Item>)</code></p>
<p>It should be noted that the parameters are zero-based - i.e the first row, column and item is 0 (though in the system it's shown in the GUI as 1 just to make things confusing).</p>
<hr>
<h2>Here are some example screenshots of source data and the output file:</h2>
<p>Source data on sheet:<br>
<a href="https://i.stack.imgur.com/2rv7n.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/2rv7n.png" alt="Source data sample"></a></p>
<p>Output file:<br>
<a href="https://i.stack.imgur.com/UK5Yz.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/UK5Yz.png" alt="Output file saved in user defined location"></a></p>
<p>For bonus points here is a snip of the system after running the output script file:<br>
<a href="https://i.stack.imgur.com/KTLhN.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/KTLhN.png" alt="System after running output script file"></a></p>
|
[] |
[
{
"body": "<p></p>\n\n<h2>Use References in place of <code>CreateObject</code></h2>\n\n<p>If you include the reference to the <code>Microsoft Scripting Runtime</code> you can reduce the <code>dim</code> and <code>set</code> of <code>objFSO</code> to </p>\n\n<pre class=\"lang-vb prettyprint-override\"><code>Dim fso As New Scripting.FileSystemObject\n</code></pre>\n\n<p>to increase readability. Note that i have removed the <code>obj</code> prefix as it is no longer dimmed as an object. Similarly, this can be done with the file as </p>\n\n<pre class=\"lang-vb prettyprint-override\"><code>Dim ScriptFile As Scripting.File\n</code></pre>\n\n<p>Doing this not only makes your code siginificantly easier to read, but also enables intellisense for these objects which makes it easier to write with them. </p>\n\n<h2>Make use of line continuation</h2>\n\n<p>You can use <code>_</code> to allow for multi-line operations, and make your code more readable. For instance </p>\n\n<pre class=\"lang-vb prettyprint-override\"><code>OutputText = OutputText & \"SET\" & vbTab & \"15-01\" & vbTab & \"(\" & ArrayElementCounter & \",0,00)\" & vbTab & vbDoubleQuote & ArrayForRange(ArrayElementCounter + 1, 1) & vbDoubleQuote & vbCrLf\n</code></pre>\n\n<p>can be formatted as </p>\n\n<pre class=\"lang-vb prettyprint-override\"><code>OutputText = _ \n OutputText & \"SET\" & vbTab & \"15-01\" & vbTab & _ \n \"(\" & ArrayElementCounter & \",0,00)\" & vbTab & _ \n vbDoubleQuote & ArrayForRange(ArrayElementCounter + 1, 1) & _ \n vbDoubleQuote & vbCrLf\n</code></pre>\n\n<p>making it easier to read. Not that the <code>_</code> must be preceded by a space and that you cannot have comments after the line continuation character</p>\n\n<h2>Consider using a named range for E3</h2>\n\n<p>To make your code more readable, you may consider naming the range <code>E3</code> to something along the names of <code>FilePath</code>. You can do this by typing over the <code>E3</code> that appears to the left of the function bar when <code>E3</code> is selected or through the <code>Name Manager</code> under the <code>Formulas</code> ribbon menu. </p>\n\n<p>This will allow you to reference the cell in VBA as <code>ws.[FilePath]</code> (where ws is your worksheet object) in place of <code>ThisWorkbook.Sheets(\"Sheet1\").Range(\"E3\")</code>. This will also make it so that if you move the named cell, you do not have to change the code (eg. if you insert a row it above for titling or something) </p>\n\n<p>If you decide against this, you can still use the <code>[...]</code> notation to get this reference down to <code>ws.[E3]</code>.</p>\n\n<h2>Consider using ListObjects</h2>\n\n<p>If you convert your table into a <a href=\"https://docs.microsoft.com/en-us/office/vba/api/excel.listobject\" rel=\"nofollow noreferrer\"><code>ListObject</code></a> using <code>CTRL + T</code> while highlighting it, you can greatly reduce the complexity of some operations. </p>\n\n<p>For instance if you define your listobject as <code>lo</code>, the row number of the last row can be found with </p>\n\n<pre class=\"lang-vb prettyprint-override\"><code>lo.Listrows.Count+lo.Range.Row\n</code></pre>\n\n<p>rather than </p>\n\n<pre class=\"lang-vb prettyprint-override\"><code>ws.Cells(Rows.Count, \"B\").End(xlUp).Row\n</code></pre>\n\n<p>Notably, the list object also allows for the data to be directly referenced with </p>\n\n<pre class=\"lang-vb prettyprint-override\"><code>lo.DataBodyRange\n</code></pre>\n\n<p>or for the iteration over <code>lo</code> as </p>\n\n<pre class=\"lang-vb prettyprint-override\"><code>For Each lr In lo.ListRows\n</code></pre>\n\n<p>where <code>lr</code> is a <code>ListRow</code> object</p>\n\n<hr>\n\n<h1>All Together</h1>\n\n<p>As you noted in your comments, it is faster to handle all the data by pushing it into an array, however, this can lead to memory issues with large datasets (particularlly if you are using 32 Bit Excel which has a 2GB memory limit). So, just to be thurough I have included two solutions, one which puts the data into a variant array, and one which iterates over the data using <code>ListRows</code>. While both are quick the iterative approach is ~6% slower.</p>\n\n<p>Both solutions assume that the table as been converted to a listobject, and that the range <code>E3</code> has been renamed to <code>FilePath</code></p>\n\n<h2>Array Approach (for small lists)</h2>\n\n<pre class=\"lang-vb prettyprint-override\"><code>Sub WriteToPCSFile_SmallList()\n '----------------------------------------------------------------------------------------------------------\n 'Description of operations:\n '----------------------------------------------------------------------------------------------------------\n '\n 'First the sub grabs data from the listobject.\n 'Then the range containing the extensions and names is created using these variables.\n '\n 'A file system object is created and a new .pcs file is created (represented by variable 'txtStream'\n 'The file path for the .pcs file is defined by the user on Sheet1 in range \"FilePath\" (E3)\n '\n 'The range is put into an array as this is quicker than reading directly from each cell in the range.\n 'The output string (out) is built by concatanating itself with each array element contatining a name.\n ' Each iteration has a carraige return/line feed (chr(13)&chr(10)) at the end of the string so\n ' it's written on a new line\n '\n 'The out string is then written to the .pcs file.\n '\n\n '==========================================================================================================\n '------------ Set variables for our range and dynamically define the range of ext and names --------------=\n '==========================================================================================================\n\n\n Dim ws As Excel.Worksheet, _\n lo As Excel.ListObject, _\n dat As Variant, _\n row As Long, _\n out As String\n\n '==========================================================================================================\n '------------ Collect data -------------------------------------------------------------------------------=\n '==========================================================================================================\n Set ws = Application.ThisWorkbook.Worksheets(\"Sheet1\")\n Set lo = ws.[A1].ListObject\n Let dat = lo.DataBodyRange.Value\n\n If lo.ListRows.Count = 0 Then\n Call MsgBox(\"Please enter at least 1 extension AND name!\", vbCritical + vbOKOnly, \"No Extension And Name\")\n Exit Sub\n End If\n\n '==========================================================================================================\n '------------ Make out string ----------------------------------------------------------------------------=\n '==========================================================================================================\n For row = 1 To UBound(dat, 1)\n If Not dat(row, 2) = Empty Then\n Let out = out & _\n \"SET\" & vbTab & \"15-01\" & vbTab & _\n \"(\" & row - 1 & \",0,00)\" & vbTab & _\n vbDoubleQuote & dat(row, 2) & _\n vbDoubleQuote & vbCrLf\n End If\n Next row\n\n '==========================================================================================================\n '------------ Create scripting file system object and create .pcs file to user defined path --------------=\n '==========================================================================================================\n Dim fso As New Scripting.FileSystemObject\n Dim txtStream As Scripting.TextStream\n\n Let UDFilePath = ws.[FilePath]\n If UDFilePath = \"\" Then\n Call MsgBox(\"Please enter a file path in cell E3 to save the script file to.\", vbInformation, \"Save Location Required\")\n Call ws.[FilePath].Select\n Exit Sub\n ElseIf Not Right(UDFilePath, 1) = \"\\\" Then\n Let UDFilePath = UDFilePath & \"\\\" ''Error check to ensure back slash is last character\n End If\n\n On Error GoTo PathNotFound\n Set txtStream = fso.CreateTextFile(UDFilePath & \"NEC_15-01_Names_Script.pcs\", 2)\n On Error GoTo 0\n\n '==========================================================================================================\n '------------ Write Data to the File ---------------------------------------------------------------------=\n '==========================================================================================================\n Call txtStream.Write(out)\n Call txtStream.Close\n\n Exit Sub\n\nPathNotFound: '' Error handler if non valid file path is used (such as non existent path)\n If Err.Number = 76 Then\n Call MsgBox(\"Run time error (76) has occured.\" & vbNewLine & vbNewLine & _\n \"The following path does not exist or is not in a valid format:\" & vbNewLine & _\n vbDoubleQuote & UDFilePath & vbDoubleQuote & vbNewLine & vbNewLine & _\n \"Please check the path in cell E3 and try again.\", _\n vbCritical + vbOKOnly, \"Invalid File Path\")\n Else '' Raise normal error if not due to invalid file path\n Call Err.Raise(Err.Number, Err.Source, Err.Description, Err.HelpFile, Err.HelpContext)\n End If\n\nEnd Sub\n</code></pre>\n\n<h2>Iterative Approach (for large lists)</h2>\n\n<pre class=\"lang-vb prettyprint-override\"><code>Sub WriteToPCSFile_LargeList()\n\n '----------------------------------------------------------------------------------------------------------\n 'Description of operations:\n '----------------------------------------------------------------------------------------------------------\n '\n 'First the sub grabs data from the listobject.\n 'Then the range containing the extensions and names is created using these variables.\n '\n 'A file system object is created and a new .pcs file is created (represented by variable 'txtStream'\n 'The file path for the .pcs file is defined by the user on Sheet1 in range \"FilePath\" (E3)\n '\n 'The range is iterated over, rather than being put into an array, as this is more memotry efficent, and\n 'the file is written to line by line\n '\n Dim ws As Excel.Worksheet, _\n lo As Excel.ListObject, _\n lr As Excel.ListRow, _\n row As Long, _\n out As String\n\n '==========================================================================================================\n '------------ Collect data -------------------------------------------------------------------------------=\n '==========================================================================================================\n Set ws = Application.ThisWorkbook.Worksheets(\"Sheet1\")\n Set lo = ws.[A1].ListObject\n\n If lo.ListRows.Count = 0 Then\n Call MsgBox(\"Please enter at least 1 extension AND name!\", vbCritical + vbOKOnly, \"No Extension And Name\")\n Exit Sub\n End If\n\n '==========================================================================================================\n '------------ Create scripting file system object and create .pcs file to user defined path --------------=\n '==========================================================================================================\n Dim fso As New Scripting.FileSystemObject\n Dim txtStream As Scripting.TextStream\n\n Let UDFilePath = ws.[FilePath]\n If UDFilePath = \"\" Then\n Call MsgBox(\"Please enter a file path in cell E3 to save the script file to.\", vbInformation, \"Save Location Required\")\n Call ws.[FilePath].Select\n Exit Sub\n ElseIf Not Right(UDFilePath, 1) = \"\\\" Then\n Let UDFilePath = UDFilePath & \"\\\" 'Error check to ensure back slash is last character\n End If\n\n On Error GoTo PathNotFound\n Set txtStream = fso.CreateTextFile(UDFilePath & \"NEC_15-01_Names_Script.pcs\", 2)\n On Error GoTo 0\n\n '==========================================================================================================\n '------------ Write Data to the File ---------------------------------------------------------------------=\n '==========================================================================================================\n\n For Each lr In lo.ListRows '' iter over rows\n If Not lr.Range(1, 2) = Empty Then '' write only if there is a name\n Call txtStream.WriteLine( _\n \"SET\" & vbTab & \"15-01\" & vbTab & _\n \"(\" & row & \",0,00)\" & vbTab & _\n vbDoubleQuote & lr.Range(1, 2) & vbDoubleQuote)\n End If\n Let row = row + 1 '' iter row counter\n Next lr\n\n Call txtStream.Close '' close the file\n\n Exit Sub\n\nPathNotFound: 'Error handler if non valid file path is used (such as non existent path)\n If Err.Number = 76 Then\n Call MsgBox(\"Run time error (76) has occured.\" & vbNewLine & vbNewLine & _\n \"The following path does not exist or is not in a valid format:\" & vbNewLine & _\n vbDoubleQuote & UDFilePath & vbDoubleQuote & vbNewLine & vbNewLine & _\n \"Please check the path in cell E3 and try again.\", _\n vbCritical + vbOKOnly, \"Invalid File Path\")\n Else 'Raise normal error if not due to invalid file path\n Call Err.Raise(Err.Number, Err.Source, Err.Description, Err.HelpFile, Err.HelpContext)\n End If\n\nEnd Sub\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-21T18:09:02.657",
"Id": "242708",
"ParentId": "242395",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "242708",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-16T12:46:03.853",
"Id": "242395",
"Score": "3",
"Tags": [
"vba",
"excel",
"file-system"
],
"Title": "Write Excel range containing names to .pcs script file for PABX programming"
}
|
242395
|
<p>I have been working on a beginner project, learning React and Typescript. The project is an expense manager application and I have tried splitting most of my applications into simple short components.
For the <code>EditExpensePage</code> component I have connected it to the Redux store for the app, in order to be able to access the state and to dispatch actions. </p>
<p>I would like to get some feedback on the code I've written, and ways I could improve it.</p>
<p>The Expense interface : </p>
<pre><code>export interface Expense {
id: string;
description: string;
note?: string;
amount: number;
createdAt: number;
}
</code></pre>
<p>The EditExpensePage : </p>
<pre><code>import * as React from "react";
import { RouteComponentProps } from "react-router";
import * as Redux from 'redux';
import {withRouter} from 'react-router';
import {connect} from 'react-redux';
import { Expense } from "../types/Expense";
import { AppState } from "../Store/configureStore";
import { compose } from "redux";
import ExpenseForm from "./ExpenseForm";
import { AppActions } from "../types/Actions";
import { addExpense, removeExpense } from "../Actions/expenses";
type PathParamsType = {
id: string;
};
//component own props
type PropsType = RouteComponentProps<PathParamsType> & {
id: string;
};
interface StateProps {
expenses: Expense[]
}
interface DispatchProps{
addExpense : (expense : Expense) => any,
removeExpense : (expenseId : string) => any
}
type Props = PathParamsType & PropsType & StateProps & DispatchProps;
function GetSelectedExpense(id : string, expenses : Expense[]){
for (var i=0 ; i<expenses.length; i++){
if (expenses[i].id === id)
{
return expenses[i];
}
}
}
const EditExpensePage: React.FunctionComponent<Props> = (props): any => {
let selectedExpense = GetSelectedExpense(props.match.params.id, props.expenses)
return (
<ExpenseForm description={selectedExpense?.description} amount={selectedExpense?.amount} onSubmit={(expense) => {
for (let i = 0; i< props.expenses.length ; i++){
if (props.expenses[i] === selectedExpense)
{
props.removeExpense(selectedExpense.id);
props.addExpense(expense);
}
}
}}/>
)
};
const mapStateToProps = (state : AppState) :StateProps => {
return({
expenses : state.expenses
})
}
const mapDispatchToProps = (dispatch : Redux.Dispatch<AppActions>) : DispatchProps => {
return {
addExpense : (expense : Expense) => dispatch(addExpense(expense)),
removeExpense : (id : string) => dispatch(removeExpense(id))
}
}
export default compose(
withRouter,
connect(mapStateToProps, mapDispatchToProps))(EditExpensePage);
<span class="math-container">```</span>
</code></pre>
|
[] |
[
{
"body": "<p>I've noticed a few things, which I'm going to elaborate in the following.</p>\n\n<h2>Interfaces</h2>\n\n<p>First off, your interface <code>Expense</code>.\nIt looks good so far, what I'd like to see is something like a structure in it, let it be alphabetically sorted or sort it optionals first or both, something like:</p>\n\n<pre><code>export interface Expense {\n amount: number;\n createdAt: number;\n description: string;\n id: string;\n note?: string;\n}\n</code></pre>\n\n<p>It increases readability and allows others to quickly parse all existing keys (it's a bit nitpicking here, but it can have a huge effect).</p>\n\n<p>Next up:</p>\n\n<pre class=\"lang-js prettyprint-override\"><code>type PathParamsType = {\n id: string;\n};\n//component own props\ntype PropsType = RouteComponentProps<PathParamsType> & {\n id: string;\n};\n\ninterface StateProps {\n expenses: Expense[]\n}\n\ninterface DispatchProps{\n addExpense : (expense : Expense) => any,\n removeExpense : (expenseId : string) => any\n}\n\ntype Props = PathParamsType & PropsType & StateProps & DispatchProps;\n</code></pre>\n\n<p>My two pain points here are, <code>PathParamsType</code> as well as <code>DispatchProps</code>.\nPathParamsType is not speaking for it self, try to give variables or interfaces a very consice name. Also I thought, you accidentially declared <code>{ id: string; }</code> twice. There is some kind of repetition that could have been avoided. Please consider the following:</p>\n\n<pre class=\"lang-js prettyprint-override\"><code>interface WithId {\n id: string;\n}\n\n/* Maybe name ComponentProps to something more speaking. */\ntype ComponentProps = RouteComponentProps<WithId> & WithId;\n</code></pre>\n\n<p>Also, you are declaring a props type below, why didn't you merge all in the first place. \nSomething along the lines like: <code>type Props = RouteComponentProps<WithId> & WithId /* & so on ... */;</code>.</p>\n\n<p><em>!!Side note!!</em> <strong>Avoid stuff like</strong>: <code>type Foo = { bar: string; foo: number; }</code> we have interfaces for that.</p>\n\n<p>Your function typing seems also a bit odd to me.</p>\n\n<pre><code>interface DispatchProps{\n addExpense : (expense : Expense) => any,\n removeExpense : (expenseId : string) => any\n}\n</code></pre>\n\n<p><code>any</code> seems in appropriate here. If you don't return a value from a function use <code>void</code>. If that function <strong>never</strong> returns (e.g. you quit the application inside that function), use the keyword <code>never</code>. But please <em>don't</em> use <code>any</code>.</p>\n\n<p>To sum the interface section up, your code from above could have looked a bit like this:</p>\n\n<pre><code>interface WithId {\n id: string;\n}\n\ninterface StateProps {\n expenses: Expense[];\n}\n\ninterface DispatchProps{\n addExpense : (expense : Expense) => void;\n removeExpense : (expenseId : string) => void;\n}\n\ntype Props = RouteComponentProps<WithId> & WithId & StateProps & DispatchProps;\n</code></pre>\n\n<h2>React Component</h2>\n\n<p>Let's get to the component itself.</p>\n\n<pre class=\"lang-js prettyprint-override\"><code>const EditExpensePage: React.FunctionComponent<Props> = (props): any => {\n /* ... */\n}\n</code></pre>\n\n<p>The same as in the <code>DispatchProps</code> interface, a function does not return any. You actually broke the type system here. The following is fully compliant to your function/ variable typing.</p>\n\n<pre class=\"lang-js prettyprint-override\"><code>const IamBroken: React.FunctionComponent<Props> = (props): any => 5;\n</code></pre>\n\n<p>This works as IamBroken should be a functional component but the function itself returns any and any is 5 (hopefully that explanation helps, at least a bit). What you would have wanted instead is:</p>\n\n<pre class=\"lang-js prettyprint-override\"><code>const IamNotBroken = (props): React.FunctionComponent<Props> => 5; /* TypeScript: ERROR!!!! */\n</code></pre>\n\n<p>To apply the above pattern to your component (two solutions are available):</p>\n\n<pre class=\"lang-js prettyprint-override\"><code>/* Variant 1 */\nconst EditExpensePage = (props: Props) => {\n /* ... */\n}\n\n/* Variant 2 */\nconst EditExpensePage: React.FunctionComponent<Props> = (props) => {\n /* ... */\n}\n</code></pre>\n\n<p>Both solutions are totally fine, if you ask me though, I prefer the first one, it's sleek and if needed the compiler is able to infere the <code>React.FunctionComponent</code> part.</p>\n\n<h2>Component internals, functional programming</h2>\n\n<p>Inside your component I've noticed a few things as well.\n<code>let selectedExpense = GetSelectedExpense(props.match.params.id, props.expenses)</code>. From what I have seen, that you never re-assign selectedExpense. Therefore it's better to keep such variables as constants: <code>const selectedExpense</code>.</p>\n\n<p>I see what you want to achieve with the GetSelectedExpense function. But there are better way's to achieve this in TypeScript/JavaScript. <a href=\"https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Global_Objects/Array\" rel=\"nofollow noreferrer\">Have a look at Arrays over at MDN</a>. There are a few helpful methods for overall array handling. What you are looking for is something like <code>find</code>.\n(<em>Side Note</em>: There is a powerful concept that is called <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment\" rel=\"nofollow noreferrer\">destructuring</a>, and it helps you to avoid to write <code>props.</code> over and over again).</p>\n\n<pre class=\"lang-js prettyprint-override\"><code>const { expenses, match } = props; /* Concept of destructuring, see my side note above */\nconst selectedExpense: Expense | undefined = expenses.find(expense => expense.id === match.params.id);\n</code></pre>\n\n<p>The <code>onSubmit</code> function could be improved in the following way. First, you want to avoid inline array functions as props (many linters are warning about possible performance issues). While that seems to be true, it also doesn't add to readability as well. Have a look at the following (I'm making use of the <a href=\"https://reactjs.org/docs/hooks-intro.html\" rel=\"nofollow noreferrer\">useCallback</a> hook):</p>\n\n<pre class=\"lang-js prettyprint-override\"><code>const { expenses, selectedExpense, removeExpense, addExpense, match } = props;\nconst selectedExpense: Expense | undefined = expenses.find(expense => expense.id === match.params.id);\n\nconst onSubmit = useCallback((expense) => {\n expenses.filter(exp => exp.id === selectedExpense).map(exp => removeExpense(exp.id));\n addExpense(expense); \n}, [removeExpense, addExpense, selectedExpense]);\n\nreturn (<ExpenseForm description={selectedExpense?.description} amount={selectedExpense?.amount} onSubmit={onSubmit}/>);\n</code></pre>\n\n<p>Last but not least, your compose thingy at the end. It seems wrong and should be like this (because <code>compose</code> is coming from redux which shouldn't be abused to chain higher order components):</p>\n\n<pre><code>export default withRouter(connect(mapStateToProps, mapDispatchToProps)(EditExpensePage));\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-17T21:04:45.993",
"Id": "242483",
"ParentId": "242396",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "242483",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-16T13:10:32.613",
"Id": "242396",
"Score": "1",
"Tags": [
"react.js",
"typescript"
],
"Title": "Page for editing an item from an expenses list"
}
|
242396
|
<p>I am new to programming and "programming thinking" as well. I have created a simple program that calculates future earnings from investing. It seems to be working correctly, but I want to be sure and ask some smarter guy out here, whether the program is really working as it should or whether it could be written in a better and cleaner form. Input in <strong>first month</strong> is <strong>15000</strong>, <strong>Other months: 1000</strong>, <strong>End</strong> of time period, when I want to see the earnings: <strong>72 months</strong>, <strong>growth/month: 0.75 %</strong>; Each new input grows every month <strong>by its 0.75 %</strong></p>
<pre><code>static void Main(string[] args)
{
double inpInt, inpMonth, inpMonthTrue, growMonth, monthCount, sum, inpTotal, earnTotal;
inpInt = 15000;
inpMonth = 0;
inpMonthTrue = 1000;
growMonth = 0.75;
monthCount = 72;
inpTotal = inpInt + inpMonthTrue * (monthCount - 1);
sum = inpInt + inpMonth;
inpInt += inpInt / 100 * 0.75;
monthCount--;
Console.WriteLine("Value in months:" );
Console.WriteLine(inpInt);
for (int i = 0; i < monthCount; i++)
{
inpMonth += inpMonthTrue;
inpInt += inpInt / 100 * growMonth;
inpMonth += inpMonth / 100 * growMonth;
sum = inpInt + inpMonth;
Console.WriteLine(sum);
}
earnTotal = sum - inpTotal;
Console.WriteLine(String.Format("Total input: {0}", inpTotal));
Console.WriteLine(String.Format("Total value: {0}", sum));
Console.WriteLine(String.Format("Total earnings: {0}", earnTotal));
Console.ReadLine();
}
</code></pre>
<p>Thanks</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-16T18:39:46.397",
"Id": "475737",
"Score": "1",
"body": "which is true to your application logic `15000 ÷ (100 * 0.75) = 200` OR `(15000 ÷ 100) x 0.75 = 112.5`? as both have different results. if the correct result is the first one, then your calculation is invalid."
}
] |
[
{
"body": "<p>Here are some points that I think can make your code look good -</p>\n\n<ol>\n<li>You can improve the readbility like you can group every set of operations with one line space. Like \n<a href=\"https://i.stack.imgur.com/AovxN.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/AovxN.png\" alt=\"enter image description here\"></a></li>\n<li><p>The local variables can be renamed better as they're not clear to me when I look at the code directly without reading the problem statement. For example <code>inpMonth</code> and <code>inpMonthTrue</code> are confusing.</p></li>\n<li><p>You can include code comments on the logic that you're performing. For example in the below snippet, it is unclear what exactly is happening. </p></li>\n</ol>\n\n<p><a href=\"https://i.stack.imgur.com/yoQsG.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/yoQsG.png\" alt=\"enter image description here\"></a></p>\n\n<ol start=\"4\">\n<li>The <code>main()</code> method can be broken into multiple meaningful methods to improve readability. Assuming that you'll be taking the input from the console\n<a href=\"https://i.stack.imgur.com/Yv3gH.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/Yv3gH.png\" alt=\"enter image description here\"></a></li>\n</ol>\n\n<p>This was just a gist of what I'm trying to convey. It needn't be the exact names, you can create any number of methods for grouping the related logic and code. Breaking a big tall method into multiple meaningful chunks gives more clarity.\nPlus, it is always helpful to detect any bugs that arise in the software, so you know where exactly to look into if the <code>Interest</code> is coming wrong for instance.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-17T16:49:13.910",
"Id": "242470",
"ParentId": "242398",
"Score": "1"
}
},
{
"body": "<p>a few things you should considered : </p>\n\n<ol>\n<li>Never change the original values, and always make your changes on different copy.</li>\n<li>Always think of a good naming strategy (Naming Convention), based on type, and purpose of the code. </li>\n<li>Always make your code available for expansions by modulate your code into different group of actions or processes (use methods, properties, classes ..etc.) apply Object-Oriented-Programming principles.</li>\n<li>Always review your code, search for weaknesses, bugs, and simulate some invalid inputs (common ones) by testing the code and handle them (like adding validations, restrictions ..etc). </li>\n<li>Always separate the business logic from user logic (define classes for them along with any related necessary objects).</li>\n<li>before using a loop, search for a way to get the same results without a loop, sometimes you can get the same output and process without a loop specially in mathematical operations. </li>\n<li>simplify your code, and avoid redundancy whenever possible.</li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-17T19:20:33.390",
"Id": "242477",
"ParentId": "242398",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "242470",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-16T15:02:50.657",
"Id": "242398",
"Score": "2",
"Tags": [
"c#",
"beginner"
],
"Title": "Simple c# for-loop program for calculating theoretical earnings from investing (beginner)"
}
|
242398
|
<p>I have over 2500 files in a directory tree- some of them are numbered, some of them aren't. eg.</p>
<pre><code>1. That night it rained.epub
The sparrow returns at dawn.epub
001. Tomorrow is a new day.epub
000.1. We are the children.epub
</code></pre>
<p>I created my C# code to iterate through all the directories and rename the numbered files to look neater, but at the same time should leave the unnumbered file unaltered like so: </p>
<pre><code>001. That night it rained.epub
The sparrow returns at dawn.epub
001. Tomorrow is a new day.epub
000.1. We are the children.epub
</code></pre>
<p>My coding looks like this:</p>
<pre><code>class Program
{
static string path = @"C:\Users\Anja\Desktop\reekse";
static string name;
static string rpath;
static int numberperiod;
static string number;
static string newname;
static string movepath;
static void Main(string[] args)
{
foreach (var file in Directory.GetFiles(path, "*.epub", SearchOption.AllDirectories)) //searches for all the epub files even if there are 20 subdirectories between the file and the main directory
{
name = System.IO.Path.GetFileName(file);//gets the filename sans the path
rpath = System.IO.Path.GetDirectoryName(file);//gets the path sans the file
numberperiod = name.IndexOf(".");//find the location of the 1st . (remember-zerobasing is used)
if (numberperiod == 1)//first period - meaning no 0's is used in numbering
{
number = name.Substring(0, numberperiod + 1);//pick up the number as well as the . that follows the numbering
name = name.TrimStart(number.ToCharArray());//convert the number to char and trim it
name = name.TrimStart('.', ' ', ' ');// remove any potential blankspaces and . that may be at the start of the filename
newname = "00" + number + " " + name; // create a name that has the 0's, the number, adequite spacing, and the name
}
if (numberperiod == 2)//same as above but the numbering contains two digits
{
number = name.Substring(0, numberperiod + 1);
name = name.TrimStart(number.ToCharArray());
name = name.TrimStart('.', ' ', ' ');
newname = "0" + number + " " + name;
}
if (numberperiod == 3)//files containing 3 digits
{
number = name.Substring(0, numberperiod + 1);
if (number == "000.")// in case the file has odd numbering as in the example
{
number = name.Substring(0, numberperiod + 3);
name = name.TrimStart(number.ToCharArray());
name = name.TrimStart('.', ' ', ' ');
newname = number + " " + name;
}
else
{
name = name.TrimStart(number.ToCharArray());
name = name.TrimStart('.', ' ', ' ');
newname = number + " " + name;
}
}
Console.WriteLine(newname.ToString());
movepath = Path.Combine(rpath, newname);
File.Move(file, movepath);
}
}
}
</code></pre>
<p>The coding works perfectly fine, but it just seems so tedious; I'm positive that there must be a simpler way of doing this like regex or Linq.</p>
<p>Can someone please help? I'm not any good when it comes to either Linq or regex. Can someone please help me rewrite this code to make it simpler?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-17T21:47:47.500",
"Id": "475843",
"Score": "0",
"body": "I cannot address the code you've written directly but I think the gut feeling that brought you here is because files + renaming + regex are very much shell-scripting territory. A compiled language is simply not \"the tool for the job\"."
}
] |
[
{
"body": "<p>using <code>Regex.Replace</code> with a help of <code>PadLeft</code> would do this in a single line. so your work can be simplified to : </p>\n\n<pre><code>foreach (var file in Directory.GetFiles(path, \"*.epub\", SearchOption.AllDirectories)) \n{\n var fileName = System.IO.Path.GetFileName(file);\n var filePath = System.IO.Path.GetDirectoryName(file);//gets the path sans the file \n var strName = Regex.Replace(fileName, @\"^((\\d+\\.){1}(\\d\\.)?\\s+)\", m => m.Groups[0].Value.Trim().PadLeft(4, '0').PadRight(8));\n\n File.Move(file, Path.Combine(filePath, strName));\n}\n</code></pre>\n\n<p>The regex should covers any string with the same pattern in your provided sample. </p>\n\n<p><strong>UPDATE :</strong> </p>\n\n<p>To make it more readable for you, you can use the following : </p>\n\n<pre><code>var regex = new Regex(@\"^([0-9]+\\.?\\.\\s)\");\n\nvar fileName = new StringBuilder();\n\nforeach (var file in Directory.GetFiles(path, \"*.epub\", SearchOption.AllDirectories))\n{\n fileName.Append(Path.GetFileName(file));\n var filePath = System.IO.Path.GetDirectoryName(file);\n\n var match = regex.Match(fileName.ToString());\n\n if (match.Success)\n {\n fileName.Clear();\n fileName\n .Append(match.Value.Trim().PadLeft(4, '0'))\n .Append(\" \")\n .Append(file.Substring(match.Value.Length).Trim());\n }\n\n fileName.Replace(fileName.ToString(), Path.Combine(Path.GetDirectoryName(file), fileName.ToString()));\n\n File.Move(filePath, fileName.ToString());\n\n fileName.Clear(); \n}\n</code></pre>\n\n<p>Using <code>StringBuilder</code> is a must in your case, since you're dealing with a list of files name, and since <code>string</code> is immutable, using <code>StringBuilder</code> will avoid creating a new string for each filename which would save your memory and also optimize the performance.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-23T19:42:02.717",
"Id": "476572",
"Score": "0",
"body": "Thank you so much for helping me renumber my files. It works like a charm! But can you please help me solve the Whitespace-issue? I want 4 whitespace-characters to be added between the number and the files actual name. (\"001.----Each dash represents a whitespace-character) I want it to be look neat."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-24T04:06:32.793",
"Id": "476591",
"Score": "0",
"body": "@diedomkop I have updated my answer with another simplified code, I avoided using expressions to make it readable and easy to edit."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-24T07:56:28.917",
"Id": "476604",
"Score": "0",
"body": "There's no benefit in using `StringBuilder` in this code. Since you call `ToString`, the new string gets created anyway."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-24T13:11:48.520",
"Id": "476629",
"Score": "0",
"body": "@RolandIllig yes, it would create one string per iteration instead of multiple strings just for the name!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-24T14:36:27.173",
"Id": "476635",
"Score": "0",
"body": "If you rewrite the replace line in the first version to `var strName = Regex.Replace(fileName, @\"^((\\d+\\.){1}(\\d\\.)?\\s+)\", m => m.Groups[0].Value.Trim().PadLeft(4, '0').PadRight(8));` it will work with regex only."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-24T14:46:33.483",
"Id": "476636",
"Score": "0",
"body": "@HenrikHansen thanks, I've updated it, this seems much better than my first version."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-25T13:03:30.527",
"Id": "476718",
"Score": "0",
"body": "Thank you both @iSR5 and@HenrikHansen, for your help."
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-19T05:56:53.377",
"Id": "242540",
"ParentId": "242400",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-16T15:22:27.393",
"Id": "242400",
"Score": "3",
"Tags": [
"c#",
"regex"
],
"Title": "Mass file renaming via regex"
}
|
242400
|
<p>I am currently working in a project based on a microservices architecture pattern.<br>
Services are wired up by HTTP calls. They eventually call each others for fetching or putting some data.</p>
<p>I am working on the web page which envelops the whole microservices. I mean, the web page actually needs to send and retrieve data from all the services (except one).<br>
There are several times where the web page behaves as a broker, <em>i.e.:</em> </p>
<blockquote>
<p><em>Fetch some data from service 1,<br>
fetch some data from service 2.<br>
Send something to service 3 based on previous responses.</em></p>
</blockquote>
<p>That's why I decided to implement some functions to avoid lots of duplicated code chunks. This is what I call the <strong>promise-based HTTP abstraction layer</strong>.</p>
<p>I am developing the web page in Typescript, by the way.</p>
<p>I want to mention what my <code>request</code> function is. The <code>request</code> function performs HTTP requests, unsurprisingly.<br>
It is an <a href="https://github.com/axios/axios" rel="nofollow noreferrer"><em>axios</em></a> call wrapper. However, for the sake of simplicity, since it is not that important I'll show only the header.</p>
<pre><code>type HttpMethod = 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE';
declare function request<TResult>(method: HttpMethod, url: string, body?: any): Promise<TResult>;
</code></pre>
<p>And, for comfort, I declared its prefixed argument different calls</p>
<pre><code>const get = request.bind(this, 'GET');
const post = request.bind(this, 'POST');
// And so on ...
</code></pre>
<p>But I refactored this to take profit of the <code>request</code> type argument</p>
<pre><code>const get = <TResult>(url: string, body: any) => request<TResult>('GET', url, body);
const post = <TResult>(url: string, body: any) => request<TResult>('POST', url, body);
// And so on ...
</code></pre>
<p>And, a <code>waitAll</code> function which requests to call the URLs passed in and returns a single <code>Promise</code> which will be resolved whenever all the requests are done.</p>
<pre><code>interface HttpRequest<TResult> {
url: string;
request: (url: string, body?: any) => Promise<TResult>;
body?: any;
};
const waitAll = (...reqs: HttpRequest<any>[]): Promise<any[]> =>
Promise.all(reqs.map(req => req.request(req.url, req.body)));
</code></pre>
<p>With this, I can do something like</p>
<pre><code>(async () => {
const req1: HttpRequest<FirstResponse> = {
url: `http://example.com/one`,
request: post,
body: {
id: 9,
data: [`hi`, `there`]
}
};
const req2: HttpRequest<SecondResponse> = {
url: `http://example.com/one`,
request: get
};
const results = await waitAll(req1, req2);
const [r1, r2] = results;
const body = { ...r1, ...r2 };
const finalResponse = await post<ThirdResponse>(`http://example.com/three`, body);
// do something w/ final response
})();
</code></pre>
<p>This is working but I notice some wrong things.<br>
It feels weird the <code>HttpResponse<></code> object, that wraps the <code>url</code> and the <code>body</code> that, in fact, will be called inside its own <code>request</code> property function.<br>
And when I call <code>waitAll</code>, I'd expect my <code>r1</code> and <code>r2</code> to be of the matching type (I mean, <code>r1</code> must be
of type <code>FirstResponse</code>, and <code>r2</code> must be of type <code>SecondResponse</code>) just like <code>finalResponse</code> is of type <code>ThirdResponse</code>.</p>
<p>I am pretty sure there are lots of improvements to achieve a better-looking API and, the most important thing, take profit of Typescript type safety.</p>
<p>Any thoughts are welcome.</p>
|
[] |
[
{
"body": "<p>First thing, you're right about <code>HttpRequest</code> and the oddness of having to pass manually <code>body</code> and <code>url</code> .</p>\n\n<p>To improve the code, I would suggest to chose a programming paradigm, and to stick to it:</p>\n\n<p>example in OOP:</p>\n\n<pre><code>class HttpRequest<TResult> {\n constructor(private method: HttpMethod, private url: string, private body?: any) {}\n request():Promise<TResult> {\n return request(this.method, this.url, this.body); \n }\n};\n\nconst req1 = new HttpRequest<FirstResponse>('POST', `http://example.com/one`, {\n id: 9,\n data: [`hi`, `there`]\n });\nconst req2 = new HttpRequest<SecondResponse>('GET', `http://example.com/one`);\n\n// you now just have to call req1.request() for example , without parameters\n</code></pre>\n\n<p>in more FP friendly way of doing thing:</p>\n\n<pre><code>function my_request<T>(httpReq: HttpRequest) {\n return (): Promise<T> => request(httpReq.method, httpReq.ufl, httpReq.body)\n}\n\nconst req1 = my_request<FirstResponse>({method:'POST', url:`http://example.com/one`, body:{\n id: 9,\n data: [`hi`, `there`]\n});\nconst req2 = my_request<SecondResponse>({method:'GET', url:`http://example.com/one`});\n\n\n// you now just have to call req1() for example , without parameters\n</code></pre>\n\n<p>Now, we can improve the typing of <code>waitAll</code> with <a href=\"https://www.typescriptlang.org/docs/handbook/advanced-types.html#mapped-types\" rel=\"nofollow noreferrer\">mapped types</a>, for example for the OOP version (it's equivalent for the FP one):</p>\n\n<pre><code>\nfunction waitAll<T extends any[]>(...reqs: {[K in keyof T]: HttpRequest<T[K]>}): Promise<T> {\n // the any here is mandatory as Promise.all doesn't support (yet) the above signature\n return Promise.all(reqs.map(req => req.request())) as any;\n}\n\n// result type will be a [FirstResponse, SecondResponse]\nconst result = waitAll(req1, req2)\n</code></pre>\n\n<p>Now, you should ask yourself if you're not \"over-abstracting\". A code like that:</p>\n\n<pre><code>const req1 = request('POST', `http://example.com/one`, {id: 9});\nconst req2 = request('GET', `http://example.com/one`);\n\nconst [r1, r2] = await Promise.all(req1, req2);\n\nconst finalResponse = await request('POST', `http://example.com/three`, body);\n</code></pre>\n\n<p>uses only standard TS stuffs (<code>await</code>, <code>Promise.all</code>), hence is often easier to read for a developper that didn't write the code.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-25T13:57:16.523",
"Id": "476722",
"Score": "0",
"body": "Hi, @Molochdaa. The idea of the mapped types for keeping the typed-member array is fantastic; never thought about it. However, I must point out the `as any` in its implementation seems quite dirty. `as Promise<T>` is allowed and it feels cleaner. On the other hand, wrapping the `HttpRequest<>` into an object makes sense for the use of the scoped `this`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-25T14:00:13.540",
"Id": "476723",
"Score": "0",
"body": "Finally, I don't really agree with the last statement you said. Note that `Promise.all` is no longer keeping the type response anymore. Moreover, I want (even need) to declare request without invoking 'em instantly, which does `request` function. So instantiating objects seems look to me. Anyways, good approach, I really like the idea. Thanks"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-26T18:38:50.537",
"Id": "476846",
"Score": "0",
"body": "If you want lazy Promise, can you also try something like (would be the same with a class or a function): \n\n`type LazyPromise<A> = {request: () => Promise<A>};`\n\n `function waitAll<T extends any[]>(t: {[K in keyof T]: LazyPromise<T[K]>}): \n LazyPromise<T> {\n return {request: () => Promise.all(t.map(p => p.request()))} as LazyPromise<T>;\n }`\n \n`Promise.all` type should keep the type of the request... up to a certain number (maybe 7 or 8 promises? ) . The different variants for pair, triplet, 4-tuple, etc. are hardcoded in TypeScript lib.d.ts"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-24T21:48:42.357",
"Id": "242876",
"ParentId": "242401",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-16T15:28:22.487",
"Id": "242401",
"Score": "1",
"Tags": [
"javascript",
"http",
"typescript",
"promise"
],
"Title": "Promise-based HTTP abstraction layer"
}
|
242401
|
<p>I have made a clone of the mobile game <a href="https://en.wikipedia.org/wiki/Ballz_(mobile_game)" rel="noreferrer">Ballz</a>, and it works quite well. However, there are a few problems:</p>
<ul>
<li>Performance. When I have more than 50 balls in the game, the FPS dips from 60. I am unsure how to (A) improve the performance of the game and (B) adapt to a low frame rate such that the game physics continues to work properly and the user sees the objects moving at the same speed.</li>
<li>Collisions: Most of the time, collisions work fine. However, when I up the speed of the balls they can sometimes go through boxes. This is not the desired result, but I am again unsure of how to fix it.</li>
<li>I am new to programming with Python, though I am fairly experienced in other languages. I would like to know if there are any small things I can improve with my style. Specifically, to create the singleton class <code>board</code> I have simply created it as a class with only static methods and variables. Is there a better way to define a singleton?</li>
<li>I would like to know how I have done with my OOP, i.e. do any objects "know" about each other that shouldn't?</li>
<li>Lastly, if there are any glitches or obvious errors I've missed please point them out!</li>
</ul>
<hr>
<p>My code is divided into several different class. Here is an image showing the flow of my program:</p>
<p><a href="https://i.stack.imgur.com/3h7I0.png" rel="noreferrer"><img src="https://i.stack.imgur.com/3h7I0.png" alt="Pickle rick"></a>
Here is a brief summary of each class (Note that I use <code>import pygame as pyg</code>):</p>
<ul>
<li>the measures module contains variables that I want to have standardized throughout the code. This includes things like the width and height of the window and borders. </li>
<li>The <code>ball</code> class is derived from <code>pyg.sprite.Sprite</code>. It is first <code>launch()</code>ed when the user hits the mouse button, and, if it falls to the ground first, sets a new "center" from which the balls are launched in the next round (<code>ball.terminus.x</code>)</li>
<li>The <code>item</code> class, derived from <code>pyg.sprite.Sprite</code> contains all of the functions used by both <code>ball_adder</code> and <code>box</code>, such as moving according to the <code>step</code> given, and has overridable functions <code>draw()</code> and <code>handleCollision()</code> </li>
<li>The <code>ball_adder</code> class, derived from <code>item</code>, disappears when hit by a ball and drops a new ball at the base (ball addition is handled by <code>board</code>)</li>
<li>The <code>box</code> class, derived from <code>item</code>, has a <code>number</code> representing its "strength". Every time it is hit by a ball, <code>number</code> is decreased. After hitting 0, the <code>box</code> instance disappears. </li>
<li>The <code>board</code> class contains a <code>pyg.sprite.Group</code> of balls(<code>board.balls</code>) and has a list of groups for each row of the board (<code>board_row</code>) which contains every <code>box</code> and <code>ball_adder</code>, and each row of balls (<code>ball_row</code>, used to optimize collisions)</li>
</ul>
<hr>
<p>Here is my code (I apologize if it takes a long time to read through it all):<br>
<strong>measures.py</strong></p>
<pre><code>window = (375, 585)
radius = 7
dimension = 45
step = 5 #space between each item in the grid
#border width (for the left and side borders) and height (for the top and bottom borders)
side_width = 10
top_height = 65
#grid positions for the boxes and ball_adders
xs = [side_width + step + (dimension + step)*x for x in range(0,7)]
ys = [top_height + dimension + 2*step + (dimension + step) * x for x in range(0,8)]
</code></pre>
<hr>
<p><strong>item.py</strong></p>
<pre><code>import pygame as pyg
import measures
class item(pyg.sprite.Sprite):
"""Base class for the members of board_row"""
def __init__(self, x_pos, y_pos = -1):
pyg.sprite.Sprite.__init__(self)
#Check if the item is a new instance or loaded from the json file. If new, place it at the initial y value.
y = 0
if y_pos == -1:
y = measures.top_height + measures.step
else:
y = measures.ys[y_pos]
self.rect = pyg.Rect(measures.xs[x_pos], y, measures.dimension, measures.dimension)
self.stepper = 0.00
self.moving = True #always move the item when it is created
def draw(self):
"""Handled by the child classes"""
pass
def initiateMove(self):
"""Start moving the item"""
self.moving = True
self.stepper = 0
def updatePosition(self, step):
if self.moving:
#Move object
self.stepper += step
if self.stepper >= step: #Once a full step has ocurred, move the object internally. This ugly workaround is necessary because pyg.Rect.top is an int
self.stepper -= 1
self.rect.top += 1
#Check if the item has hit the next y_pos
try:
measures.ys.index(self.rect.top)
self.moving = False
except:
pass
def update(self, step):
"""Updates the position and draws the item"""
self.updatePosition(step)
self.draw()
def handle_collision():
"""Handled by the child classes"""
pass
</code></pre>
<hr>
<p><strong>Box.py</strong></p>
<pre><code>import pygame as pyg
import random
from item import item
import measures
pyg.font.init() #Throws an error when declaring box.box_font if it is not called
class box(item):
box_font = pyg.font.Font("Fonts/Roboto-Light.ttf", 20)
def __init__(self, game_level, x_pos, y_pos=-1, number = 0):
item.__init__(self, x_pos, y_pos)
#Check if this is a new box instance or loaded from a json file. If new, assign it with a 3/4 of being game_level,
#and a 1/4 chance of being 2*game_level
if number == 0:
self.number = random.randint(1, 4)
if self.number == 1:
self.number = 2*game_level
else:
self.number = game_level
else:
self.number = number
self.number_text = box.box_font.render(str(self.number), True, (0,0,0))
#Pick the color
self.color = pyg.Color(0,0,0)
if self.number <= 5:
self.color = pyg.Color(245, 181, 46)
elif 5 < self.number <= 12:
self.color = pyg.Color(129, 197, 64)
elif 12 < self.number <= 31:
self.color = pyg.Color(234, 34, 94)
elif 31 < self.number < 50:
self.color = pyg.Color(196, 34, 132)
elif 50 <= self.number:
self.color = pyg.Color(22, 116, 188)
def handle_collision(self):
"""decrements the number and updates the text to match it. If number <= 0, kill()"""
self.number -= 1
self.number_text = box.box_font.render(str(self.number), True, (0,0,0))
self.color.r = min(self.color.r + 10, 255)
if self.number <= 0:
self.kill()
def draw(self):
"""Draws the rect and the text centered on the rect"""
number_text_rect = self.number_text.get_rect()
number_text_rect.center = self.rect.center
display_surface = pyg.display.get_surface()
pyg.draw.rect(display_surface, self.color, self.rect)
display_surface.blit(self.number_text, number_text_rect)
</code></pre>
<hr>
<p><strong>Ball_Adder.py</strong></p>
<pre><code>import pygame as pyg
from pygame import gfxdraw
from item import item
import measures
class ball_adder(item):
outer_width = 2
outer_radius = measures.radius + 8
def __init__(self, x_pos, y_pos = -1):
item.__init__(self, x_pos, y_pos)
def draw(self):
"""Draws the inner circle and the outer ring"""
display_surface = pyg.display.get_surface()
rect_center = self.rect.center
gfxdraw.aacircle(display_surface, rect_center[0], rect_center[1], ball_adder.outer_radius, (255,255,255))
#create the outline width since pygame doesn't implement it that.
for i in range(1, ball_adder.outer_width):
gfxdraw.circle(display_surface, rect_center[0], rect_center[1], ball_adder.outer_radius - i, (255,255,255))
gfxdraw.aacircle(display_surface, rect_center[0], rect_center[1], ball_adder.outer_radius - ball_adder.outer_width, (255,255,255))
gfxdraw.aacircle(display_surface, rect_center[0], rect_center[1], measures.radius, (255,255,255))
gfxdraw.filled_circle(display_surface, rect_center[0], rect_center[1], measures.radius, (255, 255, 255))
def handle_collision(self):
"""If there is a collision, disappear"""
self.kill()
</code></pre>
<hr>
<p><strong>ball.py</strong></p>
<pre><code>import pygame as pyg
from pygame import gfxdraw
import math
import measures
class ball(pyg.sprite.Sprite):
radius = 7
terminus = pyg.math.Vector2(measures.window[0] // 2, measures.window[1] - measures.top_height - measures.radius - 1) #launching point
new_terminus_x = 0
first = False #Flag that determines whether or not to update new_terminus_x upon hitting the ground
speed = 10
def __init__(self, x=0):
pyg.sprite.Sprite.__init__(self)
self.vector = pyg.math.Vector2(0,0)
self.moving = False
self.launching = False #Flag that says whether or not the ball is launching (updated in board and the launch thread)
#Set new_terminus_x when starting up the class (avoids the ball flying off the screen when no board.json exists)
if ball.new_terminus_x == 0:
ball.new_terminus_x = ball.terminus.x
#If it is 0, it is "dropped" from a ball_adder onto the correct x value, instead of at terminus.x
if x == 0:
x = ball.terminus.x
self.center = pyg.math.Vector2(x, ball.terminus.y)
def draw(self):
"""Draw"""
display_surface = pyg.display.get_surface()
gfxdraw.aacircle(display_surface, int(self.center.x), int(self.center.y), measures.radius, (255,255,255))
gfxdraw.filled_circle(display_surface, int(self.center.x), int(self.center.y), measures.radius, (255,255,255))
def launch(self):
self.moving = True
self.launching = False #Not launching if you have already launched
def update(self, step):
from Board import board
self.draw()
if self.moving:
#Move along the vector
self.center -= step*ball.speed*self.vector
#Detects collision with the border
#right side
if self.center.x + 7 >= board.borders[3].left:
self.center.x = board.borders[3].left - measures.radius
self.vector.x *= -1
#left side
elif self.center.x - 7 <= board.borders[2].left:
self.center.x = board.borders[2].left + board.borders[2].width + measures.radius
self.vector.x *= -1
#top
elif self.center.y - 7 <= board.borders[0].top + board.borders[0].height:
self.center.y = board.borders[0].top + board.borders[0].height + measures.radius
self.vector.y *= -1
#bottom
elif self.center.y + 7 >= board.borders[1].top:
self.moving = False
#If the first variable is false, then that means no other ball has set it to be true. Set it true and update new_terminus_x
if not ball.first:
ball.first = True
ball.new_terminus_x = self.center.x
elif not self.launching:
#Once the ball hits the ground, slide it over to new_terminus_x
if abs(self.center.x - ball.new_terminus_x) < ball.speed/2:
self.center = pyg.math.Vector2(ball.new_terminus_x, ball.terminus.y)
if self.center.x < ball.new_terminus_x:
self.center = pyg.math.Vector2(self.center.x + ball.speed, ball.terminus.y)
elif self.center.x > ball.new_terminus_x:
self.center = pyg.math.Vector2(self.center.x - ball.speed, ball.terminus.y)
#update the direction vector according to the angle between mouse and terminus
angle = 0
mouse_pos = pyg.mouse.get_pos()
if mouse_pos[1] < self.center.y - measures.radius:
try:
angle = math.atan((mouse_pos[1] - self.center.y)/(mouse_pos[0] - self.center.x))
except:
angle = math.pi /2
else:
angle = 3*math.pi / 180
if pyg.mouse.get_pos()[0] > ball.terminus.x:
angle *= -1
if pyg.mouse.get_pos()[0] > ball.terminus.x:
angle += math.pi
self.change_vector(angle)
def change_vector(self, angle):
"""Takes input angle and updates the direction vector"""
self.vector = pyg.math.Vector2(math.cos(angle), math.sin(angle))
def prepare_launch():
"""Resets the speed and first value (used as a flag to determine whether to change new_terminus_x)"""
ball.first = False
ball.terminus.x = ball.new_terminus_x
ball.speed = 10
</code></pre>
<hr>
<p><strong>Board.py</strong></p>
<pre><code>import pygame as pyg
from pygame import gfxdraw
import random
import Box
import Ball_Adder
import ball
import button
import math
import os
import json
import measures
pyg.font.init()
def pointOfIntersect(r_center, r_size, c_center):
"""Determines the closest point of a rectangle to a circle"""
v2_c_center = pyg.math.Vector2(c_center)
v2_r_center = pyg.math.Vector2(r_center)
offset = v2_c_center - v2_r_center
if offset.x == 0 and offset.y == 0:
return [v2_c_center, v2_r_center]
if offset.x == 0:
ratio = r_size[1] / abs(offset.y)
elif offset.y == 0:
ratio = r_size[0] / abs(offset.x)
else:
ratio = min(r_size[0] / abs(offset.x), r_size[1] / abs(offset.y))
ratio *= 0.5
return v2_r_center + (offset * ratio)
class board:
balls = pyg.sprite.Group()
ball_row = [pyg.sprite.Group() for x in range(0, 7)]
board_row = [pyg.sprite.Group() for x in range(0, 8)] #The last row is for when they hit they bottom and the entire board is cleared.
array_moving = False #Flag that is used to make sure that the balls aren't launched while the board is moving
#game_level and its associated text
game_level = 1
game_level_font = pyg.font.Font("Fonts/Roboto-Regular.ttf", 30)
game_level_rect = pyg.Rect(0, 0, 0, 0)
game_level_text = None
#Not the actual ball_count, just what is displayed before and while you are launching the balls (goes down each time one is launched)
ball_count = 1
gbc_font = pyg.font.Font("Fonts/Roboto-Regular.ttf", 15)
gbc_rect = pyg.Rect(0,0,0,0)
gbc_text = None
#angle between mouse and ball.terminus and the associated text (uses game_level_font)
mouse_angle = 0
ma_rect = pyg.Rect(0,0,0,0)
ma_text = None
#button that, when pressed, speeds up the balls
speed_button = button.button_image(0, 0, "Images/Lightning.png", "Images/LightningPressed.png", pyg.Color(255,255,255))
#window borders and color
border_color = (56, 56, 56)
#order: top, bottom, left, right
borders = []
def init():
#set up the borders
board.borders = [ pyg.Rect(0, 0, measures.window[0], measures.top_height),
pyg.Rect(0, measures.window[1] - measures.top_height, measures.window[0], measures.top_height),
pyg.Rect(0, 0, measures.side_width, measures.window[1]),
pyg.Rect(measures.window[0] - measures.side_width, 0, measures.side_width, measures.window[1]) ]
#Reads from the file. If it doesn't find a board.json, it simply adds a new row.
board.read_from_file()
#Add the necessary number of balls
for i in range(0, max(board.ball_count, 1)):
board.balls.add(ball.ball())
board.update_text(True) #updates the text otherwise the ball_count text is wonky
#Set the position of speed_button
board.speed_button.left = measures.window[0] - board.speed_button.regular.get_rect().width - 5
board.speed_button.top = (board.borders[0].height - board.speed_button.regular.get_rect().height) / 2
def add_row():
row = []
#3/4 chance of being a box, 1/4 chance of being 0, 0 chance of being cool
for i in range(0, 7):
if random.randint(1, 4) == 1:
row.append(0)
else:
row.append(Box.box(board.game_level, i))
#add the ball adder to the list at a random spot
ball_adder_pos = random.randint(0, 6)
del row[ball_adder_pos]
row.insert(ball_adder_pos, Ball_Adder.ball_adder(ball_adder_pos))
#initiate move animation for existing rows
game_end = False
for i in range(len(board.board_row) - 2, -1, -1):
for sprite in board.board_row[i].sprites():
sprite.initiateMove()
if i == 6: #Checks if there is a sprite in the last row
game_end = True
break
#Move the sprite to the next board_row
sprite.add(board.board_row[i+1])
sprite.remove(board.board_row[i])
if game_end:
break
board.array_moving = True #Set the flag to be true as the items are moving down
#Add the new row to the first row
for member in row:
if member != 0:
board.board_row[0].add(member)
#check if the game has ended
if game_end:
for row in board.board_row:
row.empty()
board.game_level = 1
board.add_row()
for ball_ in board.balls:
ball_.kill()
board.ball_count = 1
board.update_text(False)
board.balls.add(ball.ball())
def loop(step):
#Set it to be false
board.array_moving = False
sorted_balls = sorted(board.balls.sprites(), key = lambda x: x.center[1])
#sort to avoid branch prediction failure (I'm not sure this has a huge impact on performance one way or another)
group_collision = board.collision
for i in range(0, len(board.board_row)):
board.board_row[i].update(step) #update each box and ball adder
if board.board_row[i] and board.board_row[i].sprites()[0].moving: #Check if the row has any items and if the first sprite is moving
board.array_moving = True
if i != 7: #If i == 7 then there are boxes in the last row, at which point the game is already over.
pyg.sprite.groupcollide(board.ball_row[i], board.board_row[i], False, False, group_collision)
balls_grounded = True #Flag that tells whether or not the balls are on the ground
#reassign the ball to a new row
for ball_ in sorted_balls:
ball_.update(step)
if ball_.moving == True:
balls_grounded = False
for i in range(0, len(board.ball_row)):
lower = measures.ys[i] - ball.ball.speed - measures.radius - measures.step
upper = measures.ys[i+1] + ball.ball.speed + measures.radius + measures.step
if lower <= ball_.center.y <= upper: #adds range to make sure that all collisions can be caught in time
board.ball_row[i].add(ball_)
else:
board.ball_row[i].remove(ball_)
display_surface = pyg.display.get_surface()
#Displays the path of the ball before the user launches them
if balls_grounded:
board.display_ball_path();
#If they are on the ground and the first flag has been set, then all balls have hit the ground just after being launched
if balls_grounded and ball.ball.first:
board.speed_button.clear_state()
ball.ball.prepare_launch() #resets first
board.game_level += 1
board.ball_count = len(board.balls) #reset ball_count
board.add_row() #add another row
#if thread is true, the function returns true and the game loop starts a new thread using initiaite_launch which launches
#the balls at a set interval
thread = False
if pyg.mouse.get_pressed()[0] and not board.array_moving and balls_grounded:
ball.ball.prepare_launch()
for ball_ in board.balls.sprites():
ball_.launching = True
thread = True
#display the borders
for border in board.borders:
pyg.draw.rect(display_surface, board.border_color, border)
#update each piece of text
board.update_text(balls_grounded)
#check if speed_button has been pressed
if not balls_grounded and board.speed_button.update():
ball.ball.speed = 20
if thread:
return True
else:
return False
def collision(ball_, item):
"""Just handles the collisions"""
if type(item) == Box.box:
#convenience
left = item.rect.left
right = left + item.rect.width
top = item.rect.top
bottom = top + item.rect.height
center = ball_.center
#move foward 1 iteration (done so that the collisions are better)
center -= ball.ball.speed*ball_.vector
#rule out impossible collisions
if center.x + measures.radius <= left or center.x - measures.radius >= right or center.y + measures.radius <= top or center.y - measures.radius >= bottom:
center += ball.ball.speed*ball_.vector #move back one iteration
return None # exit the function
#find the closest point
closest = pointOfIntersect(item.rect.center, (item.rect.width, item.rect.height), center)
difference = center - closest
#move back 1 iteration
center += ball.ball.speed*ball_.vector
#handle the collsion
if difference.x**2 + difference.y**2 <= measures.radius**2:
item.handle_collision()
#find the closest point again because otherwise weird stuff happe
closest = pointOfIntersect(item.rect.center, (item.rect.width, item.rect.height), center)
#top/bottom
if top - 1 <= closest.y <= top + 1 or bottom - 1 <= closest.y <= bottom + 1:
ball_.vector.y *= -1
#left/right
elif left - 1 <= closest.x <= left + 1 or right - 1 <= closest.x <= right + 1:
ball_.vector.x *= -1
elif type(item) == Ball_Adder.ball_adder:
if math.hypot(ball_.center.x - item.rect.center[0], ball_.center.y - item.rect.center[1]) < measures.radius + Ball_Adder.ball_adder.outer_radius:
board.balls.add(ball.ball(item.rect.center[0]))
item.handle_collision()
def update_text(balls_grounded):
display_surface = pyg.display.get_surface()
#game level
board.game_level_text = board.game_level_font.render(str(board.game_level), True, (255, 255, 255))
board.game_level_rect = board.game_level_text.get_rect()
board.game_level_rect.center = board.borders[0].center
display_surface.blit(board.game_level_text, board.game_level_rect)
#ball count
if board.ball_count != 0:
board.gbc_text = board.gbc_font.render("x{}".format(str(board.ball_count)), True, (255,255,255))
board.gbc_rect = board.gbc_text.get_rect()
board.gbc_rect.center = (ball.ball.terminus.x, ball.ball.terminus.y - 3*measures.radius)
display_surface.blit(board.gbc_text, board.gbc_rect)
#mouse angle
if balls_grounded:
board.mouse_angle = math.acos(board.balls.sprites()[0].vector.x)
board.ma_text = board.game_level_font.render(str(round(180 - (board.mouse_angle * 180)/math.pi, 1)) + "°", True, (255, 255, 255))
board.ma_rect = board.ma_text.get_rect()
board.ma_rect.center = board.borders[1].center
display_surface.blit(board.ma_text, board.ma_rect)
def initiate_launch(event):
"""Launches balls at timed intervals"""
vector = tuple(board.balls.sprites()[0].vector) #save the vector so that the user can't change the trajectory mid-launch
for ball_ in board.balls.sprites():
event.wait(timeout=0.08)
ball_.center = pyg.math.Vector2(ball.ball.terminus.x, ball.ball.terminus.y)
ball_.launch()
ball_.vector = pyg.math.Vector2(vector)
board.ball_count -= 1
event.clear()
def display_ball_path():
"""Displays the path of the balls"""
display_surface = pyg.display.get_surface()
spacing = 40
start = pyg.math.Vector2(ball.ball.terminus.x, ball.ball.terminus.y)
end = pyg.math.Vector2(pyg.mouse.get_pos())
length = (start - end).length()
unit_vector = pyg.math.Vector2(start - end)
unit_vector.normalize_ip()
initial_ball = start - spacing*unit_vector
while (initial_ball - start).length() <= length:
gfxdraw.aacircle(display_surface, int(initial_ball.x), int(initial_ball.y), measures.radius, (255,255,255))
gfxdraw.filled_circle(display_surface, int(initial_ball.x), int(initial_ball.y), measures.radius, (255,255,255))
initial_ball -= spacing*unit_vector
def read_from_file():
"""Read from the saved json file or, if it does not exist, then just add a row"""
if os.path.isfile("Saves/board.json") and os.path.getsize("Saves/board.json") != 0:
with open("Saves/board.json", 'r') as f:
data = json.load(f)
board.game_level = data["game level"]
board.ball_count = data["ball count"]
ball.ball.terminus.x = data ["terminus"]
ball.ball.new_terminus_x = ball.ball.terminus.x
board.balls.empty()
for i in range(0, len(board.board_row)):
for member in data[str(i)]:
x = measures.xs.index(member[0])
if member[1] != 0:
board.board_row[i].add(Box.box(board.game_level, x, i-1, member[1]))
else:
board.board_row[i].add(Ball_Adder.ball_adder(x, i-1))
f.close()
else:
board.add_row()
def write_to_file():
"""Write to the json file"""
with open("Saves/board.json", 'w') as f:
data = {"game level": board.game_level, "ball count" : len(board.balls), "terminus": ball.ball.terminus.x}
balls_grounded = False
while board.array_moving or not balls_grounded:
board.loop(0.5)
balls_grounded = True
for ball_ in board.balls.sprites():
if ball_.moving == True:
balls_grounded = False
pyg.display.flip()
for i in range(0, len(board.board_row)):
subdata = []
for sprite in board.board_row[i]:
if type(sprite) == Box.box:
subdata.append((sprite.rect.left, sprite.number))
else:
subdata.append((sprite.rect.left, 0))
data[i] = subdata
json.dump(data, f, indent = 4)
f.close()
</code></pre>
<hr>
<p><strong>button.py</strong></p>
<pre><code>import pygame as pyg
class button_image:
def __init__(self, left, top, image_path, pressed_image_path, color_key):
self.regular = pyg.image.load(image_path)
self.pressed = pyg.image.load(pressed_image_path)
#self.regular.convert_alpha()
#self.presssed.convert_alpha()
self.regular.set_colorkey(color_key)
self.pressed.set_colorkey(color_key)
self.left = left
self.top = left
self.state = False
def check_hover(self):
rectangle = self.regular.get_rect()
rectangle.left = self.left
rectangle.top = self.top
if rectangle.collidepoint(pyg.mouse.get_pos()):
return True
else:
return False
def check_click(self):
if self.check_hover() and pyg.mouse.get_pressed()[0]:
self.state = True
return True
else:
return False
def draw(self):
display_surface = pyg.display.get_surface()
if self.state:
display_surface.blit(self.pressed, (self.left, self.top))
else:
display_surface.blit(self.regular, (self.left, self.top))
def update(self):
self.draw()
return self.check_click()
def clear_state(self):
self.state = False
</code></pre>
<hr>
<p>And, finally, the main file: <strong>Ballz.py</strong></p>
<pre><code>import pygame as pyg
import Board
import threading
import measures
#main function
def main():
pyg.init()
#initialize and set the icon
pyg.display.set_mode(measures.window)
pyg.display.set_icon(pyg.image.load("Images/Icon.png"))
pyg.display.set_caption("Ballz")
display_surface = pyg.display.get_surface()
#create game clock for keeping the framerate constant
game_clock = pyg.time.Clock()
Board.board.init()
running = True
while running:
game_clock.tick(60) #keeps framerate at a maximum of 60
#Handle events
for event in pyg.event.get():
if event.type == pyg.QUIT:
running = False
break
#Draw
try: #In place because sometimes, when I exit the program during debug, this particular section triggers an error.
display_surface.fill((33, 33, 33))
except:
break
#print("FPS: ", int(game_clock.get_fps()))
thread = False
event = threading.Event()
for i in range(0,2): #Call it twice so collisions have a finer granularity
if Board.board.loop(0.5):
thread = True #makes sure that it is not called twice
if thread:
ball_launch = threading.Thread(target=Board.board.initiate_launch, args=(event,))
ball_launch.start()
event.set()
pyg.display.flip()
Board.board.write_to_file() #Write to the file once the game is over
pyg.quit()
if __name__ == "__main__":
main()
</code></pre>
<hr>
<p>While it is not necessary to have the exact same font and images, here are the ones I used</p>
<ul>
<li>Roboto and Roboto light can be found <a href="https://fonts.google.com/specimen/Roboto" rel="noreferrer">here</a>, and must be saved in the <code>Fonts/</code> directory of the project file</li>
<li>The lightning images are right here: <a href="https://i.stack.imgur.com/jsW2Y.png" rel="noreferrer"><img src="https://i.stack.imgur.com/jsW2Y.png" alt="enter image description here"></a> <a href="https://i.stack.imgur.com/ya0x8.png" rel="noreferrer"><img src="https://i.stack.imgur.com/ya0x8.png" alt="enter image description here"></a> (These are to be saved in <code>Images/</code>)</li>
<li>Finally, the icon image: <a href="https://i.stack.imgur.com/Q4llt.png" rel="noreferrer"><img src="https://i.stack.imgur.com/Q4llt.png" alt="enter image description here"></a></li>
</ul>
<hr>
<p>Also, here is a GIF of what the program looks like. As you can see, the game is somewhat laggy starting around game level 50:<br>
<a href="https://i.stack.imgur.com/kEWky.gif" rel="noreferrer"><img src="https://i.stack.imgur.com/kEWky.gif" alt="enter image description here"></a></p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-17T22:59:21.640",
"Id": "475847",
"Score": "2",
"body": "This is nothing like Ballz, where's the bajillion of adverts?! In all seriousness, this is so cool nice job! I hope this gets answered."
}
] |
[
{
"body": "<p>I'm more of a Java guy, but I'll add my 2 cents on the collision detection, because you said it was not always working properly; I think you might solve this by creating a 'vecor' object, or ray. The idea is simple; instead of checking the static shapes, check if the vector intersects a block; and take the first intersection.</p>\n\n<p>In 1D:</p>\n\n<pre><code> t ---O--------|BLOCK|-----------------\n t+1 ------------|BLOCK|-O---------------\n</code></pre>\n\n<p>If the ball is moving quickly it will miss the shape of the block.</p>\n\n<p>Now transform the ball to a 'ray'. If you follow the ray, you'll see it hits the left of the block. </p>\n\n<pre><code> t ---O--------|BLOCK|-----------------\n ray ---O>>>>>>>>>>>>>>>>>>--------------\n</code></pre>\n\n<p>You now know it will collide with the left of the block and can calculate the bounce:</p>\n\n<pre><code> t ---O--------|BLOCK|-----------------\n ray ---O>>>>>>>>------------------------\n <<<<<<<<<<\n t+1 --O---------|BLOCK|-----------------\n</code></pre>\n\n<p>So the ball should be at the new position.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-21T03:02:41.477",
"Id": "476234",
"Score": "0",
"body": "What I do currently is divide the board into rows, and update the row of every ball each loop and check for circle-rectangle collisions normally. Do you think this would be a performance improvement, or end up slowing the game down further? From what I understand, the collisions of 3 different lines must be calculated (otherwise some collisions would be missed). Additionally, should I have to check the lines against every single other box, or should I keep what I have now where ball-box collision is only checked within rows?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-23T09:45:47.797",
"Id": "476535",
"Score": "0",
"body": "@Erdogan yes it will take more processing power if you need to calculate more boxes. However, if you partition your space (for example using quadtrees) you can quick eliminate a whole lot of boxes to check"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-23T13:44:11.130",
"Id": "476549",
"Score": "0",
"body": "I looked at the Wikipedia page for quadtrees and I (kind of) understand them, but I'm not really sure how a quadtree would be implemented with collision detection. Could you point me to an example or explain roughly how one would work?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-25T02:54:26.740",
"Id": "476681",
"Score": "0",
"body": "@Erdogan [Here's](http://www.fundza.com/algorithmic/quadtree/index.html) one."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-19T20:58:45.090",
"Id": "242592",
"ParentId": "242403",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-16T15:45:39.970",
"Id": "242403",
"Score": "8",
"Tags": [
"python",
"performance",
"python-3.x",
"pygame"
],
"Title": "Clone of mobile game Ballz"
}
|
242403
|
<p>I have to find the position (array index) of a number in an array, the number can lie in between any other two numbers in the array. I have written code for this but I want some alternative way to do this.</p>
<p>example: let the array be given as</p>
<pre><code>float arr[]={1.5, 3.65, 4.9, 8.4, 10.6, 17.5, 19.45, 21.86, 25.67, 30.65};
</code></pre>
<p>Now I have to find the position of 12.6 in the given array, since 12.6 lies between 10.6 and 17.5 in the above array so, it should return array index as 4. </p>
<p>Is there any other way to do this? I know it can be done by using binary search but I don't know how to implement it (since the number is not present in array)</p>
<p>The array is sorted (ascending order) </p>
<pre><code>#include<stdio.h>
int main()
{
int position;
int i;
float num=12.6; // position of this number has to be determined i.e. it lies between 10.6
// and 17.5 in the array given below so it should give array index as 4
float arr[]={1.5, 3.65, 4.9, 8.4, 10.6, 17.5, 19.45, 21.86, 25.67, 30.65}; // any random array
for(i=0;i<10;i++)
{
if(arr[i] > num)
{
position=i-1;
break;
}
}
printf("array index is %d",position); // this gives index as 4
return 0;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-16T16:30:19.383",
"Id": "475717",
"Score": "1",
"body": "Is this schoolwork?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-16T16:49:37.200",
"Id": "475720",
"Score": "0",
"body": "@pacmaninbw Actually my code is taking a lot of time for doing this simple task, I just want to reduce the time to find out the array index."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-16T17:09:25.527",
"Id": "475723",
"Score": "0",
"body": "Try using pointers, a good optimizing compiler should do this for you, but if you aren't optimizing the using a pointer rather than an index should be faster."
}
] |
[
{
"body": "<h2>Indent the Code</h2>\n\n<p>Most computer code is indented, in some languages indentation is used to show the level of complexity of the code, in other languages the code won't work properly unless it is indented.</p>\n\n<h2>Declare the Variables as They are Needed</h2>\n\n<p>The integer variable <code>i</code> can be declared in the for loop and that will limit the scope to just the for loop.</p>\n\n<pre><code>for(int i = 0; i < 10; i++)\n{\n if(arr[i] > num)\n {\n position = i - 1;\n break;\n }\n}\n</code></pre>\n\n<h2>Horizontal Spacing</h2>\n\n<p>To make the code more readable, put spaces between the operators and the operands as shown above in the for loop example. Squashing all the code together makes it very difficult to understand what the code is actually doing.</p>\n\n<h2>Performance</h2>\n\n<p>First run the -O3 optimizer during compilation and linking. If the program were more complicated than it is then use a profiling tool such as <a href=\"https://en.wikipedia.org/wiki/Gprof\" rel=\"nofollow noreferrer\">gprof</a>.</p>\n\n<p>Linear searches are known to be a slower way to do things.</p>\n\n<p>I think the position reported is off by one, if I was using this code to do an insertion sort, I wouldn't subtract one from position. </p>\n\n<h2>Shorten the Code.</h2>\n\n<p>There are 2 shorter ways to subtract 1 from position.</p>\n\n<pre><code> --position;\n</code></pre>\n\n<p>and</p>\n\n<pre><code> position -= 1;\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-17T00:38:55.940",
"Id": "475769",
"Score": "3",
"body": "There is no need for the combined search. You can do binary search all the way through. See how [`std::lower_bound`](https://en.cppreference.com/w/cpp/algorithm/lower_bound) does it in [tag:STL]."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-16T17:05:17.067",
"Id": "242410",
"ParentId": "242405",
"Score": "3"
}
},
{
"body": "<ol>\n<li>Learn basics of binary search. Understand it in and out.</li>\n<li>Now look again at your problem statement. Maybe modifying the binary search algorithm to suit your needs may just work out.(hint :see how you can use key in different ways)</li>\n<li>Try to find out all your test cases and end points. For instance what will you get if num = 0.5?</li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-17T06:16:20.527",
"Id": "475781",
"Score": "3",
"body": "`Hope this helps` this may help to find a procedure for the problem \"quoted\" in the question. This does not qualify as a code review [here](https://codereview.stackexchange.com/help/how-to-answer): no insight about the *code* presented."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-17T17:24:54.430",
"Id": "475834",
"Score": "0",
"body": "I will keep this in mind. Thank You. I answered because the question asked it \"to do in some other way\" using binary search."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-17T02:38:57.133",
"Id": "242440",
"ParentId": "242405",
"Score": "-3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-16T15:55:42.960",
"Id": "242405",
"Score": "3",
"Tags": [
"c"
],
"Title": "How to find position (array index ) of a number in a given array?"
}
|
242405
|
<p>I am 12 days old into Python and web scraping and managed to write my first ever automation script. Please review my code and point out blunders If any. </p>
<p>What do I want to achieve?</p>
<p>I want to scrape all chapters of each Novel in each category and post it on a WordPress blog to test. Please point out anything that I missed, and is mandatory to run this script on the WordPress blog. </p>
<pre><code>from requests import get
from bs4 import BeautifulSoup
import re
r = get(site,
headers={"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko)"})
soup = BeautifulSoup(r.text, "lxml")
category = soup.findAll(class_="search-by-genre")
# Getting all categories
categories = []
for link in soup.findAll(href=re.compile(r'/category/\w+$')):
print("Category:", link.text)
category_link = link['href']
categories.append(category_link)
# Getting all Novel Headers
for category in categories:
r = get(category_link,
headers={"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko)"})
soup = BeautifulSoup(r.text, "lxml")
Novels_header = soup.findAll(class_="top-novel-header")
# Getting Novels' Title and Link
for Novel_names in Novels_header:
print("Novel:", Novel_names.text.strip())
Novel_link = Novel_names.find('a')['href']
# Getting Novel's Info
r = get(Novel_link, headers={"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko)"})
soup = BeautifulSoup(r.text, "lxml")
Novel_divs = soup.findAll(class_="chapter-chs")
# Novel Chapters
for articles in Novel_divs:
article_ch = articles.findAll("a")
for chapters in article_ch:
ch = chapters["href"]
# Getting article
r = get(ch, headers={"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko)"})
soup = BeautifulSoup(r.content, "lxml")
title = soup.find(class_="block-title")
print(title.text.strip())
full_article = soup.find("div", {"class": "desc"})
# remove ads inside the text:
for ads in full_article.select('center, small, a'):
ads.extract()
print(full_article.get_text(strip=True, separator='\n'))
</code></pre>
|
[] |
[
{
"body": "<h1>Naming</h1>\n\n<p>Variable names should be <code>snake_case</code>, and should represent what they are containing. I would also use <code>req</code> instead of <code>r</code>. The extra two characters aren't going to cause a heartache.</p>\n\n<h1>Constants</h1>\n\n<p>You have the same headers dict in four different places. I would instead define it once at the top of the file in <code>UPPER_CASE</code>, then just use that wherever you need headers. I would do the same for <code>site</code>.</p>\n\n<h1>List Comprehension</h1>\n\n<p>I would go about collecting categories in this way:</p>\n\n<pre><code>categories = [link['href'] for link in soup.findAll(href=re.compile(r'/category/\\w+$'))]\n</code></pre>\n\n<p>It's shorter and utilizes a quirk in the python language. Of course, if you want to print out each one, then add this just after:</p>\n\n<pre><code>for category in categories:\n print(category)\n</code></pre>\n\n<p>Also, it seems like you assign <code>category_link</code> to the last element in the list, so that can go just outside the list comprehension.</p>\n\n<h1>Save your assignments</h1>\n\n<p>Instead of assigning the result of <code>soup.find</code> to a variable, then using it in a loop, simply put that <code>soup.find</code> in the loop. Take a look:</p>\n\n<pre><code>for articles in soup.findAll(class_=\"chapter-chs\"):\n for chapters in articles.findAll(\"a\"):\n ....\n</code></pre>\n\n<p><hr>\nAs a result of the above changes, you code would look something like this:</p>\n\n<pre><code>from requests import get\nfrom bs4 import BeautifulSoup\nimport re\n\nHEADERS = {\"User-Agent\": \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko)\"}\nSITE = \"https://readlightnovel.org/\"\n\nreq = get(SITE, headers=HEADERS)\nsoup = BeautifulSoup(req.text, \"lxml\")\ncategory = soup.findAll(class_=\"search-by-genre\")\n\ncategories = [link['href'] for link in soup.findAll(href=re.compile(r'/category/\\w+$'))]\ncategory_link = categories[-1]\n\n# Getting all Novel Headers\nfor category in categories:\n req = get(category_link, headers=HEADERS)\n soup = BeautifulSoup(req.text, \"lxml\")\n novels_header = soup.findAll(class_=\"top-novel-header\")\n\n\n # Getting Novels' Title and Link\n for novel_names in novels_header:\n print(\"Novel:\", novel_names.text.strip())\n\n novel_link = novel_names.find('a')['href']\n\n # Getting Novel's Info\n req = get(novel_link, headers=HEADERS)\n soup = BeautifulSoup(req.text, \"lxml\")\n\n # Novel Chapters\n for articles in soup.findAll(class_=\"chapter-chs\"):\n for chapters in articles.findAll(\"a\"):\n ch = chapters[\"href\"]\n\n # Getting article\n req = get(ch, headers=HEADERS)\n soup = BeautifulSoup(req.content, \"lxml\")\n title = soup.find(class_=\"block-title\")\n print(title.text.strip())\n full_article = soup.find(\"div\", {\"class\": \"desc\"})\n\n # remove ads inside the text:\n for ads in full_article.select('center, small, a'):\n ads.extract()\n\n print(full_article.get_text(strip=True, separator='\\n'))\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-16T19:00:06.197",
"Id": "242419",
"ParentId": "242409",
"Score": "4"
}
},
{
"body": "<p>I think you can even get rid of the regular expressions. I prefer to use the BS4 functions.</p>\n\n<p>Instead of:</p>\n\n<pre><code>categories = [link['href'] for link in soup.findAll(href=re.compile(r'/category/\\w+$'))]\n</code></pre>\n\n<p>This statement is equivalent using a <strong>CSS selector</strong>:</p>\n\n<pre><code>categories = [link['href'] for link in soup.select(\"a[href*=\\/category\\/]\")]\n</code></pre>\n\n<p>That means: fetch all the <code>a href</code> tags that contain text <code>/category/</code> (escaped).</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-16T22:09:05.240",
"Id": "242425",
"ParentId": "242409",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "242419",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-16T16:54:41.433",
"Id": "242409",
"Score": "5",
"Tags": [
"python",
"web-scraping",
"beautifulsoup"
],
"Title": "How can I make this better? Python Web scraping"
}
|
242409
|
<p>The basic idea of the code is that agents come into the world, they age and then die. I want to keep track of who is dead and who is alive. Eventually, they will do more things but I think there should be a lot of things I am not doing best practice on. I assume I'm doing something wrong with "Global" as well.</p>
<pre><code># Classes
class Agent(object):
def __init__(self, identification, productivity, wealth, preferences, age, health, alive, sex):
self.identification = identification
self.productivity = productivity
self.wealth = wealth
self.preferences = preferences
self.age = age
self.health = health
self.alive = alive
self.sex = sex
def description(self):
print("My id is", self.identification)
print("My age is", self.age)
def Create_agents():
global id
alive.append(Agent(id,100,20,"blue",30,0,True,True ))
id += 1
# functions
def Initialize():
for x in range(3):
Create_agents()
def Death():
temp = alive.copy()
for agent in temp:
if agent.age>30:
agent.alive = False
print("Death of", agent.identification)
dead.append(agent)
alive.remove(agent)
def Time_skip():
print("%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%SKIPPING TIME%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%")
global year
year += 1
print("The new year is", year)
for agent in alive:
agent.age +=1
Create_agents()
Death()
# Values
alive = []
dead = []
id = 0
year = 0
Initialize()
# Testing
for agent in alive:
agent.description()
Time_skip()
for agent in alive:
agent.description()
</code></pre>
<p>The output is: </p>
<pre><code>My id is 0
My age is 30
My id is 1
My age is 30
My id is 2
My age is 30
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%SKIPPING TIME%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
The new year is 1
Death of 0
Death of 1
Death of 2
My id is 3
My age is 30
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-16T17:57:14.670",
"Id": "475732",
"Score": "1",
"body": "Does this code work as expected?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-16T18:01:15.653",
"Id": "475733",
"Score": "0",
"body": "@pacmaninbw Yes, note the `temp = alive.copy()` change."
}
] |
[
{
"body": "<ul>\n<li><p>Python has a standardized style guide called <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"noreferrer\">PEP 8</a>. There is also <a href=\"https://google.github.io/styleguide/pyguide.html\" rel=\"noreferrer\">Google's Python style guide</a> which AFAIK is very similar to PEP 8.</p>\n\n<p>Any code that goes largely against PEP 8 normally doesn't look Pythonic.</p>\n\n<ul>\n<li><p>Python has a naming scheme to allow developers to know the variables type by it's name only.</p>\n\n<ul>\n<li>Classes are in <code>CamelCase</code>,</li>\n<li>Functions, methods and variables are in <code>snake_case</code>, and</li>\n<li>Constants are in <code>UPPER_SNAKE_CASE</code>.</li>\n</ul></li>\n<li><p>There should be a single space after commas.</p></li>\n<li>Lines should be limited to 79 characters.</li>\n<li>There should be one space between all methods, and two between top level classes and functions.</li>\n</ul>\n\n<p>Overall your code adheres to these standards pretty well. Good job.</p></li>\n<li><p><code>class Agent(object)</code> is a relic from Python 2. In Python 2 classes didn't inherit from <code>object</code> by default. These are now called old style classes. However in Python 3 everything inherits from <code>object</code> by default - making all classes in Python 3 new style classes.</p></li>\n<li><p>Your code would benefit from another class.</p>\n\n<p>I'm reluctant to suggest this as the code has an over-reliance on global variables. In the future you should try to solve the problem without globals and then see if it can be made cleaner by using a class.</p>\n\n<p>And so we can make a <code>Simulation</code> class. I would include all the global functions you have in it except <code>initialize</code>.</p></li>\n<li>I would use an <code>if __name__ == \"__main__\":</code> guard to prevent your code from running if it's been imported accidentally.</li>\n</ul>\n\n<p>This gets the following. There's some more changes that can be made, but the base of your code is good.</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>class Agent:\n def __init__(self, identification, productivity, wealth, preferences, age, health, alive, sex):\n self.identification = identification\n self.productivity = productivity\n self.wealth = wealth\n self.preferences = preferences\n self.age = age\n self.health = health\n self.alive = alive\n self.sex = sex\n\n def description(self):\n print(\"My id is\", self.identification)\n print(\"My age is\", self.age)\n\n\nclass Simulation:\n def __init__(self):\n self.alive = []\n self.dead = []\n self._id = 0\n self.year = 0\n\n def create_agent(self):\n self.alive.append(Agent(self._id, 100, 20, \"blue\", 30, 0, True, True))\n self._id += 1\n\n def deaths(self):\n for agent in self.alive.copy():\n if agent.age > 30:\n agent.alive = False\n print(\"Death of\", agent.identification)\n self.dead.append(agent)\n self.alive.remove(agent)\n\n def time_skip(self):\n print(\"%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%SKIPPING TIME%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\")\n self.year += 1\n print(\"The new year is\", self.year)\n for agent in self.alive:\n agent.age += 1\n self.create_agent()\n self.deaths()\n\nif __name__ == '__main__':\n simulation = Simulation()\n for _ in range(3):\n simulation.create_agent()\n\n # Testing\n for agent in simulation.alive: \n agent.description()\n\n simulation.time_skip()\n\n for agent in simulation.alive: \n agent.description()\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-16T18:40:34.883",
"Id": "475738",
"Score": "0",
"body": "Thanks, looks good. 1)What is the advantage of making the lists inside the class simulation?\nAnd what is the function of \" __name__ == '__main__'\"(i'm aware of what you wrote, i'm just hoping for more detail)?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-16T18:46:48.767",
"Id": "475739",
"Score": "0",
"body": "Actually, when i run it, there is an error:\nAttributeError: 'Simulation' object has no attribute 'id'"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-16T18:50:49.873",
"Id": "475740",
"Score": "0",
"body": "@Dio 1) The benefit is that you're not relying on globals. It's hard to explain with the code that you have here as there isn't really a problem that the class solves. However globals lead to poor design choices. By wrapping it in a class you're preventing these bad choices prematurely. I understand it's not much of an explanation. You'll likely only understand it once you've been bitten by it once. 2) If the file is called `foo.py` you can run `import foo` from another file, with the `if` the code doesn't run. Without the if the code does."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-16T18:53:25.910",
"Id": "475741",
"Score": "0",
"body": "@Dio I made a couple of mistakes when converting to a class. They're now fixed."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-16T18:57:54.790",
"Id": "475742",
"Score": "0",
"body": "Great! thanks a bunch, @Peilonrayz you've been very helpful :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-21T14:36:18.113",
"Id": "493820",
"Score": "0",
"body": "An alternative to yet another class would be class variables keeping track of the last created ID as well as dead and alive agents."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-21T15:07:53.250",
"Id": "493823",
"Score": "0",
"body": "@Graipher Your solution looks clean. But I don't think it's much better than just having the scope bound to the global scope. If another simulation is needed you'll need to subclass `Agent` and assign new `alive` and `dead` sets. Whilst it's hard to know if the OP will actually care about this problem I'd always prefer to be safe and have a clean option for multiple simulations."
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-16T18:29:32.727",
"Id": "242415",
"ParentId": "242411",
"Score": "6"
}
},
{
"body": "<p>Instead of using either global variables or another class to manage the collections of agents, you could use class variables that do that for you. Consider this (reduced) example of an <code>Agent</code> class:</p>\n<pre><code>class Agent:\n id_ = 0\n alive = set()\n dead = set()\n\n def __init__(self):\n self.id = Agent.id_\n Agent.id_ += 1\n self.alive = True\n Agent.alive.add(self)\n\n def die(self):\n self.alive = False\n Agent.alive.remove(self)\n Agent.dead.add(self)\n\n def __repr__(self):\n return f"Agent(id={self.id})"\n</code></pre>\n<p>which you can use like this:</p>\n<pre><code>agents = [Agent() for _ in range(3)]\nprint(Agent.alive)\n# {Agent(id=1), Agent(id=0), Agent(id=2)}\nagents[1].die()\nprint(Agent.alive)\n# {Agent(id=0), Agent(id=2)}\nprint(Agent.dead)\n# {Agent(id=1)}\n</code></pre>\n<p>Apart from that I agree with all the other points in the <a href=\"https://codereview.stackexchange.com/a/242415/98493\">excellent answer</a> by <a href=\"https://codereview.stackexchange.com/users/42401/peilonrayz\">@Peilonrayz</a>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-21T14:49:04.453",
"Id": "250961",
"ParentId": "242411",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "242415",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-16T17:08:32.897",
"Id": "242411",
"Score": "6",
"Tags": [
"python",
"python-3.x",
"object-oriented"
],
"Title": "Life and death model in python"
}
|
242411
|
<p>I haven't found a good code example for a reactive retry operator with a retry strategy that was good enough for my needs. So I tried to make my own. It seems to work in my tests but I would really appreciate some feedback. (C# 8.0)</p>
<pre><code>using System;
using System.Linq;
using System.Reactive;
using System.Reactive.Concurrency;
using System.Reactive.Linq;
namespace Fncy.Helpers
{
public static class ObeservableHelpers
{
public delegate TimeSpan? NextRetryDelay(int previousRetryCount, TimeSpan elapsedTime, Exception retryReason);
public static IObservable<TSource> RetryAfterDelay<TSource>(
this IObservable<TSource> source,
NextRetryDelay retryDelay,
IScheduler scheduler = null)
{
if (retryDelay == null) throw new ArgumentNullException(nameof(retryDelay));
scheduler ??= Scheduler.Default;
return source.RetryWhen(errors =>
{
var retryStart = scheduler.Now;
int previousRetryCount = 0;
return errors.SelectMany(ex =>
{
var delay = retryDelay(previousRetryCount++, scheduler.Now - retryStart, ex);
return delay == null
? Observable.Throw<Unit>(ex)
: Observable.Return(Unit.Default).Delay(delay.Value, scheduler);
});
});
}
}
}
</code></pre>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-16T18:13:36.180",
"Id": "242413",
"Score": "2",
"Tags": [
"c#",
"system.reactive"
],
"Title": "Reactive .NET retry policy"
}
|
242413
|
<p>So this is a pretty simple code, I think it was?</p>
<p>It asks for the user's birth day and month, and gives it back with the day a discount reminder email will be sent (the day before their birthday)</p>
<p>Now I tried to optimize as much as I could, possible wrong inputs and if the user's birthday is the first of a month</p>
<p>Even though I'm still pretty new to coding, I still want you to criticize my code as much as I could, I would like to improve as much as I can</p>
<pre><code>using System.Text.RegularExpressions;
using System.Linq;
namespace Exercice14
{
class Program
{
static void Main(string[] _)
{
// declaring some variables
int birthDay;
int reminderDay;
string suffix = "th";
string reminderSuffix = "th";
string birthDayT;
string birthMonth;
string reminderMonth;
string[] months = {"January", "February", "March", "April", "May", "June", "July", "August", "September",
"October", "November", "December" };
bool exceptionFirst = false;
// prompts for birth month and capitalize first letter
Console.WriteLine("Hello User!");
Console.Write("Please enter your birth month in letters: ");
birthMonth = Console.ReadLine();
birthMonth = char.ToUpper(birthMonth[0]) + birthMonth.Substring(1);
// check if birth month contains only letters
while(Regex.IsMatch(birthMonth, @"^[a-zA-Z]+$") == false)
{
Console.WriteLine("Birth month should only contain letters!");
Console.Write("Please enter your birth month in letters: ");
birthMonth = Console.ReadLine();
birthMonth = char.ToUpper(birthMonth[0]) + birthMonth.Substring(1);
}
// check if month is right
while (months.Contains(birthMonth) == false)
{
Console.WriteLine("Invalid month?! Please enter a valid english month");
Console.Write("Please enter your birth month: ");
birthMonth = Console.ReadLine();
birthMonth = char.ToUpper(birthMonth[0]) + birthMonth.Substring(1);
}
// prompts for birth day
Console.Write("Please enter your birth day in numbers: ");
birthDayT = Console.ReadLine();
// check for valid day
while (int.TryParse(birthDayT, out int _) == false)
{
Console.WriteLine("Invalid argument! Please enter day in numerals");
Console.Write("Please enter your birth day in numbers: ");
birthDayT = Console.ReadLine();
}
// check for valid day number
while (int.Parse(birthDayT) < 1 || int.Parse(birthDayT) > 31)
{
Console.WriteLine("Invalid date! Please enter a day between 1 and 31");
Console.Write("Please enter birth day in numbers: ");
birthDayT = Console.ReadLine();
}
// assign birth day to variable once tested
birthDay = int.Parse(birthDayT);
// set reminder day and month
reminderDay = birthDay - 1;
reminderMonth = birthMonth;
// check which suffix to use for days AND calculate reminder day and month if exception
if (birthDay == 1) //exception
{
exceptionFirst = true;
suffix = "st";
reminderMonth = months[Array.IndexOf(months, birthMonth) - 1];
}
if (birthDay == 2)
{
suffix = "nd";
reminderSuffix = "st";
reminderDay = 1;
}
if (birthDay == 3)
{
suffix = "th";
reminderSuffix = "nd";
}
if (birthDay > 3)
{
suffix = "th";
reminderSuffix = "th";
}
// print values
Console.WriteLine();
Console.WriteLine("Yer birthday is on the " + birthDay + suffix + " of " + birthMonth );
if (exceptionFirst == true)
{
Console.WriteLine("A reminder email for your birthday discount " +
"\nwill be sent on the last day of " + reminderMonth);
}
else
{
Console.WriteLine("A reminder email for your birthday discount " +
"\nwill be sent on the " + reminderDay + reminderSuffix + " of " + reminderMonth);
}
}
}
}
</code></pre>
|
[] |
[
{
"body": "<p>The code you wrote is quite large for a beginner, and its overall structure is easy to read and understand. That's quite good.</p>\n\n<p>Of course there are lots of things you can improve. One thing that comes to mind is to split the code into several separate methods. A good candidate is the part where you convert a day and month into a string. Right now almost half of the code is concerned with keeping track of <code>st, nd, rd, th</code>. That is distracting. You could define a method like this:</p>\n\n<pre class=\"lang-cs prettyprint-override\"><code>namespace Exercice14\n{\n class Program\n {\n /// The month goes from 1 to 12, the dayOfMonth goes from 1 to 31.\n /// There is no check for invalid numbers.\n string DateToString(int month, int dayOfMonth)\n {\n string ordinal = \"th\";\n if (dayOfMonth == 1)\n ordinal = \"st\";\n else if (dayOfMonth == 2)\n ordinal = \"nd\";\n\n return \"the \" + dayOfMonth + ordinal + \" of \" + MonthNames[month - 1];\n }\n }\n}\n</code></pre>\n\n<p>This way, you don't need to handle these ordinal suffixes in the rest of the code. This means you cannot accidentally mix up the ordinal of the birthday and the ordinal of the reminder day, and this already makes your code more reliable.</p>\n\n<p>Another good thing is that you can write automatic tests for this little method.</p>\n\n<pre class=\"lang-cs prettyprint-override\"><code>namespace Exercice14\n{\n class Program\n {\n void TestDateToString(string expected, int month, int dayOfMonth)\n {\n string actual = DateToString(month, dayOfMonth);\n if (actual != expected)\n {\n throw new InvalidOperationException(\n \"Expected '\" + expected + \"'\"\n + \" for month \" + month + \" and day \" + dayOfMonth + \",\"\n + \" got '\" + actual + \"'.\");\n }\n }\n\n void TestDateToString()\n {\n TestDateToString(\"1st of January\", 1, 1);\n TestDateToString(\"22nd of July\", 7, 22);\n TestDateToString(\"31st of December\", 12, 31);\n }\n }\n}\n</code></pre>\n\n<p>Having all these ingredients, you can now simply add <code>TestDateToString();</code> at the beginning of the <code>Main</code> method, just before the <code>// declaring</code> comment. This way, your program will only run if the tests run successfully.</p>\n\n<p>This is only the first step to writing reliable code. The next step is to split your code into the main code and the testing code, and use a unit test framework such as NUnit to run your tests.</p>\n\n<p>Whenever you are doing date calculations in your own code, you are doing something wrong. Date calculations are incredibly tricky, regarding time zones, daylight saving time, leap years, leap seconds, and so on. Therefore you should make use of the .NET standard library, which already defines a type called <a href=\"https://docs.microsoft.com/en-us/dotnet/api/system.datetime?view=netcore-3.1\" rel=\"nofollow noreferrer\">DateTime</a>. You need to do 3 things:</p>\n\n<ol>\n<li>construct a DateTime from its parts (month, day of month)</li>\n<li>calculate the day before that date (using <a href=\"https://docs.microsoft.com/en-us/dotnet/api/system.datetime.adddays?view=netcore-3.1#System_DateTime_AddDays_System_Double_\" rel=\"nofollow noreferrer\">DateTime.AddDays(-1)</a>)</li>\n<li>format this date back into a string (possibly using <a href=\"https://stackoverflow.com/a/9130114/225757\">this code</a>)</li>\n</ol>\n\n<p>To cut the long story short: Your code works for a few cases but crashes for some others or even prints wrong results. Writing the automatic tests and thinking of possible interesting test cases will help you find and fix these bugs.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-16T21:32:22.823",
"Id": "242422",
"ParentId": "242421",
"Score": "1"
}
},
{
"body": "<p>Notes : </p>\n\n<ul>\n<li>Months array</li>\n<li>Regex</li>\n<li>multiple loops and redundant validations. </li>\n<li>Direct parsing without validations. </li>\n</ul>\n\n<p>As Roland mentioned, you don't need to redefine what is already existed, nor handling the conversion of dates manually. You need to focus on using what <code>.NET</code> already has, if you don't know, google before you start coding. This way, you will avoid making major changes. </p>\n\n<p>You take two inputs from the user, then you only need 2 validations process. While in your code you're doubling that!, which is unnecessary if you implement it correctly.</p>\n\n<p>Let's start with the month validation, user can input a short name month, or full name, or even a number. As you're dealing with string, you need to take the inputs possibilities, even if you tried to restrict the input, there is still a chance of an invalid input with is the unknown case! So, you will focus on covering known cases, which you already mostly did. </p>\n\n<p>The repeated issue that you are unaware of is that you're assigning and processing then validating the user input, so you need to reverse that. First validate, then process based on that validation. </p>\n\n<p>Here is an example of your process of validation : </p>\n\n<pre><code>// prompts for birth month and capitalize first letter\nConsole.WriteLine(\"Hello User!\");\nConsole.Write(\"Please enter your birth month in letters: \");\nbirthMonth = Console.ReadLine();\nbirthMonth = char.ToUpper(birthMonth[0]) + birthMonth.Substring(1);\n\n\n// check if birth month contains only letters\nwhile(Regex.IsMatch(birthMonth, @\"^[a-zA-Z]+$\") == false)\n{\n Console.WriteLine(\"Birth month should only contain letters!\");\n Console.Write(\"Please enter your birth month in letters: \");\n birthMonth = Console.ReadLine();\n birthMonth = char.ToUpper(birthMonth[0]) + birthMonth.Substring(1);\n}\n</code></pre>\n\n<ol>\n<li>First you asked a user for an input</li>\n<li>then you directly get the first char assuming it's a valid string</li>\n<li>then you validate it with regex. </li>\n<li>if invalid, you do the same steps 1 to 3 until it's valid letter. </li>\n</ol>\n\n<p>what happens if <code>birthMonth</code> is empty or null? it'll throw <code>IndexOutOfRangeException</code> because of <code>birthMonth[0]</code> and if the <code>birthMonth</code> is <code>NULL</code> then it'll also throw a null exception.! these are basic validations which need to be validated before processing. </p>\n\n<p>you've applied the same process to the reset. you need to validate the string first using <code>string.IsNullOrEmpty</code> or <code>string.IsNullOrWhiteSpace</code> or if you prefer to do it manually you can do this </p>\n\n<pre><code>if(birthMonth != null && birthMonth.Length > 0)\n</code></pre>\n\n<p>for the month part, you don't need the array, you need to use <code>DateTime</code> instead. You can use something like this : </p>\n\n<pre><code>// handle the month conversion\n// acceptable inputs : short name, full name, month number \nprivate static bool TryGetMonth(string month, out DateTime date)\n{\n date = new DateTime();\n\n if(string.IsNullOrEmpty(month))\n {\n return false; \n }\n\n // default datetime format \n var format = \"dd MMMM yyyy HH:mm:ss tt\";\n\n // if user enters a repersental month number then adjust the format\n if(int.TryParse(month, out int monthInt))\n {\n format = \"dd M yyyy HH:mm:ss tt\";\n } \n else if(month.Length <= 3 && !month.Equals(\"May\", StringComparison.OrdinalIgnoreCase))\n {\n format = \"dd MMM yyyy HH:mm:ss tt\";\n }\n\n return DateTime.TryParseExact($\"01 {month} 2020 00:00:00 AM\", format, CultureInfo.InvariantCulture, DateTimeStyles.None, out date);\n}\n</code></pre>\n\n<p>the <code>DateTime.TryParseExact</code> will handle the conversion, and would return a valid date if the input meets the parsing requirements. Then, from the dateTime, you can have access to its values like month name, number ..etc.</p>\n\n<p>Also, when parsing integers, use <code>int.TryParse</code> to check the validity of the integer first, then extract the parsed integer. This would avoid throwing undesired exceptions. </p>\n\n<p>here is an untested revision of your code using the <code>TryGetMonth</code> method above along with using <code>DateTime</code> to demonstrate my points: </p>\n\n<pre><code>// prompts for birth month and capitalize first letter\nConsole.WriteLine(\"Hello User!\");\nConsole.Write(\"Please enter your birth month in letters: \");\n\nwhile(TryGetMonth(Console.ReadLine(), out DateTime monthDate ) == false)\n{\n Console.WriteLine(\"invalid month\");\n Console.WriteLine(\"Please enter your birth month name (short or full name) or number\");\n}\n\n// prompts for birth day\nConsole.Write(\"Please enter your birth day in numbers: \");\n\nwhile(int.TryParse(Console.ReadLine(), out int birthDay) && (birthDay > 0 && birthDay <= 31))\n{\n Console.WriteLine(\"Invalid argument! Please enter day between 1-31 in numerals\");\n Console.WriteLine(\"Please enter your birth day in numbers: \");\n}\n\n\nDateTime birthDate = new DateTime(DateTime.Now.Year, monthDate.Month, birthDay);\nDateTime reminderDate = birthDate.AddDays(-1);\n\nstring suffix;\nstring reminderSuffix;\nstring msg; \n\nswitch(birthDate.Day)\n{\n case 1:\n suffix = \"st\";\n reminderDate = reminderDate.AddMonths(-1);\n break;\n case 2:\n suffix = \"nd\";\n reminderSuffix = \"st\";\n break;\n case 3:\n suffix = \"rd\";\n reminderSuffix = \"nd\";\n break;\n case 4:\n suffix = \"th\";\n reminderSuffix = \"rd\";\n break;\n default: \n suffix = \"th\";\n reminderSuffix = \"th\";\n}\n\nif(birthDate.Day == 1) {\n msg = $\"A reminder email for your birthday discount \\nwill be sent on the last day of {reminderDate.ToString(\"MMMM\")}\";\n} else {\n msg = $\"A reminder email for your birthday discount \\nwill be sent on the {reminderDate.Day}{reminderSuffix} of {reminderDate.ToString(\"MMMM\")}\";\n}\n\n// print values\nConsole.WriteLine();\nConsole.WriteLine($\"Your birthday is on the {birthDate.Day}{suffix} of {birthDate.ToString(\"MMMM\")}\" );\nConsole.WriteLine(msg);\n\n// reminderDate.ToString(\"MMMM\") would return month name\n// \"MMMM\" for full name and \"MMM\" for short name (e.g. June and Jun)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-17T22:39:55.597",
"Id": "475845",
"Score": "0",
"body": "Thanks a lot for your feedback! I'm taking notes and will test all of this on my own! I'm learning a lot thanks to you!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-17T00:05:26.407",
"Id": "242430",
"ParentId": "242421",
"Score": "4"
}
},
{
"body": "<p>Your Main method is too long, to be able to even see what it does I had to read the whole method.</p>\n\n<p>You did explain what it does:</p>\n\n<blockquote>\n <p>It asks for the user's birth day and month, and gives it back with the day a discount reminder email will be sent (the day before their birthday)</p>\n</blockquote>\n\n<p>However by using classes and sub-method your Main-method could be telling you exactly this.</p>\n\n<pre><code>class Program\n{\n class MyDate {\n // ...\n }\n\n static void Main(string[] _)\n {\n MyDate birthday = ask_for_birthday();\n MyDate email_day = day_before(birthday);\n output_email_message(email_day);\n }\n}\n</code></pre>\n\n<p>If you structure your code like that it will be much easier to critique and analyse further. \nIf you use the already existing Date class of C# the day_before() method will probably pretty simple to implement even.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-17T10:19:21.200",
"Id": "242451",
"ParentId": "242421",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "242430",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-16T20:02:44.587",
"Id": "242421",
"Score": "9",
"Tags": [
"c#",
"beginner",
"strings",
"array"
],
"Title": "Roast my C# birthday code"
}
|
242421
|
<p>In order to improve my C++ skills I started doing some toy projects, one of them being my own std::string_view implementation. This was my first time implementing a std library. I'm pasting the code inline, but you can check it out at <a href="https://github.com/david89/cpp-library/tree/master/types" rel="nofollow noreferrer">https://github.com/david89/cpp-library/tree/master/types</a> if you want (there are some tests there as well).</p>
<p>Few things to take into consideration:</p>
<ul>
<li>Kept track of includes manually, maybe there are some unnecessary includes or missing ones. Next time I'll integrate iwyu into my workflow.</li>
<li>The interface is based on <a href="https://en.cppreference.com/w/cpp/string/basic_string_view" rel="nofollow noreferrer">https://en.cppreference.com/w/cpp/string/basic_string_view</a>.</li>
<li>I tried to keep it C++11 compatible. Coding this in C++17 felt weird as the library is already there.</li>
</ul>
<p>Any feedback will be appreciated, however I have some specific areas I would like to get feedback on:</p>
<ul>
<li>Any suggestions on adding constexpr support for all remaining operations? For example, std::reverse_iterator is not constexpr in C++11. I guess I could code my own version, but not sure if there is something easier I can do.</li>
<li>There are some non-member friend functions which bothers me a little bit. My understanding is that we need them to be non-member because of comparisons like const char* vs string_view, where only the right hand side can be implicitly casted into a string_view. However, if I declare them outside the class as regular non-friend functions, gtest complains about it. Not very sure why they have to be friend functions if they don't rely on protected/private implementation aspects of the class.</li>
<li>I think the answer to this is that I should write my own benchmarks and measure it myself, but any idea or intuition on how efficient char_traits operations are? For example, I'm relying on std::char_traits::compare, but maybe using memcmp may be better here.</li>
</ul>
<pre><code>#ifndef LIBRARY_STRING_VIEW
#define LIBRARY_STRING_VIEW
#include <algorithm>
#include <cassert>
#include <cstddef>
#include <cstring>
#include <ios>
#include <iostream>
#include <iterator>
#include <ostream>
#include <stdexcept>
#include <string>
namespace david {
// NOTE: using https://en.cppreference.com/w/cpp/string/basic_string_view as a
// guide.
template <class CharT, class Traits = std::char_traits<CharT>>
class basic_string_view {
public:
// Types.
using traits_type = Traits;
using value_type = CharT;
using pointer = CharT*;
using const_pointer = const CharT*;
using reference = CharT&;
using const_reference = const CharT&;
using const_iterator = const CharT*;
using iterator = const_iterator;
using const_reverse_iterator = std::reverse_iterator<const_iterator>;
using reverse_iterator = const_reverse_iterator;
using size_type = size_t;
using difference_type = ptrdiff_t;
static constexpr size_type npos = size_type(-1);
// Construction.
constexpr basic_string_view() noexcept : data_(nullptr), len_(0) {}
constexpr basic_string_view(const basic_string_view& other) noexcept =
default;
constexpr basic_string_view(const_pointer str)
: data_(str), len_(internal_strlen(str)) {}
constexpr basic_string_view(const_pointer str, size_type len)
: data_(str), len_(len) {}
basic_string_view(const std::string& str)
: data_(str.data()), len_(str.size()) {}
// Assignment.
basic_string_view& operator=(const basic_string_view&) noexcept = default;
// Iterator support.
constexpr const_iterator begin() const noexcept { return data_; }
constexpr const_iterator cbegin() const noexcept { return begin(); }
constexpr const_iterator end() const noexcept { return data_ + len_; }
constexpr const_iterator cend() const noexcept { return end(); }
// TODO: these cannot be marked as constexpr because std::reverse_iterator is
// not constexpr.
const_reverse_iterator rbegin() const noexcept {
return const_reverse_iterator(end());
}
const_reverse_iterator crbegin() const noexcept { return rbegin(); }
const_reverse_iterator rend() const noexcept {
return const_reverse_iterator(begin());
}
const_reverse_iterator crend() const noexcept { return rend(); }
// Element access.
constexpr const_reference operator[](size_type pos) const {
return data_[pos];
}
const_reference at(size_type pos) const {
if (pos > len_) {
throw std::out_of_range("Out of range");
}
return this->operator[](pos);
}
constexpr const_reference front() const { return data_[0]; }
constexpr const_reference back() const { return data_[len_ - 1]; }
constexpr const_pointer data() const noexcept { return data_; }
// Capacity.
constexpr size_type size() const noexcept { return len_; }
constexpr size_type length() const noexcept { return size(); }
constexpr size_type max_size() const noexcept { return kMaxSize; }
constexpr bool empty() const noexcept { return len_ == 0; }
// Modifiers.
void remove_prefix(size_type n) {
data_ = data_ + n;
len_ -= n;
}
void remove_suffix(size_type n) { len_ -= n; }
void swap(basic_string_view& s) noexcept {
basic_string_view other = *this;
*this = s;
s = other;
}
// Operations.
// Copies the substring [pos, pos + rcount) to the character string pointed to
// by dest, where rcount is the smaller of count and size() - pos.
size_type copy(pointer dest, size_type count, size_type pos = 0) const {
if (pos > len_) {
throw std::out_of_range("Out of range");
}
const size_type rcount = std::min(count, len_ - pos);
traits_type::copy(dest, data_ + pos, rcount);
return rcount;
}
// Returns a view of the substring [pos, pos + rcount), where rcount is the
// smaller of count and size() - pos.
basic_string_view substr(size_type pos = 0, size_type count = npos) const {
if (pos > len_) {
throw std::out_of_range("Out of range");
}
const size_type rcount = std::min(count, len_ - pos);
if (rcount > 0) {
return basic_string_view(data_ + pos, rcount);
}
return basic_string_view();
}
// Compares two character sequences.
int compare(basic_string_view s) const noexcept {
const size_t rlen = std::min(len_, s.len_);
const int comparison = traits_type::compare(data_, s.data_, rlen);
if (comparison != 0) return comparison;
if (len_ == s.len_) return 0;
return len_ < s.len_ ? -1 : 1;
}
// Compare substring(pos1, count1) with s.
int compare(size_type pos1, size_type count1, basic_string_view s) const {
return substr(pos1, count1).compare(s);
}
// Compare substring(pos1, count1) with s.substring(pos2, count2).
int compare(size_type pos1, size_type count1, basic_string_view s,
size_type pos2, size_type count2) const {
return substr(pos1, count1).compare(s.substr(pos2, count2));
}
int compare(const_pointer s) const { return compare(basic_string_view(s)); }
int compare(size_type pos1, size_type count1, const_pointer s) const {
return substr(pos1, count1).compare(basic_string_view(s));
}
int compare(size_type pos1, size_type count1, const_pointer s,
size_type count2) const {
return substr(pos1, count1).compare(basic_string_view(s, count2));
}
bool starts_with(basic_string_view s) const noexcept {
return len_ >= s.len_ && substr(0, s.len_) == s;
}
bool starts_with(value_type c) const noexcept {
return !empty() && traits_type::eq(front(), c);
}
bool starts_with(const_pointer s) const {
return starts_with(basic_string_view<CharT, Traits>(s));
}
bool ends_with(basic_string_view s) const noexcept {
return len_ >= s.len_ && substr(len_ - s.len_, npos) == s;
}
bool ends_with(value_type c) const noexcept {
return !empty() && traits_type::eq(back(), c);
}
bool ends_with(const_pointer s) const {
return ends_with(basic_string_view<CharT, Traits>(s));
}
size_type find(basic_string_view s, size_type pos = 0) const noexcept {
if (empty() && s.empty() && pos == 0) {
return 0;
}
if (pos > len_ || s.len_ > (len_ - pos)) {
return npos;
}
while (pos + s.len_ <= len_) {
if (traits_type::compare(data_ + pos, s.data_, s.len_) == 0) {
return pos;
}
pos++;
}
return npos;
}
size_type find(value_type c, size_type pos = 0) const noexcept {
return find(basic_string_view(&c, 1), pos);
}
size_type find(const_pointer s, size_type pos, size_type n) const {
return find(basic_string_view(s, n), pos);
}
size_type find(const_pointer s, size_type pos = 0) const {
return find(basic_string_view(s), pos);
}
size_type rfind(basic_string_view s, size_type pos = npos) const noexcept {
if (s.empty()) {
return std::min(pos, len_);
}
if (s.len_ > len_) {
return npos;
}
pos = std::min(pos, len_ - s.len_);
while (pos != npos) {
if (traits_type::compare(data_ + pos, s.data_, s.len_) == 0) {
return pos;
}
pos--;
}
return npos;
}
size_type rfind(value_type c, size_type pos = npos) const noexcept {
return rfind(basic_string_view(&c, 1), pos);
}
size_type rfind(const_pointer s, size_type pos, size_type n) const {
return rfind(basic_string_view(s, n), pos);
}
size_type rfind(const_pointer s, size_type pos = npos) const {
return rfind(basic_string_view(s), pos);
}
size_type find_first_of(basic_string_view s,
size_type pos = 0) const noexcept {
while (pos < len_) {
if (traits_type::find(s.data_, s.len_, data_[pos]) != nullptr) {
return pos;
}
pos++;
}
return npos;
}
size_type find_first_of(value_type c, size_type pos = 0) const noexcept {
return find_first_of(basic_string_view(&c, 1), pos);
}
size_type find_first_of(const_pointer s, size_type pos, size_type n) const {
return find_first_of(basic_string_view(s, n), pos);
}
size_type find_first_of(const_pointer s, size_type pos = 0) const {
return find_first_of(basic_string_view(s), pos);
}
size_type find_last_of(basic_string_view s,
size_type pos = npos) const noexcept {
if (empty()) {
return npos;
}
pos = std::min(pos, len_ - 1);
while (pos != npos) {
if (traits_type::find(s.data_, s.len_, data_[pos]) != nullptr) {
return pos;
}
pos--;
}
return npos;
}
size_type find_last_of(value_type c, size_type pos = npos) const noexcept {
return find_last_of(basic_string_view(&c, 1), pos);
}
size_type find_last_of(const_pointer s, size_type pos, size_type n) const {
return find_last_of(basic_string_view(s, n), pos);
}
size_type find_last_of(const_pointer s, size_type pos = npos) const {
return find_last_of(basic_string_view(s), pos);
}
size_type find_first_not_of(basic_string_view s,
size_type pos = 0) const noexcept {
while (pos < len_) {
if (traits_type::find(s.data_, s.len_, data_[pos]) == nullptr) {
return pos;
}
pos++;
}
return npos;
}
size_type find_first_not_of(value_type c, size_type pos = 0) const noexcept {
return find_first_not_of(basic_string_view(&c, 1), pos);
}
size_type find_first_not_of(const_pointer s, size_type pos,
size_type n) const {
return find_first_not_of(basic_string_view(s, n), pos);
}
size_type find_first_not_of(const_pointer s, size_type pos = 0) const {
return find_first_not_of(basic_string_view(s), pos);
}
size_type find_last_not_of(basic_string_view s,
size_type pos = npos) const noexcept {
if (empty()) {
return npos;
}
pos = std::min(pos, len_ - 1);
while (pos != npos) {
if (traits_type::find(s.data_, s.len_, data_[pos]) == nullptr) {
return pos;
}
pos--;
}
return npos;
}
size_type find_last_not_of(value_type c,
size_type pos = npos) const noexcept {
return find_last_not_of(basic_string_view(&c, 1), pos);
}
size_type find_last_not_of(const_pointer s, size_type pos,
size_type n) const {
return find_last_not_of(basic_string_view(s, n), pos);
}
size_type find_last_not_of(const_pointer s, size_type pos = npos) const {
return find_last_not_of(basic_string_view(s), pos);
}
// We need these to be friend non-member functions because we want to compare
// operands with different types (for example string_view vs const char*).
// https://stackoverflow.com/a/3850120
friend inline bool operator==(basic_string_view a,
basic_string_view b) noexcept {
return a.compare(b) == 0;
}
friend inline bool operator!=(basic_string_view a,
basic_string_view b) noexcept {
return a.compare(b) != 0;
}
friend inline bool operator<(basic_string_view a,
basic_string_view b) noexcept {
return a.compare(b) < 0;
}
friend inline bool operator>(basic_string_view a,
basic_string_view b) noexcept {
return a.compare(b) > 0;
}
friend inline bool operator<=(basic_string_view a,
basic_string_view b) noexcept {
return a.compare(b) <= 0;
}
friend inline bool operator>=(basic_string_view a,
basic_string_view b) noexcept {
return a.compare(b) >= 0;
}
friend std::ostream& operator<<(std::ostream& os, basic_string_view s) {
std::ostream::sentry sentry{os};
if (!sentry) return os;
// Ideas from:
// https://stackoverflow.com/q/39653508
size_t padding = 0;
char filler = os.fill();
if (s.size() < os.width()) {
padding = os.width() - s.size();
}
bool align_left = os.flags() & std::ios_base::left;
if (padding > 0 && !align_left) {
while (padding--) os.put(filler);
}
os.write(s.data(), s.size());
if (padding > 0 && align_left) {
while (padding--) os.put(filler);
}
os.width(0);
return os;
}
private:
constexpr static size_type internal_strlen(const_pointer str) {
return str ? traits_type::length(str) : 0;
}
static constexpr size_type kMaxSize = std::numeric_limits<size_type>::max();
const_pointer data_;
size_type len_;
};
template <class CharT, class Traits>
constexpr typename basic_string_view<CharT, Traits>::size_type
basic_string_view<CharT, Traits>::npos;
template <class CharT, class Traits>
constexpr typename basic_string_view<CharT, Traits>::size_type
basic_string_view<CharT, Traits>::kMaxSize;
using string_view = basic_string_view<char>;
using u16string_view = basic_string_view<char16_t>;
using u32string_view = basic_string_view<char32_t>;
using wstring_view = basic_string_view<wchar_t>;
string_view operator"" _sv(const char* str, std::size_t len) noexcept {
return string_view(str, len);
}
u16string_view operator"" _sv(const char16_t* str, std::size_t len) noexcept {
return u16string_view(str, len);
}
u32string_view operator"" _sv(const char32_t* str, std::size_t len) noexcept {
return u32string_view(str, len);
}
wstring_view operator"" _sv(const wchar_t* str, std::size_t len) noexcept {
return wstring_view(str, len);
}
} // namespace david
namespace std {
template <>
struct hash<david::string_view> {
size_t operator()(david::string_view s) const {
// Extracted from
// https://stackoverflow.com/a/19411888
return std::_Hash_impl::hash(s.data(), s.length());
}
};
} // namespace std
#endif // LIBRARY_STRING_VIEW
</code></pre>
<p>Thank you so much!</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-17T15:15:20.587",
"Id": "475823",
"Score": "0",
"body": "\"Not very sure why they have to be friend functions\" -- there is a subtle difference with respect to name lookup and overload resolution. Defined outside of the class, the operators are template functions, and subject to template argument deduction. So operator==(sv, sv) will only be viable if both arguments are exactly string_views. Defined as friends inside the class, the operators are not template functions, so will be found by ADL when looking up operator==(const char*, sv), and not excluded by TAD. i.e. friend defined inside == implicit conversions allowed."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-17T15:25:16.900",
"Id": "475824",
"Score": "0",
"body": "Technically, the performance of char_traits isn't guaranteed, but it'd be surprising if it weren't memcmp or better on any given implementation, and should anyone define their own traits, it'd be surprising if they weren't honored. libstdc++ uses memcmp: https://github.com/gcc-mirror/gcc/blob/master/libstdc%2B%2B-v3/include/bits/char_traits.h#L347"
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-16T23:55:19.090",
"Id": "242428",
"Score": "1",
"Tags": [
"c++",
"strings",
"c++11"
],
"Title": "Own implementation of C++ std::string_view"
}
|
242428
|
<p>I just stated learning Rust (again...), here is a short bit of code I wrote:</p>
<pre><code>#![allow(non_snake_case)]
/**
* takes a 2D Vec and returns a 90° rotated version
*/
pub fn createRotated90(arr: &Vec<Vec<bool>>) -> Vec<Vec<bool>> {
let newWidth = arr[0].len();
let newHeight = arr.len();
let mut newRetArr = createNewFilled2DVec(newWidth as u8, newHeight as u8, false);
forEachXY(
newHeight as u8,
newWidth as u8,
&mut |x: u8, y: u8| newRetArr[y as usize][newHeight - x as usize - 1] = arr[x as usize][y as usize]
);
newRetArr
}
pub fn createNewFilled2DVec<T: std::clone::Clone>(width: u8, height: u8, filler: T) -> Vec<Vec<T>> {
vec![vec![filler; height as usize]; width as usize]
}
pub fn forEachXY<F: FnMut(u8, u8)>(width: u8, height: u8, mut func: F) {
let mut x: u8 = 0;
let mut y: u8 = 0;
while x < width {
while y < height {
func(x, y);
y += 1;
}
x += 1;
}
}
</code></pre>
<p>I am hoping for some general suggestion on how to improve my "Rusting".<br>
Some points I noticed:</p>
<ul>
<li>a lot of <code>as usize</code></li>
<li>It seems Rust doesn't want me to use "normal" for loops (see <code>forEachXY</code>)</li>
<li>I am using Vec's instead of arrays, even though they don't change in size</li>
</ul>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-17T02:21:45.100",
"Id": "475771",
"Score": "2",
"body": "Welcome to Code Review. Please add an explanation of the purpose of your code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-17T11:44:51.560",
"Id": "475792",
"Score": "0",
"body": "@L.F. my code has no real purpose, I just wrote it to get to know Rust"
}
] |
[
{
"body": "<h1>Correctness</h1>\n\n<p>In</p>\n\n<pre class=\"lang-rust prettyprint-override\"><code>let mut x: u8 = 0;\nlet mut y: u8 = 0;\n\nwhile x < width {\n while y < height {\n println!(\"{}, {}\", x, y);\n func(x, y);\n\n y += 1;\n }\n\n x += 1;\n}\n</code></pre>\n\n<p><code>y</code> increments up to <code>height</code>, but then never gets reset. That means that the inner loop only runs once. To fix this, move the initialization of <code>y</code> inside the loop, or use a \"normal loop\" (see below).</p>\n\n<hr>\n\n<h1>Formatting and convention</h1>\n\n<p>Right now, it looks like you're trying to write Rust in a different language. Whenever possible, use the conventions suggested by the Rust compiler and the linter <code>clippy</code> (run <code>cargo clippy</code>). In particular, using <code>#![allow(non_snake_case)]</code> to set your own convention is discouraged.</p>\n\n<p>A few other things:</p>\n\n<ul>\n<li>Use <code>///</code> for documentation. <code>/* */</code> comments are fairly rare and <code>///</code> comments will automatically be included in the documentation produced by <code>cargo doc</code>.</li>\n<li>Keep lines fairly short. It's OK to go over the traditional limit of 80 characters sometimes, but whenever possible, break up lines for readability. For example, with a function signature or call, the arguments can be placed on separate lines. <code>cargo fmt</code> will do this automatically to the best of its ability.</li>\n<li><code>Vec<T></code> is itself a pointer (and length and capacity), so <code>&Vec<T></code> has no advantage over <code>&[T]</code>. In fact, due to automatic deref coercion, using the latter in a function signature allows that function to take either kind of argument. See <a href=\"https://stackoverflow.com/questions/40006219/why-is-it-discouraged-to-accept-a-reference-to-a-string-string-vec-vec-o\">this question</a> for more.</li>\n</ul>\n\n<hr>\n\n<h1>Use <code>for</code> loops.</h1>\n\n<p>When iterating over a collection, <code>for</code> loops are usually the best way. There's no need to keep track of mutating variables. If an index is needed, the <a href=\"https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html#method.enumerate\" rel=\"nofollow noreferrer\"><code>enumerate</code></a> method in the <code>Iterator</code> trait can be used.</p>\n\n<p>Here's how I'd rewrite your loop.</p>\n\n<pre class=\"lang-rust prettyprint-override\"><code>for (x, col) in arr.iter().enumerate() {\n for (y, &elem) in col.iter().enumerate() {\n new_arr[y][new_height - x - 1] = elem\n }\n}\n</code></pre>\n\n<hr>\n\n<h1>Add tests</h1>\n\n<p>Before I even touched your code, I made sure to add at least one test case. That alone caught the bug that I mentioned above. Adding more was very helpful when figuring out how the width and height worked (see the first item in Miscellaneous below). Just as a template, you can use</p>\n\n<pre class=\"lang-rust prettyprint-override\"><code>#[cfg(test)]\nmod tests {\n use super::*;\n\n fn my_test() {\n // Use things like `assert!` and `assert_eq!` to verify the output of your functions\n // ...\n }\n}\n</code></pre>\n\n<p>Tests can be run with <code>cargo test</code>.</p>\n\n<hr>\n\n<h1>Miscellaneous</h1>\n\n<p>This may just be personal preference, but when I see a 2-dimensional array like</p>\n\n<pre class=\"lang-rust prettyprint-override\"><code>vec![\n vec![1, 2, 3],\n vec![4, 5, 6],\n]\n</code></pre>\n\n<p>I think of this has having a width of 3 and a height of 2. That is, the first row is <code>[1, 2, 3]</code> and the second row is <code>[4, 5, 6]</code>. Indexing at <code>(x, y)</code> is <code>arr[y][x]</code> (first access <code>y</code>th row, then <code>x</code>th column). From what I can tell, you've reversed this. For example, <code>vec![vec![filler; height as usize]; width as usize]</code> would have a height of <code>width</code> and a width of <code>height</code> in my convention.</p>\n\n<p>Note that rotating the vector switches the role of <code>height</code> and <code>width</code>, so <code>new_width</code> is the height of the original and <code>new_height</code> is the width of the original.</p>\n\n<hr>\n\n<p>The <code>u8</code>/<code>usize</code> problems were largely solved by rewriting the loop, but in general, I'd suggest just sticking with one type. There's no reason for <code>create_new_filled_2d_vec</code> or <code>for_each_xy</code> to take <code>u8</code> arguments. That just leads to unnecessary conversions. Since the length of a vector is always <code>usize</code>, it makes sense to just use <code>usize</code> everywhere.</p>\n\n<hr>\n\n<p>If you want to use arrays, you'll eventually be able to use <code>const</code> generics to accomplish this. For now, they'll need to be dynamically allocated as <code>Box<[T]></code>. You can produce a <code>Box<[T]></code> from a <code>Vec<T></code> using the <code>as_boxed_slice</code> method. Since the only difference between this and <code>Vec<T></code> is the <code>capacity</code> field, <code>Box<[T]></code> is fairly rare in practice. The benefit isn't very large.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-17T03:07:08.710",
"Id": "242441",
"ParentId": "242429",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "242441",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-17T00:03:06.787",
"Id": "242429",
"Score": "0",
"Tags": [
"rust"
],
"Title": "Suggestions for beginner Rust code"
}
|
242429
|
<p>My gut tells me this is poor practice, so, I thought I would ask for some feedback.</p>
<p>The goal here is to fake a fluent API design for any class without using reflection while keeping it as pretty as possible. If I were to use reflection, I would just use <a href="https://github.com/jOOQ/jOOR" rel="nofollow noreferrer">jOOR</a>.</p>
<p>No need to comment on null-checks. I have omitted them in this post for the sake of simplicity.</p>
<p>Class:</p>
<pre><code>public final class Fluent<T> {
private final T object;
public Fluent(final T object) {
this.object = object;
}
public Fluent<T> with(final Consumer<T> consumer) {
consumer.accept(object);
return this;
}
public T get() {
return object;
}
}
</code></pre>
<p>Example:</p>
<pre><code>final MenuItem item = new Fluent<>(new MenuItem("Foo"))
.with(o -> o.setAccelerator(accelerator))
.with(o -> o.setOnAction(this::callback)).get();
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-17T03:39:00.543",
"Id": "475772",
"Score": "1",
"body": "Haven't worked with Java in a while so might be completely wrong, but shouldn't the `Supplier` be `Consumer` in `with`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-17T03:40:40.010",
"Id": "475773",
"Score": "0",
"body": "Yes, I copied my code over wrong, thank you. Editing..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-17T04:59:39.517",
"Id": "475777",
"Score": "6",
"body": "Dont take me wrong, but what is the true goal here? One usualy does not code just for the code itself, one usualy has a problem to solve. This does not seem to be any problem at all. You can just call those methods directly on the menu item..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-17T14:21:12.163",
"Id": "475815",
"Score": "0",
"body": "Aside: Kotlin has this pattern baked in: https://www.journaldev.com/19467/kotlin-let-run-also-apply-with"
}
] |
[
{
"body": "<p>Yes, your implementation is sound and possible...however, it doesn't make any sense to have it in the first place, at least not for your example.</p>\n<pre class=\"lang-java prettyprint-override\"><code>final MenuItem item = new Fluent<>(new MenuItem("Foo"))\n .with(o -> o.setAccelerator(accelerator))\n .with(o -> o.setOnAction(this::callback)).get();\n</code></pre>\n<p>Compared with:</p>\n<pre class=\"lang-java prettyprint-override\"><code>final MenuItem item = new MenuItem("foot");\nitem.setAccelerator(accelerator);\nitem.setOnAction(this::callback);\n</code></pre>\n<p>That's <em>less</em> code to type, easier to type and a little bit easier to read.</p>\n<p>And if you wanted to be a little bit more...uh...fancy, you could simply use the double-brace initialization for non-final classes at least:</p>\n<pre class=\"lang-java prettyprint-override\"><code>final MenuItem item = new MenuItem("foot") {{\n setAccelerator(accelerator);\n setOnAction(this::callback);\n}};\n</code></pre>\n<hr />\n<blockquote>\n<p>No need to comment on null-checks. I have omitted them in this post for the sake of simplicity.</p>\n</blockquote>\n<p>Please don't the next time.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-17T13:57:49.807",
"Id": "475814",
"Score": "0",
"body": "Thank you for your constructive criticism. I do agree that the example is insufficient. However, the double-braced initialization will not work for final classes, so, it will not fulfill my goal."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-17T16:35:20.140",
"Id": "475831",
"Score": "0",
"body": "Ah, I see, never used that before so I didn't know, will edit the answer."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-18T08:38:16.040",
"Id": "475871",
"Score": "0",
"body": "The so-called \"double brace initialization\" is an anonymous subclass with an object initializer. I have never seen this \"solution\" on par with the solved problem, i.e. creating a complete CLASS for a single object with concrete parameters."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-18T16:15:02.670",
"Id": "475924",
"Score": "0",
"body": "@mtj I don't like the syntax either...but, that's just me. Whether that matters in the use-case is a completely different question."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-17T11:11:43.787",
"Id": "242455",
"ParentId": "242436",
"Score": "3"
}
},
{
"body": "<p>I wrote code like the question once for a Fluent Builder which also accepted <code>Consumer</code> as parameter to allow callers to provide a set of opaque modifications determined earlier. In a menu example this might be:</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>new Fluent<>(new Menu(\"File\")))\n .with(o -> o.setAccelerator(accelerator))\n .with(contextSensitiveMenuItem)\n</code></pre>\n\n<p>This rapidly required a varargs call as the opaque-items are variable in number</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>public Fluent<T> with(Consumer<T>... consumers) {\n for (consumer in consumers) {\n consumer.accept(object);\n }\n return this;\n}\n</code></pre>\n\n<p>Generically, I'm not sure how useful <code>final</code> parameters are in this context. THe compiler will figure that out itself.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-17T13:17:26.117",
"Id": "242461",
"ParentId": "242436",
"Score": "0"
}
},
{
"body": "<p>I get the feeling you just want to call the setters in a chain to spare you from writing <code>item.</code> and <code>;</code> before and after every call, instead of actually having a <em>fluent</em> interface.</p>\n\n<p>Does this actually make your code more fluent and more maintainable or are you introducing foreign concepts that confuse the people who read it the future? Will you even remember what that code does in 6 months?</p>\n\n<p>I would say that your gut feeling is right here. You're jumping through hoops to not make much of an improvement.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-20T04:18:59.223",
"Id": "476080",
"Score": "0",
"body": "Thank you for your feedback. You just described fluent programming in your first paragraph. You are right, I am going with my gut."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-20T09:12:47.850",
"Id": "476108",
"Score": "1",
"body": "No, he didn't. Fluent programming isn't that. It's a lot more nuanced and detailed and simply having a wrapper add a 'with' command isn't the same thing at all."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-20T09:22:19.243",
"Id": "476110",
"Score": "0",
"body": "Method chaining is an integral part of fluent interfaces but an interface isn't fluent if the methods do not form a domain specific language. Also, \"fluent interfaces are evil\" is a good search query for studying the topic. :)"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-18T08:25:24.757",
"Id": "242508",
"ParentId": "242436",
"Score": "2"
}
},
{
"body": "<p>You seem to have grasped some of the mechanics of a fluent interface without grasping the fundamentals around purpose or fit (maybe your gut has, but your mind has not yet reached this understanding). When Evens and Fowler first document this pattern, their intent was to make code clearer and more readable by allowing methods to be chained together.</p>\n\n<p>Your code, while technically correct, is not clearer or more readable. It adds extra verbiage and <strong><em>doesn't remove the <code>object.setter()</code> syntax</em></strong> at all. It simply obfuscates it by hiding these calls in the heart of a functional interface. Carefully consider the point in bold and italics because it's really important here -- you haven't removed the thing you were trying to remove. This code fails in its most basic purpose, as well as making things considerably worse.</p>\n\n<p>This is a very bad idea. As @Bobby said:</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>final MenuItem item = new MenuItem(\"foot\");\nitem.setAccelerator(accelerator);\nitem.setOnAction(this::callback);\n</code></pre>\n\n<p>Is much simpler, clearer, and easy to read. If you wanted to make this fluent you would change the setters to return <code>this</code> and then you could get something like:</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>final MenuItem item = new MenuItem(\"foot\").setAccelerator(accelerator).setOnAction(this::callback);\n</code></pre>\n\n<p>However, in this specific case, you would be better off with one or more constructors to cover the most common use-cases.</p>\n\n<p>The purpose of code is 2-fold. First, it has to execute correctly, and second, it has to communicate its purpose clearly to future engineers. Code is read many more times than it is written, and it is this fact that is constantly prominent in a senior developer's mind while coding.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-20T09:29:06.960",
"Id": "242619",
"ParentId": "242436",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-17T00:58:44.290",
"Id": "242436",
"Score": "1",
"Tags": [
"java",
"design-patterns",
"fluent-interface"
],
"Title": "Java Fluent Wrapper"
}
|
242436
|
<p><strong>The idea</strong></p>
<p>At my work, I'm tasked with retrieving logs for a list of online orders from a total of 12 servers. To do this, I SSH into them (with a jump host in between) one by one, run the script for every order, then parse the output. Overall, a very tedious process that I'm sure can be automated.</p>
<p>W -> J -> S</p>
<p>W = My Windows VM</p>
<p>J = Red Hat jump box</p>
<p>S = The Red Hat production servers</p>
<p>So the basic idea is the following:</p>
<ol>
<li><p>Connect to every server by SSH</p></li>
<li><p>On every server, run the commands for all orders which are passed by command line</p></li>
<li><p>Associate each output with the order</p></li>
</ol>
<p>Here is what I've come up with so far, and it is working on my home lab. But before I bring it in to work to propose it and try it on production servers, I want to know how the code can be cleaned up or done more efficiently.</p>
<p><strong>The code</strong></p>
<pre><code>require 'net/ssh'
require 'io/console'
require 'pp'
ORDERS = ARGV.dup()
ARGV.clear()
SERVERS = [
"prod1",
"prod2",
"prod3"
]
COMMAND = "aux_search.sh"
CONFIG = "C:/Users/myuser/.ssh/config"
RESULTS = ORDERS.each_with_object({}) { |k, v| v[k] = "" }
puts("Enter your username: ")
USERNAME = gets().chomp()
puts("Enter your password for accessing the servers: ")
SERVERPASSWORD = STDIN.noecho(&:gets).chomp()
puts("Enter your sudo password: ")
SUDOPASSWORD = STDIN.noecho(&:gets).chomp()
SESSIONS = []
SERVERS.each do |server|
session = Net::SSH.start(server, USERNAME, :password => SERVERPASSWORD, :config => CONFIG,
:verbose => :debug, :auth_methods => ["publickey", "password"], :verify_host_key => :accept_new)
SESSIONS << session
end
SESSIONS.each do |ssh|
ORDERS.each do |order|
ssh.open_channel() do |channel|
channel.on_data do |_, data|
RESULTS[order].concat(data)
if data.match(/\[sudo\]/)
channel.send_data("#{SUDOPASSWORD}\n")
end
end
channel.request_pty() do |_, success|
raise "Failed to request TTY for order #{order}" unless success
end
channel.exec("sudo ./#{COMMAND} #{order}") do |_, success|
raise "Could not execute command #{COMMAND} #{order}" unless success
end
end
end
ssh.loop()
end
puts("===Results===")
pp(RESULTS)
</code></pre>
<p><strong>My ssh config</strong></p>
<pre><code>Host jumpbox
HostName 192.168.16.2
User johrus2
IdentityFile C:\Users\myuser\.ssh\id_rsa3
Port 22
Host prod1
HostName 192.168.16.3
User johrus2
IdentityFile C:\Users\myuser\.ssh\id_rsa3
ProxyJump jumpbox
Port 22
Host prod2
HostName 192.168.16.4
User johrus2
IdentityFile C:\Users\myuser\.ssh\id_rsa3
ProxyJump jumpbox
Port 22
Host prod3
HostName 192.168.16.5
User johrus2
IdentityFile C:\Users\myuser\.ssh\id_rsa3
ProxyJump jumpbox
Port 22
<span class="math-container">```</span>
</code></pre>
|
[] |
[
{
"body": "<p>I think this is interesting code. I admit I haven't dug much into Ruby's Net::SSH library, so I bet you've learned some things about it in writing this code. It sounds to me like your biggest concern now is about professionalism, stability, and dependability which is why you want feedback before offering to use this code in a production environment. If so, I feel like you're asking all the right questions.</p>\n\n<p>Here are my suggestions:</p>\n\n<ul>\n<li>Search for prior art</li>\n<li>Don't touch passwords if you can help it, and other security practices</li>\n<li>Add some tests</li>\n</ul>\n\n<h2>Prior Art</h2>\n\n<p>You haven't mentioned yet if you've looked into existing tools that have already done this work. For example, you could use <a href=\"https://github.com/capistrano/capistrano\" rel=\"nofollow noreferrer\">Capistrano</a>, which is written in Ruby and designed for the type of scenario you're describing. Capistrano is fairly well-maintained. You could put it on your jump box, if you wanted. If Capistrano looks too cumbersome for what you're doing, you may want to use its <a href=\"https://github.com/capistrano/sshkit\" rel=\"nofollow noreferrer\">sshkit</a> library, which handles some of the ssh concerns you're navigating manually here.</p>\n\n<h2>Security Practices</h2>\n\n<p>I see you have public/private keypairs for every server you're connecting to. Try to use them instead of getting user input for a password. I would lean on the side of requiring them for anyone using a tool like this. In fact, I might have a distinct identity for automation so that I can revoke or recreate its keys without affecting any other way I can log in to the system. You may also want to add logging so you can audit your script to make sure it did what you intended. This is also helpful as a changelog to look back on when your script worked fine and you're troubleshooting unexpected side-effects of the commands it ran.</p>\n\n<p>The nice thing about this specific identity is you can also leverage it to avoid passing sudo passwords around. This identity could have a limited list of commands it can run either in your sudoers file or without needing sudo. For example, I have used Capistrano to log in as a user that does not have root permissions, but does have elevated permissions that my basic account does not have. This elevated user had file permissions so it could update the code for the servers' websites without requiring sudo, though it couldn't do too much else.</p>\n\n<p>More generally, I get nervous whenever I'm writing any code that handles user input for security credentials. I'd say that if there's already an existing project where flaws in handling security are likely to result in the announcement of a public <a href=\"https://cve.mitre.org/\" rel=\"nofollow noreferrer\">CVE</a>, it's better to use those projects for than writing your own security implementations to use in production.</p>\n\n<p>In summary</p>\n\n<ul>\n<li>use something more likely to get security audits than you are</li>\n<li>have a layered plan for what you do if something goes wrong or the system is abused</li>\n</ul>\n\n<h2>Add Some Tests</h2>\n\n<p>Do you know what errors SSH is likely to raise if something goes wrong? Should that stop the whole process without continuing? Does your code do that in a way you're happy with?</p>\n\n<p>These are the kind of answers that tests are good at answering for you. One thing I like to keep in mind when writing separate test code feels like a waste of time is the saying, \"Everyone tests their code. Some people then throw the tests away, and some people keep them.\"</p>\n\n<p>I suspect, looking at your code, it would be hard to stub out the ssh library to simulate what happens when when several commands succeed and then one fails. (A discussion of how to stub and mock that sort of thing in Ruby tests feels to big to handle in this answer. Let me know if you have trouble finding guides for it online.) The fact that writing test you'd like to have feels difficult is an excellent sign that you should split up your code differently from how you've written it. </p>\n\n<p>As an example, you could have one chunk of code that accepts some generic connection management object, and then worries about the sequencing of commands and handling failed commands. Then you could have another chunk of code that is the connection object, abstracting the SSH library down to the few parts of it you care about for this script. Maybe there's an even better way to make that split that you'll find once you sit down to it.</p>\n\n<p>Either way, once you reorganize your code so the tests are easier to write, you'll also find it gets easier to make changes, fix bugs, add new features even if you were to never run the tests again. (But you should run the tests again — you already wrote them, and they're just sitting there. No need to waste the effort.)</p>\n\n<h2>Good Luck Out There</h2>\n\n<p>I hope this helps. Feel free to ask me for further clarification on any of this if you want.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-29T03:09:36.597",
"Id": "480380",
"Score": "1",
"body": "Hey! Just wanted to thank you for this. You and someone else on a different website suggested Capistrano/SSHKit, so I did some looking into those. You were very right when you said that SSHKit handled the stuff I was trying to do manually, and it did it much more elegantly than I did. So ultimately, I decided on it over Net:SSH and was able to write a much more clean and robust script than this one. I did take your advice and write tests for it to show that I'd thought through what could go wrong, and it was well received. Thank you for your review!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-22T14:20:43.693",
"Id": "242753",
"ParentId": "242438",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-17T01:36:10.960",
"Id": "242438",
"Score": "1",
"Tags": [
"ruby",
"ssh"
],
"Title": "Ruby - Sending commands to multiple servers using Net::SSH"
}
|
242438
|
<p>I'm implementing the matrix multiply function using Java's multithreading. Below is my code:<br>
So I first tried the normal single threaded approach, then tried the ExecutorService approach, I don't know why the first approach is actually faster than the multithreading approach, based on the start time and the end time, is there any mistake in my code?</p>
<pre><code>public class MatrixTest {
static int len = 1000;
static int[][] m1 = new int[len][len];
static int[][] m2 = new int[len][len];
static int[][] res = new int[len][len];
public static void main(String[] args) throws InterruptedException {
initMatrix(m1);
initMatrix(m2);
//ExecutorService executorService = Executors.newFixedThreadPool(50);
long startTime = System.nanoTime();
//res = new MatrixMulty().multi(m1, m2);
for (int i = 0; i < m1.length; i++) {
for (int j = 0; j < m2[0].length; j++) {
MatrixMulty mm = new MatrixMulty(m1[i], getCol(m2, j), res, i, j);
//executorService.submit(mm);
mm.multi();
}
}
//executorService.shutdown();
//executorService.awaitTermination(Long.MAX_VALUE, TimeUnit.DAYS);
long endTime = System.nanoTime();
System.out.println("whole time is :" + (endTime - startTime) / 10000);
}
private static int[] getCol(int[][] m2, int j) {
int[] re = new int[m2.length];
for (int i = 0; i < m2.length; i++) {
re[i] = m2[i][j];
}
return re;
}
private static void initMatrix(int[][] mtx) {
for (int i = 0; i < mtx.length; i++) {
for (int j = 0; j < mtx[0].length; j++) {
mtx[i][j] = i+j;
}
}
}
}
public class MatrixMulty implements Runnable {
int[] m1;
int[] m2;
int[][] res;
int i;
int j;
public MatrixMulty(int[] m1, int[] m2, int[][] res, int i, int j){
this.m1 = m1;
this.m2 = m2;
this.i = i;
this.j = j;
this.res = res;
}
@Override
public void run() {
int index=0;
int r = 0;
while(index<m1.length){
r += m1[index]*m2[index];
index++;
}
res[i][j] = r;
}
public void multi() {
int index=0;
int r = 0;
while(index<m1.length){
r += m1[index]*m2[index];
index++;
}
res[i][j] = r;
}
}
</code></pre>
<p><strong>UPDATE1</strong>
Based on suggestion, I have modified related code and move the executorService from the inner loop to the outer loop, new code sinppets shows below:</p>
<pre><code>public static void main(String[] args) throws InterruptedException {
initMatrix(m1);
initMatrix(m2);
ExecutorService executorService = Executors.newFixedThreadPool(45);
long startTime = System.nanoTime();
//res = new MatrixMulty().multi(m1, m2);
for (int i = 0; i < m1.length; i++) {
MatrixMulty2 mm = new MatrixMulty2(m1[i], m2, res, i);
//for (int j = 0; j < m2[0].length; j++) {
//MatrixMulty mm = new MatrixMulty(m1[i], getCol(m2, j), res, i, j);
//executorService.submit(mm);
//mm.multi();
//}
executorService.submit(mm);
}
executorService.shutdown();
executorService.awaitTermination(Long.MAX_VALUE, TimeUnit.DAYS);
long endTime = System.nanoTime();
System.out.println("whole time is :" + (endTime - startTime) / 10000);
}
</code></pre>
<p>and the new class MatrixMulty2:</p>
<pre><code>public class MatrixMulty2 implements Runnable {
int[] m1;
int[][] m2;
int[][] res;
int i;
public MatrixMulty2(int[] m1, int[][] m2, int[][] res, int i){
this.m1 = m1;
this.m2 = m2;
this.res=res;
this.i = i;
}
@Override
public void run() {
for(int j=0;j<m2[0].length;j++){
int[] co = getCol(m2,j);
int index=0;
int r = 0;
while(index<m1.length){
r += m1[index]*co[index];
index++;
}
res[i][j] = r;
}
}
private static int[] getCol(int[][] m2, int j) {
int[] re = new int[m2.length];
for (int i = 0; i < m2.length; i++) {
re[i] = m2[i][j];
}
return re;
}
}
</code></pre>
<p>After testing, I find that it is faster than the single thread approach by around 25%. Is there any more to optimize it? or from pool size aspect, here I have a fixed thread pool with size=50, I find that it is not true that the larger thread pool I have, the faster it runs. Here size=50 is an ad-hoc value, is it possible to systematically tune it?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-17T06:25:21.443",
"Id": "475783",
"Score": "2",
"body": "Try submitting in the *outer* loop. Present measurement results of all alternatives measured."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-17T15:52:01.583",
"Id": "475828",
"Score": "0",
"body": "Thanks, I've made changes. What do you mean by \"Present measurement results of all alternatives measured\"@greybeard"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-17T16:41:21.887",
"Id": "475832",
"Score": "0",
"body": "I'm not 100% thinking straight right now, but I believe your number of operations being run is a little bit low, and your number of threads a little bit high. You should have around a million integer operations, that's *nothing*. Threads are expensive to start and slow down the moment you run out of (physical?) cores. So for performance tests you might also want to test with a higher operations count and also with a lower thread count."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-17T03:24:19.227",
"Id": "242442",
"Score": "2",
"Tags": [
"java",
"multithreading"
],
"Title": "My Java matrix multiply code single thread faster than multithreading, any mistakes?"
}
|
242442
|
<p>This would be for a <code>MUD</code> client, which has elements of a sort of <code>telnet</code> bot.</p>
<p>Here, there's <code>string</code> parsing for a logged file for each line -- starting with the most recent. Once a "trigger" is invoked the parser and actions should, for the sake of simplicity, stop.</p>
<p>I'm considering a <code>records</code> class for the triggers, but for now have the trigger and result in a <code>map</code> as below.</p>
<p>Not terribly concerned about resource efficiency, as this ultimately deals with text files, but more with extensibility and flexibility.</p>
<pre><code>package net.bounceme.dur.files;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
import java.util.Map;
import java.util.logging.Logger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class BotActions {
private final static Logger log = Logger.getLogger(BotActions.class.getName());
private Map<String, String> triggers = null;
private boolean triggered = false;
private BotActions() {
}
public BotActions(Map<String, String> triggers) {
this.triggers = triggers;
}
private void pullTrigger(String line, Map.Entry<String, String> entry) {
log.info(line);
log.info(entry.toString());
}
private void triggers(String line) {
Pattern pattern = null;
Matcher matcher = null;
Iterator<Map.Entry<String, String>> triggerEntries = triggers.entrySet().iterator();
while (triggerEntries.hasNext() && !triggered) {
Map.Entry<String, String> entry = triggerEntries.next();
pattern = Pattern.compile(entry.getKey());
matcher = pattern.matcher(line);
if (matcher.matches()) {
pullTrigger(line, entry);
triggered = true;
}
}
}
public void everyLine(List<String> list) {
ListIterator listIterator = list.listIterator(list.size());
while (listIterator.hasPrevious() && !triggered) {
triggers(listIterator.previous().toString());
}
}
}
</code></pre>
<p>I'm thinking really the text lines are a <code>stack</code> while the triggers are more a <code>queue</code>, although there's more flexibility on the triggers sequence. But, just because of how the log file is initially parsed, those don't really seem options.</p>
<p>Regardless, interested in all comments.</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-17T03:51:31.967",
"Id": "242444",
"Score": "1",
"Tags": [
"java",
"regex",
"stack",
"queue",
"hash-map"
],
"Title": "regex on a log file utilizing stacks and queue's in Java"
}
|
242444
|
<p>The assumption is that k is quite large as compared to no. of elements in the array and division by 2 returns ceiling of the result.</p>
<p>Request for your review and suggestions for further improvements or simplifications.</p>
<p>Example : Array: { 10, 15, 7, 23, 5}</p>
<p>k = 6</p>
<p>Solution: {5, 4, 4, 6, 5} = 24</p>
<p>How Code Works?</p>
<p>Basically we are taking the maximum element and diving it by 2 for example in the first step we take 23 and return 12, as the ceiling of 23/2.</p>
<p>We need to repeat the above steps for k times to get the minimized sum of 24.</p>
<p>As the above algorithm is of the complexity O(kn) so to reduce the complexity I am dividing the array to sub arrays based upon their log2 values, so the no. of k and n gets reduced to very small numbers.</p>
<p>Code:</p>
<pre><code> private static int GetMinSum(int[] array, int k)
{
int n = array.Length;
var sum = 0;
k = GetOptimizedListAndK(array, n, k, out var lists);
//If more sublists are needed
if (k > 0)
{
var count = lists.CountSum;
var key = lists.Key;
if (key > 0)
{
var poweroftwo = 1 << key;
sum += count * poweroftwo - k * poweroftwo / 2;
var dictionary2 = GetDictionary(array, lists, poweroftwo);
key = dictionary2.Keys.Last();
while (k > 0 && key > 0)
{
var list2 = dictionary2[key];
count = list2.Count;
if (k >= count)
{
list2.ForEach(
index => array[index] = array[index] / 2 + array[index] % 2);
dictionary2.Remove(key);
key = dictionary2.Keys.LastOrDefault();
k -= count;
}
else
{
if (k <= Log2(count))
{
for (int i = 0; i < k; i++)
{
var indexAtMax = GetMaxIndex(list2, array);
array[indexAtMax] = array[indexAtMax] / 2 + array[indexAtMax] % 2;
}
k = 0;
}
if (count - k <= Log2(count))
{
var minIndexes = GetMinIndexes(list2, array, count - k);
foreach (var i in list2)
{
if (!minIndexes.Contains(i))
{
array[i] = array[i] / 2 + array[i] % 2;
}
}
k = 0;
}
if (k > 0)
{
poweroftwo = 1 << key;
sum += list2.Count * poweroftwo - k * poweroftwo / 2;
dictionary2 = GetDictionary(array, list2, poweroftwo);
key = dictionary2.Keys.Last();
}
}
}
}
}
return array.Sum() + sum;
}
private static int GetOptimizedListAndK(int[] array, int n, int k, out Lists lists)
{
lists = null;
Dictionary<int, Lists> dictionary = new Dictionary<int, Lists>();
PopulatePowerBasedDictionary(array, n, dictionary);
var key = dictionary.Keys.Max();
while (key > 0 && k > 0)
{
lists = dictionary[key];
var count = lists.CountSum;
if (k >= count)
{
lists.ForEach(list => list.ForEach(index => array[index] = array[index] / 2 + array[index] % 2));
if (key > 1)
{
if (dictionary.TryGetValue(key - 1, out var lowerlists))
{
lowerlists.AddRange(lists);
lowerlists.CountSum += count;
}
else dictionary.Add((key - 1), lists);
}
dictionary.Remove(key);
key--;
k -= count;
}
else
{
if (k < Log2(count))
{
for (int i = 0; i < k; i++)
{
var indexAtMax = GetMaxIndex(lists, array);
array[indexAtMax] = array[indexAtMax] / 2 + array[indexAtMax] % 2;
}
k = 0;
}
if (count - k < Log2(count))
{
var minIndexes = GetMinIndexes(lists, array, count - k);
foreach (var list in lists)
{
foreach (var i in list)
{
if (!minIndexes.Contains(i))
{
array[i] = array[i] / 2 + array[i] % 2;
}
}
}
k = 0;
}
break;
}
}
return k;
}
private static void PopulatePowerBasedDictionary(int[] array, int n, Dictionary<int, Lists> dictionary)
{
for (int i = 0; i < n; i++)
{
if (array[i] < 2) continue;
var log2 = Log2(array[i]);
if (dictionary.TryGetValue(log2, out var lists))
{
lists[0].Add(i);
lists.CountSum++;
}
else
{
lists = new Lists(1,log2) { new List<int> { i } };
dictionary.Add(log2, lists);
}
}
}
private static int GetMaxIndex(List<int> list, int[] array)
{
var maxIndex = 0;
var max = 0;
foreach (var i in list)
{
if (array[i] > max)
{
maxIndex = i;
max = array[i];
}
}
return maxIndex;
}
private static SortedDictionary<int, List<int>> GetDictionary(int[] array, Lists lists, int poweroftwo)
{
SortedDictionary<int, List<int>> dictionary = new SortedDictionary<int, List<int>>();
foreach (var list in lists)
{
foreach (var i in list)
{
array[i] = array[i] - poweroftwo;
if (array[i] < 2)
{
continue;
}
var log2 = Log2(array[i]);
if (dictionary.TryGetValue(log2, out var list2))
{
list2.Add(i);
}
else
{
list2 = new List<int> { i };
dictionary.Add(log2, list2);
}
}
}
return dictionary;
}
private static SortedDictionary<int, List<int>> GetDictionary(int[] array, List<int> list, int poweroftwo)
{
SortedDictionary<int, List<int>> dictionary = new SortedDictionary<int, List<int>>();
foreach (var i in list)
{
array[i] = array[i] - poweroftwo;
if (array[i] < 2)
{
continue;
}
var log2 = Log2(array[i]);
if (dictionary.TryGetValue(log2, out var list2))
{
list2.Add(i);
}
else
{
list2 = new List<int> { i };
dictionary.Add(log2, list2);
}
}
return dictionary;
}
private static int GetMaxIndex(Lists lists, int[] array)
{
var maxIndex = 0;
var max = 0;
foreach (var list in lists)
{
foreach (var i in list)
{
if (array[i]>max)
{
maxIndex = i;
max = array[i];
}
}
}
return maxIndex;
}
private static HashSet<int> GetMinIndexes(Lists lists, int[] array, int k)
{
var mins = new HashSet<int>();
var minIndex = 0;
var min = int.MaxValue;
for (int j = 0; j < k; j++)
{
foreach (var list in lists)
{
foreach (var i in list)
{
if (array[i] < min && !mins.Contains(i))
{
minIndex = i;
min = array[i];
}
}
}
mins.Add(minIndex);
min = int.MaxValue;
}
return mins;
}
private static HashSet<int> GetMinIndexes(List<int> list, int[] array, int k)
{
var mins = new HashSet<int>();
var minIndex = 0;
var min = int.MaxValue;
for (int j = 0; j < k; j++)
{
foreach (var i in list)
{
if (array[i] < min && !mins.Contains(i))
{
minIndex = i;
min = array[i];
}
}
mins.Add(minIndex);
min = int.MaxValue;
}
return mins;
}
private static int Log2(int n)
{
return BitOperations.Log2((uint)n);
}
</code></pre>
<p>Lists Class:</p>
<pre><code>public class Lists:List<List<int>>
{
public int Key { get; set; }
public int CountSum { get; set; }
public Lists(int countSum, int key):base()
{
CountSum = countSum;
Key = key;
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-17T13:09:11.290",
"Id": "475805",
"Score": "0",
"body": "Any reason why your algorithm is so complex? I would say this is a few lines solution: sort array, remove last element from list (max element), divide by 2, insert element into proper place to keep array sorted. Repeat k times."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-17T13:22:00.800",
"Id": "475809",
"Score": "0",
"body": "@Peska insert into proper place, to get that only I have divided into sub lists, and sorting is not needed if k>length of a sublist. The logic is that if you group based upon log2 of the value, you can always move to adjacent lower sublist when divoided by 2."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-07T23:07:34.277",
"Id": "491184",
"Score": "0",
"body": "If the maximum element is duplicated, is only one of them divided by two?"
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-17T09:08:50.367",
"Id": "242448",
"Score": "3",
"Tags": [
"c#",
"performance",
"hash-map",
"heap-sort",
"bucket-sort"
],
"Title": "C# code for minimizing the sum of an array by dividing it's elements (repetition allowed) by 2 for k times"
}
|
242448
|
<p>I tried solve this easy leetcode challenge in java. Challenge <a href="https://leetcode.com/problems/roman-to-integer/" rel="noreferrer">link</a></p>
<p>Here is my solution</p>
<pre><code>class Solution {
public int romanToInt(String s) {
Map<String, Integer> data
= new HashMap<String, Integer>() {
{
put("I", 1);
put("V", 5);
put("X", 10);
put("L", 50);
put("C", 100);
put("D", 500);
put("M", 1000);
put("IV", 4);
put("IX", 9);
put("XL", 40);
put("XC", 90);
put("CD", 400);
put("CM", 900);
}
};
String[] edge = {"IV", "IX", "XL", "XC", "CD", "CM"};
int sum = 0;
for (String val : edge) {
if(s.isBlank()) {
break;
} else if(s.contains(val)) {
sum += data.get(val);
int index = s.indexOf(val);
s = s.substring(0, index) + s.substring(index + 2);
}
}
s = s.trim();
for (char c: s.toCharArray()) {
sum += data.get("" + c);
}
return sum;
}
}
</code></pre>
<p>I am learning to compute the complexity:<br>
Here is my interpretation<br>
Looks like it is <code>O(6)</code> constant ~ <code>O(1)</code> * <code>O(len(string))</code> ~ <code>O(n)</code> => <code>O(n)</code>
Correct me if it is not O(n)</p>
<p>Any suggestions on my approach to problem and code where I can reduce time and space complexity.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-17T21:14:10.260",
"Id": "475842",
"Score": "1",
"body": "I don't think this is O(n), but rather O(13n). Both `s.contains(val)` and `s.indexOf(val)` have to enumerate through the entire string (and they even get the same result, since `.contains()` is roughly speaking `.indexOf() != -1`!) and you do both for each edge, ie. 6 times.\n\nI am not sure about the complexity of Java's String#substring(), but that might not actually be O(1) either."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-18T05:19:05.380",
"Id": "475856",
"Score": "4",
"body": "O(n) = O(13n). Elimination of constants is what Big-O-Notation is all about."
}
] |
[
{
"body": "<p>Your variable names are bad, <code>s</code>, <code>data</code>, all of these could be better, <code>input</code>, <code>romanNumerals</code> and so on.</p>\n\n<p>Your formatting is a little bit off, consider using an autoformatter.</p>\n\n<p>Also your method will spectacularly fail when handed invalid input.</p>\n\n<hr>\n\n<pre class=\"lang-java prettyprint-override\"><code>put(\"I\", 1);\n</code></pre>\n\n<p>Be aware of <a href=\"https://docs.oracle.com/javase/tutorial/java/data/autoboxing.html\" rel=\"noreferrer\">Autoboxing</a>.</p>\n\n<hr>\n\n<pre class=\"lang-java prettyprint-override\"><code>for (String val : edge) { \n if(s.isBlank()) {\n</code></pre>\n\n<p>Have the <code>if</code> outside the loop, so that you don't even need to start the loop just to bail out immediately.</p>\n\n<hr>\n\n<pre class=\"lang-java prettyprint-override\"><code>sum += data.get(\"\" + c);\n</code></pre>\n\n<p>I'm absolutely not a friend of such casts. Most of the time, they mask what you actually wanted and depend on implementation details, especially with numbers.</p>\n\n<hr>\n\n<p>Otherwise it seems to work. What you could do is split the initial <code>Map</code> into two, <code>romanNumerals</code> and <code>compoundRomanNumerals</code>, that would simplify the overall logic and would remove the duplication you have with the <code>edge</code> array.</p>\n\n<p>If you can help it, try to avoid string operations, they will always consume a lot of memory, for example:</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>String c = a + b;\n</code></pre>\n\n<p>Will result in:</p>\n\n<ol>\n<li>Allocate <code>c</code> with enough memory to hold <code>a</code> and <code>b</code></li>\n<li>Copy <code>a</code> into <code>c</code></li>\n<li>Copy <code>b</code> into <code>c</code></li>\n</ol>\n\n<p>So if <code>a</code> and/or <code>b</code> is <em>large</em>, and I mean <em>large</em>, your memory usage will spike.</p>\n\n<p>What you could do instead, is to copy the <code>String</code> into a <code>StringBuilder</code>, as that one will internally work on an array and will not create immutable instances with every change.</p>\n\n<p>And you should handle error cases, <code>null</code> as input, <code>Hello World!</code> as input, such stuff. Would be a great exercise for writing unittests.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-17T10:57:52.423",
"Id": "242454",
"ParentId": "242450",
"Score": "5"
}
},
{
"body": "<p>In this case, I think that you can simplify the algorithm quite a bit. The compound numbers are simply the left value subtracted from the right value. This can easily be calculated on the fly. This cuts down the <code>HashMap</code> to only 7 entries and eliminates the <code>edge</code>variable. Basically it could look like this:</p>\n\n<pre><code>final Map<Character,Integer> values = Map.of(\n 'I',1,\n 'V',5,\n 'X',10,\n 'L',50,\n 'C',100,\n 'D',500,\n 'M',1000\n);\n\npublic int romanToInt(String input){ \n int retVal = 0;\n int limit = input.length();\n int prevVal = 0;\n int nextVal = 0;\n for(int i = limit - 1;i >= 0; --i){\n char nextChar = input.charAt(i);\n prevVal = nextVal;\n nextVal = values.get(nextChar);\n if(nextVal < prevVal){\n retVal -= nextVal;\n }else{\n retVal += nextVal;\n }\n }\n return retVal;\n}\n</code></pre>\n\n<p>Ideally there would be validation checking required , however in this instance, the input is guaranteed to be valid.</p>\n\n<p>Since there is only one loop and the <code>Map</code> lookup should be O(1). The complexity for this should be O(n) the length of the string.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-18T14:41:45.187",
"Id": "475909",
"Score": "1",
"body": "Yuo could also change from `Map` to a `switch` statement on `char` to prevent autoboxing (twice)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-18T16:00:46.027",
"Id": "475920",
"Score": "1",
"body": "Wouldn't that change the complexity for each lookup from O(1) to O(n), since the switch is linear?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-18T19:33:11.740",
"Id": "475941",
"Score": "1",
"body": "I think this switch ends up as a table switch a lookup O(1), not a lookup O (log n)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-18T19:34:23.247",
"Id": "475942",
"Score": "1",
"body": "See here: https://stackoverflow.com/a/12938176/461499"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-18T00:11:33.117",
"Id": "242492",
"ParentId": "242450",
"Score": "2"
}
},
{
"body": "<p>By simply using an ordered map, you could arrange your keys in highest-to-lowest order, so that you can simply find the first matching prefix and take the sum from there. This way, you only need to loop over the string once.</p>\n\n<p>The only secret is, that you have to be aware of java base data structures, in this case a LinkedHashMap which guarantees unmodified key order.</p>\n\n<p>Working example:</p>\n\n<pre><code>// BTW: DON'T create a subclass just to init a map.\nprivate static LinkedHashMap<String, Integer> romanSegmentToInt = new LinkedHashMap<>();\nstatic {\n romanSegmentToInt.put(\"M\", 1000);\n romanSegmentToInt.put(\"CM\", 900);\n romanSegmentToInt.put(\"D\", 500);\n romanSegmentToInt.put(\"CD\", 400);\n romanSegmentToInt.put(\"C\", 100);\n romanSegmentToInt.put(\"XC\", 90);\n romanSegmentToInt.put(\"L\", 50);\n romanSegmentToInt.put(\"XL\", 40);\n romanSegmentToInt.put(\"X\", 10);\n romanSegmentToInt.put(\"IX\", 9);\n romanSegmentToInt.put(\"V\", 5);\n romanSegmentToInt.put(\"IV\", 4);\n romanSegmentToInt.put(\"I\", 1);\n}\n\npublic static int romanToInt(String in) {\n int sum = 0;\n while (!in.isEmpty()) {\n for (Map.Entry<String, Integer> segment : romanSegmentToInt.entrySet()) {\n if (in.startsWith(segment.getKey())) {\n sum += segment.getValue();\n in = in.substring(segment.getKey().length());\n break; // continue with outer loop\n }\n }\n // add error handling, if no prefix was found -> illegal input\n }\n return sum;\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-18T05:12:28.520",
"Id": "242499",
"ParentId": "242450",
"Score": "1"
}
},
{
"body": "<p>You could also use a switch statement to prevent auto-boxing. Taking the logic from @tinstaafl's solution:</p>\n\n<pre><code>class Solution {\n\npublic int romanToInt(String input){ \n int retVal = 0;\n int limit = input.length();\n int prevVal = 0;\n int nextVal = 0;\n for(int i = limit - 1;i >= 0; --i){\n char nextChar = input.charAt(i);\n prevVal = nextVal;\n switch(nextChar)\n {\n case 'I':\n nextVal = 1;\n break;\n case 'V':\n nextVal = 5;\n break;\n case 'X':\n nextVal = 10;\n break;\n case 'L':\n nextVal = 50;\n break;\n case 'C':\n nextVal = 100;\n break;\n case 'D':\n nextVal = 500;\n break;\n case 'M':\n nextVal = 1000;\n break;\n default:\n throw new RuntimeException(\"No valid input\");\n }\n if(nextVal < prevVal){\n retVal -= nextVal;\n }else{\n retVal += nextVal;\n }\n }\n return retVal;\n}\n}\n</code></pre>\n\n<p>For those who are interested, Java generates a nice tableswitch ( with O(1) complexity) from this:</p>\n\n<pre><code>ILOAD 6\nTABLESWITCH\n 67: L10\n 68: L11\n 69: L12\n 70: L12\n 71: L12\n 72: L12\n 73: L13\n 74: L12\n 75: L12\n 76: L14\n 77: L15\n 78: L12\n 79: L12\n 80: L12\n 81: L12\n 82: L12\n 83: L12\n 84: L12\n 85: L12\n 86: L16\n 87: L12\n 88: L17\n default: L12\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-18T14:46:09.790",
"Id": "242517",
"ParentId": "242450",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-17T10:10:56.693",
"Id": "242450",
"Score": "5",
"Tags": [
"java",
"performance",
"programming-challenge",
"complexity"
],
"Title": "LeetCode: Roman to Integer in Java"
}
|
242450
|
<p>I wrote rock paper scissors game using what I have learnt yet.It is while,for statements,list,tuple,dictionary and such simple things only.So I am interested how can I simplify this code using only what I have learnt(simple things)</p>
<p>Here is code</p>
<pre><code> k = input("Hello guys what are you names: ")
j = input("and yours? ")
print(f"""ok {k} and {j} let the game begin!"
P.s. Type exit to quit game""")
list = ["rock","paper","scissors"]
while True:
a_player = input(f"{k} choose: rock, scissors, paper : ").lower()
if a_player == "exit":
break
b_player = input(f"{j} choose: rock, scissors, paper: ").lower()
if b_player == "exit":
break
for type in list:
if a_player == type and b_player==type:
print(" Draw guys, draw")
break
if b_player != list[1] and b_player!=list[0] and b_player!=list[2] or (a_player != list[1] and a_player != list[0] and a_player != list[2]) :
print("Please type correctly")
if a_player == list[1]:
if b_player == list[0]:
print(f" {k} wins: paper beats rock")
elif b_player ==list[2] :
print(f"{j} wins: scissors beat paper")
elif a_player == list[2]:
if b_player == list[0]:
print(f"{j} wins: rock beats scissors")
elif b_player == list[1]:
print(f"{k} wins: scissors beat paper")
elif a_player == list[0]:
if b_player == list[2]:
print(f"{k} wins: rock beats scissors")
elif b_player==list[1]:
print(f"{j} wins: paper beats rock")
</code></pre>
|
[] |
[
{
"body": "<p>I'm new to this community, but I'll give this my best shot:</p>\n\n<p>Avoid single letter variable names. Names like <code>k</code> and <code>j</code> convey little about what values they represent, so replace them with something like:</p>\n\n<pre><code>a_player_name = input(\"Hello guys what are you names: \")\nb_player_name = input(\"and yours? \")\n</code></pre>\n\n<p>This code:</p>\n\n<pre><code>a_player = input(f\"{k} choose: rock, scissors, paper : \").lower()\n</code></pre>\n\n<p>creates the need to catch errors down the line and is repeated so I recommend replacing it with:</p>\n\n<pre><code> def input_choices(string):\n while True:\n choice = input(string)\n if choice.lower() in list:\n return choice\n else:\n print('Please type correctly')\n\na_player = input_choices(f\"{k} choose: rock, scissors, paper : \")\n</code></pre>\n\n<p>This avoids the need for:</p>\n\n<pre><code> if b_player != list[1] and b_player!=list[0] and b_player!=list[2] or (a_player != list[1] and a_player != list[0] and a_player != list[2]) :\n print(\"Please type correctly\")\n</code></pre>\n\n<p>Which I hope you agree is a vast improvement. Remember you can always format conditionals like this to improve readablity:</p>\n\n<pre><code>if (\n b_player != list[0] and b_player != list[1] and b_player != list[2]\n or a_player != list[1] and a_player != list[0] and a_player != list[2]\n):\n print(\"Please type correctly\")\n</code></pre>\n\n<p>Or even better use the <code>in</code> keyword</p>\n\n<pre><code>if (\n a_player not in list\n or b_player not in list\n):\n print(\"Please type correctly\")\n</code></pre>\n\n<p>As for the actual rock-paper-scissors logic:</p>\n\n<pre><code> if a_player == list[1]:\n if b_player == list[0]:\n print(f\" {k} wins: paper beats rock\")\n elif b_player ==list[2] :\n print(f\"{j} wins: scissors beat paper\")\n\n elif a_player == list[2]:\n if b_player == list[0]:\n print(f\"{j} wins: rock beats scissors\")\n elif b_player == list[1]:\n print(f\"{k} wins: scissors beat paper\")\n\n elif a_player == list[0]:\n if b_player == list[2]:\n print(f\"{k} wins: rock beats scissors\")\n elif b_player==list[1]:\n print(f\"{j} wins: paper beats rock\")\n</code></pre>\n\n<p>I'm sure this can be improved with table-driven logic, but I'm sure there's no end of examples for you to skim through in the 'Related' tab.</p>\n\n<p>Hope that helped :)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-17T11:53:14.030",
"Id": "475793",
"Score": "0",
"body": "Thanks a lot for your advises"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-17T11:28:50.937",
"Id": "242456",
"ParentId": "242452",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "242456",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-17T10:22:45.660",
"Id": "242452",
"Score": "1",
"Tags": [
"python"
],
"Title": "rock paper scissors game simplify in Python"
}
|
242452
|
<p>I am new to programming and I have tried to recreate below lines into OOP's code. Please review and provide comments.</p>
<p><strong>House has Rooms.Rooms are drawing room, bed room, bathroom etc.Each room has walls, ceiling,floor. Each room have different objects in it like drawing room has sofa, table , TV etc. , bedroom has TV etc.</strong></p>
<pre><code>//House class
import java.util.List;
public class House{
private List<Room> rooms;
public House(List<Room> rooms){
this.rooms = rooms;
}
public void getHouseDetails(){
System.out.println("The House has "+this.rooms.size()+" room");
System.out.println("-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*");
for(Room room:rooms){
room.getRoomDetails();
System.out.println("-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*");
}
}
}
//Room class
import java.util.List;
public class Room{
private List<Wall> walls;
private Ceiling ceiling;
private Floor floor;
public Room(List<Wall> walls,Ceiling ceiling,Floor floor){
this.walls = walls;
this.ceiling = ceiling;
this.floor = floor;
}
public List<Wall> getWalls(){
return this.walls;
}
public Ceiling getCeiling(){
return this.ceiling;
}
public Floor getFloor(){
return this.floor;
}
public void getRoomDetails(){
}
}
//Wall class
public class Wall{
private String type;
private String color;
public Wall(String type, String color){
this.type = type;
this.color = color;
}
public void getWallDetails(){
System.out.println("Wall is made up of "+this.type+" and is of "+this.color+" color");
}
}
//Ceiling class
public class Ceiling{
private String make;
private String color;
public Ceiling(String make,String color){
this.make = make;
this.color = color;
}
public void getCeilingDetails(){
System.out.println("Ceiling is made up of "+this.make+" and is of "+this.color+" color");
}
}
//Floor class
public class Floor{
private String make;
public Floor(String make){
this.make = make;
}
public void getFloorDetails(){
System.out.println("Floor is made up of "+this.make);
}
}
//Sofa class
public class Sofa{
private String type;
private int number;
public Sofa(String type,int number){
this.type = type;
this.number = number;
}
public void getSofaDetails(){
System.out.println("There is "+this.number+" Sofa which are "+this.type+" type");
}
}
//Chair class
public class Chair{
private String type;
private int number;
public Chair(String type,int number){
this.type = type;
this.number = number;
}
public void getChairDetails(){
System.out.println("There is "+this.number+" chair which are "+this.type+" type");
}
}
//TV class
public class TV{
private String type;
private String make;
private int number;
public TV(String type,String make,int number){
this.type = type;
this.make = make;
this.number = number;
}
public void getTVDetails(){
System.out.println("There is "+this.number+" TV which is "+this.type+" type ,manufactured by "+this.make);
}
}
//Table class
public class Table{
private String type;
private int number;
public Table(String type,int number){
this.type = type;
this.number = number;
}
public void getTableDetails(){
System.out.println("There is "+this.number+" Table which is of "+this.type);
}
}
//Drawing Room class
import java.util.List;
public class DrawingRoom extends Room{
private Sofa sofa;
private Chair chair;
private TV tv;
private Table table;
public DrawingRoom(List<Wall> walls,Ceiling ceiling,Floor floor,Sofa sofa,Chair chair,TV tv,Table table){
super(walls,ceiling,floor);
this.sofa = sofa;
this.chair = chair;
this.tv = tv;
this.table = table;
}
@Override
public void getRoomDetails(){
System.out.println(this.getClass().getSimpleName());
getWalls().get(getWalls().size()-1).getWallDetails();
getCeiling().getCeilingDetails();
getFloor().getFloorDetails();
this.sofa.getSofaDetails();
this.chair.getChairDetails();
this.tv.getTVDetails();
this.table.getTableDetails();
}
}
//Bed Room class
import java.util.List;
public class BedRoom extends Room{
private TV tv;
public BedRoom(List<Wall> walls,Ceiling ceiling,Floor floor,TV tv){
super(walls,ceiling,floor);
this.tv = tv;
}
@Override
public void getRoomDetails(){
System.out.println(this.getClass().getSimpleName());
getWalls().get(getWalls().size()-1).getWallDetails();
getCeiling().getCeilingDetails();
getFloor().getFloorDetails();
this.tv.getTVDetails();
}
}
//Bath Room class
import java.util.List;
public class BathRoom extends Room{
private TV tv;
public BathRoom(List<Wall> walls,Ceiling ceiling,Floor floor){
super(walls,ceiling,floor);
}
@Override
public void getRoomDetails(){
System.out.println(this.getClass().getSimpleName());
getWalls().get(getWalls().size()-1).getWallDetails();
getCeiling().getCeilingDetails();
getFloor().getFloorDetails();
}
}
//Main class
import java.util.List;
import java.util.ArrayList;
public class HouseTest{
public static void main(String [] args){
List<Wall> wall = new ArrayList<Wall>();
List<Room> room = new ArrayList<Room>();
wall.add(new Wall("Cement","Yellow"));
room.add(new DrawingRoom(wall,new Ceiling("Cement","Purple"),new Floor("Marble"),new Sofa("Leather",4),new Chair("Wooden",2),new TV("LED Plasma","Samsung",1),new Table("Glass",1)));
room.add(new BedRoom(wall,new Ceiling("Cement","Purple"),new Floor("Marble"),new TV("LED Plasma","Samsung",1)));
room.add(new BathRoom(wall,new Ceiling("Cement","Purple"),new Floor("Marble")));
House house = new House(room);
house.getHouseDetails();
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-17T12:43:06.507",
"Id": "475802",
"Score": "1",
"body": "It depends on what you're trying to model. I think a class for each type of furniture is possibly too deep. Assuming you're creating a room layout, I'd probably create a Furniture class that stores the size of the furniture piece and has a furniture type variable. That way, you can more easily add furniture types."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-17T13:57:31.043",
"Id": "475813",
"Score": "0",
"body": "Are you suggesting this ->\n\nprivate Furniture furniture;\n\n//Furniture class\n\npublic class Furniture{\n private String sofaType;\n private String chairType;\n private String tableType;\n private int numOfSofa;\n private int numOfChair;\n private int numOfTable;\n}"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-17T15:25:18.970",
"Id": "475825",
"Score": "0",
"body": "No, that's not a good class either. Count the number of instances of Furniture where type equals sofa. Count the number of instances of Furniture where type equals chair. And o on."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-18T06:22:38.250",
"Id": "475858",
"Score": "1",
"body": "Could you give me the purpose of your Code - what do you want to achive with this Code?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-18T10:09:55.510",
"Id": "475884",
"Score": "3",
"body": "Classes are usually created as a common denominator for things *that have something in common*. A room is a class, but a bedroom, bathroom, living room, etc. *are not*. They are *instances* of a room class. And this approach has the big advantage, that it does not limit the world to some artifical constraints. And now, I'll take my TV to the bathroom and watch some shows in the bathtub. (Excellent blog about this: https://ericlippert.com/2015/04/27/wizards-and-warriors-part-one/)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-20T09:32:26.773",
"Id": "476111",
"Score": "0",
"body": "@mtj excellent blog, and that points exactly to my question *\"what's the purpose\"* thank you for sharing this link!!!"
}
] |
[
{
"body": "<p>What you want is a <code>Furniture</code> class:</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>public abstract class AbstractFurniture {\n protected String color;\n protected String make;\n protected String type;\n\n protected AbstractFurniture(String type, String make, String color) {\n super();\n\n this.type = type;\n this.make = make;\n this.color = color;\n }\n\n // Getters go here.\n // toString with getClass().getSimpleName() goes here.\n}\n</code></pre>\n\n<p>From that, you can derive your other classes:</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>public class Sofa extends AbstractFurniture { ... }\npublic class Tv extends AbstractFurniture { ... }\npublic class Chair extends AbstractFurniture { ... }\n// ...\n</code></pre>\n\n<p>You might want to have a <code>Room</code> interface which is implemented by <code>AbstractRoom</code>, though.</p>\n\n<p>That will allow you to manage furniture as furniture, and not as a collection of TVs, chairs, etc..</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>public abstract class AbstractRoom {\n // ...\n protected List<AbstractFurniture> furniture = null;\n\n protected AbstractRoom(Wall wall, Ceiling ceiling, Floor floor, AbstractFurniture... furniture) {\n super();\n\n // ...\n // TODO Check furniture for null first.\n this.furniture = Arrays.asList(furniture);\n }\n}\n</code></pre>\n\n<p>Which will allow you to write code like:</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>AbstractRoom room = new Bedroom(\n someWall,\n someCeiling,\n someFloor,\n smallTv,\n bigBed,\n smallSofa,\n someChair,\n someChair);\n\n</code></pre>\n\n<p>The abstract classes also allow you to have code like the rendering of the room in the abstract base class, so you don't need to duplicate it.</p>\n\n<hr>\n\n<p>Consider whether your classes need to be immutable, and if they don't need to, you can use a fluent API to make it easier to use instead.</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>House house = new House()\n .addRoom(bedRoom)\n .addRoom(livingRoom)\n .addRoom(drawingRoom);\n</code></pre>\n\n<hr>\n\n<p><code>getHouseDetails</code> and <code>getRoomDetails</code> are bad names, as they actually don't get anything, but instead write to stdout.</p>\n\n<hr>\n\n<p>If you want to get <em>extra</em> fancy, <code>Room</code>s and <code>House</code> are only data holders, and you have a separate <code>HouseRenderer</code>:</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>public interface HouseRenderer {\n public void renderHouse(House house);\n}\n\npublic class StdOutStringRenderer implements HouseRenderer {\n @Override\n public void renderHouse(House house) {\n // Code goes here.\n }\n}\n</code></pre>\n\n<p>That would allow you to separate data from presentation, which is always a good idea.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-18T09:38:29.037",
"Id": "475880",
"Score": "1",
"body": "Class structure for furniture will not work. In general, representing real world as a class hierarchy never works because the world is much too complex (how about a TV with integrated DVD-player or a pull-out sofa?) You need a simple Furniture class that has a configurable list of capabilities."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-18T10:16:39.450",
"Id": "475885",
"Score": "1",
"body": "... and whenever you introduce a restriction in a subclass, you break the Liskov substition principle."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-18T16:12:46.413",
"Id": "475922",
"Score": "0",
"body": "Here it will work fine. Of course something like an Entity/Component system might be better suited, but that's absolute overkill for this description/exercise...and does nothing for OP to learn a little more OOP."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-18T16:13:59.383",
"Id": "475923",
"Score": "0",
"body": "But feel free to whip up your won solutions based on an ECS, I haven't really worked with one so far, so I'm always curios to see examples."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-29T06:30:01.097",
"Id": "477083",
"Score": "0",
"body": "Thank you everyone for pitching in and giving me link to useful blogs and sharing their version of my problem. I am trying to solidify my understanding in OOPs before I move to other concepts. This is my 10th try in Java, wonder why I was never able to join the concept pieces together. WIsh me luck."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-17T17:28:28.910",
"Id": "242471",
"ParentId": "242457",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-17T11:31:24.190",
"Id": "242457",
"Score": "2",
"Tags": [
"java",
"object-oriented"
],
"Title": "Constructing House using OOP"
}
|
242457
|
<p>So this is the code I wrote for hangman in python. I want to know of can shorten this code more further and make it look more professional</p>
<pre><code># importing random function
import random, hanged
from word_meaning import meanings
# Dictionary of random words
word_dict = '''whistle,
park,
picayune,
attach,
grubby,
gusty,
neck,
necessary,
day,
compete,
memory,
interfere,
sophisticated,
lumpy,
spiky,
frail'''.split(',\n')
# System chooses a random word
rand_word = word_dict[random.randint(0, len(word_dict)-1)]
print('Welcome to HANGMAN.\nGuess correct letters to complete the hidden word, Else hangman will be Hanged')
n = len(rand_word)
hidden_word = ((n-1)*'*')
hidden_word_1 = hidden_word.split('*')
print(f'Hidden Word: {hidden_word}*')
print(f'Hint: {meanings[str(rand_word)]}')
#This is the dictionary imported from another file. it gives the meaning of the hidden word as a hint
chances = 10
def user_lose():
global chances
print(f'Oops wrong guess\n Chances Left : {chances - 1}')
if chances > 1:
chances -= 1
user_guess()
else:
hanged.hangman()
#hanged.Hangman() this is the function which shows pic of hangman. imported from another file
def user_guess():
global chances
if '' in hidden_word_1:
user_input = str(input('\nGuess a letter: ')[0]).lower()
if user_input in rand_word:
if user_input in hidden_word_1:
user_lose()
else:
if chances > 0:
letter_index = rand_word.index(user_input)
letter_index_r = rand_word.rindex(user_input)
hidden_word_1[letter_index] = user_input
hidden_word_1[letter_index_r] = user_input
print(hidden_word_1)
user_guess()
else:
user_lose()
else:
print('Hurrah, You saved Hangman')
user_guess()
</code></pre>
<p>hanged.py file</p>
<pre><code>def hangman():
print('''You could not save hangman\n
-------------------
| |
| |
| |
| ( ` ` )
| |
| /|\\
| / | \\
| |
| / \\
| / \\
|
|
|
| ''')
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-17T12:40:30.497",
"Id": "475801",
"Score": "3",
"body": "Can you add the hanged include file, so that others can reproduce your code ?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-17T13:13:43.927",
"Id": "475807",
"Score": "1",
"body": "Oh, that might have occurred when I paste the code. I've run the code, It worked all fine."
}
] |
[
{
"body": "<p>Firstly, dictionaries are a class within python so <code>word_dict</code>, will cause confusion down the line, so instead use a different variable name eg. <code>word_list</code>.</p>\n\n<p>Whilst this code is correct:</p>\n\n<pre><code>rand_word = word_dict[random.randint(0, len(word_dict)-1)]\n</code></pre>\n\n<p>A more readable version uses <code>random.choice</code>, which return a random element from a non-empty sequence:</p>\n\n<pre><code>rand_word = random.choice(word_dict)\n</code></pre>\n\n<p>Try to keep lines to a maximum of ~80 chars and split this: </p>\n\n<pre><code>print('Welcome to HANGMAN.\\nGuess correct letters to complete the hidden word, Else hangman will be Hanged')\n</code></pre>\n\n<p>Into:</p>\n\n<pre><code>print(\"Welcome to HANGMAN.\")\nprint(\"Guess the correct letters to complete the hidden word, \"\n \"Else hangman will be Hanged\")\n</code></pre>\n\n<p>NITPICK: Whitespace around operators is nicer, eg. <code>((n-1)*'*')</code> turns into <code>((n - 1) * '*')</code></p>\n\n<p>Your variables:</p>\n\n<pre><code>n = len(rand_word)\nhidden_word = ((n - 1) * '*')\nhidden_word_1 = hidden_word.split('*')\n</code></pre>\n\n<p>Are not descriptive and as a result you've even forgot to remove <code>n</code> as a variable. Your method for generating <code>hidden_word_1</code> is convoluted, use this instead:</p>\n\n<pre><code>hidden_word_list = ['' for i in rand_word]\n</code></pre>\n\n<p>Perhaps also change the function name <code>user_lose</code> to the more descriptive <code>wrong_guess</code>. </p>\n\n<p>There's places where tail recursion fits, but I don't think <code>user_guess</code> works effectively with it. Tail recursion adds far more complexity for debugging than it adds to the effectiveness of the program, especially considering that there is no advantage over say looping with <code>while chance > 0:</code>.</p>\n\n<p>To make tail recursion practical I recommend modifying your code to fit this pseudocode:</p>\n\n<pre><code>def hangman(target_word, user_guess, chances=10):\n if target_word == user_guess:\n print('You saved hangman')\n elif chances < 0:\n print('hangman died')\n return\n\n print(\"'So far you've guessed:\", user_guess)\n user_input = str('eee'[0]).lower()\n # add use_input into user_guess based on target_word\n # Eg. target_word='random', user_guess='______', user_input='a'\n # turns into:\n # target_word='random', user_guess='_a____',\n # Eg. target_word='random', user_guess='_a____', user_input='n'\n # turns into:\n # target_word='random', user_guess='_an___',\n\n # If bad guess, then print(bad luck) ect.\n hangman(target_word, user_guess, chances=(chances - 1))\n\n\n# code to generate these params\nhangman('complete word', '________ ____')\ninput('Guess a letter: ')\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-17T14:26:15.690",
"Id": "475816",
"Score": "0",
"body": "That was a great help from you. Thank you very much."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-17T14:12:14.577",
"Id": "242462",
"ParentId": "242458",
"Score": "1"
}
},
{
"body": "<p>I don't have <code>word_meaning</code>, is that another dependency ?</p>\n\n<p>Since you are already using the <code>random</code> module, you can simply select a random element from a list with <a href=\"https://docs.python.org/3/library/random.html#random.choice\" rel=\"nofollow noreferrer\">random.choice</a> like this:</p>\n\n<pre><code>rand_word = random.choice(word_dict)\n</code></pre>\n\n<p>instead of:</p>\n\n<pre><code>rand_word = word_dict[random.randint(0, len(word_dict)-1)]\n</code></pre>\n\n<p>Here you are picking only one element at a time, but if you wanted to select several <strong>unique</strong> elements (no repeating items) then you would use <a href=\"https://docs.python.org/3/library/random.html#random.sample\" rel=\"nofollow noreferrer\">random.sample</a>.</p>\n\n<hr>\n\n<p>Your list of words is a constant, make it so:</p>\n\n<pre><code>word_dict = (\n'attach', 'compete', 'day', 'frail', 'grubby', 'gusty', 'interfere', 'lumpy', 'memory',\n'necessary', 'neck', 'park', 'picayune', 'sophisticated', 'spiky', 'whistle'\n)\n</code></pre>\n\n<p>(did a simple search & replace in Notepad++). NB: I have sorted it too.</p>\n\n<p>The way you are <code>split</code>ting the string is awkward and the comma delimiter is superfluous. This design choice forces you to waste one line per word and makes the code longer for no benefit.</p>\n\n<p>Note that I made it a <strong>tuple</strong> (non mutable) instead of a list, hence the parentheses.</p>\n\n<p>You could also load the list from a text file, if you want flexibility and separate data from code.</p>\n\n<hr>\n\n<p>It is not safe to rely on <code>\\n</code> as a line break delimiter because it is platform-specific. On Windows/Mac it is different although Python <em>should</em> still interpret it the same. But you never know. Think about portability issues.</p>\n\n<p>Relying on <strong>global variables</strong> is probably not so Pythonic. You could pass <code>chances</code> as a <strong>parameter</strong> to your functions. And if you make changes to that value, then return the value in your functions.</p>\n\n<p>Using a global variable could make debugging harder because the variable can be altered in so many places. If you refactor your functions at some point the variable could even be out of sync.</p>\n\n<hr>\n\n<p>I would aim for <strong>minimal variable scope</strong>. If <code>hidden_word_1</code> (not a great name) is only used in <code>user_guess</code> then it need no be defined as a global variable.</p>\n\n<hr>\n\n<p>I cannot run your code right now but I am not convinced you need a recursive function. You simply need a while loop eg <code>while chances > 0:</code> and decrement the counter after each wrong response.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-17T15:05:27.803",
"Id": "242465",
"ParentId": "242458",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "242465",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-17T11:35:51.730",
"Id": "242458",
"Score": "4",
"Tags": [
"python",
"python-3.x",
"hangman"
],
"Title": "hangman with ten chances"
}
|
242458
|
<p>I've started learning JavaScript last week. Today I ran into a JS exercise available at this link
<a href="https://www.codewars.com/kata/5782dd86202c0e43410001f6" rel="nofollow noreferrer">codewars exercise</a> and decided to give it a try. I've used very basic JS because I know only a small number of JS methods. Could you please review and rate my code? </p>
<p>challenge text :</p>
<blockquote>
<p>Your task is to write a function named <code>do_math</code> that receives a single argument. This argument is a string that contains multiple whitespace delimited numbers. Each number has a single alphabet letter somewhere within it. </p>
<blockquote>
<p>Example : "24z6 1x23 y369 89a 900b" </p>
</blockquote>
<p>As shown above, this alphabet letter can appear anywhere within the number. You have to extract the letters and sort the numbers according to their corresponding letters.</p>
<blockquote>
<p>Example : "24z6 1x23 y369 89a 900b" will become 89 900 123 369 246 (ordered according to the alphabet letter)</p>
</blockquote>
<p>Here comes the difficult part, now you have to do a series of computations on the numbers you have extracted.</p>
<ul>
<li>The sequence of computations are <code>+ - * /</code>. Basic math rules do <strong>NOT</strong> apply, you have to do each computation in exactly this order. </li>
<li>This has to work for any size of numbers sent in (after division, go back to addition, etc).</li>
<li>In the case of duplicate alphabet letters, you have to arrange them according to the number that appeared first in the input string.</li>
<li>Remember to also round the final answer to the nearest integer.</li>
</ul>
<blockquote>
<p>Examples :<br>
"24z6 1x23 y369 89a 900b" = 89 + 900 - 123 * 369 / 246 = 1299<br>
"24z6 1z23 y369 89z 900b" = 900 + 369 - 246 * 123 / 89 = 1414<br>
"10a 90x 14b 78u 45a 7b 34y" = 10 + 45 - 14 * 7 / 78 + 90 - 34 = 60 </p>
</blockquote>
</blockquote>
<p>my code : </p>
<pre><code>var inputStr, inputsArray, numsArray, arrayStrNumber, isAdd, isSub, isMul, isDiv;
numsArray = [];
strArray = [];
arrayStrNumber = [];
inputStr = "10a 90x 14b 78u 45a 7b 34y";
isAdd = true;
isSub = true;
isMul = true;
isDiv = true;
// create array from strings
inputsArray = inputStr.split(" ");
// loop in array
for (var i = 0; i < inputsArray.length; i++) {
var inputValue = inputsArray[i];
// seperate numbers from alphabet
for (x = 0; x < inputValue.length; x++) {
// if it's not a number add it to string's array
if (isNaN(inputValue[x])) {
strArray[i] = inputValue[x];
} else {
isNaN(numsArray[i])
? (numsArray[i] = "" + inputValue[x] + "")
: (numsArray[i] += "" + inputValue[x] + "");
}
}
//create an array with letter on start
arrayStrNumber[i] = strArray[i] + numsArray[i];
}
// sort array based on first alphabet or first number after alphabet
arrayStrNumber.sort(function (a, b) {
if (a[0] != b[0]) {
if (a > b) {
return 1;
}
if (b > a) {
return -1;
}
return 0;
} else {
if (arrayStrNumber.indexOf(a) > arrayStrNumber.indexOf(b)) {
return 1;
}
if (arrayStrNumber.indexOf(b) > arrayStrNumber.indexOf(a)) {
return -1;
}
return 0;
}
});
console.log(arrayStrNumber);
// Do math operation with order +-*/
var finalResult = 0;
for (var i = 0; i < arrayStrNumber.length; i++) {
arrayStrNumber[i] = parseInt(arrayStrNumber[i].slice(1));
if (i === 0) {
finalResult += arrayStrNumber[i];
continue;
}
if (isAdd) {
finalResult += arrayStrNumber[i];
isAdd = false;
continue;
}
if (isSub) {
finalResult -= arrayStrNumber[i];
isSub = false;
continue;
}
if (isMul) {
finalResult *= arrayStrNumber[i];
isMul = false;
continue;
}
if (isDiv) {
finalResult /= arrayStrNumber[i];
}
isAdd = true;
isSub = true;
isMul = true;
isDiv = true;
finalResult = Math.round(finalResult);
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-17T14:53:25.570",
"Id": "475820",
"Score": "1",
"body": "Please copy the contents of the programming challenge into the question, as well as providing the link, links can break."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-17T15:27:04.953",
"Id": "475826",
"Score": "0",
"body": "Challenge text added to the question. Thanks for the tip"
}
] |
[
{
"body": "<p>When writing maintainable code, I'd recommend to declare variables in <em>narrow</em> scopes, if possible. If you do something like:</p>\n\n<pre><code>var inputStr, inputsArray, numsArray, arrayStrNumber, isAdd, isSub, isMul, isDiv;\n</code></pre>\n\n<p>at the very beginning, then on every line throughout the rest of the program, you'll have to keep in mind the possible values for all of those variables. If the script is long, this can be a problem. Consider encapsulating related functionality into separate functions instead - for example, you could turn the input into an array in one function, sort it in another, and then finally iterate through it to produce the result in a third. That way, for example, <code>inputStr</code> will <em>only</em> be visible to the first function (as an argument), and neither of the first two functions will have <code>isAdd</code> etc visible to them. Separating functionality into smaller self-contained sections makes code a lot more readable.</p>\n\n<p>Since it's 2020, it would be nice to write source code in modern syntax - <em>at least</em> in ES2015. Modern syntax generally makes code more concise, easier to read, and less buggy. (I'll be using modern syntax in suggestions below.)</p>\n\n<p>Consider always using strict mode - you have some variables that you never declare (<code>strArray</code> and <code>x</code>), which means that they get implicitly assigned to the global object. This is an easy source of bugs, not to mention inelegant; strict mode will throw an error when this sort of thing happens, allowing you to fix it on sight.</p>\n\n<p>When you have to iterate over an array or a string, it's nice to be able to immediately work with <em>each item</em> being iterated over immediately, rather than having to mess with indicies. Both strings and arrays have iterators (which iterate over either each character, or each array item), so you can do this concisely with <code>for..of</code>. For example:</p>\n\n<pre><code>for (let i = 0; i < inputsArray.length; i++) {\n const inputValue = inputsArray[i];\n</code></pre>\n\n<p>can be replaced with</p>\n\n<pre><code>for (const inputValue of inputsArray) {\n</code></pre>\n\n<p>You do</p>\n\n<pre><code>isNaN(numsArray[i]) ?\n (numsArray[i] = \"\" + inputValue[x] + \"\") :\n (numsArray[i] += \"\" + inputValue[x] + \"\");\n</code></pre>\n\n<p>The conditional operator should only be used when you need an <em>expression</em> which is identified conditionally, like <code>console.log(cond ? '1' : '2')</code>. If the expression that results from using the conditional operator isn't being used, like in your code, it would be more readable to remove it and use <code>if</code>/<code>else</code> instead. (It's fine for <em>minifiers</em> to do that, but minified code isn't intended to be read - source code that developers write <em>should</em> be as readable as possible). There's even <a href=\"https://eslint.org/docs/rules/no-unused-expressions\" rel=\"nofollow noreferrer\">a linting rule</a> to help you automatically identify and fix this sort of thing.</p>\n\n<p>So, you have a string which is composed of numbers, plus one letter somewhere inside it, and you need to separate them. If you want to do this concisely, you might consider using <code>replace</code> to replace the letter character with the empty string, and use a callback to assign the matched value (the letter) to an outer variable, like this:</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>function separateWord(word) {\n let char;\n const num = Number(\n word.replace(\n /[a-z]/i,\n match => {\n char = match;\n return ''; // replace this match with the empty string\n }\n )\n );\n return { char, num };\n}\nconsole.log(separateWord('123b456'));</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p>On a broader scale, using the above function, I think the first section of the code which turns each word into a sorted array would be easier to manage if you used an <em>object</em> indexed by character instead, whose values are arrays of numbers. Eg, for the above <code>123b456</code>, that would result in the following object:</p>\n\n<pre><code>{\n b: [123456]\n}\n</code></pre>\n\n<p>Iterate over each word, pushing to an array on the object, creating it first if necessary. Then, the object properties can be arranged lexiographically by sorting its entries (<code>Object.entries</code> returns an array of entries, where an entry is an array containing the key and the value, so just compare the keys in the <code>.sort</code>). This makes things <em>so</em> much shorter and cleaner:</p>\n\n<pre><code>function getOrderedNumbers(numbersByChar) {\n return Object.entries(numbersByChar)\n .sort((a, b) => (a[0] > b[0]) - 0.5) // Order entries alphabetically\n .map(entry => entry[1]) // Take only the value of each entry\n .flat(); // Turn the array of arrays of numbers into a single array of numbers\n}\nfunction parseString(inputStr) {\n const numbersByChar = {};\n for (const word of inputStr.split(' ')) {\n const { char, num } = separateWord(word);\n if (!numbersByChar[char]) {\n numbersByChar[char] = [];\n }\n numbersByChar[char].push(num);\n }\n const numbersArr = getOrderedNumbers(numbersByChar);\n return doMath(numbersArr);\n}\n</code></pre>\n\n<p>For the <code>doMath</code> function, keeping track of 4 separate booleans and performing 4 different <code>if</code> checks is a bit verbose for the task at hand. You might consider using an array of functions instead, and using the modulo operator to identify which function to call:</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>function doMath(numbersArr) {\n const fns = [\n (subtotal, num) => subtotal + num,\n (subtotal, num) => subtotal - num,\n (subtotal, num) => subtotal * num,\n (subtotal, num) => subtotal / num,\n ];\n // Remove first value so operation can start with + with first and second value:\n let subtotal = numbersArr.shift();\n numbersArr.forEach((num, i) => {\n subtotal = fns[i % 4](subtotal, num);\n });\n return subtotal;\n}\nconsole.log(doMath([1, 2, 4, 5])); // ((1 + 2) - 4) * 5</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p><code>reduce</code> would be more appropriate than <code>forEach</code> to transform the array of numbers into a single number, but if you're a beginner, you probably prefer the <code>forEach</code> version since it's more intuitive:</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"true\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code snippet-currently-hidden\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>function doMath(numbersArr) {\n const fns = [\n (subtotal, num) => subtotal + num,\n (subtotal, num) => subtotal - num,\n (subtotal, num) => subtotal * num,\n (subtotal, num) => subtotal / num,\n ];\n // Remove first value so operation can start with + with first and second value:\n const initialValue = numbersArr.shift();\n return numbersArr.reduce((subtotal, num, i) => fns[i % 4](subtotal, num), initialValue);\n}\nconsole.log(doMath([1, 2, 4, 5])); // ((1 + 2) - 4) * 5</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p>Put it all together:</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>'use strict';\n\nconsole.log(doMath(\"10a 90x 14b 78u 45a 7b 34y\"));\n\nfunction separateWord(word) {\n let char;\n const num = Number(\n word.replace(\n /[a-z]/i,\n match => {\n char = match;\n return ''; // replace this match with the empty string\n }\n )\n );\n return { char, num };\n}\nfunction getOrderedNumbers(numbersByChar) {\n return Object.entries(numbersByChar)\n .sort((a, b) => (a[0] > b[0]) - 0.5) // Order entries alphabetically\n .map(entry => entry[1]) // Take only the value of each entry\n .flat(); // Turn the array of arrays of numbers into a single array of numbers\n}\n// Entry point:\nfunction doMath(inputStr) {\n const numbersByChar = {};\n for (const word of inputStr.split(' ')) {\n const { char, num } = separateWord(word);\n if (!numbersByChar[char]) {\n numbersByChar[char] = [];\n }\n numbersByChar[char].push(num);\n }\n const numbersArr = getOrderedNumbers(numbersByChar);\n return getTotal(numbersArr);\n}\n\nfunction getTotal(numbersArr) {\n const fns = [\n (subtotal, num) => subtotal + num,\n (subtotal, num) => subtotal - num,\n (subtotal, num) => subtotal * num,\n (subtotal, num) => subtotal / num,\n ];\n // Remove first value so operation can start with + with first and second value:\n let subtotal = numbersArr.shift();\n numbersArr.forEach((num, i) => {\n subtotal = fns[i % 4](subtotal, num);\n });\n return Math.round(subtotal);\n}</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p>Unfortunately, the latest JS version that Codewars supports is Node 8, which is old, <a href=\"https://blog.risingstack.com/update-nodejs-8-end-of-life-no-support/\" rel=\"nofollow noreferrer\">end-of-life</a>, and probably shouldn't be used - it doesn't support <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/flat\" rel=\"nofollow noreferrer\"><code>Array.prototype.flat</code></a>. An alternative to achieve the same functionality is to spread into <code>concat</code> instead:</p>\n\n<pre><code>arr.flat()\n</code></pre>\n\n<p>can be replaced by</p>\n\n<pre><code>[].concat(...arr);\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-18T11:10:32.967",
"Id": "475888",
"Score": "0",
"body": "Honestly I didn't expect to get review at all! You surprise me with this detailed answer. Thank you very much for taking time to write this awesome instruction. I don't know much about JS because this is my second week with JS and still learning :) and will try to do better next time."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-18T00:14:15.930",
"Id": "242493",
"ParentId": "242459",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "242493",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-17T12:00:32.237",
"Id": "242459",
"Score": "3",
"Tags": [
"javascript",
"beginner",
"programming-challenge"
],
"Title": "arithmetic with numbers and letters"
}
|
242459
|
<p>I wrote a script that connects to World Bank API, gathers some data (indicators) for a number of countries, creates pd.DataFrame, and saves the result as xlsx file. </p>
<p>What I had in mind when I was writing the code:</p>
<ol>
<li>I wanted to avoid constructing pd.DataFrame within the function or using the append method to store data in-memory (not sure if it helps in this case; is it a good practice in general?).</li>
<li>I thought it was a good idea to split the code into separate functions (one that iterates over data, one that makes requests for every page that is related to the indicator, and finally, the one that iterates over all indicators and calls other functions). </li>
<li>It was the first time I used <code>yield from</code> and I'm not sure if it's the correct way of using the construct. </li>
<li>Not sure about typings.</li>
</ol>
<hr>
<pre><code>import os
import requests
import pandas as pd
from time import sleep
from itertools import chain
from datetime import datetime
from typing import List, Iterator
COUNTRIES = {
"Baltic States": ["EST", "LVA", "LTU"],
"Central Asia": ["KAZ", "KGZ", "TJK", "TKM", "UZB"],
"Eastern Europe": ["BLR", "MDA", "UKR"],
"Eurasia": ["RUS"],
"Transcaucasia": ["ARM", "AZE", "GEO"]
}
INDICATORS = {
"Infrastructure": ["EG.ELC.ACCS.RU.ZS", "IT.CEL.SETS"],
"Medicine": ["SH.DYN.MORT", "SH.DYN.AIDS.ZS"],
"Public Sector": ["GC.TAX.TOTL.GD.ZS", "MS.MIL.TOTL.TF.ZS"]
}
URL = "http://api.worldbank.org/v2/country/"
DATE = datetime.today().strftime("%Y-%m-%d %H_%M")
CURRENT_DIR = os.path.dirname(os.path.abspath(__file__))
ISO3_PARAM = ';'.join(chain(*COUNTRIES.values()))
INDICATOR_PARAM = list(chain(*INDICATORS.values()))
def mapping(s: pd.Series, metadict: dict) -> str:
""" Assign categories to Series' values according to dict's keys. """
return ' '.join((k) for k,v in metadict.items() if s in v)
def item_level(data: List) -> Iterator:
""" Iterate over data and yield dict containing specific fields. """
for item in data:
yield {
"iso3": item["countryiso3code"],
"indicator": item["indicator"]["value"],
"id": item["indicator"]["id"],
"year": item["date"],
"value": item["value"]
}
def page_level(indicator: str) -> Iterator:
""" Iterate over all pages related to specific indicator. """
base_url = f"{URL}{ISO3_PARAM}/indicator/{indicator}?format=json"
next_page = 1
while True:
meta, data = requests.get(f"{base_url}&page={next_page}").json()
yield from item_level(data)
num_pages, next_page = meta["pages"], next_page + 1
if next_page > num_pages:
break
sleep(1)
def indicator_level(indicators: List) -> Iterator:
""" Iterate over all indicators. """
for indicator in indicators:
yield from page_level(indicator)
def main():
""" Create pd.DataFrame from generator and save it. """
df = pd.DataFrame(indicator_level(INDICATOR_PARAM))
df["year"] = df["year"].astype(int)
df["region"] = df["iso3"].apply(mapping, metadict=COUNTRIES)
df["category"] = df["id"].apply(mapping, metadict=INDICATORS)
df.loc[df["year"] >= 1991].to_excel(f"{CURRENT_DIR}/../../data/raw/dataset_{DATE}.xlsx", index=False)
if __name__ == "__main__":
main()
</code></pre>
|
[] |
[
{
"body": "<p>I would turn your mappings mapping countries and indicators around. Then you can simply do:</p>\n\n<pre><code>COUNTRIES = {\"EST\": \"Baltic States\", \"LVA\": \"Baltic States\", \"LTU\": \"Baltic States\", ...}\n\ndf[\"region\"] = df[\"iso3\"].map(COUNTRIES)\ndf[\"category\"] = df[\"id\"].map(INDICATORS)\n</code></pre>\n\n<p>If you are too lazy to manually invert the dictionary, or like the current structure more but still want to have the easier usage, just use this one-line function:</p>\n\n<pre><code>def invert(d):\n return {v: k for k, values in d.items() for v in values}\n</code></pre>\n\n<hr>\n\n<p>Instead of </p>\n\n<pre><code>ISO3_PARAM = ';'.join(chain(*COUNTRIES.values()))\n</code></pre>\n\n<p>Use</p>\n\n<pre><code>ISO3_PARAM = ';'.join(chain.from_iterable(COUNTRIES.values()))\n</code></pre>\n\n<p>This does not have any memory problems (not that that is a problem here, but it is good practice in general).</p>\n\n<p>And if you follow the previous recommendation, replace <code>values</code> with <code>keys</code>.</p>\n\n<hr>\n\n<p>I would slightly simplify your <code>page_level</code> function by inlining <code>meta[\"pages\"]</code> and using the <code>params</code> argument of <code>requests.get</code> to pass the parameters</p>\n\n<pre><code>def page_level(indicator: str) -> Iterator:\n \"\"\" Iterate over all pages related to specific indicator. \"\"\"\n url = f\"{URL}{ISO3_PARAM}/indicator/{indicator}\"\n page = 1\n while True:\n meta, data = requests.get(url, params={\"format\": \"json\", \"page\": page}).json()\n yield from item_level(data)\n page += 1\n if page > meta[\"pages\"]:\n break\n sleep(1)\n</code></pre>\n\n<hr>\n\n<p>I must say that while I like that you separated things into their own function, I am not so sure about their names (I know, names are hard!). They convey only at which level a function operates, but not what it <em>does</em>.</p>\n\n<p>My suggestions for names:</p>\n\n<ul>\n<li><code>indicator_level</code> -> <code>get_dataframe</code> (and directly return the dataframe) or <code>get_data</code></li>\n<li><code>page_level</code> -> <code>get_indicator_data</code></li>\n<li><code>item_level</code> -> <code>extract_items</code></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-18T17:36:50.127",
"Id": "475927",
"Score": "0",
"body": "oh this is great! I used that structure of dict because I felt it was easier to create, surely your example makes mapping much better. With the rest I also agree, thank you! In general, I wasn't sure it was a good idea to create three functions instead of one or two? And I wasn't sure if I used yeild from correctly."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-18T18:28:30.663",
"Id": "475934",
"Score": "1",
"body": "@politicalscientist: Your use of `yield from` is perfectly fine. I was also contemplating whether to put the stuff from `indicator_level` into the `page_level`, but in the end decided that it was too much clutter and nicer in its own function."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-18T16:37:23.720",
"Id": "242522",
"ParentId": "242460",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "242522",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-17T13:09:26.337",
"Id": "242460",
"Score": "3",
"Tags": [
"python"
],
"Title": "Accessing time series development data from World Bank API"
}
|
242460
|
<p>This is one of my mini project of dice rolling and I want to improve it further with more advanced Python. Maybe you have any ideas to improve the code itself?</p>
<p>This code will ask the minimum and maximum number for the dice from the user and the number of times it will roll them, giving random numbers.</p>
<pre><code>import random
#Size choosing for dice
while True:
#Choosing the minimum number
Min = input("Please input the minimum number of your dice: ")
try:
Min = int(Min)
except ValueError:
print("Invalid input")
continue
#Choosing the maximum number
Max = input("Please input the maximum number of your dice: ")
try:
Max = int(Max)
except ValueError:
print("Invalid input")
continue
#Check if the minimum and maximum is valid
if Min > Max:
print("Minimum is bigger than Maximum.\n Please reinput data...")
continue
elif Min == Max:
print("Minimum is equaled to Maximum,\n Please reinput data...")
continue
print(f"Your dice is from {Min} to {Max}.")
break
#Random number generater
while True:
Rollcount = input("How many times do you want to roll the dice: ")
try:
Rollcount = int(Rollcount)
break
except ValueError:
print("Invalid input")
continue
for i in range(0,Rollcount):
roll = random.randint(Min,Max)
print(roll)
</code></pre>
|
[] |
[
{
"body": "<p>The easiest way to improve this code is to write a generic function that asks for user input. It should be able to handle types and a validator function and keep on asking until a valid input is given. Something like this:</p>\n\n<pre><code>def ask_user(message, type_=str, valid=lambda x: True, invalid_message=\"Invalid\"):\n while True:\n try:\n user_input = type_(input(message))\n except (ValueError, TypeError):\n print(\"Invalid input\")\n continue\n if valid(user_input):\n return user_input\n else:\n print(invalid_message)\n</code></pre>\n\n<p>With which your code becomes a lot easier:</p>\n\n<pre><code>import random\n\nmin_ = ask_user(\"Please input the minimum number of your dice: \", int)\nmax_ = ask_user(\"Please input the maximum number of your dice: \", int,\n lambda x: x > min_, \"Maximum must be larger than minimum.\")\nn = ask_user(\"How many times do you want to roll the dice: \", int)\n\nrolls = [random.randint(min_, max_) for _ in range(n)]\nfor roll in rolls:\n print(roll)\n</code></pre>\n\n<p>Note that I followed Python's official style-guide, <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">PEP8</a>, which recommends using <code>lower_case</code> for functions and variables and <code>PascalCase</code> only for classes. I avoided shadowing the built-in functions <code>min</code>, <code>max</code> and <code>type</code> by adding a trailing <code>_</code>, which is what I also used for the unused loop variable. I also used a <a href=\"https://www.pythonforbeginners.com/basics/list-comprehensions-in-python\" rel=\"nofollow noreferrer\">list comprehension</a>, so you have all the rolls already in a list in case you need them later.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-18T06:39:31.423",
"Id": "475861",
"Score": "1",
"body": "i am a total beginner and does not understand some part of the code even though it works completely fine. i just wanna ask why is the type_ equals to str instead of int. should't it be int as its a number. The 2nd question is what is the messgae in the function?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-18T06:42:14.933",
"Id": "475862",
"Score": "0",
"body": "@ShreddedPumpkin That was just the default value I chose for the type. When calling the function I always passed `int`. I could also have used `int` as the default value, but then the function should probably be called `ask_number`. However, I chose `str` so the function is more generally useful, and not only for this specific usecase. In the general case the safest choice for a type is not making a choice at all and just do what `input` does, namely return a string."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-18T06:44:11.063",
"Id": "475863",
"Score": "0",
"body": "@ShreddedPumpkin The message is what is printed when the user input does not pass the validation, i.e. in your case if the second number ist not larger than the first. One could also add another parameter for the message being printed when the type cast does not work, but I did not want to clutter the function with things not needed in your code."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-17T20:14:51.070",
"Id": "242481",
"ParentId": "242463",
"Score": "1"
}
},
{
"body": "<p>I normally would agree with <a href=\"https://codereview.stackexchange.com/a/242481\">Graipher here</a>, however with your code I think there's a simpler and more readable solution.</p>\n\n<ol>\n<li><p>The first number doesn't have to be larger than the second.</p>\n\n<p>This is an artificial limitation that can be fixed by sorting the inputted values.</p></li>\n<li><p>Not allowing the same value to be selected is an artificial limitation. <code>random.randint</code> includes both bounds, meaning <code>random.randint(n, n)</code> is valid input.</p></li>\n<li><p>You can bundle the first two try statements together to simplify the code.</p>\n\n<p>This makes the code DRY as the two loops are logically doing two different things.</p></li>\n</ol>\n\n<p>Whilst longer it keeps the functionality to change the lower bound if you enter it incorrectly, without having to kill the process.</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>import random\n\nwhile True:\n try:\n min_, max_ = sorted([\n int(input(\"Please enter one of the bounds: \"))\n int(input(\"Please enter the other bound: \"))\n ])\n break\n except ValueError:\n print(\"Invalid input\")\n\nwhile True:\n try:\n amount = int(input(\"How many times do you want to roll the dice: \"))\n break\n except ValueError:\n print(\"Invalid input\")\n\nfor _ in range(amount):\n print(random.randint(min_, max_))\n</code></pre>\n\n<p><strong>Note</strong>: You can move both the <code>while</code> <code>try</code> loops into a function, and pass a lambda, however I don't think that's as readable.</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>min_, max_ = while_try(lambda: sorted([\n int(input(\"Please enter one of the bounds: \"))\n int(input(\"Please enter the other bound: \"))\n]))\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-17T21:11:10.583",
"Id": "242485",
"ParentId": "242463",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "242481",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-17T14:35:49.810",
"Id": "242463",
"Score": "3",
"Tags": [
"python",
"dice"
],
"Title": "Dice rolling simulator, any ideas on implementing any features?"
}
|
242463
|
<p>I've implemented an algorithm that generates all variations of a matrix of size <span class="math-container">\$M*N\$</span>. My approach is that I see a matrix as a list where the position of elements can be calculated from the position in the matrix. By doing that I can reduce the problem into generating all variations of a list of length <span class="math-container">\$M*N\$</span>.</p>
<p>The algorithm computes the variations recursively. I start with an empty list and pass it to my function. The list is copied. The copied list gets a <code>0</code> and the original list gets a <code>1</code> added. Then I call the function recursively with each of both resulting lists. The process is repeated until the length <span class="math-container">\$M*N\$</span> is reached. At this point, I have the set of all variations (size = <span class="math-container">\$2^{M*N}\$</span>).</p>
<p>Now I can compute the arrays from those variations and compose the resulting matrices.</p>
<p>Here is the implementation:</p>
<pre class="lang-java prettyprint-override"><code>import java.util.ArrayDeque;
import java.util.Arrays;
import java.util.Deque;
class Main {
static void addVariations(Deque<int[]> stack, int[] variation, int index) {
if (index >= 0) {
// clone for next recursion
int[] variationClone = variation.clone();
// one gets 0, the other 1 at index
variation[index] = 0;
variationClone[index] = 1;
// next recursion
addVariations(stack, variation, index - 1);
addVariations(stack, variationClone, index - 1);
}
else {
stack.push(variation);
}
}
static Deque<int[][]> getVariations(int M, int N) {
int variationLength = M*N;
// get all variations that the matrices are base on
// there are n^r, 2^variationLength of them
Deque<int[]> variations = new ArrayDeque<>();
addVariations(variations, new int[variationLength], variationLength - 1);
// container for resulting matrices
Deque<int[][]> variationMatrices = new ArrayDeque<>();
// for each matrix
for (int i = variations.size() - 1; i >= 0 ; i--) {
int[][] matrix = new int[N][M];
int[] variation = variations.pop();
// for each row add part of variation
for (int j = 0; j < matrix.length; j++) {
matrix[j] = Arrays.copyOfRange(variation, j*M, (j + 1)*M);
}
// and push the matrix to result
variationMatrices.push(matrix);
}
return variationMatrices;
}
public static void main(String[] args) {
int N = 2, M = 2;
Deque<int[][]> variations = getVariations(N, M);
variations.forEach(v -> {
System.out.println("----");
for (int i = 0; i < v.length; i++) {
System.out.println(Arrays.toString(v[i]));
}
System.out.println("----");
});
}
}
</code></pre>
<p>I'd be very happy to get tipps on how to improve the code. I'm especially interested in <em>style and readability</em> of my code.</p>
<hr>
<p>The expected output is the set of variations. Each variation is a matrix containing only <code>0</code>s and <code>1</code>s. Each matrix is represented as a 2-dimensional array where each row is an array.</p>
<p>So e.g. the output for a <span class="math-container">\$2*2\$</span> matrix is supposed to be:</p>
<p><code>[[0, 0], [0, 0]]</code>,
<code>[[1, 0], [0, 0]]</code>,
<code>[[0, 1], [0, 0]]</code>,
<code>[[1, 1], [0, 0]]</code>,</p>
<p><code>[[0, 0], [1, 0]]</code>,
<code>[[1, 0], [1, 0]]</code>,
<code>[[0, 1], [1, 0]]</code>,
<code>[[1, 1], [1, 0]]</code>,</p>
<p><code>[[0, 0], [0, 1]]</code>,
<code>[[1, 0], [0, 1]]</code>,
<code>[[0, 1], [0, 1]]</code>,
<code>[[1, 1], [0, 1]]</code>,</p>
<p><code>[[0, 0], [1, 1]]</code>,
<code>[[1, 0], [1, 1]]</code>,
<code>[[0, 1], [1, 1]]</code>,
<code>[[1, 1], [1, 1]]</code></p>
<p>The order doesn't matter.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-17T21:51:57.237",
"Id": "475844",
"Score": "0",
"body": "Doesn't look like permutations to me. Can you add a small example of the expected output?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-18T13:50:01.433",
"Id": "475904",
"Score": "0",
"body": "@vnp Thank you, you are right, it's about variations, not permutations. I've updated the question."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-18T14:08:15.870",
"Id": "475907",
"Score": "0",
"body": "A request was made to add a small example of the expected output. Would it be possible for you to add this?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-18T14:17:30.793",
"Id": "475908",
"Score": "0",
"body": "@Mast There you go."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-18T15:54:09.887",
"Id": "475918",
"Score": "0",
"body": "How about just implementing a method that visualizes the binary representation of any integer between 0 and 2^(M*N) as a 2D array?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-18T16:05:16.170",
"Id": "475921",
"Score": "0",
"body": "@TorbenPutkonen I don't know what the difference is. This is exactly what `addVariations` already does."
}
] |
[
{
"body": "<p>The code does not produce permutations. It produces the subsets of <span class=\"math-container\">\\$M * N\\$</span>-strong set. Below assumes that <em>it</em> is the goal of the code.</p>\n\n<p>Recursive solution is correct, but may take too much memory (there are exponentially many subsets, namely <span class=\"math-container\">\\$2^{N*M}\\$</span> of them). I strongly recommend to switch to an iterative approach:</p>\n\n<pre><code> bool next_subset(int [] subset) {\n for (int i = 0; i < subset.size(); i++) {\n if subset[i] == 1) {\n subset[i] == 0;\n } else {\n subset[i] = 1;\n return true;\n }\n }\n return false;\n }\n</code></pre>\n\n<p>which takes the same time, linear memory, and can be used to stream the subsets one-by-one.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-18T13:53:07.493",
"Id": "475905",
"Score": "1",
"body": "The latest edit invalidates your answer. However, since you point out in your answer that the code didn't do what it should've been doing, perhaps it's better to simply scrap the first line of your answer instead of rolling-back the edit."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-17T22:11:00.810",
"Id": "242490",
"ParentId": "242464",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "242490",
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-17T14:51:36.677",
"Id": "242464",
"Score": "2",
"Tags": [
"java",
"reinventing-the-wheel",
"combinatorics"
],
"Title": "Generating all variations of M*N matrix containing boolean values"
}
|
242464
|
<p>Below is my entire program. You can read what it does thanks to the comments and specifications in particular.</p>
<p>My question is: <strong>can it be improved?</strong> Would it be possible, for example, to avoid writing a <code>fwrite()</code> inside each <code>if</code>? Is there a good <em>pattern</em> that can be implemented somewhere in this code?</p>
<hr>
<p>The entire program is base on this UTF8 model and also studies the case in which a bit occurs in the 32nd position.
<a href="https://i.stack.imgur.com/TpoNT.png" rel="noreferrer"><img src="https://i.stack.imgur.com/TpoNT.png" alt="UTF8 model"></a></p>
<hr>
<pre class="lang-c prettyprint-override"><code>#include <stdio.h>
#include <math.h>
#include <stdint.h>
double log(double a);
/*
* This program reads 4 byte codepoints (in BIG ENDIAN) from a file strictly called "input.data" and creates another file called "ENCODED.data" with the relative encoding in UTF8.
*
* In order to compile this file, in Unix, you need to add the -lm clause because the library math.h function log() requires it.
* For example: gcc encoding.c -o encoding -lm
*/
int main() {
unsigned char bufferCP[4]; //Buffer used to store the codepoints
unsigned char bufferOut[6]; //Buffer used to store the UTF8-encoded codepoints
FILE *ptr, *out;
ptr = fopen("input.data", "rb"); //r for read, b for bynary
out = fopen("ENCODED.data", "wb");
int elem = 0, bytesRead = 0;
unsigned char mask = 0x3F; //Mask used to keep bits interesting for analysis
uint32_t codepoint = 0; //A codepoint must be an unsigned 32 bit integer
//--------------------File-Reading--------------------
while ((elem = fgetc(ptr)) != EOF) {
//Stores the character in the buffer
bufferCP[bytesRead++] = (unsigned char) elem;
if (bytesRead == 4) { //A codepoint is ready to be managed
//Builds a codepoint from the buffer. Reads it in BIG ENDIAN.
for(int j=3; j>=0; j--) {
codepoint <<= 8;
codepoint |= bufferCP[j];
}
//Searches the position of the most significant bit
double logRes = (log(codepoint)/log(2)) + 1;
int bitPos = (int) logRes;
//--------------------UTF8-Encoding--------------------
if (bitPos <= 7) {
bufferOut[0] = (unsigned char) codepoint; //No need to manage this codepoint
fwrite(bufferOut, 1, 1, out);
} else if (bitPos <= 11) {
bufferOut[0] = (codepoint >> 6) | 0xC0;
bufferOut[1] = (codepoint & mask) | 0x80;
fwrite(bufferOut, 1, 2, out);
} else if (bitPos <= 16) {
bufferOut[0] = (codepoint >> 12) | 0xE0;
for(int i=1; i<3; i++)
bufferOut[i] = ((codepoint >> 6*(2-i)) & mask) | 0x80;
fwrite(bufferOut, 1, 3, out);
} else if (bitPos <= 21) {
bufferOut[0] = (codepoint >> 18) | 0xF0;
for(int i=1; i<4; i++)
bufferOut[i] = ((codepoint >> 6*(3-i)) & mask) | 0x80;
fwrite(bufferOut, 1, 4, out);
} else if (bitPos <= 26) {
bufferOut[0] = (codepoint >> 24) | 0xF8;
for(int i=1; i<5; i++)
bufferOut[i] = ((codepoint >> 6*(4-i)) & mask) | 0x80;
fwrite(bufferOut, 1, 5, out);
} else if (bitPos <= 32) {
if (bitPos == 32)
bufferOut[0] = (codepoint >> 30) | 0xFE; //UTF8-encoding first byte would be: 11111111?
else
bufferOut[0] = (codepoint >> 30) | 0xFC;
for(int i=1; i<6; i++)
bufferOut[i] = ((codepoint >> 6*(5-i)) & mask) | 0x80;
fwrite(bufferOut, 1, 6, out);
}
bytesRead = 0; //Variable reset
}
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-18T18:45:00.857",
"Id": "475937",
"Score": "3",
"body": "See https://stackoverflow.com/a/148766/5987 for a function to convert from `wchar_t` to UTF-8, quickly and easily."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-18T19:36:50.240",
"Id": "475943",
"Score": "2",
"body": "I have to do it on my own. It's for a university task..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-18T20:00:44.087",
"Id": "475946",
"Score": "2",
"body": "You might look at it for ideas then."
}
] |
[
{
"body": "<h1>Efficient file I/O</h1>\n\n<p>By default, files opened with <code>fopen()</code> are buffered, meaning that not every call to <code>fread()</code> or <code>fwrite()</code> will result in a system call. Instead, the C library has an internal buffer and will try to read and write larger chunks at a time. However, you are still paying for the overhead of a regular function call each time you call <code>fread()</code> and <code>fwrite()</code>. To avoid this, it is best that you read and write in large chunks in your own code as well.</p>\n\n<p>While you could try to read in the whole file at once, or even use technique like <code>mmap()</code> to memory map the file, you can already get very good performance by reading and writing blocks of say 64 kilobytes at a time. This avoids using a lot of memory.\nOf course, you have to handle the last block not being exactly 64 kilobytes large, but that is quite easy to deal with.</p>\n\n<p>Furthermore, <code>fread()</code> and <code>fwrite()</code> allow you to specify the size of an element and the number of elements you want to read, this comes in handy to ensure you read in a whole number of 4-byte codepoints.</p>\n\n<p>I would structure your code like so:</p>\n\n<pre><code>uint32_t bufferIn[16384]; // 16384 4-byte code points = 64 kB\nchar bufferOut[65536];\n\nsize_t countIn;\n\nwhile ((countIn = fread(bufferIn, sizeof *bufferIn, sizeof bufferIn / sizeof *bufferIn, ptr)) > 0) {\n // There are countIn codepoints in the buffer\n for (size_t i = 0; i < countIn; i++) {\n uint32_t codepoint = ...; // Convert bufferIn[i] to native endian here.\n\n // Write UTF-8 to bufferOut here.\n // If bufferOut is almost full, fwrite() it and start writing to it from the start.\n }\n}\n\n// Flush the remaining bytes in bufferOut here.\n</code></pre>\n\n<h1>Don't use floating point math for integer problems</h1>\n\n<p>Avoid using floating point math when you are dealing with integers. It is hard to get it right, and converting <code>int</code> to <code>double</code>, doing some math operation, and then converting back again can be quite slow.</p>\n\n<p>There are several ways to get the <a href=\"https://stackoverflow.com/questions/2589096/find-most-significant-bit-left-most-that-is-set-in-a-bit-array\">highest set bit in an integer</a>. If you want a portable one, I recommend using one of the <a href=\"https://graphics.stanford.edu/~seander/bithacks.html#IntegerLogLookup\" rel=\"noreferrer\">bit twiddling hacks</a>. Sometimes compilers will even recognize such a bit twiddling hack and convert it to a single CPU instruction if possible.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-18T11:27:31.883",
"Id": "475891",
"Score": "1",
"body": "Are you really saying that the overhead of some extra *function calls* (not kernel calls) will be nontrivial in a hopefully IO limited program? That seems unlikely to me."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-18T12:20:00.493",
"Id": "475896",
"Score": "0",
"body": "@Voo: Is it I/O limited? That really depends on your hardware configuration. And even if you are I/O limited, wasting more CPU cycles than necessary wastes energy (important if your device runs off a battery), and if other processes are running in parallel, they will have less CPU cycles to spend. Also, it's not just the overhead of doing a function call, but also `fread()` having to do checks to see if the requested data is already in the internal buffer or not, and so on. Doing that every time to read just a few bytes adds up."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-18T12:39:45.623",
"Id": "475897",
"Score": "0",
"body": "The first rule of performance optimization is measuring it (well really the first rule is to avoiding premature optimization, but let's assume we've already decided it's too slow). So what do you think rewriting the code saves when converting say a 1 GB file using a modern NVME SSD? (really the best case scenario).10%? 15?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-18T15:10:31.493",
"Id": "475913",
"Score": "21",
"body": "Running some benchmarks on a AMD Ryzen 9 3900X and a Samsung 950 PRO NVMe drive and a 4 GB input file, I get on average 42.9 seconds for the unoptimized code, and on average 3.6 seconds for code which does `fread()` and `fwrite()` in 64 kiB blocks. According to hdparm, the throughput of the drive is 2.5 GB/s, so the optimized code is approximately I/O bound, whereas the unoptimized code is about 12 times slower."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-18T15:55:28.897",
"Id": "475919",
"Score": "0",
"body": "40 seconds difference is a lot! If at first I was \"lazy\" in making this change because I tend to stick with things that work now I have no choice but to implement your solution.\nVery good benchmark and thanks!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-18T18:39:54.673",
"Id": "475935",
"Score": "0",
"body": "A long time ago I needed to optimize I/O speed and discovered a function that would replace the internal buffer with a user supplied one of a larger size. Unfortunately I don't remember the name of the function or whether it was custom for the compiler I was using at the time."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-18T18:55:51.017",
"Id": "475938",
"Score": "2",
"body": "@MarkRansom: [`setvbuf()`](https://en.cppreference.com/w/cpp/io/c/setvbuf)? It's C89."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-18T19:21:48.747",
"Id": "475940",
"Score": "0",
"body": "@G.Sliepen that's probably it, it seems very familiar."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-20T18:19:42.333",
"Id": "476186",
"Score": "1",
"body": "With glibc, at least, `f*` function calls have overhead in the form of virtual function dispatch (because `FILE` structures don't have to refer to real files), locking (because multiple threads could perform file operations at the same time), bookkeeping (to adjust structure offsets, buffer pointers, allocations), and so on. They can be remarkably expensive function calls - to the point where you can probably beat them with careful use of `write`..."
}
],
"meta_data": {
"CommentCount": "9",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-17T18:50:09.767",
"Id": "242476",
"ParentId": "242473",
"Score": "22"
}
},
{
"body": "<ul>\n<li><p><code>log</code> is already declared in <code><math.h></code>. You don't need to declare it yourself. In fact, it could be harmful.</p></li>\n<li><p>As stated in another answer, do not use floating point math.</p>\n\n<p>In fact, you don't need to know the <em>exact</em> position of the leftmost bit. For your purposes, the value of <code>codepoint</code> is enough. For example, <code>bitPos <= 7</code> is equivalent to <code>codepoint < (1 << 8)</code>.</p></li>\n<li><p>I strongly recommend to separate the I/O from the conversion logic. Consider</p>\n\n<pre><code>while (read_four_bytes(input_fp, bufferCP) == 4) {\n size_t utf_char_size = convert_to_utf(bufferCP, bufferOut);\n write_utf_char(bufferOut, utf_char_size);\n}\n</code></pre></li>\n<li><p>DRY. All the conversion clauses look very similar. Consider refactoring them into a function, along the lines of</p>\n\n<pre><code>convert_codepoint(uint32_t codepoint, int utf_char_size, char * bufferOut) {\n for (int i = 0; i < utf_char_size; i++) {\n bufferOut[i] = ((codepoint >> 6 * (utf_char_size - i)) & mask) | 0x80;\n }\n bufferOut[0] |= special_mask[utf_char_size];\n}\n</code></pre>\n\n<p>and use it as</p>\n\n<pre><code>if (codepoint < (1 << 8)) {\n convert_codepoint(codepoint, 1, bufferOut);\nelse if (codepoint < (1 << 12)) {\n convert_codepoint(codepoint, 2, bufferOut);\n} ....\n</code></pre>\n\n<p>The resulting cascade of <code>if/else</code>s may also be transformed into a loop.</p></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-19T22:41:57.753",
"Id": "476051",
"Score": "0",
"body": "How can I transform it into a loop? Can you give me an example? I'm an if-else fan but I'm curious how to do it with a loop."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-20T21:57:03.347",
"Id": "476206",
"Score": "0",
"body": "You could even use a loop instead of the succession of `if` ... `else if` ... tests. And probably shift the codepoint after outputting each of the bytes."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-17T21:46:35.627",
"Id": "242488",
"ParentId": "242473",
"Score": "22"
}
},
{
"body": "<blockquote>\n <ul>\n <li>This program reads 4 byte codepoints (in BIG ENDIAN) from a file strictly called \"input.data\" and creates another file called \"ENCODED.data\" with the relative encoding in UTF8.</li>\n </ul>\n</blockquote>\n\n<p>Needless to say, that's a weird way of storing code points. I know UTF-16, but UTF-32BE (just the code point in big endian form) is not widely used, although Python seems to use it to encode strings internally. Now that you know what this encoding is called, I wonder if you need to code this yourself or that you could have used a library.</p>\n\n<pre><code>* This program reads 4 byte codepoints (in BIG ENDIAN) from a file strictly called \"input.data\" and creates another file called \"ENCODED.data\" with the relative encoding in UTF8.\n</code></pre>\n\n<p>That it reads 4 bytes at a time is really an implementation detail. Generally we don't create conversion applications that restrict themselves to specific files (or even files, to be honest).</p>\n\n<pre><code>unsigned char bufferCP[4]; //Buffer used to store the codepoints\n</code></pre>\n\n<p>If you have to spell out what a variable means, then you're generally better off spelling it out in the variable name: <code>utf32be_buffer</code> would be a good variable name.</p>\n\n<p>The value 4 doesn't have a meaning, which becomes a problem once you split the <code>main</code> method into functions (as you should).</p>\n\n<pre><code>unsigned char bufferOut[6]\n</code></pre>\n\n<p>What about <code>utf8_buffer</code>?</p>\n\n<pre><code>int elem = 0, bytesRead = 0;\n</code></pre>\n\n<p>Split the variable declaration to different lines. <code>elem</code> is also directly assigned, so assigning zero to it is completely unnecessary.</p>\n\n<pre><code>unsigned char mask = 0x3F; //Mask used to keep bits interesting for analysis\n</code></pre>\n\n<p>This comment really begs the question of the reader: which bits are \"interesting\"?</p>\n\n<pre><code>uint32_t codepoint = 0; //A codepoint must be an unsigned 32 bit integer\n</code></pre>\n\n<p>Utterly unnecessary comment. \"must be\" also begs the question: for this program or according to some kind of standard?</p>\n\n<pre><code>//--------------------File-Reading--------------------\n</code></pre>\n\n<p>What about <code>read_into_buffer</code> instead of a comment?</p>\n\n<pre><code>if (bytesRead == 4) { //A codepoint is ready to be managed \n</code></pre>\n\n<p>Repeat of a literal, while <code>utf32be_buffer</code> is already assigned a size. Use that.</p>\n\n<p>Again a comment that reads as if a method should be introduced. You can almost hear yourself defining them.</p>\n\n<p>Finally, what happens if the file doesn't contain a multiple of 4 bytes? It seems like you're just removing the last bytes without warning or error.</p>\n\n<pre><code>//Builds a codepoint from the buffer. Reads it in BIG ENDIAN.\n</code></pre>\n\n<p>There is the name, although I would simply use <code>convert_code_point()</code>.</p>\n\n<pre><code>for(int j=3; j>=0; j--) {\n</code></pre>\n\n<p>Another repeat of the same literal 4, but now disguised as a 3, i.e. 4 - 1. Great.</p>\n\n<pre><code>codepoint <<= 8;\n</code></pre>\n\n<p>I actually use a constant (<code>Byte.SIZE</code>) in Java for this, but you can be excused for using 8 here, especially since this code should perform well.</p>\n\n<pre><code>//Searches the position of the most significant bit\ndouble logRes = (log(codepoint)/log(2)) + 1;\nint bitPos = (int) logRes;\n</code></pre>\n\n<p>As already indicated, use bit ops for this. And a method please, <a href=\"https://stackoverflow.com/a/53184/589259\">here</a> is an answer on StackOverflow for that.</p>\n\n<pre><code>bufferOut[0] = (unsigned char) codepoint; //No need to manage this codepoint \n</code></pre>\n\n<p>What is \"managing\" a code point? When I first read the comment I was afraid you were going to skip it. Fortunately, that's not the case.</p>\n\n<pre><code>fwrite(bufferOut, 1, 1, out);\n</code></pre>\n\n<p>Just keep a variable of the number of bytes in the buffer and then write those in the end.</p>\n\n<pre><code>} else if (bitPos <= 32) {\n</code></pre>\n\n<p>We use zero based indexing in C-style languages. What is the chance that a significant bit is at position 32 according to you?</p>\n\n<pre><code>bytesRead = 0; //Variable reset\n</code></pre>\n\n<p>Would never have guessed that without the comment, I admit. It also shows that the name of the variable is wrong: it represents the number of bytes in the buffer, not the bytes read from the file.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-19T17:09:31.453",
"Id": "476023",
"Score": "2",
"body": "UTF-32LE is used in linux sometimes, but BE I've never encountered."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-17T22:05:10.660",
"Id": "242489",
"ParentId": "242473",
"Score": "11"
}
},
{
"body": "<p>regarding: </p>\n\n<pre><code>ptr = fopen(\"input.data\", \"rb\"); \nout = fopen(\"ENCODED.data\", \"wb\"); \n</code></pre>\n\n<p>always check (!=NULL) the returned value to assure the operation was successful. If not successful (==NULL) then call: </p>\n\n<pre><code>perror( \"your error message\" ); \n</code></pre>\n\n<p>to output both your error message and the text reason the system thinks the error occurred to <code>stderr</code>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-18T15:43:13.717",
"Id": "242520",
"ParentId": "242473",
"Score": "8"
}
},
{
"body": "<p>As others have said, don't use floating point math, but in some sense that's reviewing the wrong layer. The real issue behind that is that you don't need to be branching on a <em>derived quantity</em>, the number of bits. Instead branch on the codepoint value ranges (original input). For example (excerpt from <a href=\"https://git.musl-libc.org/cgit/musl/tree/src/multibyte/wcrtomb.c?id=v1.2.0\" rel=\"noreferrer\">my implementation</a>):</p>\n\n<pre><code>} else if ((unsigned)wc < 0x800) {\n *s++ = 0xc0 | (wc>>6);\n *s = 0x80 | (wc&0x3f);\n return 2;\n}\n</code></pre>\n\n<p>Not only is branching directly on the input quantity simpler than computing a derived quantity like number of bits; for the problem at hand (UTF-8) it's necessary in order to do proper error handling. Boundaries that are not exact numbers of bits (between D800 and DFFF, above 10FFFF) correspond erroneous inputs that should not be output as malformed UTF-8 but rejected in some manner.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-18T22:33:01.713",
"Id": "475961",
"Score": "0",
"body": "Could you explain why your solution is better inside the answer?"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-18T20:36:10.770",
"Id": "242531",
"ParentId": "242473",
"Score": "7"
}
},
{
"body": "<p><strong>Code fails to detect invalid code points</strong></p>\n\n<p>There are 1,112,064 valid unicode code points, not 2<sup>32</sup>.</p>\n\n<p>The valid range is [0x0 - 0x10FFFF] except the sub-range of [0xD800 - 0xDFFF]. This later sub-range is for <a href=\"https://en.wikipedia.org/wiki/UTF-16#U+D800_to_U+DFFF\" rel=\"noreferrer\">surrogates</a>.</p>\n\n<p>UTF-8 is not defined for 4-byte values outside this range. Code should not attempt to create a six-byte \"UTF-8\" unless it is calling it an <a href=\"https://en.wikipedia.org/wiki/UTF-8#History\" rel=\"noreferrer\">obsolete 1993</a> version of UTF-8.</p>\n\n<p>Better code would detect invalid sequences.</p>\n\n<p><strong>Code silently discard extra bytes</strong></p>\n\n<p>Should code read an extra final 1, 2 or 3 bytes, no error indication is provided.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-19T19:56:15.097",
"Id": "476039",
"Score": "0",
"body": "You're absolutely right about having to check if the bytes are being read correctly.\nI simply do not do it because this task is not worth so much so I avoid such checks that should be done in a more serious converter.\n\nAbout the UTF8 version, I edited showing which model my program is based on."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-19T17:45:07.313",
"Id": "242583",
"ParentId": "242473",
"Score": "7"
}
}
] |
{
"AcceptedAnswerId": "242476",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-17T18:13:11.780",
"Id": "242473",
"Score": "20",
"Tags": [
"c",
"file",
"homework",
"utf-8"
],
"Title": "Can I slim this UTF8-encoding program?"
}
|
242473
|
<p>I wrote this script and got what I wanted from it. However I'm looking for input on ways I can improve the function. </p>
<p>My goal was to scrape a bunch of image links from a website I'd like to rebuild. I wanted to use <a href="https://webscraper.io/" rel="nofollow noreferrer">webscraper</a> but the image links were coded into the CSS instead of the HTML mark up. </p>
<p>Hence I had difficulty getting the web scrapper to find and collect said links.
Luckily while looking at them, I was able to discern their structure and pattern into 4 formats and came up with the following script to duplicate and iterate through each format to get my links. </p>
<p>Beside the 1st group (which is comprised of 40 images), each image (n) is part of a group (x) of 12 and there are 170 groups in total. Something I had to consider while writing the script is that each image number starts with a "00" prefix and "000" for the group number. So they had to be removed as you increment through the tens(for images) and hundreds(for groups).</p>
<pre><code>let loop = 0;
for (; loop < 155; loop++) {
let n = 00;
let x = 000;
str1 = "https://site.com/content/2018/02/"; /* groups 1-155*/
str2 = "https://site.com/content/2019/07/"; /* groups 156-167*/
str3 = "https://site.com/content/2019/11/"; /* group 168*/
str4 = "https://site.com/content/2020/03/"; /* groups 169-171*/
ext = ".jpg"
z = "0";
zz ="00";
if (loop > 0 ) {
x+=loop;
console.log('one loop ' + loop );
if(x >= 9){
var zz = "00".replace('00','0');
}
if(x >= 99){
var zz = "00".replace('00','');
}
}
while (n <= 11) {
if(n >= 9){
var z = "0".replace('0','');
}
n++;
console.log(str1 + zz + x + "_" + z + n + ext);
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-17T18:45:19.693",
"Id": "475837",
"Score": "0",
"body": "You never use `str1`, `str2`, or `str3`. Is that intentional, or did you accidentally leave out some code?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-17T18:58:04.287",
"Id": "475839",
"Score": "0",
"body": "Now you aren't using `str2`, `str3`, or `str4`..?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-17T19:02:14.880",
"Id": "475840",
"Score": "0",
"body": "I wanted to run the function on one group at a time, your question made me realize I had to switch to str1 for my question, thanks."
}
] |
[
{
"body": "<p>You should consider using consistent indentation when writing code - it makes it much easier for people to read (not only for other maintainers, but for you as well). For example</p>\n\n<pre><code>let loop = 0;\nfor (; loop < 155; loop++) {\nlet n = 00;\n// ...\nzz =\"00\";\n if (loop > 0 ) {\n x+=loop;\n console.log('one loop ' + loop );\n</code></pre>\n\n<p>should be something like</p>\n\n<pre><code>let loop = 0;\nfor (; loop < 155; loop++) {\n let n = 00;\n // ...\n zz =\"00\";\n if (loop > 0 ) {\n x+=loop;\n console.log('one loop ' + loop );\n</code></pre>\n\n<p>Lots of IDEs provide an automatic tidying function.</p>\n\n<p>In this section, since you aren't using <code>str2</code>, <code>str3</code>, or <code>str4</code>, you may as well remove those assignments from the inside of the loop here, since they aren't used and only add to cognitive overhead.</p>\n\n<p>Best to always declare variables before you use them - you have a number of variables which are not declared, which will either assign to properties of the global object (in sloppy mode), or will throw an error (in strict mode). (Consider always using strict mode so that these sorts of potential bugs can be fixed early.) Specifically, lines like:</p>\n\n<pre><code>str1 = \"https://site.com/content/2018/02/\"; /* groups 1-155*/\n</code></pre>\n\n<p>where you use a variable for the first time should be prefixed with <code>const</code>, <code>let</code>, or <code>var</code>:</p>\n\n<pre><code>const str1 = \"https://site.com/content/2018/02/\"; /* groups 1-155*/\n</code></pre>\n\n<p>If you're going to use ES2015 syntax to declare some variables like <code>let</code> (which is great, you should), don't use <code>var</code> anywhere; <code>var</code> has numerous potential gotchas which can cause bugs, and doesn't really have anything positive going for it (other than compatibility with ancient browsers - but if you need that sort of compatibility, use <a href=\"https://babeljs.io/\" rel=\"nofollow noreferrer\">Babel</a> to transpile to ES5 automatically - best to keep source code in readable, pretty, modern syntax).</p>\n\n<p>When you have a <code>for</code> loop, if you need to declare a variable at the beginning that's then used inside that loop, you should put the declaration inside the <code>for</code> loop declaration. That is:</p>\n\n<pre><code>let loop = 0;\nfor (; loop < 155; loop++) {\n</code></pre>\n\n<p>should be</p>\n\n<pre><code>for (let loop = 0; loop < 155; loop++) {\n</code></pre>\n\n<p>You have</p>\n\n<pre><code>let n = 00;\nlet x = 000;\n</code></pre>\n\n<p>Leading zeros have no effect in numeric literals. Those are equal to</p>\n\n<pre><code>let n = 0;\nlet x = 0;\n</code></pre>\n\n<p>You declare the <code>zz</code> variable 3 times, but you only have one binding for it - duplicate variable declarations with <code>var</code> are ignored. If you just want <em>assignment</em>, then <em>only</em> use the assignment operator with <code>=</code>.</p>\n\n<p>The <code>x</code> variable starts at 0 and gets <code>loop</code> assigned to it once, on every iteration:</p>\n\n<pre><code>let x = 0;\n// ...\nif (loop > 0) {\n x += loop;\n</code></pre>\n\n<p>So, it's equivalent to <code>loop</code>. Best to just remove that variable completely, since it isn't doing anything useful - use the one <code>loop</code> variable completely. The <code>if (loop > 0) {</code> test is superfluous too, since the tests inside that block <code>if(x >= 9){</code> <code>if(x >= 99){</code> are only fulfilled if <code>loop</code> is greater than 0 anyway.</p>\n\n<p>Use meaningful variable names. It is very difficult to tell at a glance what <code>loop</code>, <code>n</code>, <code>x</code>, <code>z</code>, or <code>zz</code> are meant to represent. Maybe call them <code>group</code> (the number that goes from 1 to 155) and <code>subgroup</code> (the number that goes from 1 to 11) instead.</p>\n\n<p>The main block there is meant to ensure that the <code>zz</code> variable for padding the string has the right number of zeros. But there's a much easier way to do that, without creating extra variables: just use <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/padStart\" rel=\"nofollow noreferrer\"><code>String.prototype.padStart</code></a>. When you need to construct</p>\n\n<pre><code>000_01\n154_12\n</code></pre>\n\n<p>from variables 0 and 1, and from variables 154 and 12, add the leading zeros by calling <code>padStart(length, '0')</code> on them:</p>\n\n<pre><code>`${String(group).padStart(3, '0')}_${String(subgroup).padStart(2, '0')}`\n</code></pre>\n\n<p>Or, without a template literal:</p>\n\n<pre><code>String(group).padStart(3, '0') + '_' + String(subgroup).padStart(2, '0')\n</code></pre>\n\n<p>The loop over <code>subgroups</code> (or <code>n</code> in your original code) assigns a variable and increments it every iteration, breaking after a condition. This is a prime spot to be refactored into a <code>for</code> loop instead:</p>\n\n<pre><code>for (let subgroup = 1; subgroup <= 12; subgroup++) {\n</code></pre>\n\n<p>Since the <code>str1</code> never changes, and nor does the <code>ext</code>, you may as well declare them outside of the loop, rather than re-declare them every time there's another iteration:</p>\n\n<p>In full:</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>'use strict';\n\nconst str1 = \"https://site.com/content/2018/02/\"; /* groups 1-155*/\nconst ext = \".jpg\"\nfor (let group = 0; group < 155; group++) {\n console.log('one loop ' + group);\n for (let subgroup = 1; subgroup <= 12; subgroup++) {\n console.log(`${str1}${String(group).padStart(3, '0')}_${String(subgroup).padStart(2, '0')}${ext}`);\n }\n}</code></pre>\r\n</div>\r\n</div>\r\n</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-18T01:20:37.070",
"Id": "475849",
"Score": "0",
"body": "Wow this is beautiful! Apologies I wrote the script in a JS fiddle, will definitely check formatting before posting next time.\nAs per your implementation, the padStart method is really what slimmed down the script. Thank you for this approach it makes so much sense and exposed my oversights."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-17T19:33:59.960",
"Id": "242478",
"ParentId": "242475",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "242478",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-17T18:42:08.610",
"Id": "242475",
"Score": "2",
"Tags": [
"javascript",
"css",
"image",
"web-scraping",
"url"
],
"Title": "Refactoring string incrementing and duplicating function"
}
|
242475
|
<p>I've a simple code base with few 'weapon' concrete classes which implements different contracts in order to be used by its clients.</p>
<p>My contracts:</p>
<pre><code>public interface IWeaponPrimaryAttack
{
void DoAttack();
}
public interface IWeaponSecondaryAttack
{
void DoSecondaryAttack();
}
public interface IReloadable
{
void Reload();
}
</code></pre>
<p>Concrete implementation or the actual weapons:</p>
<pre><code>public class Katana : IWeaponPrimaryAttack, IWeaponSecondaryAttack
{
public void DoAttack(){Console.WriteLine ("Swing");}
public void DoSecondaryAttack() {Console.WriteLine ("Stab");}
}
public class ShotGun : IWeaponPrimaryAttack, IReloadable
{
public void DoAttack(){Console.WriteLine ("Swing");}
public void Reload() {//reload it}
}
</code></pre>
<p>Clients that uses these concrete classes:</p>
<pre><code>public class PrimaryAttack
{
private IWeaponPrimaryAttack _attack;
public PrimaryAttack(IWeaponPrimaryAttack attack)
{
_attack = attack;
}
public void DoAttack()
{
_attack.DoAttack();
}
}
public class SecondaryAttack
{
private IWeaponSecondaryAttack _attack;
public SecondaryAttack(IWeaponSecondaryAttack attack)
{
_attack = attack;
}
public void DoSecondaryAttack()
{
_attack.DoSecondaryAttack();
}
}
public class WeaponReload
{
private IReloadable _reloader;
public WeaponReload(IReloadable reloader)
{
_reloader = reloader;
}
public void Reload()
{
_reloader.Reload();
}
}
</code></pre>
<p>New of course the instantiation of concrete class only be known when the user selects one among many weapons(one among ShotGun, Katana, etc).</p>
<p>Let say the use has selected ShotGun as the weapon, based on the selection it might go like this:</p>
<pre><code>IWeaponPrimaryAttack weapon = new ShotGun(); // get it from a factory
PrimaryAttack primaryAttack = new PrimaryAttack(weapon);
primaryAttack.DoAttack();
</code></pre>
<p>Now for the WeaponReload have to do a typecast here in order to use it.</p>
<pre><code>WeaponReload reloader = new WeaponReload ((IReloadable)weapon);
reloader.Reload();
</code></pre>
<p>I have questions around it,</p>
<ul>
<li><p>Should I really have to end up typecasting eventually?</p></li>
<li><p>Or there is a better way to handle this object creation part.</p></li>
<li><p>Or there is entirely a better design that I can come up with which
does not necessarily ends up in casting.</p></li>
<li><p>Or casting it like this is totally fine.</p></li>
</ul>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-18T06:35:13.393",
"Id": "475860",
"Score": "1",
"body": "use `enum` to define types like weapon type, attack type ..etc. Also, you need to concrete implementation of attack and weapon as both have different purpose and logic, so they need to be separate. Then, you can have a container which contains both like `WeaponAttack` to control the damage, timing ..etc."
}
] |
[
{
"body": "<p><a href=\"https://en.wikipedia.org/wiki/Composition_over_inheritance\" rel=\"nofollow noreferrer\">Composition over inheritance</a> and <a href=\"https://en.wikipedia.org/wiki/Strategy_pattern\" rel=\"nofollow noreferrer\">Strategy Pattern</a></p>\n\n<p>I would, instead of having differents weapons implementing differents interfaces defining their behaviour, create classes that holds the logic of the behaviour</p>\n\n<p>Let's consider a weapon <strong>can</strong> have a primary attack, a secondary one and reload.</p>\n\n<p>The class could be defined as such :</p>\n\n<pre><code>abstract class Weapon\n{\n public IWeaponPrimaryAttack WeaponPrimaryAttack { get; set; }\n public IWeaponSecondaryAttack WeaponSecondaryAttack { get; set; }\n public IReloadable Reloadable { get; set; }\n}\n</code></pre>\n\n<p>Now, we can define classes that holds differents behaviours of the interfaces.</p>\n\n<p>In example :</p>\n\n<pre><code>public class SlashAttack : IWeaponPrimaryAttack\n{\n public void DoAttack()\n {\n Console.WriteLine(\"Performing a slash attack\");\n }\n}\n\npublic class StabAttack : IWeaponSecondaryAttack\n{\n public void DoSecondaryAttack()\n {\n Console.WriteLine(\"Performing a stab attack\");\n }\n}\n\npublic class Shooting12Caliber : IWeaponPrimaryAttack\n{\n public void DoAttack()\n {\n Console.WriteLine(\"Bam !\");\n }\n}\n\npublic class Caliber12Reloader : IReloadable\n{\n public void Reload()\n {\n Console.WriteLine(\"Reloading caliber 12 !\");\n }\n}\n\npublic class ShootingWith556 : IWeaponPrimaryAttack\n{\n public void DoAttack()\n {\n Console.WriteLine(\"Bam (version 5.56) !\");\n }\n}\n\npublic class Caliber556Reloader : IReloadable\n{\n public void Reload()\n {\n Console.WriteLine(\"Reloading caliber 5.56 !\");\n }\n}\n</code></pre>\n\n<p>And now, you can use theses class as properties in differents weapon classes.</p>\n\n<p>You'll implement once the methods and can use the same for differents weapons : </p>\n\n<pre><code>public class Katana : Weapon\n{\n public Katana()\n {\n WeaponPrimaryAttack = new SlashAttack();\n WeaponSecondaryAttack = new StabAttack();\n }\n}\n\npublic class Machete : Weapon\n{\n public Machete()\n {\n WeaponPrimaryAttack = new SlashAttack();\n }\n}\n\npublic class Shotgun : Weapon\n{\n public Shotgun()\n {\n WeaponPrimaryAttack = new Shooting12Caliber();\n Reloadable = new Caliber12Reloader();\n }\n}\n\npublic class AssaultRifleWithBayonet : Weapon\n{\n public AssaultRifleWithBayonet()\n {\n WeaponPrimaryAttack = new ShootingWith556();\n WeaponSecondaryAttack = new StabAttack();\n Reloadable = new Caliber556Reloader();\n }\n}\n</code></pre>\n\n<p>Now, your methods implementations are refactored within classes and are reusable. You don't need to typecast to check if this or that interface is implemented.</p>\n\n<pre><code>if (weapon.Reloadable != null)\n{\n weapon.Reloadable.Reload();\n}\nelse\n{\n Console.WriteLine(\"This weapon isn't meant to be reloaded\");\n}\n\n/*\nThis works too if you want to omit the Reloadable != null\n\npublic class CannotReload : IReloadable\n{\n public void Reload()\n {\n Console.WriteLine(\"This weapon isn't meant to be reloaded\");\n }\n}\n*/\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-17T20:14:17.623",
"Id": "242480",
"ParentId": "242479",
"Score": "2"
}
},
{
"body": "<p>Since <code>Weapon</code> and <code>Attack</code> are partially related, you may need to implement each separately in order to make them flexible for future changes, and since <code>Attack</code> can be defined in multiple classes (not just for weapons), we can either implement an interface for it, or an abstract class, (or both if needed) and use it as <code>definition</code> of the attack logic.</p>\n\n<p>If you want to define a concrete class for each weapon, and just inherit the <code>Weapon</code> class, you can do that, though, it won't be easy to handle nor to memorized; because more weapons, means more classes to handle.</p>\n\n<p>For your current code, you could start with something like these interfaces : </p>\n\n<pre><code>public interface IWeapon\n{\n WeaponType Type { get; set; }\n}\n\npublic interface IReloadable \n{\n double IsReloadable { get; set; } \n void Reload(); \n}\n\npublic interface IAttack\n{\n AttackType Type { get; set; }\n}\n</code></pre>\n\n<p>Then, using <code>enum</code> to define some types : </p>\n\n<pre><code>public enum WeaponType { Katana, Shutgun, Knife }\npublic enum AttackType { Primary, Secondary }\n</code></pre>\n\n<p>now, we will use them in our classes</p>\n\n<pre><code>public class Weapon : IWeapon, IReloadable\n{\n public WeaponType Type { get; set; }\n\n public bool IsReloadable { get; set; } \n\n public void Reload()\n {\n if(IsReloadable)\n {\n .....\n }\n }\n ...\n}\n\npublic class Attack : IAttack\n{\n public AttackType Type { get; set; } \n .... \n}\n\npublic class WeaponAttack\n{\n private readonly Weapon _weapon; \n\n private readonly Attack _attack;\n\n public WeaponAttack(Weapon weapon, Attack attack)\n {\n _weapon = weapon; \n _attack = attack;\n }\n\n public void DoAttack()\n {\n if(_attack.Type == AttackType.Primary)\n {\n // do something..\n } \n } \n\n}\n</code></pre>\n\n<p>With this, we know if we use <code>Weapon</code> or <code>Attack</code> we are defining types, and setting their properties, logic for each type to be ready for use. <code>WeaponAttack</code> will use these <code>prepared</code> objects to do some actions on them. </p>\n\n<p>so in your example of shutgun, we'll be revised to this </p>\n\n<pre><code>//define your weapon\nvar shutgun = new Weapon\n{\n Type = WeaponType.Shutgun, \n IsReloadable = true \n};\n//define your attack \nvar attack = new Attack\n{\n Type = AttackType.Primary, \n DamagePoints = 2.5\n}; \n\n// take the action \nvar attackAction = new WeaponAttack(shutgun, attack); \nattackAction.DoAttack();\n</code></pre>\n\n<p>This is the simplest form that came to my mind. It'll be easy to extend, for instance, say you want to add a new interface <code>IDamage</code> for storing damage points per attack : </p>\n\n<pre><code>public interface IDamage\n{\n double DamagePoints { get; set; }\n}\n</code></pre>\n\n<p>Then, you just implement it on <code>Attack</code> class : </p>\n\n<pre><code>public class Attack : IAttack, IDamage\n{\n public AttackType Type { get; set; } \n\n public double DamagePoints { get; set; }\n}\n</code></pre>\n\n<p>Same thing applies to the Weapon class, if you want to add new features, it would be easy to add with minimal modifications to the current code. Also, I would prefer to change the constructor on <code>WeaponAttack</code> to accept the interfaces instead of the concrete class, it would be more fixable this way. But I used the concrete classes just for demonstration purpose. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-18T20:02:04.933",
"Id": "242530",
"ParentId": "242479",
"Score": "2"
}
},
{
"body": "<p>Lets first respond to your initial question: </p>\n\n<h2><em>is it fine to typecast from one implementation to another?</em></h2>\n\n<p><strong>Absolutely!</strong> When using <em>interfaces</em> to declare behaviours like you have shown, not only is it <em>fine</em> but it becomes important that you <em>DO</em> typecast, otherwise what was the point of declaring the behavior through interfaces in the first place.</p>\n\n<p>The use of interfaces implies that not all classes will implement the behaviour, so you can <em>ONLY</em> access the behaviour if your code knows the exact type of the concrete class or if you know the <em>interface</em> of the behaviour you want to execute, perhaps more importantly you may need to handle the case where the concrete class <em>does NOT</em> implement the expected interface.</p>\n\n<blockquote>\n <p><em>Should you have to Type Cast?</em><br>\n If you are using interfaces, then yes you <em>should</em> have to typecast.</p>\n</blockquote>\n\n<p>A better code implementation for <em>WeaponReload</em> would be to check first that the class does in fact implement <code>IReloadable</code> before reloading, since <a href=\"https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/operators/type-testing-and-cast#is-operator\" rel=\"nofollow noreferrer\">c# 7.0 we can use the <code>is</code> operator</a> to test an expression against a pattern and we can capture the output in a single line of code:</p>\n\n<pre class=\"lang-cs prettyprint-override\"><code>if (weapon is IReloadable reloader)\n reloader.Reload();\n</code></pre>\n\n<p>Notice we didn't even need to use the Wrapper <em>Client</em> class <code>WeaponReload</code> to access the <code>IReloadable.Reload()</code> behaviour, I think this is what you are referring to with:</p>\n\n<h2>Is there a better way to handle this object creation part</h2>\n\n<p>Yes, the better way is to skip the <em>Clients</em> altogether. </p>\n\n<p>If you are set on your current implementation, then that is just as easy to incorporate, however you should still handle the cases where the passed in object does not implement your interface.</p>\n\n<pre class=\"lang-cs prettyprint-override\"><code>WeaponReload reloader = null;\nif (weapon is IReloadable r)\n reloader = new WeaponReload(r);\n...\nif (reloader != null)\n reloader.Reload();\n</code></pre>\n\n<h2>Is there an entirely better design that I can come up with which does not necessarily ends up in casting.</h2>\n\n<p>There is nothing wrong with casting, it can lead to clear and concise code as you have created clear structural boundaries that can help you separate implementation from definitions. </p>\n\n<blockquote>\n <p>If you are concerned about performance, then we have a solution for that too, <strong>but don't optimise your code for the sake of it</strong>, the performance losses due to boxing values into objects, though comparitively expensive to alternatives, wil not generally be noticied by the user unless you are performing millions of operations in quick succession.</p>\n</blockquote>\n\n<p>To avoid performance issues caused by <a href=\"https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/types/boxing-and-unboxing\" rel=\"nofollow noreferrer\"><em>Boxing and Unboxing</em></a> in C# we can use <a href=\"https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/generics/\" rel=\"nofollow noreferrer\">Generics</a>. Interfaces play a huge part in C# generics, a generic type argument on a class or method defines <em>all</em> the interfaces or conditions that an <code>object</code> <strong>MUST</strong> implement for it to be passed into the methods as a parameter or stored in a variable. </p>\n\n<p>Because these conditions are validated and enforced by the compiler, the storage and referencing to the underlying object stored in a generic typed variable is a lot more efficient at runtime compared to simply <em>boxing</em> objects into an <code>object</code> typed variable.</p>\n\n<h2>a Better design</h2>\n\n<p>Your interfaces are on the right track, interfaces allow your concrete classes to define explicit behaviors without having to incorporate those behaviours into their base class.</p>\n\n<p>What you have missed here is a base class that all your weapons can inherit from, it's the first logical assumption that one makes when rationalising a domain that includes different types of weapons like shotguns and swords... Common properties might include Name, Description, Cost, BasePower... I would argue that <em>all</em> weapons have a <em>Primary</em> attack function, so really a <code>Weapon</code> base class would be replacing <code>IWeaponPrimaryAttack</code>:</p>\n\n<pre class=\"lang-cs prettyprint-override\"><code>public abstract class Weapon ()\n{\n public string Name { get;set; }\n ... \n public abstract void DoAttack();\n}\npublic interface IWeaponSecondaryAttack\n{\n void DoSecondaryAttack();\n}\npublic interface IReloadable\n{\n void Reload();\n}\n</code></pre>\n\n<p>Now for the concrete class implementations, I would classify the weapons a bit differently again, I like to write down a breif story style description about the classes before I write the code, using the following phrasiology to help validate that my classes and interfaces make sense and can be utilised effectivly:</p>\n\n<blockquote>\n <p>A <code>Katana</code> <em>IS</em> a <code>Weapon</code>, it has a Name of 'Katana' but it does <em>NOT</em> have a <code>Reload</code> feature, it's primary attack is a 'Slash' and it has a <code>SecondaryAttack</code> that is a 'Stab'.</p>\n \n <p>A <code>Shotgun</code> <em>IS</em> a <code>Weapon</code>, it has a Name of 'Shotgun' and it <em>DOES</em> have a <code>Reload</code> feature, it only has a capacity of <code>2</code> <em>shells</em> before it must be reloaded, it does not have a <code>SecondaryAttack</code>.</p>\n</blockquote>\n\n<p>This will work with your current interfaces, but notice already we have identified an element of redundancy, the <code>Name</code> is always the same as the <code>type</code>. This isn't a problem, but it is an indicator that there is potential room for improvement. Instead lets create classes that categorise the weapons :</p>\n\n<blockquote>\n <p>In real life and in many games, you will find weapons categorised more granularly, for instance Swords vs Guns, Two handed vs One Handed, or Melee vs Ranged... Swords might include daggers and daggers can easily be Ranged as well as Melee...</p>\n</blockquote>\n\n<p>Instead if we change our concrete classes to this:</p>\n\n<pre class=\"lang-cs prettyprint-override\"><code>public class Sword : Weapon, IWeaponSecondaryAttack\n{\n public override void DoAttack() => Console.WriteLine(\"Slash\");\n public void DoSecondaryAttack() => Console.WriteLine(\"Stab\");\n}\npublic class Gun : Weapon, IReloadable\n{\n public override void DoAttack() => Console.WriteLine(\"Shoot\");\n public void Reload() => Console.WriteLine(\"Reload\");\n}\n</code></pre>\n\n<p>We haven't yet handled the capacity of attacks before reload, should be easy to add this into the <code>IReloadable</code> interface, so we'll leave this out for.</p>\n\n<p>Now we can create an array of weapons that the user might have access to that includes a 'Katana' as an <em>instance</em> of a 'Sword' as well as a 'Dagger' and of course our 'Shotgun' as an instance of <code>Gun</code>:</p>\n\n<blockquote>\n <p>even though 'Dagger' and 'Katana' have a similar attack style, one would clearly deal more damage than the other, so Damage now becomes another property that we could add...</p>\n</blockquote>\n\n<pre class=\"lang-cs prettyprint-override\"><code>List<Weapon> weapons = new List<Weapon>\n {\n new Sword { Name = \"Katana\" },\n new Sword { Name = \"Dagger\" },\n new Gun { Name = \"Shotgun\" }\n }; \n</code></pre>\n\n<p>Although it doesn't make sense in a real-world situation to talk about the <em>reload</em> function on a <em>Katana</em>, you could for the purposes of simplifying the code say that <em>all</em> <code>Weapon</code> instances do have a <code>Reload</code> function, but the <code>Reload</code> function on a <em>Katana</em> does nothing. The same could be said for SecondaryAttack, in that case these become properties on the <code>Weapon</code> base class. The argument about if it should or shouldn't be an interface could swing either way depending on how you implement it in the rest of your code. </p>\n\n<p>Another scenario to consider is <em>What is an Attack</em>? By making the attack method a <code>void</code> response type, we're really saying that anything and everything could occur when the method is executed, we have not feedback and cannot determine if the attack succeeded, or if it even ocurred at all.</p>\n\n<p>If Attack returned a value or better yet an object that defined the parameters of the attack, then we can start to tell some interesting stories! Take </p>\n\n<blockquote>\n <p>On the <em>third</em> attack, user with <em>Shotgun</em> equipped was out of ammo and had to use it as a 'blunt force' <em>melee</em> weapon, that had less damage, but required the user to be within melee range...</p>\n</blockquote>\n\n<p>Write out user stories that explain the values and states of the objects over time, this will help you to identify the structures that you need, then we can talk about better implementations ;) </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-22T18:54:46.257",
"Id": "476464",
"Score": "0",
"body": "Thanks for nice answer. Now I think I have a better understand the of the idea. Though I have one thing in my mind. Let's consider that a Baseball Bat or a Hockey stick can be used as a weapon, but it's not really a weapon. So just to fit into real world can I just use an `interface` instead of an `abstract` class and have behavior like `DoAttack` . I'm not sure is this really mane any difference. Just asking if the way I'm looking into objects are right."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-25T00:53:10.960",
"Id": "476676",
"Score": "1",
"body": "You could, if you really wanted to, but it's far more efficient and simpler to understand the code if you can constrain your classes to simpler concepts than what might be in real life. If _any_ object could have _any_ behaviour, then the reasoning behind your class design becomes ambiguous and your vision can become diluted over time or if you have to work in a team. So while you _can_, that doesn't mean you _should_, or that it is a good idea to do so. This is where the answer from @Cid and looking at Composition, over inheritance is a good place to start"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-25T01:05:55.673",
"Id": "476678",
"Score": "0",
"body": "A different design then might be for a `BaseballBat` (and all weapons) to inherit from `GameObject` that has an _array_ of abilities, then _instead_ of interfaces, (or as well as) use an Enum as a type discriminator on the ability, 'Melee, Ranged, ???'. Baseball bat has ['two hand swing' (Melee), 'one hand swing' (Melee), 'block' (Melee and Ranged defence) and throw (Ranged)] abilities. You can play baseball with these abilities, you can also fight with them, or use them to break other 'things'."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-25T01:13:55.010",
"Id": "476679",
"Score": "1",
"body": "Have a clear understanding of what the finite list of objects are, how they might each independently vary and how they will interact with each other. Then look for the right balance of code constructs to help you achieve your aims. Don't try and cater for too many unknowns, put constraints on those unknowns to keep them and your code base manageable"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-19T15:48:53.720",
"Id": "242574",
"ParentId": "242479",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "242574",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-17T19:35:07.673",
"Id": "242479",
"Score": "3",
"Tags": [
"c#",
"object-oriented",
"design-patterns"
],
"Title": "Is it fine to typecast from one implementation type to another while using an object?"
}
|
242479
|
<p>Decided to give ReactJS + Redux + Typescript a try this weekend.<br>
Going to include the code first and then summerize a few questions that came into my mind during development.<br>
Also posting here to get general feedback on what I can improve on.</p>
<p><a href="https://codesandbox.io/s/friendly-fog-6p34j?file=/src/index.tsx" rel="nofollow noreferrer">The whole project on codesandbox.io</a></p>
<p>index.tsx</p>
<pre><code>import * as React from "react";
import * as ReactDOM from "react-dom";
import App, { PipelineItemType } from "./App";
import { createStore } from "redux";
import { Provider } from "react-redux";
import { EXECUTE } from "./Execute";
import { COPY } from "./Copy";
export const ADD_PIPELINE_ITEM = "ADD_ITEM";
interface AddPipelineItemAction {
type: typeof ADD_PIPELINE_ITEM;
data: PipelineItemType;
}
export const UPDATE_PIPELINE_ITEM = "UPDATE_ITEM";
interface UpdatePipelineItemAction {
type: typeof UPDATE_PIPELINE_ITEM;
data: PipelineItemType;
}
export const DELETE_PIPELINE_ITEM = "DELETE_ITEM";
interface DeletePipelineItemAction {
type: typeof DELETE_PIPELINE_ITEM;
idx: number;
}
export type ActionTypes =
| AddPipelineItemAction
| UpdatePipelineItemAction
| DeletePipelineItemAction;
export interface StoreState {
pipelineItems: PipelineItemType[];
}
const initialState: StoreState = {
pipelineItems: [
{ type: EXECUTE, idx: 0, commandLine: "npm run build" },
{ type: EXECUTE, idx: 1, commandLine: "npm run test" },
{ type: COPY, idx: 2, source: "sourceDir", destination: "destinationDir" },
{ type: EXECUTE, idx: 3, commandLine: "npm run deploy" }
]
};
let nextComponentId = 0;
function pipelineActions(
state = initialState,
action: ActionTypes
): StoreState {
switch (action.type) {
case ADD_PIPELINE_ITEM:
return {
...state,
pipelineItems: [
...state.pipelineItems,
{ ...action.data, idx: nextComponentId++ }
]
};
case UPDATE_PIPELINE_ITEM:
return {
...state,
pipelineItems: state.pipelineItems.map((el: PipelineItemType) => {
return el.idx === action.data.idx ? action.data : el;
})
};
case DELETE_PIPELINE_ITEM:
console.log("Delete" + action.idx);
return {
...state,
pipelineItems: state.pipelineItems.filter(
(el: PipelineItemType) => el.idx !== action.idx
)
};
default:
return state;
}
}
let store = createStore(pipelineActions);
ReactDOM.render(
<Provider store={store}>
<App />
</Provider>,
document.getElementById("app")
);
</code></pre>
<p>App.tsx</p>
<pre><code>import React, { Dispatch, Component } from "react";
import {
StoreState,
ADD_PIPELINE_ITEM,
ActionTypes,
UPDATE_PIPELINE_ITEM,
DELETE_PIPELINE_ITEM
} from ".";
import { connect } from "react-redux";
import { ExecuteComponent, Execute, EXECUTE } from "./Execute";
import { CopyComponent, Copy, COPY } from "./Copy";
export type PipelineItemType = Copy | Execute;
export interface AppProps {
pipelineItems: PipelineItemType[];
addItem: (data: PipelineItemType) => void;
updateItem: (data: PipelineItemType) => void;
removeItem: (idx: number) => void;
}
export class App extends Component<AppProps> {
render() {
return (
<div className="App">
{this.props.pipelineItems.map(el => {
switch (el.type) {
case COPY:
return (
<CopyComponent
removeItem={this.props.removeItem}
updateItem={this.props.updateItem}
key={el.idx}
idx={el.idx}
source={el.source}
destination={el.destination}
/>
);
case EXECUTE:
return (
<ExecuteComponent
removeItem={this.props.removeItem}
updateItem={this.props.updateItem}
key={el.idx}
idx={el.idx}
commandLine={el.commandLine}
/>
);
default:
return <div>???</div>;
}
})}
<br />
<br />
Debug Output:
<br />
{JSON.stringify(this.props.pipelineItems)}
</div>
);
}
}
const mapStateToProps = (state: StoreState) => ({
pipelineItems: state.pipelineItems
});
const mapDispatchToProps = (dispatch: Dispatch<ActionTypes>) => ({
addItem: (data: PipelineItemType) =>
dispatch({ type: ADD_PIPELINE_ITEM, data: data }),
updateItem: (data: PipelineItemType) =>
dispatch({ type: UPDATE_PIPELINE_ITEM, data: data }),
removeItem: (idx: number) =>
dispatch({ type: DELETE_PIPELINE_ITEM, idx: idx })
});
export default connect(
mapStateToProps,
mapDispatchToProps
)(App);
</code></pre>
<p>Copy.tsx</p>
<pre><code>import React, { Component } from "react";
import { PipelineItemType } from "./App";
export const COPY = 'COPY'
export interface Copy {
type: typeof COPY;
idx: number;
source: string;
destination: string;
}
export interface CopyItemProps {
idx: number;
source: string;
destination: string;
updateItem: (data: PipelineItemType) => void;
removeItem: (idx: number) => void;
}
export class CopyComponent extends Component<CopyItemProps> {
render() {
return (<div>Will copy from
<input type="text" defaultValue={this.props.source} onBlur={(e) => this.props.updateItem({ type: COPY, idx: this.props.idx, source: e.target.value, destination: this.props.destination })} />
to<input type="text" defaultValue={this.props.destination} onBlur={(e) => this.props.updateItem({ type: COPY, idx: this.props.idx, source: this.props.source, destination: e.target.value })} />
<input type="button" value="X" onClick={(e) => this.props.removeItem(this.props.idx)} />
</div>)
};
}
</code></pre>
<p>Execute.tsx</p>
<pre><code>import React, { Component } from "react";
import { PipelineItemType } from "./App";
export const EXECUTE = "EXECUTE";
export interface Execute {
type: typeof EXECUTE;
idx: number;
commandLine: string;
}
export interface ExecuteItemProps {
idx: number;
commandLine: string;
updateItem: (data: PipelineItemType) => void;
removeItem: (idx: number) => void;
}
export class ExecuteComponent extends Component<ExecuteItemProps> {
render() {
return (
<div>
Will execute
<input
type="text"
defaultValue={this.props.commandLine}
onBlur={e =>
this.props.updateItem({
type: EXECUTE,
idx: this.props.idx,
commandLine: e.target.value
})
}
/>
<input
type="button"
value="X"
onClick={e => this.props.removeItem(this.props.idx)}
/>
</div>
);
}
}
</code></pre>
<p>Questions: </p>
<ul>
<li><p>Is there a better way to render a list of different react components? Currently using a switch as type-guard to get the current component to render. Coming from a C++ background this feels kinda wrong since you do something different based on the type.<br>
I was thinking about storing the react component instance inside the array but I read somewhere that this is bad and will most likely cause multiple issues (Unfortunately I can't find the source anymore)</p></li>
<li><p>Should I keep the add/update/removeItem handler together?<br>
Technically I could dispatch updateItem and removeItem from the child-components, but for me it seems cleaner to keep them bundled together with the addItem method, which means I have to define a callback for the child components.</p></li>
<li><p>In the App.tsx is there an easier way for keys?<br>
Currently using a counter to have unique keys for the Component List</p></li>
<li>When creating a new child component via addItem I need to set <code>idx</code> to an arbitrary value, since it is part of the interface. Is there a better way to do this? Just creating a new interface that doesn't include <code>idx</code> seems a bit redundant for me.</li>
</ul>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-25T11:12:54.147",
"Id": "486532",
"Score": "0",
"body": "Didn't take a look at the whole atm, but what I noticed, your Redux Code is pretty boilerplatey, maybe have a look at `typesafe-actions` package. Further more `idx` is not updated when you remove any item, this seems like an unwanted bug. If I got time, I'll write up a complete review"
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-17T20:15:44.050",
"Id": "242482",
"Score": "1",
"Tags": [
"react.js",
"typescript",
"redux"
],
"Title": "React App with Redux"
}
|
242482
|
<p>This is my current View hierarchy:</p>
<pre><code>ParentView:View {
ChildView1: UIViewRepresentable
ChildView2: View
}
</code></pre>
<p>In ChildView2 I have a button who's action I want to pass to ChildView1. That action is a <code>@Binding</code> on ChildView2, a <code>@State</code> in ParentView where it also is declared, and also a <code>@Binding</code> on ChildView1, where the action takes place.</p>
<p>This is my code:</p>
<pre><code>typealias OnClickHandler = (() -> Void)
struct ParentView: View {
@State var onClick: OnClickHandler = { }
var body: some View {
ZStack {
VStack {
ChildView1(onClick: $onClick)
}
VStack(alignment:.trailing) {
Spacer()
HStack {
Spacer()
ChildView2(onClick: $onClick)
}.padding(EdgeInsets(top: 0, leading: 0, bottom: 30, trailing: 5))
}
}
}
}
struct ChildView2: View {
@Binding var onClick: OnClickHandler
var body: some View {
VStack {
Button(action: onClick) {
Image("SexyImage")
}
}
}
struct ChildView1: UIViewRepresentable {
@Binding var onClick: OnClickHandler
func makeUIView(context: Context) -> UIView {
let view = UIView()
//"Modifying state during view update, this will cause undefined behavior"
//if I don't send it to a background thread.
DispatchQueue.global(qos: .background).async {
self.onClick = self.foo
}
return view
}
public func foo() {
print("bar")
}
internal func makeCoordinator() -> Coordinator {
Coordinator(self)
}
}
</code></pre>
<p>After a couple of days of trial and error, this is the best (and only) solution I found. I use a background thread, otherwise I get a warning for modifying the state during UI update.</p>
<p>I'm curious if there is a better solution.</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-17T21:08:53.703",
"Id": "242484",
"Score": "1",
"Tags": [
"swift",
"swiftui"
],
"Title": "SwiftUI Passing closure between sibling views"
}
|
242484
|
<p>I'm trying to make an ID generator that generates 64 bit longs. The IDs should be globally unique even between two offline machines. This is the same idea as UUID (GUID), but UUID is 128 bit long and contains redundant (constant) bits (eg. it uses the millisecs passed since the year 1980 and has 5-8 versioning bits). I could use either the least or most significant 64 bits of a UUID, but because it contains these constant bits, it may not be unique enough.</p>
<p>So I made my own logic. It's important that it has to run everywhere, so I can't use MAC address, because it's not always accessible (eg. on Android). What do you think of my code?</p>
<pre><code>public class UID {
private static long swRndVal;
private static Random random = new Random();
private static final long mstsigMask = 0b11111111_00000000_00000000_00000000_00000000_00000000_00000000_00000000L;
private static final long middleMask = 0b00000000_11111111_11111111_11111111_11111111_11111111_11111111_11111111L;
private static final long lstsigMask = 0b00000000_00000000_00000000_00000000_00000000_00001111_11111111_11111111L;
static {
String s1 = System.getProperty("os.arch", "");
String s2 = System.getProperty("os.version", "");
String s3 = System.getProperty("java.vm.version", "");
String s4 = System.getProperty("java.class.version", "");
Random rand1 = new Random((s1+s2+s3+s4).hashCode());
Random rand2 = new Random();
swRndVal = rand1.nextLong() ^ rand2.nextLong();
}
public static long getUniqueLong() {
//8 bits of random, 36 bits of millis (~800 days), 20 bits of nanos (~1ms)
return ((random.nextLong() & mstsigMask) | (System.currentTimeMillis() & middleMask) | (System.nanoTime() & lstsigMask)) ^ swRndVal;
}
}
</code></pre>
|
[] |
[
{
"body": "<p>I would just use <a href=\"https://docs.oracle.com/en/java/javase/14/docs/api/java.base/java/util/Random.html#nextLong()\" rel=\"nofollow noreferrer\"><code>SecureRandom#nextLong()</code></a>. <code>SecureRandom</code> will seed itself and shouldn't be the same between two similar computers at the same time. Also, it uses more bits of state than Random (128 vs 48).</p>\n\n<p>I don't know exactly what computers you'll be running this on, but if it's something like a cluster of servers they'll probably have the exact same s1/s2/s3/s4. If they happen to start at the same time (plausible if two processes on two cores are launched by a parents at the same time), then that only leaves the 48 bits of random state.</p>\n\n<p>If you use <code>SecureRandom</code>, you can just call it and immediately get a 64 bit UUID that will have as few collisions as you can possibly guarantee with two offline computers.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-18T13:18:44.383",
"Id": "475902",
"Score": "0",
"body": "SecureRandom is a good idea, I think I'll use it instead of `random` and `rand2`. But I think it's a good idea to leave some machine-specific info in it. It won't help in cluster scenarios, but it won't really hurt either. And in any other situation it can help. Currently I plan to use it in an Android app that will eventually synchronize back to a server. Also I intend to use this mostly for small projects, so I wouldn't worry that much about collision. For larger projects I would probably find a way to include the MAC address."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-19T02:37:52.060",
"Id": "475972",
"Score": "1",
"body": "It's a bit counterintuitive, but adding something machine specific won't help unless you can guarantee that it will be unique (i.e. MAC address) and separate it from the random value. If you don't separate it from the random value (e.g. by XORing it in), it adds nothing as the result has the same chance of collisions. If you separate it from the random value (by masking off the random value and ORing it in), then it's beneficial if you can guarantee uniqueness and detrimental otherwise, as it removes entropy."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-20T07:36:43.170",
"Id": "476098",
"Score": "0",
"body": "That's right, I didn't see that. So I should ditch the machine specific part, because it would take away too much random state if I separated it from the rest. But I can still see that adding the time is useful. I would use this for an application where the IDs are generated in about 5pcs batch and at least a few seconds are passed between batches. Do you think it's a better idea to leave out the nanos and use 28 bits of random instead?"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-18T02:29:13.043",
"Id": "242495",
"ParentId": "242486",
"Score": "3"
}
},
{
"body": "<p>It's a terrible idea to use only 64 bits for a \"globally unique ID\". As soon as you generate <span class=\"math-container\">\\$2^{32}\\$</span> IDs with that, the <a href=\"https://en.wikipedia.org/wiki/Birthday_problem#Probability_table\" rel=\"nofollow noreferrer\">probability of a collision</a> is 50 percent, and <span class=\"math-container\">\\$2^{32}\\$</span> can be achieved in less than a day by a single computer.</p>\n\n<p>I also cannot follow your reasoning:</p>\n\n<blockquote>\n <p>UUID uses 128 bits in the encoded value, and 6 of them are fixed when using random UUIDs. This means 122 random bits remain. That's not enough for me, therefore I use my own scheme that has only 64 bits of randomness.</p>\n</blockquote>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-18T13:12:14.190",
"Id": "475901",
"Score": "0",
"body": "That is nothing like my reasoning. I said that I must have 64 bit ids, 128 bit is out of question. So I could take a UUID and split it to 2 pieces. Java has two methods for this: getMostSignificantBits() and getLeastSignificantBits(). My reasoning is that neither of these have 64 bits of randomness in a certain timeframe. I agree that using a UUID as it is is better than my method, but using half of it is worse."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-18T06:24:07.250",
"Id": "242504",
"ParentId": "242486",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-17T21:37:43.833",
"Id": "242486",
"Score": "3",
"Tags": [
"java",
"random"
],
"Title": "Universally unique 64 bit long generator"
}
|
242486
|
<p>Could you look at my code for the completed training project of the Python Hangman game and tell me where you can improve the code style?</p>
<p><a href="https://github.com/sergeVe/python-hangman-game/blob/master/hangman/hangman.py" rel="nofollow noreferrer">Code on GitHub</a></p>
<pre><code>import random
from string import ascii_lowercase
class Hangman:
@staticmethod
def print_welcome():
print('H A N G M A N')
def __init__(self):
self.__state = 'welcome'
self.__keyword = None
self.__keywords = ['python', 'java', 'kotlin', 'javascript']
self.__letters_number = None
self.placeholder = '-'
self.hint = []
self.keyword_set = set()
self.attempt = 8
self.victory = False
self.user_letters_set = set()
self.deleted_letters_set = set()
self.mistake_message = ''
self.user_choice = ''
@property
def state(self) -> str:
return self.__state
@state.setter
def state(self, state_string):
self.__state = state_string
@property
def keyword(self) -> str:
return self.__keyword
@keyword.setter
def keyword(self, new_word):
self.__keyword = new_word
@property
def keywords(self) -> list:
return self.__keywords
def print_query_message(self):
self.user_choice = input('Type "play" to play the game, "exit" to quit:')
def run(self):
self.print_welcome()
while True:
if self.state == 'welcome':
while self.user_choice not in ['play', 'exit']:
self.print_query_message()
if self.user_choice == 'exit':
return None
self.state = 'init'
if self.state == 'init':
self.init_func()
self.state = 'on'
if self.state == 'on':
if not self.process_player():
self.state = 'off'
if self.state == 'off':
print(f'{self.get_analyze_result()}\n')
self.user_choice = ''
self.state = 'welcome'
def process_player(self):
print('\n' + ''.join(self.hint))
answer = input('Input a letter: ')
self.check_answer(answer)
if len(self.keyword_set) == 0:
self.victory = True
return False
if self.attempt == 0:
return False
return True
def find_letter_pos(self, letter):
letter_positions = []
ind = 0
while ind < len(self.keyword):
pos = self.keyword.find(letter, ind)
if pos == -1:
break
letter_positions.append(pos)
ind = pos + 1
return letter_positions
def transform_hint(self, letter):
positions = self.find_letter_pos(letter)
temp = self.hint
for ind in positions:
temp[ind] = letter
self.hint = temp
def init_func(self):
self.keyword = random.choice(self.keywords)
self.keyword_set = set(self.keyword)
self.hint = [self.placeholder for _i in range(len(self.keyword))]
def check_answer(self, letter):
if self.is_input_mistake(letter):
print(self.mistake_message)
elif letter in self.keyword_set:
self.transform_hint(letter)
self.keyword_set.discard(letter)
self.deleted_letters_set.add(letter)
else:
if not self.victory:
self.for_reduce_attempt(letter)
print(self.mistake_message)
def is_input_mistake(self, letter):
if len(letter) != 1:
self.mistake_message = 'You should print a single letter'
return True
if letter not in ascii_lowercase:
self.mistake_message = 'It is not an ASCII lowercase letter'
return True
if any([letter in self.deleted_letters_set, letter in self.user_letters_set]):
self.mistake_message = 'You already typed this letter'
return True
return False
def get_analyze_result(self):
if self.victory:
return 'You guessed the word!\nYou survived!'
return 'You are hanged!'
def for_reduce_attempt(self, letter):
self.user_letters_set.add(letter)
self.mistake_message = 'No such letter in the word'
self.attempt -= 1
hangman = Hangman()
hangman.run()
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-18T11:55:40.940",
"Id": "475895",
"Score": "0",
"body": "What's \"© 2020 GitHub, Inc.\" doing inside your code? I've removed it for now, but please take care while copying your code."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-17T21:41:55.810",
"Id": "242487",
"Score": "4",
"Tags": [
"python",
"python-3.x",
"hangman"
],
"Title": "Check the organization and code style of a small Python project"
}
|
242487
|
<p>In a personal project I was working on, I had a vector of <code>std::vector< std::pair<unsigned,char>></code>'s that represented a character and its position in the alphabet. I found that using/manipulating that vector to be clumsy so I wrote this implementation. Essentially, it just wraps the usual vector operations. I'm hoping for the following things to be considered, as well as the usual areas of review:</p>
<ul>
<li>Are there any other operations that should be implemented?</li>
<li>I didn't have a C++20 compiler available at the time of writing this, what needs to be done to "modernize" the code?</li>
<li>Are there specific ways to change or improve the code?</li>
</ul>
<p>And a few notices</p>
<ul>
<li>I know that <code>begin()</code> and <code>end()</code> should return a <code>std::vector::iterator</code>, but I was having difficulties making that compile so I kept it as <code>auto</code> for the time begin. (Yes,I know that is a dirty hack. It's on my to do list.</li>
<li>There are other operators that need to be overloaded ( <code>=</code> and <code>==</code> especially), but I wanted to improve the existing code before adding more.</li>
</ul>
<p>The code is licensed under the BSD Clause 3 license, if you wish to use it/change it.</p>
<pre><code>#include <iostream>
#include <vector>
template< typename Left, typename Right>
class Vecpair
{
public:
auto begin(void);
auto end(void);
void pushBack(Left,Right);
void pushBack( std::pair<Left,Right> );
void popBack(void);
void clear(void);
std::size_t getSize(void);
std::pair<Left,Right> atPos(unsigned);
std::pair<Left,RIght> front(void);
std::pair<Left,Right> back(void):
std:::pair<Left,Right> operator [] (unsigned i){ return( internal.at(i) ); }
private:
std::size_t numElem = 0;
std::vector< std::pair<Left,Right>> internal;
};
// Returns an iterator to the beginning of 'internal'.
template< typename Left, typename Right>
auto Vecpair<Left,Right>::begin(void)
{
return( internal.begin() );
}
// Returns an iterator to the end of 'internal'.
template< typename Left, typename Right>
auto Vecpair<Left,Right>::end(void)
{
return( internal.end() );
}
// Takes two separate values and pushes them to the back of 'internal' as a pair.
template< typename Left, typename Right>
void Vecpair<Left,Right>::pushBack(Left l, Right r)
{
internal.push_back( {l,r} );
numElem++;
}
// Takes a pair and pushes to the back of 'internal'.
template< typename Left, typename Right>
void Vecpair<Left,Right>::pushBack( std::pair<Left,Right> p )
{
internal.push_back( p );
numElem++;
}
// Pops the last element.
template< typename Left, typename Right>
void Vecpair<Left,Right>::popBack(void);
{
internal.pop_back();
numElem--;
}
// Clears 'internal'.
template< typename Left, typename Right>
void Vecpair<Left,Right>::clear(void)
{
internal.clear();
numElem = 0;
}
// Returns the number of elements;
template< typename Left, typename Right>
std::size_t Vecpair<Left,Right>::getSize(void)
{
return( numElem );
}
// Returns the pair at the given position.
template< typename Left, typename Right>
std::pair<Left, Right> Vecpair<Left,Right>::atPos(unsigned idx)
{
return( internal.at(idx) );
}
// Returns the first pair.
template< typename Left, typename Right>
std::pair<Left,Right> Vecpair<Left,Right>::front(void)
{
return( internal.front() );
}
// Returns the last pair.
template<typename Left, Typename Right>
std::pair<Left,Right> Vecpair<Left,Right>::back(void)
{
return( internal.back() );
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-18T02:13:40.910",
"Id": "475851",
"Score": "4",
"body": "I don't see what benefits this provides over just using the original type. Can you give an example of a usage that yours is better for?"
}
] |
[
{
"body": "<p>I believe you had to put <code>typename</code> before <code>std::vector<...>::iterator</code> to make it compile. <code>iterator</code> is a dependent name, thus compiler needs a hint (well, in reality it doesn't need it in context of type alias declaration, it is just how syntax is defined <a href=\"http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2018/p0634r3.html\" rel=\"nofollow noreferrer\">before C++20</a>).</p>\n\n<h2>Interface</h2>\n\n<p>Lets address the elephant in the room first. This class trims down the features of <code>std::vector<std::pair<T, U>></code> without any visible benefit. Things like <code>std::back_inserter</code> will not work because members are named with different name, comparison operators will not work, there are no type aliases inside the class so users will have to write template metaprogramming for simple things, and so on. </p>\n\n<p>I do not see any benefit of using this instead of <code>std::vector<std::pair<T, U>></code>.</p>\n\n<h2>Implementation</h2>\n\n<p>There is no need to have <code>void</code> in the parameter list, empty parameter list means the functions doesn't take any parameters.</p>\n\n<p><code>numElem</code> looks redundant.</p>\n\n<p>Access functions should be <code>const</code>, possibly <code>noexcept</code>.</p>\n\n<p>Some functions are defined inline, some are not, although they are of the same complexity. This might lead to nasty linker issues.</p>\n\n<p>Putting return value in <code>()</code> might get problematic. When using things like <code>decltype</code>, that will actually alter the result.</p>\n\n<h2>Designing interfaces</h2>\n\n<p>Wrappers are usually made to <em>streamline</em> one way of usage, possibly without losing any expressive power over original. I believe the main idea was to provide a two-way mapping from two continuous ranges. When designing such wrappers, it is important to understand under which constraints the wrappers are going to work. Let me throw some from top of my head:</p>\n\n<ol>\n<li><p>The input will be in the form <code>{index-like, index-like}</code></p></li>\n<li><p>Two ranges are continuous (from 1 to 26, from 'a' to 'z' given ASCII)</p></li>\n<li><p>It is possible to normalize the values (e.g. substract a value to make the first one 0), for example for letters it will be substract the value of <code>'a'</code></p></li>\n<li><p>No values outside of the given ranges are ever to be queried</p></li>\n<li><p>The mapping is one-to-one and onto, e.g. for each value on one side, there is corresponding value on the other side, and it is unique.</p></li>\n</ol>\n\n<p>If the (1) and/or (2) don't hold. one will need to consider <code>std::map</code> and siblings.</p>\n\n<p>The usage scenarios are as following:</p>\n\n<ol>\n<li><p>User can somehow read/provide the mapping in the form of a range of <code>std::pair<T, U></code> or as two separate ranges</p></li>\n<li><p>User wants to query both ways, e.g. <code>mapping[right]</code> would return an object of <code>Left</code> type, and <code>mapping[left]</code> will return an object of <code>Right</code> type: <code>mapping[3] == 'c' && mapping['c'] == 3</code>.</p></li>\n<li><p>User might want to know if two mapping are equal, e.g. <code>operator==</code> and <code>operator!=</code> should be provided.</p></li>\n<li><p>Users might want to define some relationships after the object was created, thus insertion functions like <code>define(const Left& left, const Right& right)</code> are needed. Perfect forwarding might be needed.</p></li>\n<li><p>Users do not modify the relationships (the pair itself) after they are defined</p></li>\n<li><p>Users might want to remove a relationship</p></li>\n</ol>\n\n<p>With those, I believe something like this could fit in:</p>\n\n<pre><code>template <typename Left, typename Right>\nclass mapping\n{\n // internals \npublic:\n template <typename InputIterator>\n mapping(InputIterator first, InputIterator last); //extract mappings from iteator range\n\n // C++20 range version here\n // ditto for version where mappings provided as two ranges\n\n // rule of 0/3/5 depending on the implementation\n\n const Right& operator[](const Left& left) const; // no need for non-const version\n const Left& operator[](const Right& right) const;\n\n // returns false if either side is already in some relationship\n bool define(const Left& left, const Right& right) noexcept; \n // overload for `std::pair` version\n\n // throws f either side is already in some relationship\n void try_define(const Left& left, const Right& right);\n // overload for `std::pair` version\n\n // returns true if the relationship existed and now removed\n bool remove(const Left& left, const Right& right) noexcept(destructor(Left) && destructor(Right)); //pseudocode for noexcept\n // pair version\n // throwing version\n\n\n\n template <typename Left, typename Right>\n friend bool operator==(const mapping<Left, Right>& lhs, const mapping<Left, Right>& rhs);\n\n template <typename Left, typename Right>\n friend bool operator!=(const mapping<Left, Right>& lhs, const mapping<Left, Right>& rhs);\n\n template <typename Left, typename Right>\n friend void swap(mapping<Left, Right>& lhs, mapping<Left, Right>& rhs);\n};\n\n</code></pre>\n\n<p>There are other things one might need, since those are basically sets, operations like</p>\n\n<ol>\n<li><p>Merge</p></li>\n<li><p>Difference</p></li>\n<li><p>Intersection</p></li>\n</ol>\n\n<p>might be needed for the user.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-18T13:19:36.290",
"Id": "242514",
"ParentId": "242494",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-18T01:39:12.670",
"Id": "242494",
"Score": "0",
"Tags": [
"c++",
"template",
"vectors",
"wrapper"
],
"Title": "Implementation of a vector of pairs"
}
|
242494
|
<p>I have a very simple file where I have a Qcombobox Filter. When you select the filter, I run through a case on the index and output results.</p>
<p>So, on selection I trigger:</p>
<pre><code>self.comboBox.activated.connect(self.handleActivated)
</code></pre>
<p>Then,</p>
<p>my handled function is</p>
<pre class="lang-py prettyprint-override"><code> def handleActivated(self, index):
db = QSqlDatabase.addDatabase("QSQLITE")
db.setDatabaseName("data.db")
db.open()
# tableView = QtWidgets.QTableView()
if index == 0:
sourceModel = QSqlQueryModel()
sourceModel.setQuery(
"SELECT url,size,content_type FROM 'google.com.au'",
db)
proxyModel = QSortFilterProxyModel(self)
proxyModel.setSourceModel(sourceModel)
self.tableView.setModel(proxyModel)
self.tableView.setSortingEnabled(True)
elif index == 1:
sourceModel = QSqlQueryModel()
sourceModel.setQuery(
"SELECT url,size,content_type FROM 'google.com.au' WHERE content_type LIKE '%html%'",
db)
proxyModel = QSortFilterProxyModel(self)
proxyModel.setSourceModel(sourceModel)
self.tableView.setModel(proxyModel)
self.tableView.setSortingEnabled(True)
elif index == 2:
sourceModel = QSqlQueryModel()
sourceModel.setQuery(
"SELECT url,size,content_type FROM 'google.com.au' WHERE content_type LIKE '%javascript%'",
db)
proxyModel = QSortFilterProxyModel(self)
proxyModel.setSourceModel(sourceModel)
self.tableView.setModel(proxyModel)
self.tableView.setSortingEnabled(True)
</code></pre>
<p>My question is, is this the most efficient way of writing this code ? I have upto 15 filters and this will become really cumbersome in my main file.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-18T09:20:38.553",
"Id": "475877",
"Score": "0",
"body": "Welcome to CodeReview@SE. Well done on acting on your doubts about the advisability of the approach presented."
}
] |
[
{
"body": "<p>Well you have already identified the problem: <strong>repetition</strong>.\nIt can be tackled fairly easily. Instead of that <code>if/elif</code> block you can use a (zero-indexed) list that contains the <code>WHERE</code> clause for the query:</p>\n\n<pre><code> options = [ None, '%html%', '%javascript%']\n query = \"SELECT url,size,content_type FROM 'google.com.au'\"\n\n if options[index] is not None:\n query += f\" WHERE content_type LIKE '{options[index]}'\"\n\n sourceModel = QSqlQueryModel()\n sourceModel.setQuery(query, db)\n proxyModel = QSortFilterProxyModel(self)\n proxyModel.setSourceModel(sourceModel)\n self.tableView.setModel(proxyModel)\n self.tableView.setSortingEnabled(True)\n</code></pre>\n\n<p>Only the first option is different: there is no <code>WHERE</code> clause. In the other places the request is always the same, it's only the search pattern that is different.</p>\n\n<p>What I am doing here is simply selective string concatenation. Note: using an F-string for the <code>WHERE</code> clause, requires Python >= 3.6. Usage is not mandatory but if you have a recent version of Python embrace the new features.</p>\n\n<p>Instead of <code>None</code> you could say <code>''</code> (an empty string). I chose <code>None</code> to signify option #0 is a special case. I am not checking that <code>index</code> is actually in the range 0->2. If you think this could happen, add a <code>if</code> to check.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-19T00:23:54.043",
"Id": "475968",
"Score": "0",
"body": "Wow ! Thank you, that makes much more sense. On running your code I got a small error `TypeError: can only concatenate tuple (not “str”) to tuple Error' which I fixed by adding a `()` on the query and it works as expected."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-18T18:58:19.510",
"Id": "242527",
"ParentId": "242498",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "242527",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-18T05:03:11.003",
"Id": "242498",
"Score": "0",
"Tags": [
"python",
"sqlite",
"qt",
"pyside"
],
"Title": "QCombobox Case selection - Pyside2 Index via Sqlite"
}
|
242498
|
<p>This BST implementation seems to work, I would appreciate an advice on how to improve the code. I am also interested in the following: </p>
<ul>
<li>rule-of-5 methods, are all of them necessary (e.g. is destructor necessary when using smart pointers)? Are they implemented correctly?</li>
<li>Does <code>Node</code> class need rule-of-5 methods?</li>
<li>is <code>clear()</code> method implemented correctly? I think that if I set the <code>root</code> to <code>nullptr</code>, the rest of the <code>Node</code>s will be deleted by the smart pointer's destructor when the <code>BinarySearchTree</code> and therefore the <code>Node</code> go out of scope, is it correct?</li>
<li>Is the use of smart/raw pointers correct? I want to use raw pointers everywhere, where they don't need to own the object, right?</li>
<li><code>const</code> correctness</li>
</ul>
<p>Any other advice will be appreciated too.</p>
<p><strong>BinarySearchTree.hpp</strong></p>
<pre><code>#ifndef BINARY_SEARCH_TREE_H
#define BINARY_SEARCH_TREE_H
#include <iostream>
#include <vector>
#include <queue>
class BinarySearchTree {
public:
BinarySearchTree();
BinarySearchTree(const int& value);
BinarySearchTree(const BinarySearchTree& other_tree);
BinarySearchTree(BinarySearchTree&& other_tree);
BinarySearchTree& operator=(const BinarySearchTree& other_tree);
BinarySearchTree& operator=(BinarySearchTree&& other_tree);
~BinarySearchTree();
void build_from_vector(std::vector<int>& values);
void build_from_vector_balanced(std::vector<int>& values);
void insert_node(const int& value);
void remove_node(const int& value);
void clear();
int min_val() const;
int max_val() const;
bool contains(const int& val) const;
int max_depth() const;
bool balanced() const;
std::vector<int> get_inorder_vals() const;
std::vector<int> get_preorder_vals() const;
std::vector<int> get_postorder_vals() const;
std::vector<int> get_level_order_vals() const;
inline int size() const {
return tree_size;
}
inline bool empty() const {
return tree_size == 0;
}
private:
struct Node {
int val;
std::unique_ptr<Node> left = nullptr;
std::unique_ptr<Node> right = nullptr;
Node(const int value) :
val{value},
left{nullptr},
right{nullptr}
{}
};
std::unique_ptr<Node> root;
int tree_size;
void deep_copy_tree(std::unique_ptr<Node>& dest_node, const std::unique_ptr<Node>& source_node);
void build_from_vector_balanced(std::vector<int>::iterator it_b, std::vector<int>::iterator it_e);
void insert_node(const int& value, std::unique_ptr<Node>& curr_node);
void remove_node(const int value, std::unique_ptr<Node>& curr_node);
Node* find_min_node(const std::unique_ptr<Node>& curr_node) const;
Node* find_max_node(const std::unique_ptr<Node>& curr_node) const;
bool contains(const int& value, const std::unique_ptr<Node>& curr_node) const;
bool balanced(const std::unique_ptr<Node>& curr_node, int& height) const;
int max_depth(const std::unique_ptr<Node>& curr_node) const;
void get_inorder_vals(std::vector<int>& vals, const std::unique_ptr<Node>& curr_node) const;
void get_preorder_vals(std::vector<int>& vals, const std::unique_ptr<Node>& curr_node) const;
void get_postorder_vals(std::vector<int>& vals, const std::unique_ptr<Node>& curr_node) const;
void get_level_order_vals(std::vector<int>& vals, const std::unique_ptr<Node>& curr_node) const;
};
#endif /* BINARYSEARCHTREE_H */
</code></pre>
<p><strong>BinarySearchTree.cpp</strong></p>
<pre><code>#include "BinarySearchTree.hpp"
BinarySearchTree::BinarySearchTree() : root{nullptr}, tree_size{0}
{}
BinarySearchTree::BinarySearchTree(const int& value) : root{std::make_unique<Node>(value)}, tree_size{1}
{}
BinarySearchTree::BinarySearchTree(const BinarySearchTree& other_tree) {
if (other_tree.tree_size == 0) return;
tree_size = other_tree.tree_size;
deep_copy_tree(root, other_tree.root);
}
BinarySearchTree::BinarySearchTree(BinarySearchTree&& other_tree) :
root(std::exchange(other_tree.root, nullptr)), tree_size(std::exchange(other_tree.tree_size, 0))
{
}
BinarySearchTree& BinarySearchTree::operator=(const BinarySearchTree& other_tree) {
clear();
tree_size = other_tree.tree_size;
deep_copy_tree(root, other_tree.root);
return *this;
}
BinarySearchTree& BinarySearchTree::operator=(BinarySearchTree&& other_tree) {
clear();
tree_size = other_tree.tree_size;
deep_copy_tree(root, other_tree.root);
other_tree.tree_size = 0;
other_tree.root = nullptr;
return *this;
}
BinarySearchTree::~BinarySearchTree() {
clear();
}
void BinarySearchTree::build_from_vector(std::vector<int>& values) {
for (const int& value : values) {
insert_node(value);
}
}
void BinarySearchTree::build_from_vector_balanced(std::vector<int>& values) {
std::sort(values.begin(), values.end());
std::vector<int>::iterator it_b = values.begin();
std::vector<int>::iterator it_e = values.end() - 1;
build_from_vector_balanced(it_b, it_e);
}
void BinarySearchTree::insert_node(const int& value) {
insert_node(value, root);
}
void BinarySearchTree::remove_node(const int& value) {
remove_node(value, root);
}
void BinarySearchTree::clear() {
root = nullptr;
tree_size = 0;
}
int BinarySearchTree::min_val() const {
return find_min_node(root)->val;
}
int BinarySearchTree::max_val() const {
return find_max_node(root)->val;
}
bool BinarySearchTree::contains(const int& val) const {
return contains(val, root);
}
int BinarySearchTree::max_depth() const {
return max_depth(root);
}
bool BinarySearchTree::balanced() const {
int height = 0;
return balanced(root, height);
}
std::vector<int> BinarySearchTree::get_inorder_vals() const {
std::vector<int> vals;
get_inorder_vals(vals, root);
return vals;
}
std::vector<int> BinarySearchTree::get_preorder_vals() const {
std::vector<int> vals;
get_preorder_vals(vals, root);
return vals;
}
std::vector<int> BinarySearchTree::get_postorder_vals() const {
std::vector<int> vals;
get_postorder_vals(vals, root);
return vals;
}
std::vector<int> BinarySearchTree::get_level_order_vals() const {
std::vector<int> vals;
get_level_order_vals(vals, root);
return vals;
}
void BinarySearchTree::deep_copy_tree(std::unique_ptr<Node>& dest_node, const std::unique_ptr<Node>& source_node) {
if (!source_node) return;
dest_node = std::make_unique<Node>(source_node->val);
deep_copy_tree(dest_node->left, source_node->left);
deep_copy_tree(dest_node->right, source_node->right);
}
void BinarySearchTree::build_from_vector_balanced(std::vector<int>::iterator it_b, std::vector<int>::iterator it_e) {
if (it_b > it_e) return;
int range = std::distance(it_b, it_e);
std::vector<int>::iterator it_m = it_b + range / 2;
insert_node(*it_m);
build_from_vector_balanced(it_b, it_m - 1);
build_from_vector_balanced(it_m + 1, it_e);
}
void BinarySearchTree::insert_node(const int& value, std::unique_ptr<Node>& curr_node) {
if (!curr_node) {
curr_node = std::make_unique<Node>(value);
tree_size++;
return;
}
if (value == curr_node->val)
return;
if (value < curr_node->val)
insert_node(value, curr_node->left);
else // (value > curr_node->val)
insert_node(value, curr_node->right);
}
void BinarySearchTree::remove_node(const int value, std::unique_ptr<Node>& curr_node) {
if (!curr_node) return;
if (value < curr_node->val) {
remove_node(value, curr_node->left);
} else if (value > curr_node->val) {
remove_node(value, curr_node->right);
} else { // (value == curr_node->val)
// remove it
if (!curr_node->left && !curr_node->right) { // leaf
tree_size--;
curr_node = nullptr;
} else if (curr_node->left && !curr_node->right) { // only left child
tree_size--;
curr_node = std::move(curr_node->left);
} else if (!curr_node->left && curr_node->right) { // only right child
tree_size--;
curr_node = std::move(curr_node->right);
} else {
// both right and left children: replace val by left subtree's max value
Node* temp = find_max_node(curr_node->left); // ok to have raw pointer here?
curr_node->val = temp->val;
// then remove left subtree's max node
remove_node(temp->val, curr_node->left);
}
}
}
BinarySearchTree::Node* BinarySearchTree::find_min_node(const std::unique_ptr<Node>& curr_node) const {
if (!curr_node) return nullptr;
if (!curr_node->left) return curr_node.get();
return find_min_node(curr_node->left);
}
BinarySearchTree::Node* BinarySearchTree::find_max_node(const std::unique_ptr<Node>& curr_node) const {
if (!curr_node) return nullptr;
if (!curr_node->right) return curr_node.get();
return find_max_node(curr_node->right);
}
bool BinarySearchTree::contains(const int& value, const std::unique_ptr<Node>& curr_node) const {
if (!curr_node) return false;
if (value == curr_node->val) return true;
if (value < curr_node->val) return contains(value, curr_node->left);
return contains(value, curr_node->right);
}
bool BinarySearchTree::balanced(const std::unique_ptr<Node>& curr_node, int& height) const {
if (!curr_node) {
height = -1;
return true;
}
int left = 0;
int right = 0;
if (balanced(curr_node->left, left)
&& balanced(curr_node->right, right)
&& std::abs(left - right) < 2) {
height = std::max(left, right) + 1;
return true;
}
return false;
}
int BinarySearchTree::max_depth(const std::unique_ptr<Node>& curr_node) const {
if (!curr_node) return -1;
return std::max(max_depth(curr_node->left), max_depth(curr_node->right)) + 1;
}
void BinarySearchTree::get_inorder_vals(std::vector<int>& vals,
const std::unique_ptr<Node>& curr_node) const {
if (!curr_node) return;
get_inorder_vals(vals, curr_node->left);
vals.push_back(curr_node->val);
get_inorder_vals(vals, curr_node->right);
}
void BinarySearchTree::get_preorder_vals(std::vector<int>& vals,
const std::unique_ptr<Node>& curr_node) const {
if (!curr_node) return;
vals.push_back(curr_node->val);
get_preorder_vals(vals, curr_node->left);
get_preorder_vals(vals, curr_node->right);
}
void BinarySearchTree::get_postorder_vals(std::vector<int>& vals,
const std::unique_ptr<Node>& curr_node) const {
if (!curr_node) return;
get_postorder_vals(vals, curr_node->left);
get_postorder_vals(vals, curr_node->right);
vals.push_back(curr_node->val);
}
void BinarySearchTree::get_level_order_vals(std::vector<int>& vals,
const std::unique_ptr<Node>& curr_node) const {
if (!curr_node) return;
std::queue<Node*> nodes_by_level;
nodes_by_level.push(curr_node.get());
while (!nodes_by_level.empty()) {
Node* temp_node = nodes_by_level.front();
nodes_by_level.pop();
if (temp_node->left) nodes_by_level.push(temp_node->left.get());
if (temp_node->right) nodes_by_level.push(temp_node->right.get());
vals.push_back(temp_node->val);
}
}
</code></pre>
<p><strong>main.cpp</strong></p>
<pre><code>int main() {
std::cout << "=== BINARY SEARCH TREE ===\n";
std::cout << "--------------------------\n";
std::cout << "Build unbalanced vs balanced" << std::endl;
BinarySearchTree myBST_unb;
BinarySearchTree myBST_b;
std::vector<int> values_sorted_back {9, 8, 7, 6, 5, 4, 3, 2, 1};
myBST_unb.build_from_vector(values_sorted_back);
myBST_b.build_from_vector_balanced(values_sorted_back);
std::cout << "Is balanced myBST_unb: " << myBST_unb.balanced() << std::endl;
std::cout << "Is balanced myBST_b: " << myBST_b.balanced() << std::endl;
std::cout << "Max depth myBST_unb: " << myBST_unb.max_depth() << std::endl;
std::cout << "Max depth myBST_b: " << myBST_b.max_depth() << std::endl;
std::cout << "myBST_unb size: " << myBST_unb.size() << std::endl;
std::cout << "myBST_unb empty? " << myBST_unb.empty() << std::endl;
std::cout << "myBST_b size: " << myBST_b.size() << std::endl;
std::cout << "myBST_b empty? " << myBST_b.empty() << std::endl;
// Traversals:
std::vector<int> vals_inorder_unb = myBST_unb.get_inorder_vals();
std::vector<int> vals_preorder_unb = myBST_unb.get_preorder_vals();
std::vector<int> vals_postorder_unb = myBST_unb.get_postorder_vals();
std::vector<int> vals_level_order_unb = myBST_unb.get_level_order_vals();
std::vector<int> vals_inorder_b = myBST_b.get_inorder_vals();
std::vector<int> vals_preorder_b = myBST_b.get_preorder_vals();
std::vector<int> vals_postorder_b = myBST_b.get_postorder_vals();
std::vector<int> vals_level_order_b = myBST_b.get_level_order_vals();
std::cout << "Inorder values myBST_unb: " << std::endl;
for (auto& val : vals_inorder_unb)
std::cout << val << " ";
std::cout << std::endl;
std::cout << "Preorder values myBST_unb: " << std::endl;
for (auto& val : vals_preorder_unb)
std::cout << val << " ";
std::cout << std::endl;
std::cout << "Postorder values myBST_unb: " << std::endl;
for (auto& val : vals_postorder_unb)
std::cout << val << " ";
std::cout << std::endl;
std::cout << "Level order values myBST_unb: " << std::endl;
for (auto& val : vals_level_order_unb)
std::cout << val << " ";
std::cout << std::endl;
std::cout << "Inorder values myBST_b: " << std::endl;
for (auto& val : vals_inorder_b)
std::cout << val << " ";
std::cout << std::endl;
std::cout << "Preorder values myBST_b: " << std::endl;
for (auto& val : vals_preorder_b)
std::cout << val << " ";
std::cout << std::endl;
std::cout << "Postorder values myBST_b: " << std::endl;
for (auto& val : vals_postorder_b)
std::cout << val << " ";
std::cout << std::endl;
std::cout << "Level order values myBST_b: " << std::endl;
for (auto& val : vals_level_order_b)
std::cout << val << " ";
std::cout << std::endl;
// ---------------------------------------
std::cout << "--------------------------\n";
std::cout << "Remove nodes" << std::endl;
BinarySearchTree myBST;
std::vector<int> values {1, 2, 3, 4, 5, 6, 7, 8, 9};
myBST.build_from_vector_balanced(values);
std::cout << "Max value: " << myBST.max_val() << std::endl;
std::cout << "Min value: " << myBST.min_val() << std::endl;
std::cout << "Contains 5: " << myBST.contains(5) << std::endl;
std::cout << "Contains 15: " << myBST.contains(15) << std::endl;
std::cout << "Before removing nodes" << std::endl;
std::cout << "myBST size: " << myBST.size() << std::endl;
std::cout << "myBST empty? " << myBST.empty() << std::endl;
std::vector<int> vals_inorder = myBST.get_inorder_vals();
std::cout << "Inorder values: " << std::endl;
for (auto& val : vals_inorder)
std::cout << val << " ";
std::cout << std::endl;
myBST.remove_node(9);
myBST.remove_node(5);
myBST.remove_node(2);
myBST.remove_node(1);
myBST.remove_node(1);
std::cout << "Removed 9, 5, 2, 1, 1" << std::endl;
std::cout << "myBST size: " << myBST.size() << std::endl;
std::cout << "myBST empty? " << myBST.empty() << std::endl;
vals_inorder = myBST.get_inorder_vals();
std::cout << "Inorder values: " << std::endl;
for (auto& val : vals_inorder)
std::cout << val << " ";
std::cout << std::endl;
myBST.remove_node(80);
myBST.remove_node(2);
myBST.remove_node(3);
myBST.remove_node(4);
myBST.remove_node(6);
myBST.remove_node(7);
myBST.remove_node(8);
std::cout << "Removed 80, 2, 3, 4, 6, 7, 8" << std::endl;
std::cout << "myBST size: " << myBST.size() << std::endl;
std::cout << "myBST empty? " << myBST.empty() << std::endl;
// ---------------------------------------
std::cout << "--------------------------\n";
std::cout << "Insert nodes" << std::endl;
myBST.insert_node(10);
myBST.insert_node(50);
myBST.insert_node(20);
myBST.insert_node(5);
std::cout << "Inserted 10, 50, 20, 5" << std::endl;
std::cout << "myBST size: " << myBST.size() << std::endl;
std::cout << "myBST empty? " << myBST.empty() << std::endl;
vals_inorder = myBST.get_inorder_vals();
std::cout << "Inorder values: " << std::endl;
for (auto& val : vals_inorder)
std::cout << val << " ";
std::cout << std::endl;
// ---------------------------------------
std::cout << "--------------------------\n";
std::cout << "Copy constructor" << std::endl;
BinarySearchTree myBST_orig;
myBST_orig.build_from_vector_balanced(values);
BinarySearchTree myBST_copy = myBST_orig;
myBST_orig.insert_node(15);
myBST_copy.insert_node(12);
std::vector<int> vals_inorder_orig = myBST_orig.get_inorder_vals();
std::vector<int> vals_inorder_copy = myBST_copy.get_inorder_vals();
std::cout << "Inorder values myBST_orig: " << std::endl;
for (auto& val : vals_inorder_orig)
std::cout << val << " ";
std::cout << std::endl;
std::cout << "Inorder values myBST_copy: " << std::endl;
for (auto& val : vals_inorder_copy)
std::cout << val << " ";
std::cout << std::endl;
// ---------------------------------------
std::cout << "--------------------------\n";
std::cout << "Copy assignment operator" << std::endl;
// Not really sure how to test this
BinarySearchTree myBST_orig_assign;
std::vector<int> values1 {1, 2, 3, 4, 5};
myBST_orig_assign.build_from_vector_balanced(values1);
BinarySearchTree myBST_copy_assign;
std::vector<int> values2 {6, 7, 8, 9};
myBST_copy_assign.build_from_vector_balanced(values2);
std::vector<int> vals_inorder_orig_assign = myBST_orig_assign.get_inorder_vals();
std::vector<int> vals_inorder_copy_assign = myBST_copy_assign.get_inorder_vals();
std::cout << "Inorder values before assign: myBST_orig_assign: " << std::endl;
for (auto& val : vals_inorder_orig_assign)
std::cout << val << " ";
std::cout << std::endl;
std::cout << "Inorder values before assign: myBST_copy_assign: " << std::endl;
for (auto& val : vals_inorder_copy_assign)
std::cout << val << " ";
std::cout << std::endl;
myBST_orig_assign = myBST_copy_assign;
vals_inorder_orig_assign = myBST_orig_assign.get_inorder_vals();
vals_inorder_copy_assign = myBST_copy_assign.get_inorder_vals();
std::cout << "Inorder values after assign: myBST_orig_assign: " << std::endl;
for (auto& val : vals_inorder_orig_assign)
std::cout << val << " ";
std::cout << std::endl;
std::cout << "Inorder values after assign: myBST_copy_assign: " << std::endl;
for (auto& val : vals_inorder_copy_assign)
std::cout << val << " ";
std::cout << std::endl;
// ---------------------------------------
std::cout << "--------------------------\n";
std::cout << "Move constructor" << std::endl;
BinarySearchTree myBST_orig_move;
myBST_orig_move.build_from_vector_balanced(values);
std::cout << "myBST_orig_move before move: empty? " << myBST_orig_move.empty() << "\n";
BinarySearchTree myBST_target_move(std::move(myBST_orig_move));
std::cout << "myBST_orig_move after move: empty? " << myBST_orig_move.empty() << "\n";
std::cout << "myBST_target_move after move: empty? " << myBST_target_move.empty() << "\n";
// ---------------------------------------
std::cout << "--------------------------\n";
std::cout << "Move assignment operator" << std::endl;
BinarySearchTree myBST_orig_move_assign;
myBST_orig_move_assign.build_from_vector_balanced(values1);
BinarySearchTree myBST_target_move_assign;
myBST_target_move_assign.build_from_vector_balanced(values2);
std::cout << "myBST_orig_move_assign before move: empty? " << myBST_orig_move_assign.empty() << "\n";
std::cout << "myBST_target_move_assign before move: empty? " << myBST_target_move_assign.empty() << "\n";
myBST_target_move_assign = std::move(myBST_orig_move_assign);
std::cout << "myBST_orig_move_assign after move: empty? " << myBST_orig_move_assign.empty() << "\n";
std::cout << "myBST_target_move_assign after move: empty? " << myBST_target_move_assign.empty() << "\n";
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-18T15:47:26.790",
"Id": "475916",
"Score": "1",
"body": "It would help us review the code if you included the testing code as well."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-18T17:43:06.447",
"Id": "475931",
"Score": "1",
"body": "Good point, @pacmaninbw. I added the ```main.cpp``` code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-18T18:40:38.770",
"Id": "475936",
"Score": "2",
"body": "For rule-of-5, since you don't have any resources to explicitly release, you don't need a specialized destructor. However, the rule applies for this: make your intent clear by declaring it `default`, so the next person looking at your code knows that you didn't just miss it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-19T16:29:12.430",
"Id": "476019",
"Score": "0",
"body": "@Oppen, thanks! What about Node struct? Should I also declare destructor as ```default```?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-19T16:51:41.693",
"Id": "476022",
"Score": "1",
"body": "I'm generally in favor of being explicit, but I don't know what's considered \"idiomatic\" in this case, as it's not part of the rule-of-5. I think I would mark it default."
}
] |
[
{
"body": "<p>This is too long for me to review thoroughly, but on a cursory glance (I'll just go go top to bottom):</p>\n\n<ol>\n<li><code>#include <iostream></code> is unneeded</li>\n<li>There is no point in calling clear in the destructor. This class should not have any code in the destructor at all. The smart pointers are meant to clean up nicely.</li>\n<li>There is no point passing int as a const reference</li>\n<li>You are too attached to vectors. It may be fine for the specific task, but for a more library-oriented class this would be a burden. But even if you stick to vectors, having a type alias would help readability and maintanability</li>\n<li>Node* find_min_node(const std::unique_ptr& curr_node) const;\nIt should really be const Node*</li>\n<li>BinarySearchTree::BinarySearchTree(const BinarySearchTree& other_tree) {\nif (other_tree.tree_size == 0) return;\nthis constructor does not initialize the fields. Which is quite strange because the default constructor does.</li>\n<li><code>std::vector<int>::iterator it_e = values.end() - 1;</code> This is incorrect. If values is empty it will give you an invalid iterator. You check it with < later in the code, but this is not correct C++, you can only compare iterators from the same container, which are [begin, end+1]. It will probably work just because vector iterators are likely to be just numbers, but it can break with any library or compiler update.</li>\n<li>min_val will break horribly if the tree is empty</li>\n<li>Your insert code suggests that the tree can not contain duplicate values. It is totally fine, but for me it would be unexpected from a class with such a generic name.</li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-20T20:30:44.033",
"Id": "476198",
"Score": "0",
"body": "Thank you for your reply, I have a couple of follow up questions: 4. What would you use instead of vectors? 5. Should it be ```const Node* const``` then, as I don't want to modify neither pointer itself nor its contents? 7. So, if I want to do binary search in a vector, should I use indexes instead of iterators or could I still use iterators, but in a different way?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-21T06:04:16.567",
"Id": "476246",
"Score": "1",
"body": "4.Ideally you should use iterators, the same principle as the STL does. 5. Yo can not modify the pointer itself, you are returning a copy of the pointer, so second const is unnecessary. 7. You can play with iterator_categories. If your iterator is random-access you can use binary search. Or you can just use operator + for example, in that case a non-random-access iterator won't compile."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-20T09:47:41.287",
"Id": "242620",
"ParentId": "242501",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "242620",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-18T05:21:28.473",
"Id": "242501",
"Score": "3",
"Tags": [
"c++",
"binary-search-tree"
],
"Title": "BST implementation using smart pointers in C++"
}
|
242501
|
<p>I tried it using the code given below.</p>
<pre><code>big=0 ; c=0
def largest(n):
global c
c+=1
global big
if n//10!=0:
if big<n%10:
big=n%10
return largest(n//10)
if n//10==0:
if c==1:
return n
else:
return big
</code></pre>
<p>But, when I input more than one number in which the first number has the digit of all of them, then the output is the largest digit of the first number, which is repeated.</p>
<blockquote>
<p>For example:
If i input 3 numbers like </p>
</blockquote>
<pre><code>259, 33, 26
</code></pre>
<p>Then the output will be:</p>
<pre><code>9
9
9
</code></pre>
<p>How to resolve this?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-18T09:08:36.787",
"Id": "475873",
"Score": "0",
"body": "Because big is a global which never resets"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-18T09:11:08.240",
"Id": "475875",
"Score": "0",
"body": "Does it need to be recursive? Why not just cast to string split all and sort"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-18T09:15:33.403",
"Id": "475876",
"Score": "0",
"body": "This is a homework from school, so I have to use recursion. If big never resets, how do I fix that?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-18T09:22:48.763",
"Id": "475878",
"Score": "2",
"body": "As presented, the code does not work as intended: [off-topic at CodeReview@SE](https://codereview.stackexchange.com/help/on-topic)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-18T09:42:43.663",
"Id": "475882",
"Score": "0",
"body": "Get this working with `reduce` and then converting to an, honestly really poor use of recursion, is easy."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-18T09:46:42.663",
"Id": "475883",
"Score": "0",
"body": "Ok, suppose I want to convert it into a not really poor use of recursion, then how do I do it?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-18T10:51:02.367",
"Id": "475886",
"Score": "0",
"body": "You need an inner function that takes the biggest digit up to now and the number as parameters, and calls itself with the maximum of the biggest digit up to now and the current digit, and the number divided by 10, until the number is 0. Sorry, I don't do Python very well; in F# this might look as follows (please excuse the one-liner due to the comment not supporting line breaks): ``let largestDigit n = let rec inner d n = if n = 0 then d else inner (max (n % 10) d) (n / 10) in inner 0 (abs n)``"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-18T12:41:46.010",
"Id": "475898",
"Score": "0",
"body": "@AritraPal a better use of recursion would be: a function which takes two params (n, biggestSoFar = 0)\n0. if n == \"\" return biggestSoFar\n1. Otherwise take the first digit of n (maybe use strings for simplicity). And pass the rest to the function again and max of (biggest and the firstNumber taken)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-18T12:45:04.750",
"Id": "475899",
"Score": "0",
"body": "@AritraPal as greybeard said, its off-topic here at code-review since your function does not work. This forum is only helping in improving working code, try other forum"
}
] |
[
{
"body": "<p>As was pointed out, this question is off-topic here because this channel is for reviewing and improving code that works as designed. That said, an easy recursive solution using a normal outer function with a recursive inner function could look as follows:</p>\n\n<pre><code>def largestDigit(n):\n def inner(d, n):\n if n == 0:\n return d\n else:\n return inner(max(d, n % 10), n // 10)\n return inner(0, abs(n))\n</code></pre>\n\n<p><strong>Edit:</strong> To keep with the topic of improving working code, here is a shorter version using an <code>if</code> expression instead of an <code>if</code> statement:</p>\n\n<pre><code>def largestDigit(n):\n def inner(d, n):\n return d if n == 0 else inner(max(d, n % 10), n // 10)\n return inner(0, abs(n))\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-18T17:42:31.840",
"Id": "475930",
"Score": "1",
"body": "Please refrain from answering off-topic questions. There are plenty of on-topic questions that could use a review."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-18T13:09:13.847",
"Id": "242513",
"ParentId": "242509",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "242513",
"CommentCount": "9",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-18T08:49:50.947",
"Id": "242509",
"Score": "-4",
"Tags": [
"python",
"python-3.x",
"recursion"
],
"Title": "Finding The Largest Digit in a Number using a Recursive Function in Python"
}
|
242509
|
<p>I must allow user to add city, state and country if it is not already present in the drop-down. Then I must create the respective model instances and then update the city in the userprofile. The below is the working code. I have not checked it for all cases but I have checked it for most cases. Please tell me if there is a better way to achieve the same.</p>
<p><strong>app_1/models.py</strong></p>
<pre><code>from app_2.models import City
class UserProfile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
profile_pic = models.ImageField(default='default.jpg', upload_to='profile_pics')
website_url = models.URLField(max_length=250, default='http://#')
city = models.ForeignKey(City, models.SET_NULL, blank=True, null=True)
location = models.TextField(blank=True, null=True)
</code></pre>
<p><strong>app_1/forms.py</strong></p>
<pre><code>from .models import UserProfile
from app_2.models import City, State, Country
class UserProfileUpdateForm(forms.ModelForm):
website_url = forms.URLField(help_text='http://')
def __init__(self, *args, **kwargs):
super(CompanyProfileUpdateForm, self).__init__(*args, **kwargs)
for visible in self.visible_fields():
visible.field.widget.attrs['class'] = 'form-control'
class Meta:
model = UserProfile
fields = ['logo', 'city', 'website_url', 'location']
</code></pre>
<p><strong>app_1/views.py</strong></p>
<pre><code>from app_2.models import City, State, Country
@login_required
def profile(request):
if request.method == 'POST':
u_form = UserUpdateForm(request.POST, instance=request.user)
up_form = UserProfileUpdateForm(request.POST, request.FILES, instance=request.user.userprofile)
if u_form.is_valid() and up_form.is_valid():
u_form.save()
if request.POST['input_city']:
uncommitted_up_form = up_form.save(commit=False)
co = Country.objects.create(name=request.POST['input_country'])
st = State.objects.create(country=co, name=request.POST['input_state'])
cit = City.objects.create(state=st, name=request.POST['input_city'])
uncommitted_up_form.city = cit
uncommitted_up_form.save()
else:
up_form.save()
messages.success(request, f'Your profile has been updated!')
return redirect('profile')
else:
u_form = UserUpdateForm(instance=request.user)
up_form = UserProfileUpdateForm(instance=request.user.userprofile)
context = {
'u_form': u_form,
'up_form': up_form
}
</code></pre>
<p><strong>app_1/templates/app_1/profile.html</strong></p>
<pre><code>{% extends 'companies/base.html' %}
{% load crispy_forms_tags %}
{% block content %}
<form method="POST" enctype="multipart/form-data">
{% csrf_token %}
<fieldset>
<legend>
User Info
</legend>
{{ u_form|crispy }}
<label for="id_logo">Logo</label>
<p>{{ up_form.logo }}</p>
<label for="id_city">City</label>
<p>{{ up_form.city }}</p>
<div><a href="javascript:void(0);" onclick="toggleDisplay();">City not present?</a></div><br>
<div id="hidden_visible_input" style="display: none;">
<label>City</label>
<input type="test" name="input_city" required>
<label>State</label>
<input type="test" name="input_state" required>
<label>Country</label>
<input type="test" name="input_country" required>
</div><br>
<label for="id_website_url">Website URL</label>
<p>{{ up_form.website_url }}</p>
<label for="id_location">Location</label>
<p>{{ up_form.location }}</p>
</fieldset>
<div class="form-group">
<button type="submit">
Update
</button>
</div>
</form>
<script type="text/javascript">
const toggleDisplay = () => {
let hidden_visible = document.getElementById('hidden_visible_input');
if (hidden_visible.style.display == 'none') {
hidden_visible.style.display = 'block';
} else {
hidden_visible.style.display = 'none';
}
}
</script>
{% endblock content %}
</code></pre>
<p><strong>app_2/models.py</strong></p>
<pre><code>from django.db import models
class Country(models.Model):
name = models.CharField(max_length=150)
def __str__(self):
return self.name
class State(models.Model):
country = models.ForeignKey(Country, on_delete=models.CASCADE)
name = models.CharField(max_length=200)
def __str__(self):
return self.name
class City(models.Model):
state = models.ForeignKey(State, on_delete=models.CASCADE)
name = models.CharField(max_length=200)
def __str__(self):
return f'{self.name}, {self.state.name}'
</code></pre>
<p>Is there any better way create the <code>city</code>, <code>state</code> and <code>country</code> model instances and then update the userprofile with that value?</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-18T09:25:35.557",
"Id": "242510",
"Score": "1",
"Tags": [
"python",
"django"
],
"Title": "One form for multiple models in Django"
}
|
242510
|
<p>I have cleared all my scripting from the use of JQuery, but sometimes I miss a few handy extensions. Now I'm playing with the idea to "extend" <code>document.querySelectorAll</code> with some handy stuff, using the <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy" rel="nofollow noreferrer"><code>proxy Object</code></a>. Here's a snippet to demostrate that idea. </p>
<p>The advantage seems that there's no juggling around with <code>this</code> or extending <code>NodeList.prototype</code> etc., the disadvantage may be that using <code>proxy</code> this way can be 'expensive'. Or maybe it's just a bad idea after all.</p>
<p>Thanks in advance for your review.</p>
<p><div class="snippet" data-lang="js" data-hide="true" data-console="false" data-babel="false">
<div class="snippet-code snippet-currently-hidden">
<pre class="snippet-code-js lang-js prettyprint-override"><code>// -------------------
// the idea to review
// -------------------
const $ = (selector, root = document) => {
const extensions = {
toggleClass: (el, className) => el.classList.toggle(className),
addClass: (el, classNames) => {
classNames = !(classNames.constructor instanceof Array)
? [classNames] : classNames;
classNames.forEach(cn => el.classList.add(cn));
},
removeClass: (el, classNames) => {
classNames = !(classNames.constructor instanceof Array)
? [classNames] : classNames;
classNames.forEach(cn => el.classList.remove(cn));
},
attr: (el, key, value) => el.setAttribute(key, value),
text: (el, value) => el.textContent = value,
toggleAttr: (el, key, value) =>el.getAttribute(key)
? el.removeAttribute(key) : el.setAttribute(key, value),
each: (el, callBack) =>
callBack && callBack instanceof Function && callBack(el),
};
const proxyTrap = {
get: (obj, key) => {
if (key === "first") {
return obj[0];
}
if (key in obj[0] && obj[0][key] instanceof Function ||
key in extensions && extensions[key] instanceof Function) {
obj[key] = (...args) => {
obj.forEach(el => key in extensions ?
extensions[key].apply(null, [el].concat(args)) :
el[key].apply(el, args));
return toProxy(obj); // <-- chainable, but expensive?
};
}
return obj[key];
}
}
const toProxy = obj => new Proxy(obj, proxyTrap);
return toProxy(root.querySelectorAll(selector));
};
// ------------
// useless demo
// ------------
if (document.documentMode) {
alert("Internet explorer is not supported, sorry");
}
const log = (...txt) => {
const logElem = $("#log")[0];
logElem.textContent += txt.join("\n") + "\n";
logElem.scrollTop = logElem.scrollHeight;
};
const createSpan = () => {
const span = document.createElement("span");
span.appendChild(document.createTextNode(" HI, i'm added tot this <p>"));
return span;
}
// native forEach
$("p[data-addtxt]").forEach(el => el.appendChild(createSpan()));
// extensions each/text/toggleClass
$("span")
.each(el => el.style.backgroundColor = "#eee")
.text(" --- backgroundColor and text added from $([...]).each")
.toggleClass("green");
document.addEventListener("click", evt => {
const origin = evt.target;
if (origin.nodeName === "BUTTON") {
if (origin.id == "nothing") {
// extension toggleAttr
$("p").toggleAttr("data-nada", "Nothing");
log("Toggled data-nada");
}
if (origin.id === "blue") {
// native setAttribute
const isBlue = origin.style.color === "blue";
$("[data-maybeblue]").setAttribute("style",
isBlue ? "color:back" : "color:blue");
origin.textContent = isBlue ? "Make me blue" : "Make me black";
log(`it's ${isBlue ? "black" : "blue"}`);
}
if (!origin.id) {
// extension toggleClass
$("p").toggleClass("red"); // extension toggleClass
log(`Toggled color by class`);
origin.textContent = `Toggle all <p> ${
$("p").first.classList.contains("red") ? "black" : "red"}`;
}
}
});</code></pre>
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
font: 12px/15px normal verdana, arial;
margin: 0.5rem;
}
.red {
color: red;
}
.green {
color: green;
}
[data-nada]:before {
content: attr(data-nada)' ';
color: green;
font-weight: bold;
}
#log {
max-height: 200px;
overflow: auto;
}
button {
margin: 0.4rem 0;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><p>Hi</p>
<p>There</p>
<p>How are you?</p>
<p data-addtxt>text1</p>
<p data-addtxt>text2</p>
<button>Toggle all &lt;p> red</button> (extension toggleClass)<br>
<button id="nothing">Toggle all &lt;p> attribute</button> (extension toggleAttr)<br>
<button id="blue" data-maybeblue>Make me blue</button> (native setAttribute)
<pre id="log" data-maybeblue></pre></code></pre>
</div>
</div>
</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-19T08:14:35.210",
"Id": "475983",
"Score": "0",
"body": "Please do not update the code in your question to incorporate feedback from answers, doing so goes against the Question + Answer style of Code Review. This is not a forum where you should keep the most updated version in your question. Please see *[what you may and may not do after receiving answers](//codereview.meta.stackexchange.com/a/1765)*."
}
] |
[
{
"body": "<p>Proxies are weird and slow. Their main <em>useful</em> purpose in real code is when a bad script <em>that you don't have control over</em> is calling <em>your</em> code in an undesirable manner, and you need to intercept property access / function calls / etc so as to run custom code rather than simply returning the value or calling the function. (I suppose proxies are also arguably useful in esoteric Javascript trivia quizzes.)</p>\n\n<p>But they're there as a <em>workaround</em> for a bad situation, not as a solution-of-choice. Their behavior is somewhat unintuitive and hard-to-understand at a glance.</p>\n\n<p>If you want to include both your custom methods <em>and</em> built-in methods, consider creating a class which has your custom methods, and then iterate over the built-in methods and assign them as methods to the class too:</p>\n\n<pre><code>class CustomCollection {\n constructor(selector, root = document) {\n const elements = root.querySelectorAll(selector);\n Object.assign(this, elements);\n this.length = elements.length;\n }\n _iterate(callback, ...possibleArgs) {\n for (let i = 0; i < this.length; i++) {\n callback(this[i]);\n }\n return this;\n }\n toggleClass(className) {\n this._iterate(el => el.classList.toggle(className));\n }\n // etc - other custom methods that reference _iterate\n}\n// Assign methods on Element.prototype to CustomCollection.prototype:\nconst descriptors = Object.getOwnPropertyDescriptors(Element.prototype);\nfor (const [key, { value }] of Object.entries(descriptors)) {\n // Only assign plain functions (don't invoke getters)\n if (typeof value !== 'function') {\n continue;\n }\n CustomCollection.prototype[key] = function(...args) {\n for (let i = 0; i < this.length; i++) {\n value.apply(this[i], args);\n }\n return this;\n };\n}\n</code></pre>\n\n<p>A class is arguably the right tool for the job here because you want to create collections of persistent elements (data) associated with methods which operate on those elements. So, don't be afraid of using <code>this</code> - in a class method, it'll refer to the current instance, which is just what you'll need in order to reference the elements on the instance.</p>\n\n<p>It's quite possible to write this without classes and <code>this</code>, but I think the class approach is most understandable at a glance.</p>\n\n<p>Other notes:</p>\n\n<p>In order to emulate the iteration over collections (and like jQuery does it), I assigned the elements of the collection to the instance in the constructor, as you can see above. Since all the methods need to iterate over the selected elements, call a function whose first argument is the element, and finally return the collection itself (so that the methods are chainable), I made a <code>_iterate</code> method for that.</p>\n\n<p>Regarding</p>\n\n<pre><code>addClass: (el, classNames) => {\n classNames = !(classNames.constructor instanceof Array) \n ? [classNames] : classNames;\n classNames.forEach(cn => el.classList.add(cn));\n},\n</code></pre>\n\n<p>This logic is incorrect. To check whether an expression is an array, the standard method to use is <code>Array.isArray</code>:</p>\n\n<pre><code>const classNamesArr = Array.isArray(classNames) ? classNames : [classNames];\n</code></pre>\n\n<p>The constructor property will be a function, which will never be an instance of an array:</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>const something = [];\nconsole.log(something.constructor instanceof Array);</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p>Also, regarding the above, It's good to avoid reassigning variables when not necessary - code is more readable when you know, at a particular point where a variable is declared, the variable will always contain that value where it's declared. (see linting rule <a href=\"https://eslint.org/docs/rules/no-param-reassign\" rel=\"nofollow noreferrer\">no-param-reassign</a>) That's why I declared the <code>classNamesArr</code> rather than reassigning the <code>classNames</code> parameter.</p>\n\n<p>You have</p>\n\n<pre><code>span.appendChild(document.createTextNode(\" HI, i'm added tot this <p>\"));\n</code></pre>\n\n<p>When you want to set the text content of an element which starts out empty, it's less verbose to simply assign to the <code>textContent</code> property:</p>\n\n<pre><code>span.textContent = \" HI, i'm added tot this <p>\";\n</code></pre>\n\n<p>Live snippet:</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"true\" data-console=\"false\" data-babel=\"false\">\r\n<div class=\"snippet-code snippet-currently-hidden\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>const $ = (() => {\n // Create a persistent CustomCollection class in this closure:\n class CustomCollection {\n constructor(selector, root = document, elements = root.querySelectorAll(selector)) {\n Object.assign(this, elements);\n this.length = elements.length;\n }\n _iterate(callback, ...possibleArgs) {\n for (let i = 0; i < this.length; i++) {\n callback(this[i]);\n }\n return this;\n }\n toggleClass(className) {\n this._iterate(el => el.classList.toggle(className));\n }\n addClass(classNames) {\n const classNamesArr = Array.isArray(classNames) ? classNames : [classNames];\n return this._iterate((el) => {\n classNamesArr.forEach(cn => el.classList.add(cn));\n });\n }\n removeClass(classNames) {\n const classNamesArr = Array.isArray(classNames) ? classNames : [classNames];\n return this._iterate((el) => {\n classNamesArr.forEach(cn => el.classList.delete(cn));\n });\n }\n attr(key, value) {\n return this._iterate(el => el.setAttribute(key, value));\n }\n text(value) {\n return this._iterate(el => el.textContent = value);\n }\n toggleAttr(key, value) {\n return this._iterate((el) => {\n el[el.hasAttribute(key) ? 'removeAttribute' : 'setAttribute'](key, value);\n });\n }\n each(callback) {\n return this._iterate(callback)\n }\n // duplicate method with new name - kinda weird\n forEach(callback) {\n return this._iterate(callback)\n }\n get first() {\n return this[0];\n }\n }\n // Assign functions on Element.prototype to CustomCollection.prototype:\n const descriptors = Object.getOwnPropertyDescriptors(Element.prototype);\n for (const [key, { value }] of Object.entries(descriptors)) {\n // Only assign plain functions (don't invoke getters)\n if (typeof value !== 'function') {\n continue;\n }\n CustomCollection.prototype[key] = function(...args) {\n for (let i = 0; i < this.length; i++) {\n value.apply(this[i], args);\n }\n return this;\n };\n }\n return (...args) => new CustomCollection(...args);\n})();\n\n\nif (document.documentMode) {\n alert(\"Internet explorer is not supported, sorry\");\n}\nconst log = (...txt) => {\n const logElem = $(\"#log\")[0];\n logElem.textContent += txt.join(\"\\n\") + \"\\n\";\n logElem.scrollTop = logElem.scrollHeight;\n};\nconst createSpan = () => {\n const span = document.createElement(\"span\");\n span.textContent = \" HI, i'm added tot this <p>\";\n return span;\n}\n// native forEach\n$(\"p[data-addtxt]\").forEach(el => el.appendChild(createSpan()));\n\n// extensions each/text/toggleClass\n$(\"span\")\n .each(el => el.style.backgroundColor = \"#eee\")\n .text(\" --- backgroundColor added from $([...]).each\")\n .toggleClass(\"green\");\n\ndocument.addEventListener(\"click\", evt => {\n const origin = evt.target;\n\n if (origin.nodeName === \"BUTTON\") {\n if (origin.id == \"nothing\") {\n // extension toggleAttr\n $(\"p\").toggleAttr(\"data-nada\", \"Nothing\");\n log(\"Toggled data-nada\");\n }\n if (origin.id === \"blue\") {\n // native setAttribute\n const isBlue = origin.style.color === \"blue\";\n $(\"[data-maybeblue]\").setAttribute(\"style\", isBlue ? \"color:back\" : \"color:blue\");\n origin.textContent = isBlue ? \"Make me blue\" : \"Make me black\";\n log(`it's ${isBlue ? \"black\" : \"blue\"}`);\n }\n if (!origin.id) {\n // extension toggleClass\n $(\"p\").toggleClass(\"red\"); // extension toggleClass\n log(`Toggled color by class`);\n origin.textContent = `Toggle all <p> ${\n $(\"p\").first.classList.contains(\"red\") ? \"black\" : \"red\"}`;\n }\n }\n});</code></pre>\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>body {\n font: 12px/15px normal verdana, arial;\n margin: 0.5rem;\n}\n\n.red {\n color: red;\n}\n\n.green {\n color: green;\n}\n\n[data-nada]:before {\n content: attr(data-nada)' ';\n color: green;\n font-weight: bold;\n}\n\n#log {\n max-height: 200px;\n overflow: auto;\n}\n\nbutton {\n margin: 0.4rem 0;\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><p>Hi</p>\n<p>There</p>\n<p>How are you?</p>\n<p data-addtxt>text1</p>\n<p data-addtxt>text2</p>\n<button>Toggle all &lt;p> red</button> (extension toggleClass)<br>\n<button id=\"nothing\">Toggle all &lt;p> attribute</button> (extension toggleAttr)<br>\n<button id=\"blue\" data-maybeblue>Make me blue</button> (native setAttribute)\n<pre id=\"log\" data-maybeblue></pre></code></pre>\r\n</div>\r\n</div>\r\n</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-19T06:31:39.067",
"Id": "475976",
"Score": "0",
"body": "Hi @CertainPerformance, thanks for your comprehensive answer, +1 for that. It's a bit opinionated imho. Not everyone thinks proxies are weird (slow should be tested). The idea of my code was in particalar to avoid `this` etc. Call me old fashioned ( I started using javascript - well Mochascript in the days - in 1995), but I never use the `class` sugar of modern js, or better said, never felt the need to use it. Still, your code is certainly a viable alternative."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-19T06:37:14.420",
"Id": "475977",
"Score": "0",
"body": "The `constructor instanceof`-code was a remnant of older code. I'll correct it. `Array.isArray` is a perfect suggestion here. Concerning your code: `el.classList.delete` would throw a `TypeError`, it should be `el.classList.remove`."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-18T17:39:29.503",
"Id": "242524",
"ParentId": "242512",
"Score": "1"
}
},
{
"body": "<p>Let me add my own review after some tinkering with my and <a href=\"https://codereview.stackexchange.com/users/167260/certainperformance\">CertainPerformances</a> code. I think it may be viable to use a proxy, but still am not sure if it has consequences for performance. It's pretty simple and concise to code. One consequence is that it's a restricting solution: you can't use it (the same way as jQuery does) for non existing elements (e.g. <code>$(\".IDoNotExist\").each(el => {})</code> would throw). That may also be a blessing if you like such restrictiveness.</p>\n\n<p>The <code>CustomCollection</code>-class offered by <a href=\"https://codereview.stackexchange.com/users/167260/certainperformance\">CertainPerformance</a> is excellent and also very usable. I hold a bit of a grudge to the <code>class</code> sugar that is added to Ecmascript, probably because (having programmed JS/ES from the start of it) I always liked the elegance an simplicity of its prototypal nature of it and didn't feel the need for classes.</p>\n\n<p>So here's a more 'classic' approach for extending a <code>NodeList</code> like jQuery.</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"true\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code snippet-currently-hidden\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>if (document.documentMode) {\n alert(\"Internet explorer is not supported, sorry\");\n throw new InternalError(\"No IE here\");\n}\n\nconst $ = (() => {\n const extensions = {\n toggleClass(className) {\n this.forEach(el => el.classList.toggle(className));\n },\n addClass(classNames) {\n this.forEach(el => {\n (Array.isArray(classNames) ? classNames : [classNames])\n .forEach(cn => el.classList.add(cn));\n });\n },\n removeClass(classNames) {\n this.forEach(el => {\n (Array.isArray(classNames) ? classNames : [classNames])\n .forEach(cn => el.classList.remove(cn));\n });\n },\n attr(key, value) {\n this.setAttribute(key, value);\n },\n text(value) {\n this.forEach(el => el.textContent = value);\n },\n html(value) {\n this.forEach(el => el.innerHTML = value);\n },\n toggleAttr(key, value) {\n this.forEach(el => {\n el[el.hasAttribute(key) ? 'removeAttribute' : 'setAttribute'](key, value);\n });\n },\n each(callback) {\n this.forEach(callback);\n },\n };\n\n function ExtendedNodeListCollection(selector, root = document) {\n this.collection = root.querySelectorAll(selector);\n this.first = this.collection[0];\n\n if (ExtendedNodeListCollection.prototype.isSet === undefined) {\n\n Object.entries(Object.getOwnPropertyDescriptors(Element.prototype))\n .forEach(([key, {\n value\n }]) => {\n if (value instanceof Function) {\n ExtendedNodeListCollection.prototype[key] = function(...args) {\n this.collection.forEach(elem => value.apply(elem, args));\n return this;\n }\n };\n });\n\n Object.entries(Object.getOwnPropertyDescriptors(NodeList.prototype))\n .forEach(([key, {\n value\n }]) => {\n if (value instanceof Function) {\n ExtendedNodeListCollection.prototype[key] = function(callBack) {\n this.collection[key](callBack);\n return this;\n };\n }\n });\n\n Object.entries(extensions)\n .forEach(([key, value]) => {\n ExtendedNodeListCollection.prototype[key] = function(...args) {\n value.apply(this, args);\n return this;\n }\n });\n\n ExtendedNodeListCollection.prototype.isSet = true;\n }\n }\n\n return (...args) => new ExtendedNodeListCollection(...args);\n})();\n\n//-----DEMO\nconst logElem = $(\"#log\").first;\nconst log = (...txt) => {\n logElem.textContent += txt.join(\"\\n\") + \"\\n\";\n logElem.scrollTop = logElem.scrollHeight;\n};\n\nlog(`${new Date().toLocaleString()} $ initialized`);\n\n// native forEach\n$(\"p[data-addtxt]\").forEach(el => el.appendChild(document.createElement(\"span\")));\n\n// extensions each/text/toggleClass\n$(\"span\")\n .each(el => el.style.backgroundColor = \"#eee\")\n .text(\" --- backgroundColor and text added from $([...]).each\")\n .toggleClass(\"green\");\n\n// will silently be eaten, no error\n$(\".notExisting\").toggleClass(\"red\"); \n\ndocument.addEventListener(\"click\", evt => {\n const origin = evt.target;\n\n if (origin.nodeName === \"BUTTON\") {\n if (origin.id == \"nothing\") {\n // extension toggleAttr\n $(\"p\").toggleAttr(\"data-nada\", \"Nothing\");\n log(\"Toggled data-nada\");\n }\n if (origin.id === \"blue\") {\n // native setAttribute\n const isBlue = origin.style.color === \"blue\";\n $(\"[data-maybeblue]\").setAttribute(\"style\", isBlue \n ? \"color:back\" \n : \"color:blue\");\n origin.textContent = isBlue ? \"Make us blue\" : \"Make us black\";\n log(`We are ${isBlue ? \"black\" : \"blue\"}`);\n }\n if (!origin.id) {\n // extension toggleClass\n $(\"p\").toggleClass(\"red\"); // extension toggleClass\n log(`Toggled color by class`);\n origin.textContent = `Toggle all <p> ${\n $(\"p\").first.classList.contains(\"red\") ? \"black\" : \"red\"}`;\n }\n }\n});</code></pre>\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>body {\n font: 12px/15px normal verdana, arial;\n margin: 2rem;\n}\n\n.red {\n color: red;\n}\n\n.green {\n color: green;\n}\n\n[data-nada]:before {\n content: attr(data-nada)' ';\n color: green;\n font-weight: bold;\n}\n\n#log {\n max-height: 200px;\n overflow: auto;\n}\n\nbutton {\n margin: 0.4rem 0;\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><p>Hi</p>\n<p>There</p>\n<p>How are you?</p>\n<p data-addtxt>text1</p>\n<p data-addtxt>text2</p>\n<button>Toggle all &lt;p> red</button> (extension toggleClass)<br>\n<button id=\"nothing\">Toggle all &lt;p> attribute</button> (extension toggleAttr)<br>\n<button id=\"blue\" data-maybeblue>Make us blue</button> (native setAttribute)\n<pre id=\"log\" data-maybeblue></pre></code></pre>\r\n</div>\r\n</div>\r\n</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-19T11:07:49.197",
"Id": "242558",
"ParentId": "242512",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-18T12:47:07.323",
"Id": "242512",
"Score": "1",
"Tags": [
"javascript",
"extension-methods",
"proxy",
"ecmascript-8"
],
"Title": "Use proxy for jQuery-like DOM extensions"
}
|
242512
|
<p>This is my first Haskell project so I don't really have a good feel for what makes Haskell code clean, so they'll be lots of things that can be improved.</p>
<p>Things I have a gut feeling are bad design:</p>
<p>pieceAt on line 194 throws an error when it's called on an empty square. My reasoning was that it's<br>
undefined behaviour and means I've made a mistake when programming it. Analogous to an assertionError
in Java.</p>
<p>When pattern matching with moves on line 117, only the pawn uses the board team and pos arguments.
This is definitely not a great way to handle pawn behaviour, but I can't think of a better way to do
it as pawns are tricky to program.</p>
<p>Edit: In case anyone is confused my program does work, or at the very least seems to be able to play chess half-decently. I always check that the square is filled before calling pieceAt</p>
<pre><code>import Data.Char
type Board = [[Square]]
type Move = (Int, Int)
type Pos = (Int, Int)
data PieceType = Rook | Knight | Pawn | King | Queen | Bishop deriving (Eq)
data Square = Filled Piece | Empty deriving (Eq)
data Piece = Piece Team PieceType deriving (Eq)
data Team = Black | White deriving (Eq)
data GameTree = Leaf Int | Node [GameTree] deriving (Show)
--Get AI's choice of move
pickMove :: Board -> Team -> Board
pickMove board team = fst $ getOptimalMove (possibleBoards board team) team
--For all moves the AI could make, run minimax on them all and return the best one
getOptimalMove :: [Board] -> Team -> (Board, Int)
getOptimalMove boards team = foldl accumFunction (head boards, minBound) boards
where accumFunction = \acc n -> let currentValue = minimizer $ generateGameTree (otherTeam team) team n in
if (currentValue >= snd acc) then (n, currentValue) else acc
--For all moves the AI could make, return most optimal
maximizer :: GameTree -> Int
maximizer (Leaf value) = value
maximizer (Node xs) = maximum $ map minimizer xs
--For all moves the opposing team could make, return least optimal for the AI
minimizer :: GameTree -> Int
minimizer (Leaf value) = value
minimizer (Node xs) = minimum $ map maximizer xs
--Generates a game tree
generateGameTree :: Team -> Team -> Board -> GameTree
generateGameTree = depthLimitedTree 1
--Helper function that generates game tree of a limited depth
depthLimitedTree :: Int -> Team -> Team -> Board -> GameTree
depthLimitedTree depth team originalTeam board | depth == 3 = Leaf $ evalBoard board originalTeam
| otherwise = Node $ map (depthLimitedTree (depth + 1) (otherTeam team) originalTeam) (possibleBoards board team)
--Generate all possible boards that can result from a teams move
possibleBoards :: Board -> Team -> [Board]
possibleBoards board team = foldl (\acc n -> acc ++ (genMoves board team n)) [] allMovesForTeam
where allMovesForTeam = posTeam board team
--Generate all possible boards that can come from moving a piece at some position
genMoves :: Board -> Team -> Pos -> [Board]
genMoves board team pos = map (movePos board pos) listOfValidDestinations
where listOfValidDestinations = filter (isValidMove board pos) listOfDestinations
listOfDestinations = map (makeDestinationPos pos) (moves board team pos (extractType board pos))
--Return true if destination is on board and piece doesn't take its own team
isValidMove :: Board -> Pos -> Pos -> Bool
isValidMove board start destination = isOnBoard destination && not (takesOwnTeam board start destination) && isClearPath board path
where path = drawPathKnightWrapper board start destination
-- Return true if the result of a move is a piece checking its own team
takesOwnTeam :: Board -> Pos -> Pos -> Bool
takesOwnTeam board start destination | squareAt board destination == Empty = False
| extractTeam board start == extractTeam board destination = True
| otherwise = False
-- Returns true if no pieces lie in the path
isClearPath :: Board -> [Pos] -> Bool
isClearPath _ [] = True
isClearPath board (x:xs) | squareAt board x /= Empty = False
| otherwise = isClearPath board xs
--Checks if piece path is being drawn from is a knight before drawing path
drawPathKnightWrapper :: Board -> Pos -> Pos -> [Pos]
drawPathKnightWrapper board start destination | extractType board start == Knight = []
| otherwise = tail $ drawPath start destination
-- Given 2 positions, return all the positions that lie in between
drawPath :: Pos -> Pos -> [Pos]
drawPath (a, b) (x, y) | a == x && b == y = []
| otherwise = (a, b):(drawPath (nextRow, nextCol) (x, y))
where nextRow = a + rowDirection (a, b) (x, y)
nextCol = b + colDirection (a, b) (x, y)
-- Return the directions that a movement takes, represented as a vector
movementType :: Pos -> Pos -> Move
movementType pos1 pos2 = (rowDirection pos1 pos2, colDirection pos1 pos2)
--Row component of movementType
rowDirection :: Pos -> Pos -> Int
rowDirection (a, _) (x, _) | x - a > 0 = 1
| x - a < 0 = -1
| x - a == 0 = 0
--Column component of movementType
colDirection :: Pos -> Pos -> Int
colDirection (_, b) (_, y) | y - b > 0 = 1
| y - b < 0 = -1
| y - b == 0 = 0
--Return true if position lies within dimensions of the board
isOnBoard :: Pos -> Bool
isOnBoard (row, col) = row >= 0 && row < 8 && col >= 0 && col < 8
--Given a position and a move, return the position that results from applying the move
makeDestinationPos :: Pos -> Move -> Pos
makeDestinationPos (x, y) (a, b) = (x + a, y + b)
--Given a piece type, return all the moves that it could make represented as vectors
moves :: Board -> Team -> Pos -> PieceType -> [Move]
moves board team pos Pawn = generatePawnMoves board team pos
moves _ _ _ King = [(-1, -1), (-1, 0), (-1, 1), (0, -1), (0, 1), (1, -1), (1, 0), (1, 1)]
moves _ _ _ Knight = [(-2, -1), (-2, 1), (-1, -2), (-1, 2), (1, -2), (1, 2), (2, -1), (2, 1)]
moves _ _ _ Queen = forAllRangesInBoard [(-1, -1), (-1, 0), (-1, 1), (0, -1), (0, 1), (1, -1), (1, 0), (1, 1)] 1
moves _ _ _ Rook = forAllRangesInBoard [(-1, 0), (0, -1), (0, 1), (1, 0)] 1
moves _ _ _ Bishop = forAllRangesInBoard [(-1, -1), (-1, 1), (1, -1), (1, 1)] 1
--Return list of moves a pawn can make
generatePawnMoves :: Board -> Team -> Pos -> [Move]
generatePawnMoves board team pos = getFront board team pos 1 ++ getFront board team pos 2 ++ getDiagonal board team pos (-1) ++ getDiagonal board team pos 1
--Returns a move if there's no pieces in front to block it
getFront :: Board -> Team -> Pos -> Int -> [Move]
getFront board team (row, col) jumpSize | not $ isOnBoard posInFront = []
| squareAt board posInFront == Empty = [( getPawnDirection team * jumpSize, 0)]
| otherwise = []
where posInFront = (row + (getPawnDirection team) * jumpSize, col)
--Returns a move if there's an opposing teams piece to take
getDiagonal :: Board -> Team -> Pos -> Int -> [Move]
getDiagonal board team (row, col) modif | not $ isOnBoard diagonalPos = []
| squareAt board diagonalPos == Empty = []
| extractTeam board diagonalPos /= team = [(getPawnDirection team, modif)]
| otherwise = []
where diagonalPos = (row + (getPawnDirection team), col + modif)
--Return the direction a team's pawn will move in
getPawnDirection:: Team -> Int
getPawnDirection White = (-1)
getPawnDirection Black = 1
--Helper function for moves, scales a list of tuples to everything in range of a single move on a standard chess board
forAllRangesInBoard :: [Move] -> Int -> [Move]
forAllRangesInBoard list c | c == 8 = []
| otherwise = movesForCurrentRange ++ restOfMoves
where movesForCurrentRange = map (tupleProduct c) list
tupleProduct = (\mul tuple -> (fst tuple * mul, snd tuple * mul))
restOfMoves = forAllRangesInBoard list (c + 1)
--Given a board and a team, return all positions in the board that have a piece of that team
posTeam :: Board -> Team -> [Pos]
posTeam board team = posTeamIter board team 0 0
--Helper function for posTeam
posTeamIter :: Board -> Team -> Int -> Int -> [Pos]
posTeamIter board team row col | squareAt board (row, col) == Empty = recursiveCase
| extractTeam board (row, col) == team = (row, col):recursiveCase
| otherwise = recursiveCase
where recursiveCase | row == 7 && col == 7 = []
| col == 7 = posTeamIter board team (row + 1) 0
| otherwise = posTeamIter board team row (col + 1)
--Given 2 positions, move whatever is at the first position to the second position
movePos :: Board -> Pos -> Pos -> Board
movePos board from to = replaceEndSquare
where removeStartPiece = replaceSquare board from Empty
replaceEndSquare = replaceSquare removeStartPiece to (squareAt board from)
--Given a position and a square, replace whatever is at that position with the square that came as an argument
replaceSquare :: Board -> Pos -> Square -> Board
replaceSquare xs (row, col) square = replaceElem row replacedRow xs
where pickRow = xs !! row
replacedRow = replaceElem col square pickRow
--Given a position, return the square that resides there. Only intended to be called if there's actually a piece
squareAt :: Board -> Pos -> Square
squareAt xs (row, col) = (xs !! row) !! col
-- Gets the piece that resides at a square. Throws an error if you try to get the piece of an empty square
pieceAt :: Square -> Piece
pieceAt Empty = error "Only intended to be called if there's actually a piece there"
pieceAt (Filled piece) = piece
getType :: Piece -> PieceType
getType (Piece _ pieceType) = pieceType
getTeam :: Piece -> Team
getTeam (Piece team _) = team
-- Given a position, return the team of the piece residing there. Throws an error if called for an empty square
extractTeam :: Board -> Pos -> Team
extractTeam board = getTeam . pieceAt . (squareAt board)
-- Given a position, return the type of the piece residing there. Throws an error if called for an empty square
extractType :: Board -> Pos -> PieceType
extractType board = getType . pieceAt . (squareAt board)
otherTeam :: Team -> Team
otherTeam Black = White
otherTeam White = Black
--Heuristic value for all pieces in the board
evalBoard :: Board -> Team -> Int
evalBoard [] _ = 0
evalBoard (x:xs) team = evalRow x team + evalBoard xs team
--Helper function for evalRow, heuristic value of all pieces in a row
evalRow :: [Square] -> Team -> Int
evalRow [] _ = 0
evalRow (x:xs) team = valueSquare x team + evalRow xs team
--Helper function for evalRow, heuristic value of a square with team taken into account
valueSquare :: Square -> Team -> Int
valueSquare Empty _ = 0
valueSquare (Filled piece) team | getTeam piece == team = valuePieceType $ getType piece
| otherwise = (-1) * (valuePieceType $ getType piece)
--Helper function for valueSquare, heuristic value of a piece without team taken into account
valuePieceType :: PieceType -> Int
valuePieceType Pawn = 10
valuePieceType Knight = 30
valuePieceType Bishop = 40
valuePieceType Rook = 60
valuePieceType Queen = 100
valuePieceType King = 1000
-- The starting board for a game of chess
initBoard :: Board
initBoard = ([firstRow] ++ [secondRow] ++ middle ++ [secondLastRow] ++ [lastRow])
where firstRow = map Filled $ map (Piece Black) [Rook, Knight, Bishop, King, Queen, Bishop, Knight, Rook]
secondRow = replicate 8 (Filled $ Piece Black Pawn)
middle = replicate 4 (replicate 8 Empty)
secondLastRow = replicate 8 (Filled $ Piece White Pawn)
lastRow = map Filled $ map (Piece White) [Rook, Knight, Bishop, King, Queen, Bishop, Knight, Rook]
--Returns string representation of a board. Note: Use putStrLn to render the line breaks properly
boardString :: Board -> String
boardString [] = ""
boardString (x:xs) = rowString x ++ (boardString xs)
--Helper function for boardString, returns string representation of a row
rowString :: [Square] -> String
rowString [] = "\n"
rowString (x:xs) = show x ++ rowString xs
instance Show Square where
show Empty = "-"
show (Filled piece) = show piece
instance Show Piece where
show (Piece Black pieceType) = toLowerString $ show pieceType
show (Piece White pieceType) = show pieceType
instance Show PieceType where
show Rook = "R"
show King = "K"
show Pawn = "P"
show Queen = "Q"
show Bishop = "B"
show Knight = "N"
--Generic Helper functions -----------------------------------------------------------------------------------------------------------------
toLowerString :: String -> String
toLowerString = map toLower
--Given a list, an index and an element, replace the index of that list with the element. Indexing starts at 0
replaceElem :: Int -> a -> [a] -> [a]
replaceElem _ _ [] = []
replaceElem counter elem (x:xs) | counter == 0 = elem:recursiveCase
| otherwise = x:recursiveCase
where recursiveCase = replaceElem (counter - 1) elem xs
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-18T15:04:21.180",
"Id": "475910",
"Score": "0",
"body": "Is the code working as expected? It seems that the person that down voted the question felt that it didn't because of the statement `pieceAt on line 194 throws an error when it's called on an empty square.` I'm not the one that down voted so I can't be sure of there reasoning."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-18T15:53:45.543",
"Id": "475917",
"Score": "3",
"body": "Yes it works as expected as I always check if the square is filled before calling pieceAt."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-18T14:17:03.387",
"Id": "242515",
"Score": "5",
"Tags": [
"haskell",
"chess"
],
"Title": "A simple chess engine in Haskell"
}
|
242515
|
<p>Here's a function I use to generate a 2.5 gig SQL dump file for testing. It works but it takes a long time. How can I make it more efficient?</p>
<pre class="lang-js prettyprint-override"><code>const crypto = require("crypto");
const fs = require('fs');
const os = require('os');
const path = require('path');
(async function main(){
var dumpfile = await generate_large_dump();
console.log("\nDump created: ", dumpfile);
})();
function generate_large_dump(){
return new Promise(async (resolve, reject)=>{
var total_bytes = 0;
const target_bytes = 2.5 * 1e+9;
const target_file = path.join(os.tmpdir(), 'large_dump.sql');
const writerStream = fs.createWriteStream(target_file, {flags: 'w'});
writerStream.on('error', console.error);
const age = ()=>Math.floor(Math.random() * (95 - 18 + 1)) + 18;
const name = ()=>crypto.randomBytes(16).toString("hex");
const write = str => new Promise(resolve=>{
total_bytes += Buffer.byteLength(str, 'utf8');
writerStream.write(str, resolve);
var pct = Math.min(100, Math.floor(total_bytes / target_bytes * 10000)/100);
process.stdout.clearLine();
process.stdout.cursorTo(0);
process.stdout.write(pct+"% complete");
});
var create_sql = "CREATE TABLE `sample_table` (`id` int(11) NOT NULL AUTO_INCREMENT, `name` varchar(250) NOT NULL, `age` int(11) NOT NULL, `date` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (`id`));\n";
await write(create_sql);
while(total_bytes < target_bytes) await write("INSERT INTO `sampe_table` (`name`, `age`) VALUES ('"+name()+"', '"+age()+"');\n");
writerStream.end();
process.stdout.write("\n");
resolve(target_file);
});
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-18T17:41:45.063",
"Id": "475929",
"Score": "2",
"body": "Please do not update the code in your question to incorporate feedback from answers, doing so goes against the Question + Answer style of Code Review. This is not a forum where you should keep the most updated version in your question. Please see *[what you may and may not do after receiving answers](//codereview.meta.stackexchange.com/a/1765)*."
}
] |
[
{
"body": "<p><strong>The main culprit here is your progress indicator</strong>.</p>\n\n<p>You're continuously refreshing a line in <code>stdout</code> every time <code>write</code> is called, and <code>write</code> is called a <em>very large</em> number of times. If you reduce the frequency of console writes, you'll make your script a whole lot faster. One option is to write to the console only every 0.5 seconds or so:</p>\n\n<pre><code>// Performance checker:\nsetTimeout(() => {\n console.log('Process after 10 seconds: ', Math.floor(total_bytes / target_bytes * 10000)/100);\n}, 10000);\n// Actual code:\nlet timeoutId;\nconst write = str => new Promise(resolve=>{\n total_bytes += Buffer.byteLength(str, 'utf8');\n writerStream.write(str, resolve);\n if (!timeoutId) {\n timeoutId = setTimeout(() => {\n process.stdout.clearLine();\n process.stdout.cursorTo(0);\n const pct = Math.min(100, Math.floor(total_bytes / target_bytes * 10000)/100);\n process.stdout.write(pct+\"% complete\");\n timeoutId = null;\n }, 500);\n }\n});\n</code></pre>\n\n<p>On my machine, this results in a speed improvement from around 0.25% in 10 seconds, to around 2.03% in 10 seconds - an improvement of a whole order of magnitude.</p>\n\n<p>Another thing: if you're going to use ES2015+ syntax - which you are, and should - then always declare variables with <code>const</code> when possible. Never use <code>var</code>, it has too many gotchas to be worth using (such as function scope instead of block scope, the ability to accidentally re-declare it, automatically putting properties on the global object when on the top level in a browser, etc).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-18T17:39:06.887",
"Id": "475928",
"Score": "0",
"body": "thanks! that got me down from 70 minutes to 10 minutes run time."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-18T15:19:06.970",
"Id": "242519",
"ParentId": "242516",
"Score": "4"
}
},
{
"body": "<h1>Question</h1>\n<blockquote>\n<p>How can I make it more efficient?</p>\n</blockquote>\n<p>In addition to the suggestion by CertainPerformance, you may be able to find a more efficient way to write the data. I haven't tried this before but you could try making a stream (e.g. <a href=\"https://nodejs.org/api/stream.html#stream_new_stream_readable_options\" rel=\"nofollow noreferrer\"><code>Readable</code></a>) to <a href=\"https://nodejs.org/api/stream.html#stream_readable_push_chunk_encoding\" rel=\"nofollow noreferrer\">push</a> the lines to, and then use <a href=\"https://nodejs.org/api/stream.html#stream_readable_pipe_destination_options\" rel=\"nofollow noreferrer\"><code>readable.pipe()</code></a> to pipe the data to the writable stream.</p>\n<h1>Review</h1>\n<h2>Nesting levels, re-used variable names</h2>\n<p>This code has more nesting levels than are necessary, and could be considered by some as <a href=\"http://callbackhell.com\" rel=\"nofollow noreferrer\">"callback hell"</a>. The function <code>write</code> can be moved out of the function passed to <code>new Promise</code> that gets returned at the end of <code>generate_large_dump</code>, along with all the variables that <code>write()</code> needs like <code>writerStream</code>, <code>target_file</code>, <code>total_bytes</code>, etc. While they would have separate scopes, this can help avoid confusion of variables like <code>resolve</code>, which has a re-used name. If you need to have a nested promise it would be better to use distinct names for the sake of readability.</p>\n<p>This would lead to the function passed to the returned promise being much smaller. It could also be pulled out to a named function as well.</p>\n<h2>Constants</h2>\n<p>Idiomatic JavaScript, as is the case for many other languages (e.g. C-based) tend to have hard-coded constants declared in <code>ALL_CAPS</code> format - so <code>target_bytes</code> would be better as <code>TARGET_BYTES</code>. It can still be declared within <code>generate_large_dump()</code> to limit the scope unless it would be useful elsewhere.</p>\n<h2>Braces</h2>\n<p>While braces obviously aren't required for expressions following <code>while</code> it can be helpful if you ever need to add a line to the block.</p>\n<blockquote>\n<pre><code>while(total_bytes < TARGET_BYTES) await write("INSERT INTO `sampe_table` (`name`, `age`) VALUES ('"+name()+"', '"+age()+"');\\n");\n</code></pre>\n</blockquote>\n<p>Even with bracts the line can stay as a one-liner:</p>\n<pre><code>while(total_bytes < TARGET_BYTES) { await write("INSERT INTO `sampe_table` (`name`, `age`) VALUES ('"+name()+"', '"+age()+"');\\n"); }\n</code></pre>\n<p>Though some would argue it would be more readable with separate lines:</p>\n<pre><code>while(total_bytes < TARGET_BYTES) {\n await write("INSERT INTO `sampe_table` (`name`, `age`) VALUES ('"+name()+"', '"+age()+"');\\n");\n}\n</code></pre>\n<p>Some style guides disallow keeping the expression on the same line as the control structure - e.g. The <a href=\"https://google.github.io/styleguide/jsguide.html\" rel=\"nofollow noreferrer\">Google JS Style guide</a>:</p>\n<blockquote>\n<h3>4.1.1 Braces are used for all control structures</h3>\n<p>Braces are required for all control structures (i.e. <code>if</code>, <code>else</code>, <code>for</code>, <code>do</code>, <code>while</code>, as well as any others), even if the body contains only a single statement. The first statement of a non-empty block must begin on its own line.</p>\n<p>Disallowed:</p>\n<blockquote>\n<pre><code>if (someVeryLongCondition())\n doSomething();\n\nfor (let i = 0; i < foo.length; i++) bar(foo[i]);\n</code></pre>\n</blockquote>\n<p><strong>Exception</strong>: A simple if statement that can fit entirely on a single line with no wrapping (and that doesn’t have an else) may be kept on a single line with no braces when it improves readability. This is the only case in which a control structure may omit braces and newlines.</p>\n<pre><code>if (shortCondition()) foo();\n</code></pre>\n</blockquote>\n<p><sup><a href=\"https://google.github.io/styleguide/jsguide.html#formatting-braces\" rel=\"nofollow noreferrer\">1</a></sup></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-18T17:35:12.103",
"Id": "475926",
"Score": "0",
"body": "thank you! that was very thorough!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-18T16:26:01.073",
"Id": "242521",
"ParentId": "242516",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "242519",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-18T14:43:34.807",
"Id": "242516",
"Score": "4",
"Tags": [
"javascript",
"performance",
"node.js",
"file",
"ecmascript-8"
],
"Title": "Efficiently generate large file to create SQL table and insert sample user data"
}
|
242516
|
<p>I'm reading "Introduction to Algorithms" by CLRS and I can't find an implementation of the pseudo code from the book in golang. By the original implementation I mean that we deal with extra parameters in the function to define slice of an original array. All implementations on the web deal with whole array. And that's not what Thomas Cormen wanted.
So I write this one: </p>
<pre><code>package sort_merge
import (
"math"
)
/*
CLRS implementation - we deal with slice of original array arr[p, r], indexes p and r are inclusive
*/
// arr={6, 5, 4, 3}; p=0; q=3
// arr={6, 5}; p=0; q=1
// arr={6}; p=0; q=0
func MergeSort(arr []int, p int, r int) {
if p < r {
q := (p + r) / 2 // last index of left array (rounding down)
MergeSort(arr, p, q)
MergeSort(arr, q+1, r)
Merge(arr, p, q, r)
}
}
func Merge(arr []int, p int, q int, r int) {
left := make([]int, len(arr[p:q+1])) // q+1, because right part of slice is exclusive
right := make([]int, len(arr[q+1:r+1])) // q+1, because this is last index of left array
copy(left, arr[p:q+1])
copy(right, arr[q+1:r+1]) // r+1, because right part of slice is exclusive
left = append(left, math.MaxInt64) // math.MaxInt64 used here as Infinity from original implementation
right = append(right, math.MaxInt64)
i, j := 0, 0
for k := p; k <= r; k++ {
if left[i] <= right[j] {
arr[k] = left[i]
i++
} else { // left[i] > right[j]
arr[k] = right[j]
j++
}
}
}
</code></pre>
<p>You can run it:</p>
<pre><code>package main
import "fmt"
import "./sort-merge"
func main() {
arr := []int{6, 5, 4, 3}
sort_merge.MergeSort(arr, 0, len(arr)-1)
fmt.Println(arr)
}
</code></pre>
|
[] |
[
{
"body": "<blockquote>\n <p>I'm reading \"Introduction to Algorithms\" by CLRS and I can't find an\n implementation of the pseudo code from the book in golang.</p>\n</blockquote>\n\n<hr>\n\n<p>Here is my Go implementation of the pseudocode from the book.</p>\n\n<pre><code>package main\n\nimport (\n \"fmt\"\n \"math\"\n)\n\n// Introduction to Algorithms\n// Third Edition\n// Cormen, Leiserson, Rivest, Stein\n\nfunc merge(a []float64, p, q, r int) {\n nLeft := q - p + 1\n nRight := r - q\n t := make([]float64, (nLeft+1)+(nRight+1))\n left := t[:nLeft+1]\n right := t[nLeft+1:]\n copy(left[:nLeft], a[p:])\n copy(right[:nRight], a[q+1:])\n left[nLeft] = math.Inf(0)\n right[nRight] = math.Inf(0)\n\n i, j := 0, 0\n for k := p; k <= r; k++ {\n if left[i] <= right[j] {\n a[k] = left[i]\n i++\n } else {\n a[k] = right[j]\n j++\n }\n }\n}\n\n// MergeSort sorts the slice a[p:r+1] in nondecreasing order.\nfunc MergeSort(a []float64, p, r int) {\n if p < r {\n q := (p + r) / 2\n MergeSort(a, p, q)\n MergeSort(a, q+1, r)\n merge(a, p, q, r)\n }\n}\n\nfunc main() {\n a := []float64{9: 2, 4, 5, 7, 1, 2, 3, 6}\n fmt.Println(a)\n MergeSort(a, 9, 16)\n fmt.Println(a)\n}\n</code></pre>\n\n<hr>\n\n<hr>\n\n<p>This is a real-world code review: Code should be correct, maintainable, robust, reasonably efficient, and, most importantly, readable.</p>\n\n<p>Your code is not readable. Your code does not closely follow the pseudocode. For example, you deleted the n1 and n2 pseudocode variables:</p>\n\n<pre><code>n1 = q - p + 1\nn2 = r - q\n</code></pre>\n\n<p>As a result, your code is very inefficient. Your code is off-by-one.</p>\n\n<blockquote>\n <p><a href=\"https://golang.org/ref/spec\" rel=\"nofollow noreferrer\">The Go Programming Language\n Specification</a></p>\n \n <p><a href=\"https://golang.org/ref/spec#Appending_and_copying_slices\" rel=\"nofollow noreferrer\">Appending to and copying\n slices</a></p>\n \n <p>The variadic function append appends zero or more values x to s of\n type S, which must be a slice type, and returns the resulting slice,\n also of type S. ... If the capacity of s is not large enough to fit\n the additional values, append allocates a new, sufficiently large\n underlying array that fits both the existing slice elements and the\n additional values. Otherwise, append re-uses the underlying array.</p>\n</blockquote>\n\n<p>For left and right subarrays, you allocate slice with a capacity equal to the number of elements, then you immediately append a sentinel value. This allocates a new slice and copies the old values from the old slice to the new slice.</p>\n\n<p>In my code, I renamed <code>n1</code> and <code>n2</code> to a more readable <code>nLeft</code> and <code>nRight</code>. In my code, I minimized the number and size of allocations.</p>\n\n<p>A benchmark (1000 random elements) for my code</p>\n\n<pre><code>$ go test msort.go msort_test.go -bench=. -benchmem\nBenchmarkMSort-4 18720 64849 ns/op 98048 B/op 999 allocs/op\n</code></pre>\n\n<p>versus a benchmark (1000 random elements) for your code</p>\n\n<pre><code>$ go test msort.go msort_test.go -bench=. -benchmem\nBenchmarkMSort-4 6996 150493 ns/op 242880 B/op 3996 allocs/op\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-21T14:44:09.263",
"Id": "476287",
"Score": "1",
"body": "Thanks for the review, I rewrite my solution with `n1` and `n2`. I understand inefficient parts of my code, but what is \"not readable\" in it?"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-20T15:12:19.707",
"Id": "242646",
"ParentId": "242525",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "242646",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-18T18:10:55.283",
"Id": "242525",
"Score": "4",
"Tags": [
"algorithm",
"sorting",
"go",
"mergesort"
],
"Title": "CLRS implementation (opportunity to sort subarray) of merge sort in golang"
}
|
242525
|
<h2>Background</h2>
<p>I am a total beginner in Haskell, so after reading the <a href="http://learnyouahaskell.com/starting-out" rel="nofollow noreferrer">Starting out</a>-chapter of "Learn you a Haskell", I wanted to create my first program that actually does something.</p>
<p>I decided to do the famous Caesar-Cipher.</p>
<h2>Code</h2>
<pre><code>import Data.Char
encryptChar :: Char -> Int -> Int
encryptChar char shift = if ord char > 64 && ord char < 91 --Only encrypt A...Z
then (if ord char + shift > 90 --"Z" with shift 3 becomes "C" and not "]"
then ord char + shift - 26
else ord char + shift)
else ord char
decryptChar :: Char -> Int -> Int
decryptChar char shift = if ord char > 64 && ord char < 91
then (if ord char - shift < 65
then ord char - shift + 26
else ord char - shift)
else ord char
encrypt :: String -> Int -> String
encrypt string shift = [chr (encryptChar (toUpper x) shift) | x <- string] --"Loop" through string to encrypt char by char
decrypt :: String -> Int -> String
decrypt string shift = [chr (decryptChar (toUpper x) shift) | x <- string]
main = print(decrypt "KHOOR, ZRUOG!" 3)
</code></pre>
<p>(The code does work as intended.)</p>
<h2>Question(s)</h2>
<ul>
<li>How can this code be improved in general?</li>
<li>Do I follow the style guide of Haskell (indentation, etc.)?</li>
<li>I have a background in imperative languages. Did I do something that is untypical for functional programming languages?</li>
</ul>
<p>I would appreciate any suggestions.</p>
|
[] |
[
{
"body": "<ol>\n<li><p>I'd start by avoiding directly encoding ASCII character codes into the logic. For example, instead of:</p>\n\n<pre><code>if ord char > 64 && ord char < 91\n</code></pre>\n\n<p>I'd probably use:</p>\n\n<pre><code>if char >= 'A' && char <= 'Z'\n</code></pre>\n\n<p>I think this shows the intent enough more clearly to be worthwhile.</p></li>\n<li><p>Given that you also do this a couple of different places, I'd probably write a small <code>isUpper</code> function to return a <code>Bool</code> indicating whether a character is an upper-case letter:</p>\n\n<pre><code>isUpper :: Char -> Bool\nisUpper char = char >= 'A' && char <= 'Z'\n</code></pre>\n\n<p>Then the rest of the code can use that:</p>\n\n<pre><code>encryptChar char shift = if isUpper char -- ...\n\ndecryptChar char shift = if isUpper char -- ...\n</code></pre></li>\n</ol>\n\n<p>[Note: the standard library already has an <code>isUpper</code>, but it may not fit your needs, since it's Unicode-aware, and here you apparently only want to deal with English letters.]</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-18T20:40:10.333",
"Id": "242532",
"ParentId": "242529",
"Score": "5"
}
},
{
"body": "<p>This is mostly fine but there is a lot of repetition as well and it is not broken up very well. Remember that haskell is lazy so none of the operations in the where clauses will be executed unless they are needed, so it is safe to just set them up. Keep in mind I went to the extreme and made a where clause for everything but you can keep it more sensible if you want.</p>\n\n<pre class=\"lang-hs prettyprint-override\"><code>decryptChar char shift =\n if inRange\n then if wouldWrap\n then wrapped\n else iShifted\n else i\n where\n i = ord char\n inRange = i > 64 && i < 91\n iShifted = i - shift\n wouldWrap = iShifted < 65\n wrapped = iShifted + 26\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-20T19:40:47.577",
"Id": "242657",
"ParentId": "242529",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "242532",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-18T19:36:20.430",
"Id": "242529",
"Score": "3",
"Tags": [
"beginner",
"haskell",
"caesar-cipher"
],
"Title": "Caesar-Cipher Implementation"
}
|
242529
|
<p>I am currently working with the <a href="https://archive.org/details/stackexchange" rel="nofollow noreferrer">Stack Exchange Data Dump</a> - to be more precise - with the dumped <code>Posts.xml</code> data set from Stack Overflow.</p>
<p><strong>What am I trying to achieve?</strong>
I want to read the whole data set and import each row (a post on Stack Overflow) as a document into an MongoDB database.</p>
<p><strong>What am I doing right now?</strong>
I am using the <code>iterparse()</code> function from <code>lxml</code> to iterate over each row, without building a DOM. Every row contains attributes which hold the actual data. As every attribute is a String, I need to parse some attributes into Integers, Dates and Lists. This is done by the <code>attrib_to_dict()</code> function. The resulting Dictionary is simply inserted into the database collection.</p>
<p><strong>What is the problem?</strong>
The parsing of the attributes is quite slow. The whole process took about two hours on my machine. By using the <code>multiprocessing</code> module I was able to speed up the process substantially. The iteration over the whole data set without doing anything is quite fast.</p>
<pre class="lang-py prettyprint-override"><code># main.py
from lxml import etree as et
from tqdm import tqdm
import multiprocessing as mp
import pymongo
from constants import POSTS_SIZE
from posts import attrib_to_dict
client = pymongo.MongoClient("mongodb://localhost:27017/")
# database
stackoverflow = client["stackoverflow"]
# collection
posts = stackoverflow["posts"]
def work(elem):
try:
# turn the String back into an element, pass attributes to parsing function
posts.insert_one(attrib_to_dict(et.fromstring(elem).attrib))
except pymongo.errors.DuplicateKeyError:
# skip element
pass
if __name__ == "__main__":
pool = mp.Pool(4)
# progress bar
pbar = tqdm(total=POSTS_SIZE)
def update(*args):
# add one to total processed elements
pbar.update(1)
try:
for event, elem in et.iterparse("Posts.xml", tag="row"):
# pass element as a String to the worker
# passing the attribute object directly did not seem to work
pool.apply_async(work, args=(et.tostring(elem),), callback=update)
elem.clear()
pool.close()
except KeyboardInterrupt:
pool.terminate()
finally:
pbar.close()
pool.join()
</code></pre>
<pre class="lang-py prettyprint-override"><code># posts.py
from datetime import datetime as dt
def attrib_to_dict(attrib):
result = {}
result["_id"] = int(attrib.get("Id"))
result["PostTypeId"] = int(attrib.get("PostTypeId"))
# nullable attributes
acceptedAnswerId = attrib.get("AcceptedAnswerId")
if acceptedAnswerId: result["AcceptedAnswerId"] = int(acceptedAnswerId)
result["CreationDate"] = dt.fromisoformat(attrib.get("CreationDate"))
# about 10 more conversions ...
tags = attrib.get("Tags")
# "<python><mongodb>" -> ["python", "mongodb"]
if tags: result["Tags"] = [tag[:-1] for tag in tags.split("<")[1:]]
return result
</code></pre>
<p>Some performance metrics:</p>
<pre><code>no inserts, no parsing, passing None to worker: 13427.88 items/s
no inserts, no parsing, passing et.tostring(elem) to worker: 10177.07 items/s
no inserts, parsing, passing et.tostring(elem) to worker: 9637.41 items/s
inserts, parsing, passing et.tostring(elem) to worker: 7185.15 items/s
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-18T20:47:16.540",
"Id": "475948",
"Score": "4",
"body": "Hey, welcome to Code Review! Here we like to have as much of the code as possible. You might get better reviews if you also include the skipped conversions, there might be some structure there that helps simplifying it. You might also want to mention the size of the XML file (14.6GB in 7z format). Have you tried profiling your code to see which part exactly is the slowest? Maybe it is the inserting rows one at a time into the DB and not the parsing?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-19T19:36:53.517",
"Id": "476038",
"Score": "0",
"body": "Thanks for your comment and interest! The skipped conversions are structurally build like the ones posted, but simply with other attribute names, which is why I have skipped them. I included all types of conversions that I used. I added some performance metrics to show the processing speed with and without parsing, etc.\nIt seems that the insertion into the database is slowing down the process more than the parsing itself."
}
] |
[
{
"body": "<p>Since inserting into the DB takes a non-negligible amount of time, you should try to use <code>insert_many</code>, instead of <code>insert_one</code>. If you used a single thread this would be easy, just chunk your file and insert a whole chunk. Since you are using multiprocessing, this is a bit more complicated, but it should still be doable </p>\n\n<p>(untested code)</p>\n\n<pre><code>from itertools import islice\nimport pymongo\nimport multiprocessing as mp\nfrom tqdm import tqdm\nimport et\n\n\ndef chunks(iterable, n):\n it = iter(iterable)\n while (chunk := tuple(islice(it, n))): # Python 3.8+\n yield chunk\n\ndef work(chunk):\n try:\n posts.insert_many([attrib_to_dict(elem.attrib) for _, elem in chunk],\n ordered=False)\n except pymongo.errors.BulkWriteError:\n # skip element\n pass\n\nif __name__ == \"__main__\":\n pool = mp.Pool(4)\n # progress bar\n pbar = tqdm(total=POSTS_SIZE)\n n = 100\n try:\n for chunk in chunks(et.iterparse(\"Posts.xml\", tag=\"row\"), n):\n pool.apply_async(work, args=(chunk,),\n callback=lambda: pbar.update(len(chunk)))\n pool.close()\n except KeyboardInterrupt:\n pool.terminate()\n finally:\n pbar.close()\n pool.join()\n</code></pre>\n\n<p>Here I used <a href=\"https://stackoverflow.com/a/56319442/4042267\">this</a> to ignore duplicate keys.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-27T13:02:48.580",
"Id": "476918",
"Score": "1",
"body": "Thanks for your help! I'm struggling with the multiprocessing implementation because I'm not able to clear the current element correctly with `elem.clear()` to free memory.\n\nI used your chunk based approach with a single thread instead which already resulted in a processing speed of 15596.80 items/s. Maybe updating the progress bar every item also slowed the process down, I am updating it for every chunk now instead."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-20T10:43:54.913",
"Id": "242627",
"ParentId": "242533",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "242627",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-18T20:43:05.793",
"Id": "242533",
"Score": "2",
"Tags": [
"python",
"performance",
"parsing",
"xml",
"mongodb"
],
"Title": "Import huge XML data set into MongoDB while parsing data"
}
|
242533
|
<p>I did some manual tests by instantiating the class and it seems to be working okay. I wanted some feedback on the following:</p>
<ol>
<li><p>Is the code well structured? I notice I have a lot of redundancy. The search and delete methods are almost the same.</p></li>
<li><p>I use a string to flag deleted keys until they are replaced, is there a better way to do this. Another boolean array maybe?</p></li>
</ol>
<pre><code>public class HashTable {
//known limitation: This will break if the key value is set to none because I use none as the identifier string for deleted keys.
private int capacity;
String values[];
String keys[];
public HashTable(int capacity){
this.capacity = capacity;
values = new String[this.capacity];
keys = new String[this.capacity];
}
public int hash(String key){
int sum = 0;
for (int i=0; i<key.length();i++){
sum+=key.charAt(i);
}
return sum%capacity;
}
public void add(String key, String value){
int keyhash;
int i = 0;
while(i!=capacity-1){
keyhash = (hash(key)+i)%capacity;
System.out.println("Try "+ i);
if(values[keyhash]==null || values[keyhash].equals("none")) { //add delete flag to this condition after implementing delete.
values[keyhash] = value;
keys[keyhash] = key;
break;
}
if(values[keyhash]!=null && keys[keyhash].equals(key)){
values[keyhash]=value;
break;
}
i++;
}
if(i==capacity-1)
System.out.println("Table appears to be full,unable to insert value");
else
System.out.println("Value inserted successfully.");
}
public String get(String key){
int i = 0;
int keyhash = (hash(key)+i)%capacity;
while(values[keyhash]!=null && i<capacity){
//System.out.println("Try " +i + " of finding the key.");
if(keys[keyhash].equals(key))
return values[keyhash];
i++;
keyhash = (hash(key)+i)%capacity;
}
return null;
}
public void remove(String key){
int i = 0;
int keyhash = (hash(key)+i)%capacity;
while(keys[keyhash]!=null && i<capacity) {
if (keys[keyhash].equals(key)) {
keys[keyhash] = "none";
values[keyhash] = "none";
return;
}
i++;
keyhash = (hash(key)+i)%capacity;
}
System.out.println("Key does not exist in table");
}
public void getHashedValues(){
System.out.println();
for(int i = 0; i<values.length;i++){
System.out.print(" "+ values[i]);
}
System.out.println();
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-19T16:47:49.477",
"Id": "476021",
"Score": "0",
"body": "If the capacity is a power of 2, then can use bit wise logic instead of modulo which is quite expensive"
}
] |
[
{
"body": "<p>I formatted your code and added a <code>main</code> method to test the functionality of your <code>HashTable</code>.</p>\n\n<p>I removed all System calls from the <code>HashTable</code> class and replaced the important text displays with <code>Exceptions</code>. Generally, utility classes don't write to <code>System.out</code> or <code>System.err</code>.</p>\n\n<p>I modified your <code>getHashedValues</code> method to return the values.</p>\n\n<p>I'd change your use of <code>i</code> to <code>index</code>, but that's a minor point.</p>\n\n<p>All in all, good work.</p>\n\n<pre><code>public class HashTableTestbed {\n\n public static void main(String[] args) {\n HashTableTestbed test = new HashTableTestbed();\n HashTable hashTable = test.new HashTable(3);\n\n hashTable.add(\"alpha\", \"zeta\");\n hashTable.add(\"beta\", \"theta\");\n hashTable.add(\"gamma\", \"tau\");\n System.out.println(hashTable.get(\"alpha\"));\n System.out.println(hashTable.get(\"beta\"));\n System.out.println(hashTable.get(\"gamma\"));\n\n hashTable.remove(\"beta\");\n System.out.println(hashTable.get(\"beta\"));\n\n hashTable.add(\"beta\", \"theta\");\n System.out.println(hashTable.get(\"beta\"));\n }\n\n public class HashTable {\n // known limitation: This will break if the key value\n // is set to none because I\n // use none as the identifier string for deleted keys.\n private int capacity;\n String values[];\n String keys[];\n\n public HashTable(int capacity) {\n this.capacity = capacity;\n values = new String[this.capacity];\n keys = new String[this.capacity];\n }\n\n public int hash(String key) {\n int sum = 0;\n for (int i = 0; i < key.length(); i++) {\n sum += key.charAt(i);\n }\n return sum % capacity;\n }\n\n public void add(String key, String value) {\n int keyhash;\n int i = 0;\n while (i != capacity - 1) {\n keyhash = (hash(key) + i) % capacity;\n if (values[keyhash] == null ||\n values[keyhash].equals(\"none\")) {\n // add delete flag to this condition\n // after implementing delete.\n values[keyhash] = value;\n keys[keyhash] = key;\n break;\n }\n\n if (values[keyhash] != null &&\n keys[keyhash].equals(key)) {\n values[keyhash] = value;\n break;\n }\n i++;\n }\n if (i == capacity - 1) {\n String text = \"Table appears to be full, \"\n + \"unable to insert value\";\n throw new ArrayIndexOutOfBoundsException(text);\n }\n }\n\n public String get(String key) {\n int i = 0;\n int keyhash = (hash(key) + i) % capacity;\n while (values[keyhash] != null && i < capacity) {\n if (keys[keyhash].equals(key))\n return values[keyhash];\n i++;\n keyhash = (hash(key) + i) % capacity;\n }\n return null;\n }\n\n public void remove(String key) {\n int i = 0;\n int keyhash = (hash(key) + i) % capacity;\n while (keys[keyhash] != null && i < capacity) {\n if (keys[keyhash].equals(key)) {\n keys[keyhash] = \"none\";\n values[keyhash] = \"none\";\n return;\n }\n i++;\n keyhash = (hash(key) + i) % capacity;\n }\n String text = \"Key does not exist in table\";\n throw new IllegalArgumentException(text);\n }\n\n public String[] getHashedValues() {\n return values;\n }\n\n }\n\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-19T09:36:04.293",
"Id": "242551",
"ParentId": "242538",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "242551",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-19T04:09:16.533",
"Id": "242538",
"Score": "2",
"Tags": [
"java",
"hash-map"
],
"Title": "Hash table in Java with arrays and linear probing"
}
|
242538
|
<p>I have concurrency tasks in my module: user code is able to instantiate my object and specify <code>Executor</code> service, then user can submit requests to this object which should be run on specified executor. I'm calling this object requests queue. Also, this object holds internal state, but it's not relevant for this question. I have these abstractions:</p>
<pre class="lang-java prettyprint-override"><code>interface Request {
void process(SomeState state);
}
class RequestsQueue {
public RequestsQueue(Executor exec) {
this.exec = exec;
}
void accept(Request req) {
//
}
}
</code></pre>
<p>The problem is that user is able to submit multiple requests simultaneously from different threads and all requests should be processed sequentially.</p>
<p>I'm using the combination of <code>AtomicBoolean</code> and <code>ConcurrentLinkedQueue</code> to achieve it:</p>
<pre class="lang-java prettyprint-override"><code>class RequestsQueue implements Runnable {
// queue of requests
private final Queue<Request> queue = new ConcurrentLinkedQueue<>();
// atomic running state flag
private final AtomicBoolean running = new AtomicBoolean();
// user specified executor
private final Executor exec;
// some internal state
private final SomeState state;
public RequestsQueue(SomeState state, Executor exec) {
this.state = state;
this.exec = exec;
}
@Override
public void run() {
// run this task until internal state will be marked as done by request
while (!this.state.done()) {
Request next = this.queue.poll();
// if no next item, try to exit the loop
boolean empty = next == null;
if (empty) {
// try to recover: user may submit next request between
// checking for empty and running.set(false) call,
// this is why I'm checking next item and running state twice
// mark this loop as finished
this.running.set(false);
// check if any next item available
next = this.queue.peek();
empty = next == null;
// if next item available and this loop is still not running
// continue running this loop and process next item
if (!empty && this.running.compareAndSet(false, true)) {
if (this.state.done()) {
// done - exit loop, perform cleanup
break;
}
// remove peeked item
this.queue.remove(next);
} else {
// exit if empty or acquired by next loop, don't cleanup,
// wait for next request
return;
}
}
next.process(this.state);
}
// some cleanup
// ...
// mark as not running
this.running.set(false);
}
public void accept(final Request req) {
if (this.state.done()) {
return;
}
// add request to the queue
this.queue.add(req);
// start this task with queue loop if it is not running already
if (this.running.compareAndSet(false, true)) {
this.exec.execute(this);
}
}
}
</code></pre>
<p>Why such implementation: I tried to avoid synchronization and locks here, since expected use case is when the user will submit many requests before first will complete, and the queue will be populated without exiting from first task. Also, the amount of requests may be huge enough, so synchronizing each request may hurt performance a lot. So usually all requests will be processed within one loop without starting multiple tasks. But it's also possible that user will have some delay and tasks will be submitted to executor when previous exited the loop.</p>
<p>I wrote some unit tests to verify different scenarios and it seems everything works fine. But I'm not sure if I missed something. Is it enough to use double check the concurrent queue with conjunction of atomic boolean to be sure that none of the requests was lost? And can I be sure that all the requests will be processed without hanging in queue with stopped while-loop?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-19T09:20:27.477",
"Id": "475985",
"Score": "0",
"body": "Shouldn't a [`SingleThreadExecutor`](https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/Executors.html#newSingleThreadExecutor()) fulfill your needs?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-19T09:41:38.007",
"Id": "475987",
"Score": "0",
"body": "@XtremeBiker no, I can't specify executor, since it's configured from client side by protocol, the user (client programmer) will use shared fixed size thread pool for multiple different `RequestsQueue`s."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-19T10:22:54.790",
"Id": "475990",
"Score": "0",
"body": "I don't understand it, so you only can process one request at the same time but you decide to do your own implementation because your client's implementation? As far as I see what you want to do here is FIFO processing, so then what's the problem?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-19T10:26:24.987",
"Id": "475991",
"Score": "0",
"body": "Keep in mind that a Java `ExecutorService` provides the [`submit`](https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/ExecutorService.html#submit(java.util.concurrent.Callable)) feature, that's not \"execute this now\", which is what you're doing in your code, but \"enqueue this to be executed as soon as you can and notify me with the result\". You just need to implement `Callable` instead of `Runnable` to use it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-19T17:44:30.920",
"Id": "476025",
"Score": "0",
"body": "@XtremeBiker actual implementation is a bit complexer than in the example, I removed all non relevant details from this implementation. You can check origin class here: https://github.com/g4s8/rio/blob/master/src/main/java/wtf/g4s8/rio/file/WriteTaskQueue.java"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-19T18:58:09.390",
"Id": "476032",
"Score": "0",
"body": "The executor and the state being passed as constructor arguments are bad dessign IMO. They should be encapsulated in the class."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-19T06:38:23.167",
"Id": "242541",
"Score": "1",
"Tags": [
"java",
"object-oriented",
"concurrency",
"queue"
],
"Title": "Run non overlapped periodical tasks on user specified executor"
}
|
242541
|
<p>I have a simple scrapy spider that crawls a page and returns H1 on the pages. Since, each page is unique, one cannot know how many h1's will be on the page. Since the scrapy spider returns a list, I need to convert the list of lists into variables that I can then insert.</p>
<p>The output of H1 could look like</p>
<pre><code>['some text h1','second h1', 'third h1']
</code></pre>
<p>I have a working code that looks like the following</p>
<pre class="lang-py prettyprint-override"><code> def _h1(self, page, response) :
if isinstance(response, HtmlResponse):
h1 = response.xpath("//h1/text()").getall()
length_h1 = (len(h1))
page['h1_count'] = length_h1
if length_h1 >= 4:
page["h1"] = h1[0]
page["h11"] = h1[1]
page["h12"] = h1[2]
page["h13"] = h1[3]
elif length_h1 == 3:
page["h1"] = h1[0]
page["h11"] = h1[1]
page["h12"] = h1[2]
elif length_h1 == 2:
page["h1"] = h1[0]
page["h11"] = h1[1]
elif length_h1 == 1:
page["h1"] = h1[0]
else :
page["h1"] = "---"
</code></pre>
<p>Now I am only accounting for 5 cases but sometimes the page may have as many as 15 h1's.</p>
<p>I have considered a for loop but not sure if that is a more memory efficient way or a better way exists in Python at all ? Please consider me a beginner and go gentle.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-19T11:48:07.353",
"Id": "475994",
"Score": "1",
"body": "The provided code doesn't work with 15 h1's, and so this code does not work the way you intend."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-20T23:46:19.810",
"Id": "476217",
"Score": "0",
"body": "@Peilonrayz - You are being pedantic and infact closing the question based on code that works and requires review for scalability. Good way to tel a new user that you are not welcome here ! Thank you."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-20T23:51:25.170",
"Id": "476218",
"Score": "0",
"body": "No. Everyone has to follow the rules. If you have a problem with how you've been treated you can raise it on [meta]."
}
] |
[
{
"body": "<p>Why don't use a 2-dimesion array? It's more simple and efficent, you don't need to waste time in condition statemento or loop.</p>\n\n<pre><code>def _h1(self, page, response) :\n if isinstance(response, HtmlResponse):\n page[\"h1\"] = response.xpath(\"//h1/text()\").getall()\n</code></pre>\n\n<p>If you need the number of <code>H1</code> in page simply use <code>len(page[\"h1\"])</code> or if you need second result of your search use <code>page[\"h1\"][1]</code> and so on.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-19T09:24:26.940",
"Id": "475986",
"Score": "0",
"body": "This makes much more sense. This creates another problem though that I am then inserting this into a db and a sqlite will usually not insert a list but that another problem altogether. Thank you for taking the time to respond."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-19T10:00:46.867",
"Id": "475989",
"Score": "0",
"body": "@Sam When you save in db use un loop, something like this `for r in page[\"h1\"]: db.insert(col=r)`"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-19T08:44:30.977",
"Id": "242548",
"ParentId": "242542",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "242548",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-19T06:47:23.757",
"Id": "242542",
"Score": "-1",
"Tags": [
"python",
"hash-map",
"iteration"
],
"Title": "Best way of converting a dynamic number of list items into variables in Python"
}
|
242542
|
<p>I have written a simple logger, AsyncFile, which asynchronously writes data to a file. Since data is going to be written very often (E.g. 10 writes per 30 milliseconds from different threads, my system has a 30ms sync time), I would like to know if:</p>
<pre><code>1. The design makes sense att all? Am I missing something obvious?
2. If the logger is fairly optimal, e.g. that no unneccessary copying takes place.
</code></pre>
<p>Basically, my idea is to write data to a shared buffer(<code>m_queue</code>), then copy that data to a <code>tempBuffer</code> from which I then write to a file.</p>
<p>The method <code>write</code> can be called from multiple threads.</p>
<p>I have tested this logger and it seems to work fine, but like all problems involving shared resources, it is hard to know if it is well-designed until you have tried it for a good amount of time. </p>
<p>AsyncFile.h:</p>
<pre><code>#pragma once
#include <cstdint>
#include <cstddef>
#include <array>
#include <mutex>
#include <condition_variable>
class AsyncFile
{
public:
AsyncFile();
void write(std::array<char,40>& buffer);
void done();
private:
std::array<char, 160> m_queue;
std::array<char, 160> tempBuffer;
std::mutex queue_mutex;
std::condition_variable cv;
size_t counter = 0;
bool readyToCopy = false;
bool finished = false;
void logger_thread();
}; // class AsyncFile
</code></pre>
<p>AsyncFile.cpp:</p>
<pre><code>#include <thread>
#include <fstream>
#include <string.h>
#include <iostream>
#include <chrono>
void AsyncFile::logger_thread()
{
FILE* file = fopen("test_file.bin", "wb");
while(!finished) // Pass "finished" as a parameter by ref? Protect by a mutex?
{
std::unique_lock<std::mutex> lk(queue_mutex);
cv.wait(lk, [&]{return readyToCopy;});
std::copy(m_queue.begin(), m_queue.end(), tempBuffer.begin());
readyToCopy = false;
lk.unlock();
// Now write to file from the temporary buffer:
fwrite(&tempBuffer, sizeof(char), sizeof(tempBuffer), file);
}
fclose(file);
}
AsyncFile::AsyncFile()
{
std::thread m_worker(&AsyncFile::logger_thread, this);
m_worker.detach(); // let the worker thread live on its own.
}
void AsyncFile::done()
{
finished = true;
}
void AsyncFile::write(std::array<char, 40>& buffer) // 40 should probably be a
// configurable parameter.
{
std::lock_guard<std::mutex> guard(queue_mutex);
std::copy(buffer.begin(), buffer.end(), m_queue.begin() + counter);
if (counter == 120) // fill the queue, 40 char each time, until we have 160 chars in total. Then
// notify the writing thread we are ready.
{
counter = 0;
readyToCopy = true;
cv.notify_one();
}
else
{
counter += 40;
}
}
</code></pre>
|
[] |
[
{
"body": "<p>There are some issues with this solution:</p>\n\n<ol>\n<li>You are saying that this class will be used from many threads under a heavy load. In this case a lock in AsyncFile::write is not going to scale well. Only one thread can write logs at a time, depending on the load this kind of thing can bring the whole system down. Though of course with your load pattern it might be just fine.</li>\n<li>I agree that the constants should be configurable</li>\n<li>fopen is most likely a buffered api. So, if your app crashes, the logs will be corrupted. </li>\n<li>There is no overflow mechanism. What would happen if the clients write faster than the writing thread can consume? </li>\n<li>If no one writes anything, how would your thread finish? You should check finished in the condition variable.</li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-22T19:14:05.277",
"Id": "476467",
"Score": "0",
"body": "Thanks for you feedback, it is really helpful! I just have a couple of questions. Regarding your 4th point, is there any strategy you would recommend, regarding the overflow? I hardly see any other strategy than just discarding the data if the buffer is full? \n\nMy second question is about your point on multiple threads writing to the same buffer. Would it be more efficient to have some kind of atomic offset which is incremented after each write, instead of protecting the whole \"m_queue\" with a mutex? I am thinking of locking it ONLY when it is full, in order to copy m_queue to tempBuffer."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-23T20:33:20.633",
"Id": "476574",
"Score": "0",
"body": "I case of overflow, you basically have only two choices, either wait or discard. For minimizing locking there are more choices than I can describe in a comment: you can use a buffer for each thread and then ether join them inside the logging thread or use some kind of write-gather api. You can use a concurrent container, with finer-grained locking or lock-free instead of your queue and so on."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-20T10:13:23.020",
"Id": "242624",
"ParentId": "242547",
"Score": "1"
}
},
{
"body": "<p>To make a fast logger you need to </p>\n\n<ul>\n<li>minimise the use of mutexes.</li>\n<li>detach the logging from the writing.</li>\n<li>minimise copying</li>\n<li>pre-alloc the buffers\n\n<ul>\n<li>no allocs during logging.</li>\n</ul></li>\n<li>make a ring buffer\n\n<ul>\n<li>fixed number of logging</li>\n<li>decide what should happen if its full</li>\n<li>slightly slower using a dequeue with minimises allocs</li>\n</ul></li>\n<li>use atomic indexes to the (ring) buffer\n\n<ul>\n<li>if your system if fully loaded, you have to log often use the cv or wait until the logger thread gets scheduled by the OS.</li>\n<li>use the cv.notice_one where the index is updated if the front is sufficient in front of the back end.</li>\n</ul></li>\n</ul>\n\n<p>So a few of the things that are issues</p>\n\n<ul>\n<li>The logger_thread blocks further logging while it writes.</li>\n<li>The write blocks other threads logging</li>\n</ul>\n\n<p>Running into a mutex that is taken causes a task switch, typically taking from 1000ns to 22000ns on a x86, nearer the lower if its started again on the same hardware thread.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-20T18:36:57.063",
"Id": "476188",
"Score": "0",
"body": "Thank you for your feedback! But I thought the writing to file is done asynchronously, since I unlock the lock before I write? The lock only protects the copying to tempBuffer?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-20T20:14:59.150",
"Id": "476197",
"Score": "0",
"body": "@Wballer3 you are right you do unlock before write."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-20T12:14:46.187",
"Id": "242634",
"ParentId": "242547",
"Score": "2"
}
},
{
"body": "<p>An alternative to using (ring)buffers, mutexes and condition variables is to use a datagram UNIX <a href=\"https://pubs.opengroup.org/onlinepubs/009695399/functions/socketpair.html\" rel=\"nofollow noreferrer\">socket pair</a>. Writes to a datagram socket are atomic, so multiple threads can safely write to it without the messages getting mixed up. Also, you can choose whether or not to make the socket non-blocking. On Windows you might have to use something else, like a UDP socket.</p>\n<p>The drawbacks are that it is not as portable (sockets are not part of the C++ standard library), and that each write to a socket will be a system call, so it has a higher overhead than just adding something to a ringbuffer. On the other hand, if you write so often that you have lock contention then the difference is likely minimal.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-19T21:51:55.613",
"Id": "244198",
"ParentId": "242547",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-19T08:35:08.310",
"Id": "242547",
"Score": "2",
"Tags": [
"c++",
"multithreading"
],
"Title": "Logger which writes asynchronously to file from multiple threads"
}
|
242547
|
<p>Good morning,</p>
<p>I have the following code:</p>
<pre><code>Option Explicit
Private Sub CommandButton1_Click()
Dim LastRowA As Long, LastRowB As Long, LastRowC As Long, lastrowD As Long, LastrowE As Long,
LastrowF As Long, LastrowG As Long, LastrowH As Long, LastrowI As Long, LastrowK As Long, LastrowL
As Long
Dim ws As Worksheet
Set ws = Sheets("Sheet1")
LastRowA = ws.Range("A" & Rows.Count).End(xlUp).Row + 1 'Finds the last blank row
LastRowB = ws.Range("B" & Rows.Count).End(xlUp).Row + 1
LastRowC = ws.Range("C" & Rows.Count).End(xlUp).Row + 1
lastrowD = ws.Range("D" & Rows.Count).End(xlUp).Row + 1
LastrowE = ws.Range("E" & Rows.Count).End(xlUp).Row + 1
LastrowF = ws.Range("F" & Rows.Count).End(xlUp).Row + 1
LastrowG = ws.Range("G" & Rows.Count).End(xlUp).Row + 1
LastrowH = ws.Range("H" & Rows.Count).End(xlUp).Row + 1
LastrowI = ws.Range("I" & Rows.Count).End(xlUp).Row + 1
LastrowK = ws.Range("K" & Rows.Count).End(xlUp).Row + 1
LastrowL = ws.Range("L" & Rows.Count).End(xlUp).Row + 1
ws.Range("A" & LastRowA).Value = JobID.Text 'Adds the TextBox3 into Col A & Last Blank Row
ws.Range("B" & LastRowB).Value = Surveyor.Text
ws.Range("C" & LastRowC).Value = DateBox.Text
ws.Range("D" & LastRowC).Value = AddressBox.Text
ws.Range("E" & LastrowE).Value = CityBox.Text
ws.Range("F" & LastrowF).Value = PostcodeBox.Text
ws.Range("G" & LastrowG).Value = THPBox.Text
ws.Range("H" & LastrowH).Value = ChamberBox.Text
ws.Range("I" & LastrowI).Value = ORFibreBox.Text
ws.Range("K" & LastrowK).Value = ("=I" & LastrowI & "*5")
End Sub
</code></pre>
<p>which helps me to autofill the table columns based on the user form.</p>
<p>The code is valid, but I am wondering how can I write it smarter. Is it possible at all?</p>
<p><a href="https://i.stack.imgur.com/3L0wb.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/3L0wb.png" alt="enter image description here"></a></p>
|
[] |
[
{
"body": "<p>Whenever you find yourself writing a block of nearly identical code, I recommend creating a common function that simplifies and isolates that functionality. The advantage is that you now have a single location for the logic and can easily make a change that is consistent for each instance you need to use that logic. In your case, you are repeatedly finding the last row in a column and adding a value to the first empty row in that column. So create a separate routine for that.</p>\n\n<p>You have three tricky parts. The first is that you're not always adding a value. In at least one case, you want to add a formula. For this, I created a simple enumeration type as an optional parameter. The second is you wanted to use the row index in your formula, so that row index value is returned from the function to use if needed. The last tricky bit is adding a value to a column that is completely empty. You can't blindly always add one to the <code>lastRow</code> value because you'll end up skipping that top row. This isn't always a problem since many folks reserve the first row for a column header, but the function takes this into account to be thorough.</p>\n\n<pre><code>Option Explicit\n\nPrivate Enum DataType\n DataValue\n FormulaValue\nEnd Enum\n\nPrivate Sub CommandButton1_Click()\n AppendToColumn Sheet1, \"A\", JobID.Text 'Adds the TextBox3 into Col A & Last Blank Row\n AppendToColumn Sheet1, \"B\", Surveyor.Text\n AppendToColumn Sheet1, \"C\", DateBox.Text\n AppendToColumn Sheet1, \"D\", AddressBox.Text\n AppendToColumn Sheet1, \"E\", CityBox.Text\n AppendToColumn Sheet1, \"F\", PostcodeBox.Text\n AppendToColumn Sheet1, \"G\", THPBox.Text\n AppendToColumn Sheet1, \"H\", ChamberBox.Text\n Dim lastRowI As Long\n lastRowI = AppendToColumn(Sheet1, \"I\", ORFibreBox.Text)\n AppendToColumn Sheet1, \"K\", (\"=I\" & lastRowI & \"*5\"), FormulaValue\nEnd Sub\n\nPrivate Function AppendToColumn(ByRef ws As Worksheet, _\n ByVal columm As Variant, _\n ByVal value As Variant, _\n Optional ByVal kindOfValue As DataType = DataValue) As Long\n '--- copies the given value to the first empty cell in the\n ' specified column. the \"columm\" value can be either numeric\n ' or alphabetic. RETURNS the index of the last row\n Dim colIndex As Long\n Dim lastRow As Long\n Dim firstEmptyRow As Long\n With ws\n '--- quick conversion to make sure we have a numeric column index\n colIndex = IIf(IsNumeric(columm), columm, .Cells(1, columm).column)\n lastRow = .Cells(.Rows.Count, colIndex).End(xlUp).Row\n '--- if the column is completely empty, the first empty row is 1,\n ' otherwise it's one row down from the last row\n firstEmptyRow = IIf(IsEmpty(.Cells(lastRow, colIndex)), 1, lastRow + 1)\n Select Case kindOfValue\n Case DataValue\n .Cells(firstEmptyRow, colIndex).value = value\n Case FormulaValue\n .Cells(firstEmptyRow, colIndex).Formula = value\n End Select\n End With\n AppendToColumn = lastRow\nEnd Function\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-20T13:57:10.090",
"Id": "242642",
"ParentId": "242553",
"Score": "4"
}
},
{
"body": "\n\n<p>Assuming that you always want the data from a single button press to fall on the same row, you can achieve this functionality with</p>\n\n<pre class=\"lang-vb prettyprint-override\"><code>let ws.[A1].Offset(row-1).Resize(1,10) = _ \n Array( _ \n JobID.Text, _ \n Surveyor.Text, _ \n DateBox.Text, _ \n AddressBox.Text, _ \n CityBox.Text, _ \n PostcodeBox.Text, _ \n THPBox.Text, _ \n ChamberBox.Text, _ \n ORFibreBox.Text) \nlet ws.[K1].Offset(row-1).Formula=\"=I\" & row & \"*5\"\n</code></pre>\n\n<p>where you have to row is found in the same way as you had been doing before, with some column that is garunteed not to have a blank.\nOr, if we assume that column J will always be blank at the time a new row is added, you can do this with </p>\n\n<pre class=\"lang-vb prettyprint-override\"><code>let ws.[A1].Offset(row-1).Resize(1,10) = _ \n Array( _ \n JobID.Text, _ \n Surveyor.Text, _ \n DateBox.Text, _ \n AddressBox.Text, _ \n CityBox.Text, _ \n PostcodeBox.Text, _ \n THPBox.Text, _ \n ChamberBox.Text, _ \n ORFibreBox.Text, _ \n \"\", _ \n (\"=I\" & row & \"*5\"))\n</code></pre>\n\n<p>That said, you should probably look into making the table into a <a href=\"https://docs.microsoft.com/en-us/office/vba/api/excel.listobject\" rel=\"nofollow noreferrer\">ListObject</a>. If you do so (CTRL + T while highlighting the table; yes it has headers), you can make your code look like </p>\n\n<pre class=\"lang-vb prettyprint-override\"><code>dim lo as ListObject, _\n lr as ListRow\n\nSet lo = ws.[A1].listobject\nSet lr = lo.ListRows.Add\nlet lr.Range(1, 1).Resize(1, 11) = _ \n Array( _ \n JobID.Text, _ \n Surveyor.Text, _ \n DateBox.Text, _ \n AddressBox.Text, _ \n CityBox.Text, _ \n PostcodeBox.Text, _ \n THPBox.Text, _ \n ChamberBox.Text, _ \n ORFibreBox.Text, _ \n \"\", _ \n (\"=I\" & row & \"*5\"))\n</code></pre>\n\n<p>and, if you do end up doing this, you would probably want to change the way that the final formula is assigned to reflect <a href=\"https://support.office.com/en-us/article/using-structured-references-with-excel-tables-f5ed2452-2337-4f71-bed3-c8ae6d2b276e\" rel=\"nofollow noreferrer\">Excel Table Reference notation</a></p>\n\n<p>If you choose to do either of these ways, it will greatly reduce the number of updates that are made to the worksheet by pushing the entire row at once. This should make the method run significantly faster - thought I would expect this not to be very noticible with this relatively small number of columns.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-21T15:49:06.600",
"Id": "242703",
"ParentId": "242553",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "242642",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-19T10:23:31.220",
"Id": "242553",
"Score": "0",
"Tags": [
"vba",
"excel"
],
"Title": "Autofill a table based on the input provided in a userform"
}
|
242553
|
<p>I want to have a test fail, because the email already exists, so I create duplicate@dave.com and dave@dave.com, but is there a way to do it without this?</p>
<pre><code>it('prepare', (done) => {
chai.request(rest_api_url).post('/subscribers')
.send({email: 'dave@dave.com', name: 'klaas'})
.end((err, res) => {
res.should.have.status(200);
});
chai.request(rest_api_url).post('/subscribers')
.send({email: 'duplicate@dave.com', name: 'klaas'})
.end((err, res) => {
res.should.have.status(200);
done();
});
});
it('it should not edit to email that is duplicate', (done) => {
chai.request(rest_api_url).put('/subscriber/dave@dave.com')
.send({email: 'duplicate@dave.com', name: 'klaas'})
.end((err, res) => {
res.should.have.status(403);
done();
});
});
it('cleanup', (done) => {
chai.request(rest_api_url).delete('/subscriber/' + 'duplicate@dave.com')
.end((err, res) => {
res.should.have.status(200);
});
chai.request(rest_api_url).delete('/subscriber/' + 'dave@dave.com')
.end((err, res) => {
res.should.have.status(200);
done();
});
});
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-19T22:56:45.867",
"Id": "476056",
"Score": "1",
"body": "This seems like a reasonable solution, but there are other issues with this code. For one, the unit tests are non-idemponent, so state carries from one test to the next which can lead to very confusing situations and makes the tests difficult to reason about. I'd write an answer with this and other suggestions, but it sounds like you're not asking for general feedback. I'd recommend editing your post to include your question as well as inviting general feedback, and maybe showing the full `describe` block and a bit of context. See [ask]."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-22T11:32:31.933",
"Id": "476416",
"Score": "0",
"body": "@ggorlen Yeah, I never head of idemponent, but I have this problem of creating the duplicate@dave.com sometimes gets excuted after my test. At least this is how it feels when the test sometimes doesn't work. Also the test is slow.\n\nGeneral feedback is welcome."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-19T10:31:55.067",
"Id": "242554",
"Score": "1",
"Tags": [
"javascript",
"node.js",
"mocha"
],
"Title": "Mocha chai tests"
}
|
242554
|
<p>The goal is to have well defined state transitions, and the ability to provide the next event to execute.</p>
<p>I'd like to know if this is a proper implementation of State Machine, considering how states and transitionTable are defined, and how I handle event as input and output via <code>nextEvent</code>.</p>
<p>In many examples I cannot clearly define verbiage for state, so I defined them as verbs (notice ing suffix), as if it represents the ongoing progress of workflow. This may be wrong..</p>
<p>I also defined multiple events that could occur for a single state. For example, GetDeviceStatus and GetIntegrityStatus events both occur in RetrievingStatus state. This is also the case for Downloading state. You can see in the cases, when determining the next event, I need to check what the previous state was first.</p>
<p>If flawed, what are the pitfalls to my design, and how could it be improved? thanks.</p>
<pre><code>enum ExampleState {
case Initiate
case Authorizing
case RetrievingStatus
case Downloading
case Confirming
case End
}
enum ExampleEvent {
case InitiateSequence
case GetAuthToken
case GetDeviceStatus
case GetIntegrityStatus
case DownloadFromServer
case DownloadToDevice
case Confirm
}
class StateMachine {
var oldState: ExampleState!
var currentState: ExampleState!
var currentEvent: ExampleEvent!
var table: [ExampleState: [ExampleEvent: ExampleState]] = [.Initiate: [.InitiateSequence: .Authorizing],
.Authorizing: [.GetAuthToken: .RetrievingStatus],
.RetrievingStatus: [.GetDeviceStatus: .Downloading, .GetIntegrityStatus: .Confirming],
.Downloading: [.DownloadFromServer: .Downloading, .DownloadToDevice: .RetrievingStatus],
.Confirming: [.Confirm: .End]]
func nextEvent(event: ExampleEvent) -> EventExecutor? {
let transitionState = table[currentState]![event]!
let oldState = currentState
switch (transitionState) {
case .Initiate:
currentState = .Initiate
return InitiateSequence()
case .Authorizing:
currentState = .Authorizing
return GetAuthToken()
case .RetrievingStatus:
currentState = .RetrievingStatus
switch (oldState) {
case .Authorizing: return GetDeviceStatus()
case .Downloading: return GetIntegrityStatus()
default: return nil
}
case .Downloading:
currentState = .Downloading
switch (oldState) {
case .RetrievingStatus: return DownloadFromServer()
case .Downloading: return DownloadToDevice()
default: return nil
}
case .Confirming:
currentState = .Confirming
return Confirm()
case .End:
currentState = .End
return nil
}
}
}
</code></pre>
<p><strong>Use case</strong> </p>
<pre><code>@objc func rxExecute() {
publisher
.map { self.stateMachine.nextEvent(event: $0) } // $0 == event that just completed
.flatMap { $0!.rxExecute() } // execute next event from state machine output
.subscribe(subscriber) // handles errors/success from completed event
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-19T19:33:10.190",
"Id": "476037",
"Score": "2",
"body": "Please do not edit the question after an answer has been posted https://codereview.stackexchange.com/help/someone-answers."
}
] |
[
{
"body": "<p>First there are a few things about design</p>\n<p>Does you machine has something like 'error' that is not handled (e.g. by throwing an exception) or you have only 'outcomes' that handled in the same matter.</p>\n<p>Do you expect branches in the FSM? Is it possible for an fsm method to fail? If possible how it is handled? E.g. ignored (say we rely on caller to retry on timer), raise failure event and queue it for execution, use return value as a guard to branch in state machine method.</p>\n<p>Do you expect your code to maintained over 20+ years period?</p>\n<p>After many attempts to make better existing FSMs, making my own, trying different frameworks and making my own frameworks too, I came to a trivially simple conclusion (aka 'dumb' FSM pattern): each event should be represented by a function and each function should contain a switch by state; or every state should be represented by a function and every function should contain a switch by event.</p>\n<p>In the long run this is the cheapest solution. E.g. if you do not have branches/failures one can write a simple table driven fsm, however, once we will get the first branch/failure to handle we will need to either make it way more complicated or throw it away and rewrite using the 'dumb' approach</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-19T19:28:34.653",
"Id": "476036",
"Score": "0",
"body": "Ok thanks. I think I understand, but it would help if you could share an examples of this. In my case, the state machine wont be responsible for handling any errors except invalid state transitions. The `ResponseSubscriber` actually handles the errors from the actual event task, and if there are no errors I save and emit completed event to publisher. I'll add code, and would like your opinion of this approach."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-19T20:04:44.753",
"Id": "476041",
"Score": "1",
"body": "Your simple fsm, your code will work as is and it is very close to the 'dumb' one I described. The only difference is that you have one switch statement to handle all combinations of state/and events and a table to figure out next state. And the real 'dumb' one will have one switch per state that will perform actions and figure out next state."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-19T17:58:16.403",
"Id": "242584",
"ParentId": "242555",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "242584",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-19T10:47:18.870",
"Id": "242555",
"Score": "1",
"Tags": [
"object-oriented",
"swift",
"state-machine"
],
"Title": "Simple State Machine and Transition Table"
}
|
242555
|
<p>I'm developing a man-in-the-middle proxy that will let the user see and modify HTTP and HTTPS requests before they leave the client and responses before they arrive at the client. The code I'm working on is working, but I don't know if it's the right or beast way to achieve this behaviour. I'm waiting for all request and response chunks before moving on the the next step.</p>
<p>Browsing with the proxy on is clearly slower, although this is not a problem to the application I'll use this proxy on. Below is the code I'm using to wait for all body chunks before performing the next step.</p>
<pre class="lang-js prettyprint-override"><code>let requestBody: Buffer
try {
requestBody = await this.collectMessageBody(req)
} catch (error) {
req.destroy(new ProxyError('Error while fetching request body', ErrorType.unknown, error))
return
}
let modifiedRequest: any
try {
// Send the intercepted request to the client before forwarding to its destination
modifiedRequest = await this.interceptHandler('request', request, response)
} catch (error) {
req.destroy(new ProxyError('Request dropped by the client', ErrorType.denied, error))
return
}
// Handle the response from the forwarded request. The logic is similar to above but can be ignored to this question scope
const responseHandler = async (serverResponse: http.IncomingMessage) => this.receiveResponse(request, response, serverResponse, res)
// Creates the request that will be sent to the final destination using http.request(...)
const forwardedRequest = Router.forward(modifiedRequest, responseHandler)
forwardedRequest.on('error', error => this.emit('error', error))
// Write the original request body to the forwarded one
forwardedRequest.write(requestBody)
// Send the request
forwardedRequest.end()
private collectMessageBody(incomingMessage: http.IncomingMessage): Promise<Buffer> {
return new Promise<Buffer>((resolve, reject) => {
let bodyBuffers: Buffer[] = []
incomingMessage.on('data', chunk => bodyBuffers.push(chunk))
incomingMessage.on('end', () => resolve(Buffer.concat(bodyBuffers)))
incomingMessage.on('error', error => reject(error))
})
}
<span class="math-container">```</span>
</code></pre>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-19T11:03:16.173",
"Id": "242557",
"Score": "1",
"Tags": [
"node.js",
"typescript"
],
"Title": "Await all HTTP request body chunks before moving on"
}
|
242557
|
<p>My program , developed with C using win_flex , implements lexical, syntatic and semantic analysis , given defined grammar rules.</p>
<p>I would like to know if you any suggestion for improving or refactoring this.</p>
<p>Here is my code:</p>
<p><strong>main.c</strong></p>
<pre><code>#define _CRT_SECURE_NO_DEPRECATE
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "LEXYY.h"
#include "PARSER.h"
#include "semantic.h"
char *yytext;
FILE *yyin;
int yylex();
void printToken() {
const char *TokenNames[11] = {
"PROGRAM", "END",
"INTEGER", "REAL", "INT_NUMBER", "REAL_NUMBER",
"ID", "VOID", "RETURN",
"COMMA", "SEMICOLON",
};
char buffer[] = { (char)token->kind, '\0' };
const char *token_name = token->kind >= PROGRAM ? TokenNames[token->kind - PROGRAM] : buffer;
token->count = strlen(token->lexeme);
fprintf(yyout, "Token of kind '%s' was found at line: %d, lexeme: '%s'\n", token_name, token->line, token->lexeme);
}
int main(int argc, char *argv[]) {
int current_token;
for (int i = 1; i < 3; i++) {
if (i == 1) {
yyin = fopen("C:\\temp\\test1.txt", "r");
yyout = fopen("C:\\temp\\test1_200419513_lex.txt", "w");
}
else {
yyin = fopen("C:\\temp\\test2.txt", "r");
yyout = fopen("C:\\temp\\test2_200419513_lex.txt", "w");
}
if (yyin == NULL) {
printf("Cannot find file.\nPlease use standard input.\n");
yyin = stdin;
}
if (yyout == NULL) {
printf("Cannot open output file.\n");
yyout = stdout;
}
initLexer();
while ((current_token = yylex()) != 0) {
create_and_store_token(current_token, (char *)yytext, line_number);
printToken();
}
if (i == 1) {
yyout = fopen("C:\\temp\\test1_200419513_syntatic.txt", "w");
}
else {
yyout = fopen("C:\\temp\\test2_200419513_syntatic.txt", "w");
}
if (yyout == NULL) {
printf("Cannot open output file.\n");
yyout = stdout;
}
if (lexer_errors) {
fprintf(yyout, "Detected Errors by lexical analysis.\nPlease first fix lexical error.\n");
continue;
}
parser();
if (i == 1) {
yyout = fopen("C:\\temp\\test1_200419513_semantic.txt", "w");
}
else {
yyout = fopen("C:\\temp\\test2_200419513_semantic.txt", "w");
}
if (yyout == NULL) {
printf("Cannot open output file.\n");
yyout = stdout;
}
if (parser_errors) {
fprintf(yyout, "Detected Errors by syntatic analysis.\nPlease first fix syntax error.\n");
continue;
}
semantic();
}
return 0;
}
</code></pre>
<p><strong>LEXYY.Y</strong></p>
<pre><code>program : PROGRAM var_definitions ';' statements END func_definitions
;
var_definitions : var_definition
| var_definition ';' var_definitions
;
var_definition : type variables_list
;
type : REAL
| INTEGER
;
variables_list : variable
| variables_list ',' variable
;
variable : ID
| ID '[' INT_NUMBER ']'
;
func_definitions : func_definition
| func_definitions func_definition
;
func_definition : returned_type ID '(' param_definitions ')' block
;
returned_type : VOID
| type
;
param_definitions : /* empty */
| var_definitions
;
block : '{' var_definitions ';' statements '}'
;
statements : statement ';'
| statement ';' statements
;
statement : variable '=' expression
| block
| RETURN
| RETURN expression
| function_call
;
function_call : ID '(' parameters_list ')'
;
parameters_list : /* empty */
| variables_list
;
expression : INT_NUMBER
| REAL_NUMBER
| variable
| ID ar_op expression
;
ar_op : '*'
| '/'
;
</code></pre>
<p><strong>LEXYY.h</strong></p>
<pre><code>#pragma once
#include <stdio.h>
typedef struct YYTYPE {
int kind;
char *lexeme;
int line;
int count;
struct YYTYPE *next;
struct YYTYPE *prev;
} YYSTYPE;
YYSTYPE *token;
YYSTYPE *tokens;
int line_number;
int lexer_errors;
void initLexer();
void create_and_store_token(int, char *, int);
#define PROGRAM 256
#define END 257
#define INTEGER 258
#define REAL 259
#define INT_NUMBER 260
#define REAL_NUMBER 261
#define ID 262
#define VOID 263
#define RETURN 264
#define COMMA 265
#define SEMICOLON 266
YYSTYPE *next_token();
YYSTYPE *back_token();
int match(int);
int type();
int ar_op();
int returned_type();
int not_var_definitions();
int not_statements();
</code></pre>
<p><strong>LEXYY.C</strong></p>
<pre><code>%option nounistd
%option noyywrap
%{
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <io.h>
#include "LEXYY.h"
#define isatty _isatty
#define fileno _fileno
void initLexer();
void create_and_store_token(int, char *, int);
void errorPrint(char);
void illegalError(const char *, const char *);
%}
WHITESPACE ([ \t]+)
NEWLINE (\r|\n|\r\n)
COMMENT ("--"[^\r\n]*)
ID ([A-Za-z]([_]?[A-Za-z0-9]+)*)
ILLEGALID ([_][A-Za-z0-9_]*|[A-Za-z][A-Za-z0-9_]*[_]|[0-9][A-Za-z0-9]*|[A-Za-z]([_]*[A-Za-z0-9]*)*)
INTEGER (0|[0-9]+)
REAL (0\.[0-9]+|[0-9]+\.[0-9]+)
WRONGNUMBER ([0][0-9]+|[0][0-9]+[.][0-9]*|[.][0-9]+|[0-9]+[.])
OPERATOR ([*/=])
SEPARATION ([[\]{}\(\)])
%%
{NEWLINE} { line_number++; }
{WHITESPACE}+ {}
{COMMENT} {}
"program" { return PROGRAM; }
"end" { return END; }
"real" { return REAL; }
"integer" { return INTEGER; }
"void" { return VOID; }
"return" { return RETURN; }
{INTEGER} { return INT_NUMBER; }
{REAL} { return REAL_NUMBER; }
{WRONGNUMBER} { illegalError(yytext, "Number"); }
"," { return COMMA; }
";" { return SEMICOLON; }
{ID} { return ID; }
{ILLEGALID} { illegalError(yytext, "ID"); }
{OPERATOR} { return yytext[0]; }
{SEPARATION} { return yytext[0]; }
. { errorPrint(yytext[0]); }
%%
void initLexer() {
line_number = 1;
lexer_errors = 0;
tokens = NULL;
token = NULL;
}
void create_and_store_token(int kind, char *lexeme, int line) {
if (token == NULL) {
tokens = (YYSTYPE *)malloc(sizeof(YYSTYPE));
token = tokens;
token->next = NULL;
token->prev = NULL;
} else {
token->next = (YYSTYPE *)malloc(sizeof(YYSTYPE));
token->next->next = NULL;
token->next->prev = token;
token = token->next;
}
token->kind = kind;
token->line = line;
token->lexeme = (char *)malloc(sizeof(lexeme) + 1);
#ifdef _WIN32
strcpy_s(token->lexeme, strlen(lexeme) + 1, lexeme);
#else
strcpy(token->lexeme, lexeme);
#endif
}
YYSTYPE *next_token() {
if (token)
return (token = token->next);
return NULL;
}
YYSTYPE *back_token() {
if (token)
return (token = token->prev);
return NULL;
}
int match(int kind) {
if (token && token->kind == kind)
return kind;
return 0;
}
int type() {
return (match(REAL) ? REAL : match(INTEGER));
}
int ar_op() {
if (match('*') || match('/'))
return 1;
return 0;
}
int returned_type() {
return (match(VOID) ? VOID : type());
}
int not_var_definitions() {
int flag = 0;
if (!token)
flag = 1;
else if (match(ID)) {
next_token();
if (match('=') || match('('))
flag = 2;
if (match('[')) {
next_token();
next_token();
next_token();
if (match('=') || match('('))
flag = 2;
back_token();
back_token();
back_token();
}
back_token();
}
else
flag = 3;
return flag;
}
int not_statements() {
if (!token)
return 1;
if (!match(ID) && !match(RETURN) && !match('{'))
return 1;
return 0;
}
void errorPrint(char ch) {
fprintf(yyout, "The character '%c' at line: %d does not begin any legal token in the language.\n", ch, line_number);
}
void illegalError(const char *text, const char *type) {
fprintf(yyout, "Illegal %s '%s' was found at line %d\n", type, text, line_number);
}
</code></pre>
<p><strong>parser.c</strong></p>
<pre><code>#pragma once
#include "LEXYY.h"
int parser_errors, recovery;
FILE *yyout;
void error_handle(char *, YYSTYPE *);
void print_token(char *, YYSTYPE *);
int parser();
void var_definitions();
void var_definition();
void variables_list();
void variable();
void statements();
void statement();
void function_call();
void parameters_list();
int expression();
void block();
void func_definitions();
void func_definition();
void param_definitions();
</code></pre>
<p><strong>parser.c</strong></p>
<pre><code>#include <stdio.h>
#include "PARSER.h"
void error_handle(char *expected, YYSTYPE *token) {
if (token) {
fprintf(yyout, "Error: Expected token is { %s }, but actual token is [ %s ] at line %d\n", expected, token->lexeme, token->line);
parser_errors++;
recovery = 1;
}
}
void print_token(char *str, YYSTYPE *token) {
if (token)
fprintf(yyout, str, token->lexeme, token->line);
}
int parser() {
parser_errors = 0;
recovery = 0;
token = tokens;
if (!token)
return 0;
fprintf(yyout, "Starting Program...\n");
if (!match(PROGRAM)) {
error_handle("program", token);
recovery = 0;
}
else
print_token("[ %s ] at line %d\n", token);
next_token();
var_definitions();
statements();
if (!match(END)) {
error_handle("end", token);
recovery = 0;
}
else
print_token("[ %s ] at line %d\n", token);
next_token();
func_definitions();
return parser_errors;
}
void var_definitions() {
if (!type())
if (not_var_definitions())
return;
fprintf(yyout, "Variable Definitions...\n");
while (token) {
if (!type()) {
if (not_var_definitions()) {
recovery = 0;
break;
}
}
var_definition();
if (match(')'))
break;
if (!match(SEMICOLON))
error_handle(";", token);
next_token();
}
}
void var_definition() {
if (type())
print_token("Variable Type [ %s ] at line %d\n", token);
else if (!type())
error_handle("integer, real", token);
next_token();
variables_list();
}
void variables_list() {
int error;
do {
error = not_var_definitions();
variable();
if (error == 2) {
error_handle(",", token);
while (!match(COMMA) && !match(SEMICOLON)) next_token();
recovery = 0;
}
} while (match(COMMA) && next_token());
}
void variable() {
token->lexeme[token->count] = '\0';
if (!match(ID)) {
if (recovery) {
while (!match(ID) && !match(COMMA) && !match(SEMICOLON)) next_token();
recovery = 0;
if (!match(ID)) return;
}
else error_handle("Variable Name(id)", token);
}
next_token();
if (match('[')) {
if (!recovery) {
back_token();
if (token) fprintf(yyout, "Array Variable %s\n", token->lexeme);
next_token();
}
next_token();
if (!match(INT_NUMBER)) {
error_handle("int number", token);
}
else print_token("Array Size [%s] at line %d\n", token);
next_token();
if (!match(']') && token) {
if (recovery) {
while (!match(']')) next_token();
recovery = 0;
}
else error_handle("]", token);
}
next_token();
}
else {
if (!recovery) {
back_token();
print_token("Variable [ %s ] at line %d\n", token);
next_token();
}
}
}
void statements() {
if (not_statements()) return;
fprintf(yyout, "Statement List...\n");
while (!not_statements()) {
statement();
if (!match(SEMICOLON)) {
if (recovery) {
while (!match(SEMICOLON) && !match('{') && !match(END))
if (!next_token())
break;
recovery = 0;
}
else
error_handle(";", token);
}
if (match(END))
break;
if (match('{'))
continue;
next_token();
if (match(SEMICOLON))
next_token();
}
}
void statement() {
fprintf(yyout, "Statement...\n");
if (match(ID)) {
next_token();
if (match('(')) {
back_token();
function_call();
}
else {
back_token();
fprintf(yyout, "Variable Assignment...\n");
variable();
if (!match('=')) {
if (!match(SEMICOLON))
error_handle("=", token);
if (recovery) {
while (!match('=') && !match(SEMICOLON) && !match('{') && !match(END))
next_token();
recovery = 0;
if (match(SEMICOLON) || match('{') || match(END))
return;
print_token("Assign Operator [ %s ] at line %d\n", token);
}
}
else
print_token("Assign Operator [ %s ] at line %d\n", token);
next_token();
if (!expression()) {
if (match(END) || match('{'))
return;
error_handle("int number, real number, id", token);
next_token();
}
}
}
else if (match(RETURN)) {
fprintf(yyout, "Return Statement...\n");
next_token();
if (match(SEMICOLON)) fprintf(yyout, "Empty Statement\n");
else {
if (!expression())
error_handle("ID, int number, real number", token);
expression();
}
}
else if (match('{')) {
block();
}
}
void function_call() {
fprintf(yyout, "Function Call...\n");
print_token("Function Name [ %s ] at line %d\n", token);
next_token();
next_token();
parameters_list();
if (!match(')')) {
error_handle(", or )", token);
next_token();
while (!match(')') && !match(SEMICOLON))
next_token();
back_token();
}
next_token();
}
void parameters_list() {
fprintf(yyout, "Parameters List...\n");
if (match(')')) {
fprintf(yyout, "Empty Parameter\n");
}
else
variables_list();
}
int expression() {
fprintf(yyout, "Expression...\n");
if (recovery) {
while (!match(INT_NUMBER) && !match(REAL_NUMBER) && !match(ID) && !match('{')) next_token();
recovery = 0;
if (match('{'))
return 0;
}
if (match(INT_NUMBER)) {
print_token("int number [ %s ] at line %d\n", token);
next_token();
}
else if (match(REAL_NUMBER)) {
print_token("real number [ %s ] at line %d\n", token);
next_token();
}
else if (match(ID)) {
next_token();
if (ar_op()) {
back_token();
print_token("ID [ %s ] at line %d\n", token);
next_token();
print_token("Arithmetic Operator [ %s ] at line %d\n", token);
next_token();
if (!expression()) {
error_handle("int number, real number, id", token);
next_token();
}
}
else {
back_token();
variable();
}
}
else
return 0;
return 1;
}
void block() {
fprintf(yyout, "Block Statement...\n");
if (!match('{')) {
if (match(END))
return;
error_handle("{", token);
}
next_token();
var_definitions();
back_token();
if (!match(SEMICOLON) && !match('{')) {
if (match(END))
return;
error_handle(";", token);
}
next_token();
statements();
if (!match('}')) {
if (match(END))
return;
error_handle("}", token);
}
next_token();
}
void func_definitions() {
fprintf(yyout, "Function Definitions List...\n");
while (token)
func_definition();
}
void func_definition() {
if (!returned_type()) {
error_handle("integer, real, void", token);
while (!returned_type() && !match(ID))
next_token();
}
recovery = 0;
fprintf(yyout, "Function Definition...\n");
if (returned_type())
print_token("Return Type [ %s ] at line %d\n", token);
else
error_handle("integer, real, void", token);
next_token();
if (!match(ID))
error_handle("id", token);
else
print_token("Function Name [ %s ] at line %d\n", token);
next_token();
if (!match('('))
error_handle("(", token);
next_token();
param_definitions();
if (!match(')'))
error_handle(")", token);
next_token();
block();
if (recovery) {
while (!match('}')) next_token();
next_token();
recovery = 0;
}
}
void param_definitions() {
fprintf(yyout, "Parameter definitions List...\n");
if (match(')'))
fprintf(yyout, "Empty Parameter\n");
else
var_definitions();
</code></pre>
<p><strong>semantic.h</strong> </p>
<pre><code>#pragma once
#include "LEXYY.h"
typedef struct SCOPES {
struct SCOPES *parent;
struct SCOPES *first_child; /*for right */
struct SCOPES *next_sibling; /*for left*/
struct SYMBOLS *symbols;
} SCOPE;
typedef struct SYMBOLS {
char *name;
int type;
int size;
int initialized;
int used;
int line;
struct SYMBOLS *next;
struct SYMBOLS *prev;
} SYMBOL;
typedef struct FUNCTIONS {
char *name;
int returnd_type;
int param_number;
int line;
struct SYMBOLS *params;
struct SCOPES *scope;
struct FUNCTIONS *prev_func;
struct FUNCTIONS *next_func;
} FUNCTION;
SCOPE *root;
FUNCTION *func;
int semantic_errors, semantic_warnings;
FILE *yyout;
int return_statement;
FUNCTION *find_func(char *);
SYMBOL *find_symbol(SCOPE *, char *, SYMBOL *);
void semantic_error_handle(char *, char *, int);
int semantic();
FUNCTION *get_function_list();
FUNCTION *get_function();
SYMBOL *semantic_var_definitions(SCOPE *, SYMBOL *, int);
SYMBOL *semantic_var_definition(SCOPE *);
SYMBOL *semantic_vars_list(SCOPE *, int);
SYMBOL *semantic_var(SCOPE *, int);
SCOPE *semantic_statements(SCOPE *, int, SYMBOL *);
void semantic_statement(SCOPE *, int, SYMBOL *);
void semantic_function_call(SCOPE *, SYMBOL *);
int semantic_expression(SCOPE *, SYMBOL *);
SCOPE *semantic_block(SCOPE *, int, SYMBOL *);
void semantic_func_definitions();
void semantic_func_definition(FUNCTION *f);
void check_unused_in_scope(SCOPE *);
void check_unused_in_function(FUNCTION *);
</code></pre>
<p><strong>semantic.c</strong></p>
<pre><code>#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "semantic.h"
/*find function definition*/
FUNCTION *find_func(char *name) {
FUNCTION *f = func;
while (f && strcmp(f->name, name))
f = f->prev_func;
return f;
}
/*finding variable definition*/
SYMBOL *find_symbol(SCOPE *scope, char *name, SYMBOL *params) {
SYMBOL *symbols;
/*if function definition, searching in function parameters*/
if (params) {
symbols = params;
while (symbols) {
if (!strcmp(symbols->name, name))
return symbols;
symbols = symbols->next;
}
}
if (!scope)
return NULL;
/*searchinf in scope variables*/
symbols = scope->symbols;
while (symbols) {
if (!strcmp(symbols->name, name))
return symbols;
symbols = symbols->next;
}
return find_symbol(scope->parent, name, NULL);
}
void semantic_error_handle(char *str, char *name, int line) {
fprintf(yyout, str, name, line);
semantic_errors++;
}
/*processing semantic analysis*/
int semantic() {
semantic_errors = semantic_warnings = 0;
token = tokens;
if (!token)
return 0;
//preload function definitions for function call
while (!match(END))
next_token();
func = get_function_list();
token = tokens;
next_token();
/*creating new scope for main program*/
root = (SCOPE *)malloc(sizeof(SCOPE));
root->parent = root->first_child = root->next_sibling = NULL;
root->symbols = NULL;
/*get variable definitions in current scope*/
root->symbols = semantic_var_definitions(root, NULL, 1);
/*analysing statements and get sub scope*/
root->first_child = semantic_statements(root, VOID, NULL);
next_token();
check_unused_in_scope(root);
semantic_func_definitions();
if (!semantic_errors)
fprintf(yyout, "Semantic analysis success!\n");
return semantic_errors;
}
/*getting function definition list before start analysis*/
FUNCTION *get_function_list() {
FUNCTION *functions = NULL;
next_token();
while (token) {
if (functions) {
functions->next_func = get_function();
functions->next_func->prev_func = functions;
functions = functions->next_func;
}
else
functions = get_function();
}
return functions;
}
/*getting function definition before start of analysis*/
FUNCTION *get_function() {
FUNCTION *f = (FUNCTION *)malloc(sizeof(FUNCTION));
SYMBOL *temp;
f->next_func = f->prev_func = NULL;
f->scope = NULL;
int block_number = 0;
f->returnd_type = returned_type();
next_token();
f->name = token->lexeme;
f->line = token->line;
next_token();
next_token();
/*getting function parameters list and number*/
f->params = semantic_var_definitions(NULL, NULL, 0);
f->param_number = 0;
temp = f->params;
while (temp) {
f->param_number++;
temp = temp->next;
}
next_token();
do {
if (match('{'))
block_number++;
if (match('}'))
block_number--;
next_token();
} while (block_number);
return f;
}
/*get variables definitions*/
SYMBOL *semantic_var_definitions(SCOPE *scope, SYMBOL *params, int check) {
SYMBOL *symbols = NULL, *temp = NULL, *temp1;
/*creating symbol table for current scope*/
while (token) {
if (!type())
break;
if (symbols) {
while (temp->next) temp = temp->next;
temp->next = semantic_var_definition(scope);
temp->next->prev = temp;
}
else {
temp = symbols = semantic_var_definition(scope);
while (temp->next) temp = temp->next;
}
if (match(')'))
break;
next_token();
}
/*after getting variables, checking for duplicated definitions. if function definition, checking function parameters*/
if (params) {
temp = symbols;
while (temp) {
/*if varialble name is function name, then error*/
if (find_func(temp->name)) {
semantic_error_handle("Error: Cannot use function name [ %s ] with varaible at line [ %d ]\n", temp->name, temp->line);
if (scope) {
if (temp->prev) {
temp->prev->next = temp->next;
if (temp->next)
temp->next->prev = temp->prev;
temp1 = temp;
temp = temp->next;
free(temp1);
}
else {
symbols = temp->next;
if (symbols)
symbols->prev = NULL;
free(temp);
temp = symbols;
}
}
continue;
}
temp1 = params;
/*check in parameter definitions*/
while (temp1) {
if (!strcmp(temp->name, temp1->name))
break;
temp1 = temp1->next;
}
/*if duplicated definition*/
if (temp1) {
semantic_error_handle("Error: Duplicated variable [ %s ] declaration with parameters at line %d\n", temp->name, temp->line);
if (scope) {
if (temp->prev) {
temp->prev->next = temp->next;
if (temp->next)
temp->next->prev = temp->prev;
temp1 = temp;
temp = temp->next;
free(temp1);
}
else {
symbols = temp->next;
if (symbols)
symbols->prev = NULL;
free(temp);
temp = symbols;
}
}
else
temp = temp->next;
}
else
temp = temp->next;
}
}
/*checking scope variables*/
if (check) {
temp = symbols;
while (temp) {
/*if varialble name is function name - error*/
if (find_func(temp->name)) {
semantic_error_handle("Error: Cannot use function name [ %s ] with varaible at line [ %d ]\n", temp->name, temp->line);
if (scope) {
if (temp->prev) {
temp->prev->next = temp->next;
if (temp->next)
temp->next->prev = temp->prev;
temp1 = temp;
temp = temp->next;
free(temp1);
}
else {
symbols = temp->next;
if (symbols)
symbols->prev = NULL;
free(temp);
temp = symbols;
}
}
continue;
}
if (!temp->size)
semantic_error_handle("Error: Array size cannot be zero at line %s%d\n", "", temp->line);
temp1 = temp->prev;
while (temp1) {
if (!strcmp(temp->name, temp1->name))
break;
temp1 = temp1->prev;
}
if (temp1) {
semantic_error_handle("Error: Duplicated variable [ %s ] declaration within same scope at line %d\n", temp->name, temp->line);
if (scope) {
if (temp->prev) {
temp->prev->next = temp->next;
if (temp->next)
temp->next->prev = temp->prev;
temp1 = temp;
temp = temp->next;
free(temp1);
}
else {
symbols = temp->next;
if (symbols)
symbols->prev = NULL;
free(temp);
temp = symbols;
}
}
else
temp = temp->next;
}
else
temp = temp->next;
}
}
return symbols;
}
/*getting variable definition*/
SYMBOL *semantic_var_definition(SCOPE *scope) {
int var_type = type();
next_token();
return semantic_vars_list(scope, var_type);
}
/*getting variables list, each variable separated by comma, and insert into symbol table*/
SYMBOL *semantic_vars_list(SCOPE *scope, int var_type) {
SYMBOL *symbols = NULL, *temp = NULL;
do {
if (symbols) {
temp->next = semantic_var(scope, var_type);
temp->next->prev = temp;
temp = temp->next;
}
else
temp = symbols = semantic_var(scope, var_type);
} while (match(COMMA) && next_token());
return symbols;
}
/*getting variables separated by comma and make symbol item for symbol table*/
SYMBOL *semantic_var(SCOPE *scope, int var_type) {
SYMBOL *symbol;
if (!match(ID))
return NULL;
symbol = (SYMBOL *)malloc(sizeof(SYMBOL));
symbol->type = var_type;
symbol->name = token->lexeme;
symbol->line = token->line;
symbol->initialized = 0;
symbol->used = 0;
next_token();
/*check if array varaible*/
if (match('[')) {
next_token();
symbol->size = atoi(token->lexeme);
next_token(); next_token();
}
else
symbol->size = -1;
symbol->next = symbol->prev = NULL;
return symbol;
}
/*analysis statements and get sub scopes*/
SCOPE *semantic_statements(SCOPE *parent, int return_type, SYMBOL *params) {
SCOPE *scope = NULL, *temp = NULL;
while (!not_statements()) {
/* new scope for sub scope*/
if (!scope) {
scope = (SCOPE *)malloc(sizeof(SCOPE));
scope->parent = parent;
scope->first_child = scope->next_sibling = NULL;
scope->symbols = NULL;
}
/*analysising each statementand get symbols for sub scope*/
semantic_statement(scope, return_type, params);
if (match(END))
break;
if (match('{'))
continue;
next_token();
}
return scope;
}
/*analysinf each statement*/
void semantic_statement(SCOPE *scope, int return_type, SYMBOL *params) {
SYMBOL *symbol, *cur_symbol;
FUNCTION *f_temp = NULL;
int type, line;
/*if current statement is assignment or function call */
if (match(ID)) {
next_token();
/*if function call*/
if (match('(')) {
back_token();
semantic_function_call(scope, params);
}
/*assignment*/
else {
back_token();
/*getting variable for assignment*/
symbol = semantic_var(scope, 0);
/*check if current variable is declaration*/
cur_symbol = find_symbol(scope, symbol->name, params);
/*if current variable is declaration*/
if (cur_symbol) {
cur_symbol->initialized = 1;
cur_symbol->used = 1;
symbol->type = cur_symbol->type;
/*if variable is arra*/
if (cur_symbol->size > -1) {
/*check array size for array index */
if (symbol->size > cur_symbol->size)
semantic_error_handle("Error: Exceed bound of array [ %s ] at line %d\n", symbol->name, symbol->line);
else if (symbol->size < 0)
semantic_error_handle("Error: Expressions can't refer to entire array [ %s ] at line %d\n", symbol->name, symbol->line);
}
else if (symbol->size > -1)
semantic_error_handle("Error: Not array variable [ %s ] at line %d\n", symbol->name, symbol->line);
}
/*if current variable is not declared*/
else {
f_temp = find_func(symbol->name);
/*if symbole is function*/
if (f_temp)
semantic_error_handle("Error: Cannot assign to function name [ %s ] at line %d\n", symbol->name, symbol->line);
/*undefined variable*/
else
semantic_error_handle("Error: Undefined variable [ %s ] at line %d\n", symbol->name, symbol->line);
}
next_token();
type = semantic_expression(scope, params);
/*if erro type, then error*/
if (!type)
semantic_error_handle("Error: Cannot eval expression type [ %s ] at line %d\n", "error_type", symbol->line);
/*if type mismatch, then error */
if (!f_temp && (!type || (symbol->type != type && !(symbol->type == REAL && type == INTEGER))))
semantic_error_handle("Error: Cannot assign variable [ %s ] type mismatch at line %d\n", symbol->name, symbol->line);
}
}
/*return statement*/
else if (match(RETURN)) {
next_token();
line = token->line;
if (match(SEMICOLON)) {
if (return_type != VOID)
semantic_error_handle("Error: Return type mismatch %s at line %d\n", "", line);
}
/*if return type mismatch */
else {
type = semantic_expression(scope, params);
if (return_type == VOID || (return_type != type && return_type != REAL && type != INTEGER))
semantic_error_handle("Error: Return type mismatch %s at line %d\n", "", line);
}
return_statement = 1;
}
/*block statement*/
else if (match('{'))
semantic_block(scope, return_type, params);
}
/*analysis function call*/
void semantic_function_call(SCOPE *scope, SYMBOL *params) {
/*check function definition*/
FUNCTION *f = find_func(token->lexeme), *f_temp;
SYMBOL *actual_params, *func_params = NULL, *cur_symbol;
int param_number = 0, call_line = token->line;
if (!f)
semantic_error_handle("Error: Undefined function [ %s ] at line %d\n", token->lexeme, token->line);
next_token(); next_token();
/*getting parameters list of function call*/
actual_params = semantic_vars_list(NULL, 0);
/*get parameters list of function definition*/
if (f)
func_params = f->params;
/*compare function call parameters with function definition parameters*/
while (actual_params) {
param_number++;
/*checking parameter of funciton call in scopes*/
cur_symbol = find_symbol(scope, actual_params->name, params);
/*if found*/
if (cur_symbol) {
cur_symbol->used = 1;
/*if variable is array*/
if (cur_symbol->size > -1) {
if (actual_params->size > cur_symbol->size)
semantic_error_handle("Error: Exceed bound of array [ %s ] at line %d\n", actual_params->name, actual_params->line);
else if (actual_params->size < -1)
semantic_error_handle("Error: Expressions can't refer to entire array [ %s ] at line %d\n", actual_params->name, actual_params->line);
}
/*if variable is not array but it's as sucj, then error*/
else if (actual_params->size > -1)
semantic_error_handle("Error: Not array variable [ %s ] at line %d\n", actual_params->name, actual_params->line);
/*if variable type of function call doesn't mismatch with varaible type of function definition*/
if (func_params && cur_symbol->type != func_params->type && !(cur_symbol->type == INTEGER && func_params->type == REAL))
semantic_error_handle("Error: Variable type [ %s ] does not match with function parameters at line %d\n", cur_symbol->type == INTEGER ? "integer" : "real", actual_params->line);
}
/*if not found*/
else {
f_temp = find_func(actual_params->name);
/*if symbole is function*/
if (f_temp)
semantic_error_handle("Error: Cannot use function name as variable [ %s ] at line %d\n", actual_params->name, actual_params->line);
/*undefined variable*/
else
semantic_error_handle("Error: Undefined variable [ %s ] at line %d\n", actual_params->name, actual_params->line);
}
actual_params = actual_params->next;
if (func_params)
func_params = func_params->next;
if (actual_params)
free(actual_params->prev);
}
/*check function parameters number*/
if (f && param_number > f->param_number)
semantic_error_handle("Error: Too much parameters for [ %s ] at line %d\n", f->name, call_line);
else if (f && param_number < f->param_number)
semantic_error_handle("Error: Too few parameters for [ %s ] at line %d\n", f->name, call_line);
next_token();
}
/*analysis expression and get its type*/
int semantic_expression(SCOPE *scope, SYMBOL *params) {
SYMBOL *symbol, *cur_symbol;
FUNCTION *f_temp;
int type = 0;
/*int number is integer*/
if (match(INT_NUMBER)) {
next_token();
type = INTEGER;
}
/*real number is real*/
else if (match(REAL_NUMBER)) {
next_token();
type = REAL;
}
else if (match(ID)) {
symbol = semantic_var(scope, 0);
cur_symbol = find_symbol(scope, symbol->name, params);
/*if it is declared*/
if (cur_symbol) {
cur_symbol->used = 1;
symbol->type = cur_symbol->type;
type = symbol->type;
/*if variable is array*/
if (cur_symbol->size > -1) {
/*checking array size*/
if (symbol->size > cur_symbol->size)
semantic_error_handle("Error: Exceed bound of array [ %s ] at line %d\n", symbol->name, symbol->line);
else if (symbol->size < 0)
semantic_error_handle("Error: Expressions can't refer to entire array [ %s ] at line %d\n", symbol->name, symbol->line);
}
/*if variable is not array but it's used with as such- then error*/
else if (symbol->size > -1)
semantic_error_handle("Error: Not array variable [ %s ] at line %d\n", symbol->name, symbol->line);
}
/*if declaration of variable is not found*/
else {
f_temp = find_func(symbol->name);
if (f_temp)
semantic_error_handle("Error: Cannot use function name as variable [ %s ] at line %d\n", symbol->name, symbol->line);
else
semantic_error_handle("Error: Undefined variable [ %s ] at line %d\n", symbol->name, symbol->line);
}
/*if arithmetic operation, geting next expression's type*/
if (ar_op()) {
next_token();
type = semantic_expression(scope, params);
if (type && (symbol->type == REAL || !symbol->type))
type = symbol->type;
}
}
return type;
}
/*analysing block and get sub scope */
SCOPE *semantic_block(SCOPE *parent, int return_type, SYMBOL *params) {
/*createing new scope for sub scope*/
SCOPE *scope = (SCOPE *)malloc(sizeof(SCOPE)), *temp = parent;
scope->parent = parent;
scope->first_child = scope->next_sibling = NULL;
next_token();
/*getting variables list in sub scope*/
scope->symbols = semantic_var_definitions(scope, params, 1);
/*analysing statements in sub scope*/
scope->first_child = semantic_statements(scope, return_type, params);
next_token();
/*linking with parent scope*/
if (temp) {
if (temp->first_child) {
while (temp->next_sibling->next_sibling) temp = temp->next_sibling;
temp->next_sibling = scope;
}
else
temp->first_child = scope;
}
return scope;
}
/*analysing function definitions*/
void semantic_func_definitions() {
FUNCTION *f;
func = NULL;
/*get function definitions list*/
while (token) {
f = (FUNCTION *)malloc(sizeof(FUNCTION));
f->next_func = f->prev_func = NULL;
if (func) {
func->next_func = f;
func->next_func->prev_func = func;
func = func->next_func;
}
else
func = f;
semantic_func_definition(f);
}
}
/*analysing function definition and getting scopes for each function*/
void semantic_func_definition(FUNCTION *f) {
FUNCTION *f_temp = func->prev_func;
SYMBOL *temp;
/*type of function*/
f->returnd_type = returned_type();
next_token();
f->name = token->lexeme;
f->line = token->line;
/*checking if definition deplicated*/
while (f_temp) {
if (!strcmp(f->name, f_temp->name))
break;
f_temp = f_temp->prev_func;
}
if (f_temp)
semantic_error_handle("Error: Function [ %s ] overloading at line %d\n", f->name, f->line);
next_token();
next_token();
if (token->line == 100)
token->line = token->line;
f->params = semantic_var_definitions(NULL, NULL, 1);
f->param_number = 0;
temp = f->params;
while (temp) {
f->param_number++;
temp = temp->next;
}
next_token();
return_statement = 0;
/*sub scope of this function*/
f->scope = semantic_block(NULL, f->returnd_type, f->params);
if (!return_statement && f->returnd_type != VOID)
semantic_error_handle("Error: No return statement in function [ %s ]\n", f->name, 0);
/*checking if any variable is not used in function*/
check_unused_in_function(f);
}
/*check if any variables are not declared in scope*/
void check_unused_in_scope(SCOPE *root) {
if (!root)
return;
while (root->symbols) {
if (!root->symbols->used) {
semantic_error_handle("Error: Unused variable [ %s ] at line %d\n", root->symbols->name, root->symbols->line);
}
root->symbols = root->symbols->next;
}
if (root->first_child)
check_unused_in_scope(root->first_child);
if (root->next_sibling)
check_unused_in_scope(root->next_sibling);
}
/*checking if any variables are not declared in function*/
void check_unused_in_function(FUNCTION *func) {
if (func->params) {
SYMBOL *symbol = func->params, *temp;
while (symbol) {
temp = symbol->prev;
while (temp) {
if (!strcmp(temp->name, symbol->name))
break;
temp = temp->prev;
}
if (!temp && !symbol->used)
semantic_error_handle("Error: Unused variable [ %s ] at line %d\n", symbol->name, symbol->line);
symbol = symbol->next;
}
}
if (func->scope)
check_unused_in_scope(func->scope);
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-19T13:15:50.727",
"Id": "475998",
"Score": "2",
"body": "Welcome to Code Review! Was any of the code generated by tools such as `Lex` or `Flex` for the lexical analyzer or `YACC` or `Bison` for the parser? If so please indicte which parts."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-19T13:25:29.130",
"Id": "475999",
"Score": "1",
"body": "@pacmaninbw flex"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-19T19:58:01.663",
"Id": "476040",
"Score": "0",
"body": "Does this program build properly for you? Are you using Visual Studio?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-19T20:30:42.510",
"Id": "476045",
"Score": "0",
"body": "@pacmaninbw yes"
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-19T12:21:12.250",
"Id": "242559",
"Score": "2",
"Tags": [
"c",
"compiler",
"lex"
],
"Title": "implementing lexical, syntatic and semantic analysis"
}
|
242559
|
<p>Here is some code that sends an email using Mimekit for .net C# to send email via Office365. DI is done using TinyIOC. It downloads an image from blob storage and then sends it with an attachment. Each email will ALWAYS have at least one attachment. Code feels a bit messy, especially the body/subject selector. </p>
<pre><code>/// <summary> Handles emails using Office365 </summary>
public class EmailService : IEmailService
{
/// <summary> Default body of email </summary>
private static string _body = "Please check system, something went wrong";
/// <summary> Default subject of email </summary>
private static string _subject = "Error";
private readonly IBlobStorageService _blobStorageService;
private readonly EmailSettings _emailSettings;
public EmailService(IBlobStorageService blobStorageService, EmailSettings emailSettings)
{
_emailSettings = emailSettings ?? throw new ArgumentNullException("Email configuration cannot be null.");
_blobStorageService = blobStorageService;
}
/// <summary> Sends an email using Office365 with the credentials specified in configuration. </summary>
/// <param name="motionActivity"></param>
/// <param name="mediaResults"></param>
/// <returns></returns>
/// <exception cref="ArgumentException"></exception>
public async Task<bool> SendEmail(MotionActivity motionActivity, List<MediaAnalysis> mediaResults)
{
if (motionActivity == null)
throw new ArgumentException("Motion activity cannot be null");
if (mediaResults == null)
throw new ArgumentException("Media result should not be null");
// Filter out all results below 60% probability
var mediaResultsAbove60Percent = mediaResults.FindAll(x => x.Probability >= 60);
// If no pictures remain afterwards, return
if (mediaResultsAbove60Percent.Count == 0) return false;
var highestProbability = mediaResultsAbove60Percent.Max(x => x.Probability);
var message = await CreateEmailMessage(motionActivity, highestProbability, mediaResultsAbove60Percent);
var fullMessage = AddRecipients(message, highestProbability);
return await SendMessageAsync(fullMessage).ConfigureAwait(false);
}
/// <summary> Sends the message using MimeMessage/office365 </summary>
/// <param name="message"> The message we are sending </param>
/// <returns>Whether or not the message send was successful.</returns>
private async Task<bool> SendMessageAsync(MimeMessage message)
{
try
{
using (var client = new SmtpClient())
{
await client.ConnectAsync(_emailSettings.Host, _emailSettings.Port, false);
await client.AuthenticateAsync(_emailSettings.FromAddress, _emailSettings.Password);
await client.SendAsync(message);
await client.DisconnectAsync(true);
}
}
catch (Exception ex)
{
Log.Error(
"An error occurred trying to send an Office 365 email: {message}, {innerException}, {stacktrace}",
ex.Message, ex.InnerException, ex.StackTrace);
return false;
}
return true;
}
/// <summary> Creates the templates used for emails </summary>
/// <param name="motionActivity"> is the data of the entire time we collected motion for ONE camera </param>
/// <param name="highestProbability"> the highest probability we found that we think there is a canister </param>
private async Task<MimeMessage> CreateEmailMessage(MotionActivity motionActivity, double highestProbability,
List<MediaAnalysis> mediaResultsAbove60Percent)
{
//Changes subject headline based on probability
if (highestProbability >= 60 && highestProbability <= 74)
{
var auditText =
"Dear Auditor please review, " +
$"\r\n Images captured: {motionActivity}";
_subject = $"Detect: Audit Image - {highestProbability}%";
_body = auditText;
}
if (highestProbability >= 75 && highestProbability <= 87)
{
var lowProbabilityText =
"Dear Concierge, " +
"\r\n It is possible that an explosive canister has entered the building at the address above. Please review the attached photographs and take precautionary action." +
$"\r\n Images captured: {motionActivity}";
_subject = $"Detect: Warning Image - {highestProbability}%";
_body = lowProbabilityText;
}
if (highestProbability >= 88 && highestProbability <= 100)
{
var highProbabilityText =
"Dear Concierge, " +
"\r\n It is likely that an explosive canister has entered the building at the address above. Please review the attached photographs and take immediate action." +
$"\r\n Images captured: {motionActivity}";
_subject = $"Detect: High Risk Image - {highestProbability}%";
_body = highProbabilityText;
}
// Construct the email body.
var builder = new BodyBuilder {HtmlBody = _body};
var message = new MimeMessage();
message.From.Add(new MailboxAddress(_emailSettings.DisplayName, _emailSettings.FromAddress));
message.Subject = _subject;
var emailWithAttachments = await AddImageAttachment(mediaResultsAbove60Percent, message, builder);
emailWithAttachments.Body = builder.ToMessageBody();
return emailWithAttachments;
}
/// <summary> Adds all recipients to our email </summary>
/// <param name="email"> the email we are sending </param>
/// <param name="highestProbability"></param>
private MimeMessage AddRecipients(MimeMessage email, double highestProbability)
{
if (highestProbability >= 75)
foreach (var recipient in _emailSettings.FullRecipients)
email.To.Add(new MailboxAddress(recipient));
else
foreach (var recipient in _emailSettings.Recipients)
email.To.Add(new MailboxAddress(recipient));
return email;
}
/// <summary> Takes all images above 60% probability and adds the image to the email</summary>
/// <param name="mediaResultsAbove60Percent"> images above 60% </param>
/// <param name="email"> the email we will be sending </param>
/// <param name="bodyBuilder"> the body builder for emails </param>
/// <returns></returns>
private async Task<MimeMessage> AddImageAttachment(IEnumerable<MediaAnalysis> mediaResultsAbove60Percent,
MimeMessage email, BodyBuilder bodyBuilder)
{
foreach (var mediaResult in mediaResultsAbove60Percent)
{
if (mediaResult.MediaUrl == null) continue;
var download = await _blobStorageService.DownloadFile(mediaResult.MediaUrl).ConfigureAwait(false);
var byteArray = ReadFully(download.Content);
bodyBuilder.Attachments.Add(mediaResult.MediaUrl, byteArray);
}
return email;
}
/// <summary> Helper method for add image attachment. Converts stream to byte array. </summary>
/// <param name="input"> the image we are converting </param>
/// <returns> the byte array </returns>
private static byte[] ReadFully(Stream input)
{
using (var ms = new MemoryStream())
{
input.CopyTo(ms);
return ms.ToArray();
}
}
}
</code></pre>
|
[] |
[
{
"body": "<p>Some quick remarks:</p>\n\n<ul>\n<li><p><code>if (mediaResultsAbove60Percent.Count == 0) return false;</code> can be replaced by the much more readable <code>return !mediaResultsAbove60Percent.Any();</code>.</p></li>\n<li><p>I'd extract parts of <code>CreateEmailMessage</code> to a separate method, or even class of its own, for instance a <code>BodyRetriever</code> class. Right now it does way too much.</p></li>\n<li><p>You use <code>bodyBuilder.HtmlBody</code> yet the body you compile is plain text. Instead of using string concatenation, why not design nicer email texts as HTML files, embed those HTML files and <a href=\"https://stackoverflow.com/questions/15822625/read-content-of-html-file-at-runtime-in-c-not-using-physical-path\">read those at runtime</a>? (You can have placeholders in the HTML file and replace those if necessary.)</p></li>\n<li><p>I don't see the point in creating <code>auditText</code>, <code>lowProbabilityText</code> and <code>highProbabilityText</code>, considering you immediately assign these to <code>_body</code>.</p></li>\n<li><p>Don't use <code>\"\\r\\n\"</code>, use <code>Environment.NewLine</code>.</p></li>\n<li><p>Comments should explain the why, not the what. If <code>// Construct the email body.</code> only applies to the next line -- <code>var builder = new BodyBuilder {HtmlBody = _body};</code> -- it is pointless, if it applies to the whole block of lines below it, it is incorrect.</p></li>\n<li><p><code>ReadFully()</code> isn't proper English and pretty meaningless. Why not <code>ToByteArray()</code>?</p></li>\n<li><p><code>AddRecipients</code> has duplicate code. Instead, do this: <code>var recipients = highestProbability >= 75 ? _emailSettings.FullRecipients : _emailSettings.Recipients;</code> and then loop through <code>recipients</code>.</p></li>\n<li><p>No need to <code>return email;</code> at the end of <code>AddRecipients</code>: this method has already updated <code>MimeMessage email</code> passed as an parameter. Just call <code>AddRecipients(message, highestProbability);</code>, no need to assign the result to <code>var fullMessage</code>.</p></li>\n</ul>\n\n<hr>\n\n<p>IMHO you should consider splitting up this class into smaller ones, e.g. one to construct the <code>MimeMessage</code>, which itself should call a class to construct the email body etc. I'd rather have a couple of small classes where each does one particular task, than a 200 line \"Service\" class that contains a lot of private methods etc. </p>\n\n<p><code>SendEmail</code> should basically call something like <code>ComposeEmail</code> and then <code>SendEmail</code> (please don't add \"Async\" to the end of methods where there is no need). Quite honestly I'd even extract <code>SendMessageAsync</code> to a class of its own (something like <code>EmailSender</code>). Keep the Service class clean, and simply have it delegate its work to other classes.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-20T09:44:23.413",
"Id": "476113",
"Score": "0",
"body": "These are some very good tips! Cheers a lot man. Agree with all changes, will implement em today. :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-20T10:32:38.067",
"Id": "476117",
"Score": "0",
"body": "Should I also consider putting the SMTP client in dependency injected interface so it can be mocked? \n\nColleague is telling me to do this for unit testing purposes but then I won't be able to do a \"using\" with the SMTP client"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-20T12:40:20.837",
"Id": "476138",
"Score": "0",
"body": "Also attempting to implement this.\nHow did you intend the \"return !mediaResultsAbove60Percent.Any()\" to be used?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-20T12:45:42.850",
"Id": "476141",
"Score": "1",
"body": "If you want to unit test the client, then I'd say to extract SendMessageAsync to a class of its own with a single method, and inject that class."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-19T16:56:01.373",
"Id": "242578",
"ParentId": "242562",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "242578",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-19T13:14:47.027",
"Id": "242562",
"Score": "1",
"Tags": [
"c#",
".net",
"email"
],
"Title": "Email Service - Sending an email with azure blob storage"
}
|
242562
|
<p>Task:<br>
Complete the following function that determines if the number of even and odd values in an list of Integers is the same. </p>
<pre><code>| In | Out | Why |
|------------------|-------|------------------------|
| [5, 1, 0, 2] | true | two evens and two odds |
| [5, 1, 0, 2, 11] | false | too many odds |
| [] | true | both have 0 |
</code></pre>
<p>The function should not affect the contents of the list.</p>
<p>My code:</p>
<pre><code>def balanced(lst):
n = len(lst)
if n % 2 != 0:
return False
if n % 2 == 0:
count_1 = 0
count_2 = 0
for item in lst:
if item % 2 == 0: #even
count_1 += 1
if item % 2 != 0: #odd
count_2 += 1
if count_1 == count_2:
return True
else:
return False
def result(lst):
if balanced(lst):
print("Your list is successfully balanced! It has same number of evens and odds!!")
else:
print("Oh no! Sorry! Your list seems to be not balanced! Try another list please!")
def main():
lst_1 = [1,2,3,5,6,8,5,9]
lst_2 = []
lst_3 = [2,4,5,7]
lst_4 = [1,2,4,4]
lst_5 = [1,2,3]
result(lst_1)
result(lst_2)
result(lst_3)
result(lst_4)
result(lst_5)
main()
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-20T06:46:08.270",
"Id": "476089",
"Score": "0",
"body": "I don't think this deserves its own answer, but I didn't see any others mention it: your code would be a lot more readable if you inserted a new line after logically grouped parts of your code, such as the end of functions."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-21T14:24:31.203",
"Id": "476283",
"Score": "3",
"body": "A lot of people are trying to \"improve\" your code be trading readability for small gains in performance. I want to tell you - please don't think that that is what your Python code should look like. Your code should be first of all readable. IF and only IF that part of your codebase turns out to be a bottleneck, ONLY THEN optimize it! Premature optimization is the root of all evil."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-23T00:42:57.243",
"Id": "476502",
"Score": "0",
"body": "This question inspired [Check if an array (or equivalent) has the same number of odd and even numbers - Code Golf Edition!](https://codegolf.stackexchange.com/q/205103) - various languages, smallest code challenge"
}
] |
[
{
"body": "<ul>\n<li><p>You don't need <code>count_1</code> and <code>count_2</code> just one count.</p>\n\n<p><span class=\"math-container\">$$\n\\begin{align}\n \\text{even}\\ + \\text{odd} &= \\text{length}\\\\\n \\text{even}\\ = \\text{odd} &= \\text{count}\\\\\n \\therefore 2\\text{count} &= \\text{length}\n\\end{align}\n$$</span></p></li>\n<li><p>You can just <code>return <exp></code> rather than </p>\n\n<pre class=\"lang-py prettyprint-override\"><code>if <exp>:\n return True\nelse:\n return False\n</code></pre></li>\n<li><p>You don't need the first <code>if n % 2 == 0:</code> check.</p></li>\n</ul>\n\n<pre class=\"lang-py prettyprint-override\"><code>def balanced(lst):\n n = len(lst)\n if n % 2 != 0:\n return False\n count = 0\n for item in lst:\n if item % 2 == 1:\n count += 1\n return 2 * count == n\n</code></pre>\n\n<ul>\n<li><p>You can use <a href=\"https://docs.python.org/3/library/functions.html#sum\" rel=\"noreferrer\"><code>sum</code></a> and a comprehension to create <code>count</code>.\nIf we build a list of counts then we can see how <code>sum</code> works with lists:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>counts = []\nfor item in lst:\n if item % 2 == 1:\n counts.append(1)\ncount = sum(counts)\n</code></pre>\n\n<p>This should make sense as it's just totalling all the values. From here we can use some sugar to build a <a href=\"https://docs.python.org/3/tutorial/datastructures.html#list-comprehensions\" rel=\"noreferrer\">list comprehension</a>.\nThis would look like:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>counts = [\n 1\n for item in lst\n if item % 2 == 1\n]\ncount = sum(counts)\n</code></pre>\n\n<p>You should see that it builds the list with a lot less noise. Making code quicker to read and more minimalistic.</p>\n\n<p>From here we can merge them all into one line, and convert the list comprehension to an implicit <a href=\"https://www.python.org/dev/peps/pep-0289/\" rel=\"noreferrer\">generator expression</a>.</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>count = sum(1 for item in lst if item % 2 == 1)\n</code></pre></li>\n<li><p>You can remove the <code>if</code> as <code>item % 2</code> is either 1 or 0, and so summing will provide the count of odd numbers.</p></li>\n<li>I would prefer seeing <code>items</code> or <code>values</code> rather then <code>lst</code></li>\n</ul>\n\n<pre class=\"lang-py prettyprint-override\"><code>def balanced(items):\n if len(items) % 2 != 0:\n return False\n count = sum(i % 2 for i in items)\n return 2 * count == len(items)\n</code></pre>\n\n<p>If we remove your well thought out optimization, then we can put this on one line:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>def balanced(items):\n return len(items) == 2 * sum(i % 2 for i in items)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-19T14:24:25.663",
"Id": "476001",
"Score": "0",
"body": "What is the content in this new sum function \"sum(.....)\" called? Does this function come under advanced courses of python?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-19T14:27:51.993",
"Id": "476002",
"Score": "0",
"body": "@UncalledAstronomer I do not know what you mean by context. It's a [built-in function](https://docs.python.org/3/library/functions.html#sum). I have not followed any Python courses and so I do not know what 'level' it is. However I personally would say it's either beginner/basic or not included in your course."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-19T15:11:49.323",
"Id": "476009",
"Score": "3",
"body": "@UncalledAstronomer it's technically a generator expression. If you look them up, their content is the same as list comprehensions, but they're surrounded by parentheses. If they're used as the only argument to a function, like what's going on here in the call to ``sum``, then instead of having two sets of parentheses (one for the function call, one for the generator expression), you can discard the redundant parenthesis and get what you see above."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-19T22:59:05.577",
"Id": "476058",
"Score": "1",
"body": "@EricDuminil B-but, [mine is one pass](https://wiki.python.org/moin/TimeComplexity)! ;)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-21T02:05:37.427",
"Id": "476229",
"Score": "0",
"body": "In general an either-or per-element classification should be optimized for count one thing and calculate the other from `y = length - x` after the loop. This optimization isn't limited to cases where you're looking for balanced. E.g. if you just want to return both odd and even counts you should still only count one in the loop (or list comprehension). But yes, optimizing it to `2*count_odd == len` is good."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-21T02:19:50.150",
"Id": "476230",
"Score": "0",
"body": "@PeterCordes I'm don't understand you. Do you have a problem with the changes I've made? The first part of your comment sounds like you do, but you say \"But yes, ... is good\" at the end."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-21T02:22:51.157",
"Id": "476231",
"Score": "0",
"body": "I'm only expanding on the point you made; you went straight from the `odd + even = length` to `odd * 2 = length` without pointing out the general-case idea of sinking one counter out of the loop. I thought that's a useful point to make that's applicable to more situations, which future readers (including the OP) could benefit from remembering, and thus maybe useful for your answer to cover somewhere in that early stuff about only counting one thing. So I'm suggesting changes to your text, not your code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-21T08:42:59.420",
"Id": "476258",
"Score": "0",
"body": "Sorry but what you did was minifying the code, not bettering it. This code is not a comprehensible description of its purpose, it's just a logic riddle."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-21T10:22:22.797",
"Id": "476261",
"Score": "0",
"body": "@PeterCordes Thank you for the explanation, I now understand you. However I don't really understand why rearranging the first equation to \\$\\text{even} = \\text{length} - \\text{odd}\\$ and adding it to the three at the beginning is helpful. My answers are long already, if I were to address ever alternate everyone involved in my answers would go insane."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-21T10:27:36.673",
"Id": "476262",
"Score": "0",
"body": "@kangalioo Many things in programming follow the idea that less is more. The less code, the less time it takes to read, the more we can solve other problems. However it would be interesting to see how you would better the code. Care to enlighten me?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-21T11:43:25.853",
"Id": "476267",
"Score": "0",
"body": "@Peilonrayz I wanna excuse for me extremely negative comment of your solution. I've realized every answer is helpful than no answer, because all answers give a new perspective onto the problem. _Anyway_, [this is how I would do it](https://codereview.stackexchange.com/a/242688/220605)"
}
],
"meta_data": {
"CommentCount": "11",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-19T14:16:13.090",
"Id": "242565",
"ParentId": "242563",
"Score": "10"
}
},
{
"body": "<p>This is a good candidate for <strong>list comprehensions</strong>.</p>\n\n<p>Here is some proposed code (not the most compact but should be fairly easy to understand):</p>\n\n<pre><code>from typing import List\n\ndef is_even(number: int) -> bool:\n return (number % 2) == 0\n\n\ndef balanced(lst: List)-> bool:\n\n # list empty: return True by choice\n if len(lst) == 0:\n return True\n\n return len([item for item in lst if is_even(item)]) == len([item for item in lst if not is_even(item)])\n\n# testing\nlst1 = [1, 2, 3, 4, 5, 6]\nprint(f'List: {lst1} - balanced: {balanced(lst1)}')\n</code></pre>\n\n<hr>\n\n<p>For convenience I have defined an additional function <code>is_even</code>.</p>\n\n<p>Logic: count the even numbers, do the same with odd numbers and if both sets have the same length, return True.\nI am not verifying that all items in the list are <code>int</code>...</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-22T12:57:21.210",
"Id": "476428",
"Score": "1",
"body": "As a note, this makes two full lists, whereas the filtering conditions for the lists are mutually exclusive. That means we could omit one of the two (if a number is not even, it is automatically uneven) and still reach the same result. That saves [a lot of work](https://codereview.stackexchange.com/a/242697/223083)."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-19T14:21:34.223",
"Id": "242566",
"ParentId": "242563",
"Score": "3"
}
},
{
"body": "<p>There are a few optimizations that seem obvious to me, but the algorithm seems fine for what is does.</p>\n\n<pre><code>if n % 2 != 0:\n return False\nif n % 2 == 0:\n # ...\n</code></pre>\n\n<p>There is no need for the second <code>if</code> statement, as you already know that <code>n % 2 == 0</code> is <code>True</code>, as you would have returned otherwise. </p>\n\n<pre><code>if item % 2 == 0: #even\n count_1 += 1\nif item % 2 != 0: #odd\n count_2 += 1\n</code></pre>\n\n<p>You should use an <code>if ... else</code> construct, if the number isn't even, then it is odd. This makes one less check for each item.</p>\n\n<pre><code>if count_1 == count_2:\n return True\nelse:\n return False\n</code></pre>\n\n<p>You can simply <code>return count_1 == count_2</code>. This simplifies the code and saves a branch, making it slightly more efficient.</p>\n\n<p>You could also use more meaningful variable names, and include a docstring documentating what the code does</p>\n\n<p>Here is my take on your code:</p>\n\n<pre><code>def balanced(lst):\n '''Checks if a list contains the same amount of even and odd numbers'''\n\n if len(lst) % 2 != 0:\n return False\n count_even = 0\n count_odd = 0\n for item in lst:\n if item % 2 == 0:\n count_even += 1\n else: \n count_odd += 1\n return count_even == count_odd\n</code></pre>\n\n<p>You could probably trim the code even more, for example using only one variable for counting, adding <code>1</code> on even numbers and subtracting <code>1</code> on odd numbers, and returning whether that value is <code>0</code>, but I feel like it would affect negatively the readability.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-20T11:41:46.857",
"Id": "476120",
"Score": "2",
"body": "I like this. Its less clever than many others, but it retains a property I liked about the original code; it takes me a single glance over it to know exactly what it does, while removing some of the obvious eye-sores."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-20T13:05:25.113",
"Id": "476144",
"Score": "3",
"body": "@epa095 I feel like its a common issues with python. A lot of things can be turned into nifty one-liners, but it defeats one of the purposes of the language: it's designed to be readable."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-21T20:15:21.160",
"Id": "476334",
"Score": "2",
"body": "@epa095 - In my opinion, 'Cleverness' in code is a drawback, not a benefit. Simplicity and Readability are the things that really matter 99% of the time."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-19T14:23:22.730",
"Id": "242567",
"ParentId": "242563",
"Score": "12"
}
},
{
"body": "<p>Do not use recursion for simple use cases like this one (OP has asked about this in the original, unedited question)!\nIt can be done simply, as shown below.\nFirst, a walkthrough:</p>\n\n<p>A construct like</p>\n\n<pre class=\"lang-py prettyprint-override\"><code> if n % 2 != 0:\n return False\n if n % 2 == 0:\n</code></pre>\n\n<p>can be simplified by omitting the second <code>if</code> statement, since you return early anyway.\nThis saves a whole level of indentation:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code> if n % 2 != 0:\n return False\n count_1 = 0\n ...\n</code></pre>\n\n<p>If you did not return and thus exit but instead did something else, use an <code>else</code> clause to avoid repeating yourself, which might introduce subtle errors and bugs.\nInstead do:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code> if n % 2 != 0:\n <something other than return>\n else:\n count_1 = 0\n</code></pre>\n\n<hr>\n\n<p>Further, this</p>\n\n<pre class=\"lang-py prettyprint-override\"><code> if count_1 == count_2:\n return True\n else:\n return False\n</code></pre>\n\n<p>can just be</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>return count_1 == count_2\n</code></pre>\n\n<hr>\n\n<p>In your code, you loop over the list manually.\nThis can be replaced by (faster) list comprehension.\nIn fact, it can be a one-liner altogether, while still being readable:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>def balanced(lst):\n return len([number for number in lst if number % 2 == 0]) == len(lst) / 2\n</code></pre>\n\n<p>This works without your <code>if n % 2 != 0</code> guard clause, because an uneven list length divided by <code>2</code> (<code>len(lst) / 2</code>) will never return an integer (gives <code>float</code> with non-zero decimal part), and therefore always compare unequal to the left side.</p>\n\n<p>The left side is a list comprehesion that simply gets all even numbers in the sequence.\nIt could also grab all uneven ones.\nThis will always be an integer.</p>\n\n<p>This solution is faster and reasonably Pythonic.\nIt does not treat the special case of a list of odd length.</p>\n\n<p>Keeping it speeds up the code however.\nThe following is roughly 20% faster than the above one-liner:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>from timeit import timeit\n\ndef balanced(lst):\n n = len(lst)\n if n % 2 != 0:\n return False\n return len([number for number in lst if number % 2 == 0]) == n / 2\n\ndef main():\n test_lists = [\n [5, 1, 0, 2],\n [5, 1, 0, 2, 11],\n [],\n [1, 2, 3, 5, 6, 8, 5, 9],\n [2, 4, 5, 7],\n [1, 2, 4, 4],\n [1, 2, 3],\n [1, 2],\n [1],\n [0],\n [1, 1, 1, 1],\n [1, 1, 2, 2],\n [1, 2, 3, 4, 5],\n # [\"hello\"], # error\n ]\n for test_list in test_lists:\n # print(balanced(test_list), test_list, sep=\":\\t\")\n balanced(test_list)\n\nprint(timeit(\"main()\", globals=globals()))\n</code></pre>\n\n<p>Uncommenting <code>print(balanced(test_list), test_list, sep=\":\\t\")</code> and just running <code>main()</code> without timing, it prints:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>True: [5, 1, 0, 2]\nFalse: [5, 1, 0, 2, 11]\nTrue: []\nFalse: [1, 2, 3, 5, 6, 8, 5, 9]\nTrue: [2, 4, 5, 7]\nFalse: [1, 2, 4, 4]\nFalse: [1, 2, 3]\nTrue: [1, 2]\nFalse: [1]\nFalse: [0]\nFalse: [1, 1, 1, 1]\nTrue: [1, 1, 2, 2]\nFalse: [1, 2, 3, 4, 5]\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-19T14:56:40.620",
"Id": "476005",
"Score": "0",
"body": "@Peilonrayz Thank you, I am well aware! In the original question, OP had asked for a recursive solution."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-19T15:00:28.870",
"Id": "476006",
"Score": "0",
"body": "Indeed they did in the original title. Might I suggest you [edit] your answer to clarify that for future readers."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-21T14:10:18.353",
"Id": "476282",
"Score": "2",
"body": "I [benchmarked](https://codereview.stackexchange.com/a/242697/220605) the answers and your code is the fastest of them all! 10% faster even than [Peilonrayz' answer](https://codereview.stackexchange.com/a/242565/220605) which heavily traded readability for performance"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-22T12:52:49.517",
"Id": "476426",
"Score": "0",
"body": "@kangalioo Interesting, thanks for putting it together. I guess that is all down to our highly optimized lord and savior, list comprehensions."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-19T14:31:50.903",
"Id": "242570",
"ParentId": "242563",
"Score": "7"
}
},
{
"body": "<p>There's no need to keep counts at all. All you need to do is keep track of whether the sequence is balanced or not as you check every element. And the special tests you had for an empty list or odd list length are redundant.</p>\n\n<pre><code>def balanced(lst):\n tilt = 0\n for item in lst:\n if item % 2 == 0: #even\n tilt += 1\n else: #odd\n tilt -= 1\n return tilt == 0\n</code></pre>\n\n<p>Or if you prefer terseness over readability, you can turn it into a one-liner.</p>\n\n<pre><code>def balanced(lst):\n return sum(1 if item % 2 else -1 for item in lst) == 0\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-19T22:53:24.523",
"Id": "476053",
"Score": "2",
"body": "Indeed. I wrote `tilt += 1 - 2 * (item % 2)`, which is shorter but probably less readble."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-19T23:02:22.317",
"Id": "476059",
"Score": "1",
"body": "@EricDuminil definitely less readable. I considered `item & 1` but that would have been even worse. The whole function could be condensed to one line: `return sum(1 - 2 * (item & 1) for item in lst) == 0`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-20T02:46:55.430",
"Id": "476073",
"Score": "0",
"body": "@MarkRansom I'd just use a turnery, much clearer `1 if item % 2 else -1`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-20T03:27:07.550",
"Id": "476077",
"Score": "0",
"body": "@Peilonrayz or you can go old-school: `item % 2 or -1`. That's how you did it before they introduced ternaries into Python. There's 100 variations on this problem."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-20T11:48:12.293",
"Id": "476122",
"Score": "1",
"body": "I look at your code and I see that it is more elegant than the original code. But still, I can glance over OPs code and know what it does, booting up only the dumbest part of my brain. This submission gives me just that tiny bit of extra resistance :-/"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-20T19:38:26.663",
"Id": "476193",
"Score": "0",
"body": "@epa095 I thought being simpler would make it easier to understand, but obviously not in your case. That's OK. Code readability is a highly personal thing."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-20T19:58:45.030",
"Id": "476195",
"Score": "3",
"body": "@MarkRansom Its shorter, not simpler (although I do agree that \"simple\" is a subjective notion). If I show you a pile of apples and oranges and asks you if there are equally many of them, what do you do? I would count oranges and apples respectibly and compare. I would not keep a single variable (tilt) which I let go above and below zero until I finally check if it is zero. It takes just that tiny bit of extra mental effort to handle the `tilt` variable, which can be both negative and positive, and the fact that it is zero iff the two amounts are equal."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-20T22:03:30.260",
"Id": "476208",
"Score": "0",
"body": "I think OP's check on the length of the list was useful to produce the answer much faster (for half the cases). Why get rid of it? It's just two lines of code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-20T22:12:47.450",
"Id": "476209",
"Score": "0",
"body": "@Thanassis it prevents you from passing a generic iterator into the function rather than a list. Fewer constraints are usually a good thing."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-20T22:17:00.837",
"Id": "476210",
"Score": "0",
"body": "Sure, that's true but the OP seems to be handling lists. By making it more flexible you are losing the performance feature of OP's solution."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-20T22:29:19.383",
"Id": "476211",
"Score": "0",
"body": "@Thanassis: first make it work, then make it fast. Less code, less chance for bugs."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-21T01:58:38.640",
"Id": "476227",
"Score": "1",
"body": "Testing for odd length isn't necessary for correctness, but it could be a useful early-out optimization. I don't see a special case for empty lists, just a redundant check for `n%2 == 0` after already ruling out the `!= 0` case."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-21T03:37:30.867",
"Id": "476237",
"Score": "0",
"body": "@PeterCordes you're right about the empty list! I guess I was confused by the second `if`, since it's checking for a condition that's already guaranteed to be true. I still stand by my assertion that testing for an odd length is counter-productive, even if it leads to a faster result in some cases."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-21T03:45:13.210",
"Id": "476238",
"Score": "1",
"body": "Depends on the use-case. Sure it's often not necessary or useful to optimize at the expense of having more code, and your description of it as \"redundant\" is not wrong. If this operation over large lists (for which an early out would matter a lot) was an overall bottleneck in a real-world program, the best solution would probably not be to micro-optimize this with an early out. e.g. update a `tilt` stored with the array when you change an element so you don't need to scan the whole array, or other kinds of caching or an even larger redesign."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-21T08:39:58.397",
"Id": "476257",
"Score": "1",
"body": "It's a plain bad idea to use a tilt variable here. It's one less line of code, but way harder to figure out for a reader. If this were C - fine, for the sake of performance, I guess a tilt variable approach is ok. But this is Python, the readability language. Readability > one less line of code. You don't condense a 20 LOC into a 500 char list comprehension just because you can, do you? Neither should we do a fewest-line-of-code competition here."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-21T15:28:25.837",
"Id": "476297",
"Score": "3",
"body": "@kangalioo I'm afraid I must disagree, this form is more readable to me than the original in the question. It distills the concept of \"balance\" down to its essence. Imagine a balance scale, and you're dropping items on to one side or the other depending on if they're odd or even. You will never know the exact count on either side of the scale, nor will you care."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-21T18:39:53.150",
"Id": "476322",
"Score": "0",
"body": "this is one of the only answers that works on generators and not strict lists, because it doesn't rely on len(lst) being implemented. It could also be constructed using a map if for some reason you don't like generators: `sum(map(lambda n: 1 if n%2 else -1, lst)) == 0`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-21T21:22:18.337",
"Id": "476347",
"Score": "0",
"body": "I actually think that the on-liner using the generator expression is *more* readable because it concisely yet explicitly describes what is being computed. The first solution describes the exact same idea (albeit using a slightly different logic), just more verbosely."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-21T21:27:10.200",
"Id": "476348",
"Score": "0",
"body": "@KonradRudolph that's why I presented both forms. I thought that having a variable named `tilt` would make it clear what was being calculated, but I see that some still find it confusing."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-12T22:00:36.627",
"Id": "488563",
"Score": "0",
"body": "Your description disagrees with your code. You say \"no need to keep counts at all\", but then you count how many more or fewer evens there are. And you say \"All you need to do is keep track of whether the sequence is balanced or not\", i.e., boolean, but that's not what you keep track of."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-12T22:44:01.100",
"Id": "488567",
"Score": "0",
"body": "@superbrain what I meant and perhaps didn't do a good enough job of explaining, is that there's no need to keep a total count of the evens and a total count of the odds. The integer you see in my code isn't keeping a count, it goes both up and down."
}
],
"meta_data": {
"CommentCount": "21",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-19T22:41:21.873",
"Id": "242598",
"ParentId": "242563",
"Score": "24"
}
},
{
"body": "<p>Here's a compact way of doing it, without using any loops or if statements.</p>\n\n<pre><code>lst = [1,2,3,5,6,8,5,9,4,6]\n\ndef balanced(lst):\n return(sum(map(lambda x: x%2, lst))==0.5*len(lst))\n\nprint(balanced(lst))\n</code></pre>\n\n<p>The <code>map</code> function creates a new list consisting of 1's and 0's corresponding to each element in the input list. 1 means the corresponding element is odd, 0 means the corresponding element is even. Then, the <code>sum</code> function is used to add up all the elements in the resulting list from the <code>map</code> fucntion. This tells us the number of odd elements in the original list. The result of the sum function is then compared to half the number of elements in the original list. If the comparison is equal, this means that there are an equal number of odd and even elements in the original list.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-20T07:06:18.947",
"Id": "476094",
"Score": "0",
"body": "`map` and `lambda` (for filtering) are often better replaced by (list) comprehension, which is usually found to be more readable and often faster (when [passing `lambda` that is](https://stackoverflow.com/a/40948713/11477374)). `map` and `lambda`, among other things, were even supposed to be [removed for Python 3](https://www.artima.com/weblogs/viewpost.jsp?thread=98196). So they work, but aren't \"pythonic\", which is not entirely objective, of course."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-20T09:38:43.920",
"Id": "476112",
"Score": "2",
"body": "In this case, using `sum(map(lambda x: x%2 or -1, lst))` might be nicer (no float comparison and tells which and how many wrong elements there are). If one wants a bool, `return not bool()` of the above will work."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-20T10:15:00.840",
"Id": "476116",
"Score": "1",
"body": "Map is discouraged by Guido and deprecated by Google. Additionally the Pythonic solution to this is comprehensions as explained by Alex Povel. This is bad advice, it still has a loop too..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-22T07:30:40.793",
"Id": "476377",
"Score": "1",
"body": "@Peilonrayz It’s worth noting that the Google style guide explicitly says the usage `map(f, seq)` is OK. Only `map(lambda …, seq)` is discouraged."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-22T12:27:07.760",
"Id": "476422",
"Score": "0",
"body": "@KonradRudolph Indeed it does say something like that. I'm not sure it applies here as even if you were to remove the `lambda` I'm not sure the author would be happy seeing `f = 2..__rmod__` :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-22T12:27:17.597",
"Id": "476423",
"Score": "0",
"body": "Also worth noting is that x % 2 == x & 1 in Python. But although it produces different bytecode, it apparently has no effect on speed: https://stackoverflow.com/questions/51597019/which-is-faster-to-find-the-even-number-ifn2-0-or-ifn1-0"
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-20T02:31:59.047",
"Id": "242605",
"ParentId": "242563",
"Score": "1"
}
},
{
"body": "<p>A response to the answerers on here so far: if you want best performance, use a C extension. If you want readability, use this:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>def balanced(lst):\n num_even = sum(item % 2 == 0 for item in lst)\n num_odd = sum(item % 2 == 1 for item in lst)\n return num_even == num_odd\n</code></pre>\n\n<p>This is <em>readable</em> AND compact AND probably decently fast. The only thing that might be hard-to-understand, especially for new Python programmers, is the <code>sum(<generator>)</code> construct. You can also expand that construct for better accessibility for new programmers:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>def balanced(lst):\n num_even = 0\n num_odd = 0\n for number in lst:\n if number % 2 == 0: # even\n num_even += 1\n else: # odd\n num_odd += 1\n return num_even == num_odd\n</code></pre>\n\n<p>These code snippets are very concise and clear, in contrast to the currently most-upvoted answers:</p>\n\n<p>The top answer right now uses a special <code>tilt</code> variable. That seems to me like a cryptic trick just for the purpose of using one less variable. Why? We have lots of variables to spare. It's hard-to-understand AND not compact AND probably not even faster than the naive solution.</p>\n\n<p>The second top answer right now uses mathematical tricks to prove that you only need to count half of the numbers to do the checking. That person is probably a great mathematician. Please don't code like that, though. At least not without commenting your hard-to-understand intent.</p>\n\n<p>The most important metric to keep in mind while coding, especially in a language like Python, is readability. Like 99% of your codebase won't ever be a performance issue - and if performance is not an issue, the top priority is readability (after correctness, of course).</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-21T08:58:31.313",
"Id": "242688",
"ParentId": "242563",
"Score": "2"
}
},
{
"body": "<p>I made a benchmark. The test data is a Python list with 1,000,000 numbers between 1 and 30 (inclusive). I've tested every answer that has been given so far:</p>\n\n<pre><code>0.044s mean time - balanced_alex_2\n0.047s mean time - balanced_alex\n0.050s mean time - balanced_peilonrayz\n0.060s mean time - balanced_mark\n0.061s mean time - balanced_delta\n0.065s mean time - balanced_mti2935\n0.066s mean time - balanced_kangalioo_expanded\n0.154s mean time - balanced_kangalioo_compact\n0.178s mean time - balanced_anonymous\n</code></pre>\n\n<p><a href=\"https://pastebin.com/37Xsfqej\" rel=\"noreferrer\">Benchmark code</a></p>\n\n<p>The top two answers by Mark and Peilonrayz carelessly traded readability in an attempt to gain speed - only somewhat successfully as you can see. Alex' answers dominate the benchmark instead.</p>\n\n<p>My answers went all in on readability, while disregarding performance. You can see that even my answer is in the same ballpark as the optimized version from Alex.</p>\n\n<p>Even Alex' code is not as fast as you can go, though. Changing the code to use a NumPy array yields a mean runtime of 0.011s for Numpy - 4x faster than the fastest Python answer.</p>\n\n<p>Conclusion; if you need</p>\n\n<ul>\n<li>best performance and ok readability => Numpy</li>\n<li>ok performance and bad readability => <a href=\"https://codereview.stackexchange.com/a/242570/220605\">Alex</a></li>\n<li>acceptable performance and best readability => <a href=\"https://codereview.stackexchange.com/a/242688/220605\">kangalioo</a></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-22T07:32:50.567",
"Id": "476378",
"Score": "2",
"body": "“The top two answers by Mark and Peilonrayz carelessly traded readability in an attempt to gain speed” — That’s explicitly *not* what Mark’s doing."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-21T14:07:28.283",
"Id": "242697",
"ParentId": "242563",
"Score": "6"
}
},
{
"body": "<p>There are general refactoring lessons to be learned here. First, if you exit in an <code>if</code> statement, you don't need what follows to be the opposite of that <code>if</code>, because you can only reach that lower code if the original condition is falsy [sic]. The advantage is later code is less deeply nested. Similarly, the ending simplifies. Never return <code>True</code> if something and <code>False</code> otherwise, just return that something (cast to a <code>bool</code> if necessary). This insight simplifies your original logic for <code>balanced</code> to</p>\n<pre><code>def balanced(lst):\n if len(lst) % 2 != 0: return False\n count_1 = 0\n count_2 = 0\n for item in lst:\n if item % 2 == 0: count_1 += 1\n if item % 2 != 0: count_2 += 1\n return count_1 == count_2\n</code></pre>\n<p>(Note the guard clause meant we no longer needed to cache what you called <code>n</code>.) While the remaining pair of if statements could be an if/else instead, at this point it's worth simplifying with the mathematical insight others mentioned:</p>\n<pre><code>def balanced(lst):\n if len(lst) % 2: return False\n evens_minus_odds = 0\n for item in lst:\n evens_minus_odds += 1 if item % 2 == 0 else -1\n return evens_minus_odds == 0\n</code></pre>\n<p>Suddenly, you can't help but make it declarative instead of imperative:</p>\n<pre><code>def balanced(lst):\n return len(lst) % 2 == 0 and sum(1 if item % 2 == 0 else -1 for item in lst) == 0\n</code></pre>\n<p>Which is basically what everyone else got. Well, not everyone even bothered including the first check: it saves time for odd-length lists, but that's premature optimization because it'd be neater still to write</p>\n<pre><code>def balanced(lst):\n return sum(1 if item % 2 == 0 else -1 for item in lst) == 0\n</code></pre>\n<p>(Incidentally, <code>1 if item % 2 == 0 else -1</code> could also be replaced with <code>(-1) ** (item %2)</code>.)</p>\n<p>What have we learned?</p>\n<ul>\n<li>Long imperative code is often crying out to become short declarative code;</li>\n<li>Refactoring what little you can at first will gradually give you new ideas;</li>\n<li>Boolean logic cries out for simplification. It just so happens your code had no bugs, but the anti-if campaign exists because many aren't so lucky. I'm a big advocate of making code more declarative, in part because it makes it harder to create, or at least miss, certain bugs.</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-22T08:19:22.273",
"Id": "476382",
"Score": "0",
"body": "Hmm you may have gone slightly overboard swinging the axe now; but it’’s definitely a good, concise answer."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-21T17:41:11.727",
"Id": "242706",
"ParentId": "242563",
"Score": "3"
}
},
{
"body": "<h3>collections.Counter</h3>\n\n<p>I'm surprised <code>Counter()</code> hasn't been mentioned yet. It's raison d'être is to count things. Using <code>Counter()</code> results in a short easy to read function:</p>\n\n<pre><code>from collections import Counter\n\ndef is_balanced(seq):\n '''determines if seq has equal numbers of odd/even items'''\n\n count = Counter(item % 2 for item in seq)\n\n return count[0] == count[1]\n</code></pre>\n\n<p>It's not the fastest of the alternatives, but the performance is probably acceptable.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-22T19:06:32.620",
"Id": "242764",
"ParentId": "242563",
"Score": "2"
}
},
{
"body": "<p>There are some interesting ideas raised by this problem, guard clauses (or perhaps we should say short circuits) being one of them, we can extend</p>\n\n<pre><code>if len(lst) % 2 != 0: return False\n</code></pre>\n\n<p>with </p>\n\n<pre><code>if len(lst) == 0: return True\n</code></pre>\n\n<p>This raises the question (from the point of view of efficiency) which order should they go in? The answer depends on the expected data. If empty arrays are very common, we should test for that first, if they are never (or extremely rarely) going to occur we don't need the test.</p>\n\n<p>Since we can't do a good design without some knowledge of the domain, suppose we have to test only ISBN 13s? In that case we can just write </p>\n\n<pre><code>return False\n</code></pre>\n\n<p>Another thing we can do is add a short circuit in the loop, something like:</p>\n\n<pre><code>length = len(list) \nfor index, item in enumerate(list)\n if (length - index < abs(count) ) return False \n count += ...\n</code></pre>\n\n<p>Again in most circumstances this is not worth the candle, but if we have billion digit ternary numbers the potential time saving would be considerable! (We might even decide to sort such an array with the smaller, and hence shorter numbers first.)</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-24T21:46:19.823",
"Id": "242875",
"ParentId": "242563",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-19T13:48:16.293",
"Id": "242563",
"Score": "16",
"Tags": [
"python",
"python-3.x"
],
"Title": "Check if array has the same number of even and odd values in Python"
}
|
242563
|
<p>I have two fuctions: </p>
<p>f2 - first allocate memory , then move data.</p>
<p>f - deallocate + move = emplace_back.</p>
<p>I am trying to understand what is faster and better to use in terms of performance and code quality?</p>
<pre><code>void f2(const std::vector<std::string>& users) {
std::vector<std::pair<std::string, int>> userOccurancies(users.size());
auto userOcIt = userOccurancies.begin();
for (const auto & user : users) {
userOcIt->first = std::move(user);
userOcIt->second = 0;
userOcIt++;
}
}
void f(const std::vector<std::string>& users) {
std::vector < std::pair<std::string, std::size_t>> userCount;
userCount.reserve(users.size());
for (auto& user : users) {
userCount.emplace_back(user, 0);
}
}
</code></pre>
<p>As for performance I tried to check it with MS VS2019 profiler but it always gives me different results if a swap calls of these funcions with each other: <code>f2(users);f(users);</code> and <code>f(users);f2(users);</code> gives different call tree.</p>
<p>Can you help me?</p>
<p>What is faster and better to use in terms of performance and code quality?</p>
<p>I use only c++11.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-19T15:40:58.557",
"Id": "476017",
"Score": "1",
"body": "https://stackoverflow.com/questions/61893787/emplace-back-is-faster-than-allocate-once-move-in-c11/61894931#61894931 Main discussion and an answer is here"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-20T03:18:08.683",
"Id": "476076",
"Score": "1",
"body": "Welcome to Code Review Stack Exchange! Unfortunately, such questions are not allowed. This website is people who want a critique of their working code."
}
] |
[
{
"body": "<p>[I'm reviewing this because I believe that both <code>f</code> and <code>f2</code> actually work; I think the discussion of \"different call tree\" is just talking about difficulty in profiling them meaningfully.]</p>\n\n<p>From a code quality viewpoint, I think <code>f</code> is a clear win. <code>emplace_back</code> precisely describes what we want to accomplish here. <code>f2</code> spends a great deal more effort on the mechanics of filling the vector with the desired data.</p>\n\n<p>However, I can't say I'm particularly excited about either one. First of all, I'm...less than excited about using <code>std::pair</code>. In most cases, I'd rather define a class with meaningful names for the members. In this case, it at least <em>looks</em> like you're counting the number of times each user name occurs (or something on that order). That being the case, I'd probably define a structure something along this line:</p>\n\n<pre><code>struct UserCount { \n std::string userName;\n int count { 0 };\n UserCount(std::string const &s) : userName(s) {}\n};\n</code></pre>\n\n<p>With that in place, we can construct our vector directly from the source:</p>\n\n<pre><code>std::vector<UserCount> userOccurancies(users.begin(), users.end());\n</code></pre>\n\n<p>This should normally be at least as fast as either <code>f</code> or <code>f2</code>, and may be faster than either (though honestly, I wouldn't expect a huge speed gain from it).</p>\n\n<p>That does lead to two other possibilities though. </p>\n\n<ol>\n<li>If we can count on <code>users</code> remaining valid for the entire time that <code>userOccurancies</code> will exist, we can have <code>UserCount</code> store just a reference to the user name rather than storing a copy of it. </li>\n<li>Conversely, if we know that <code>users</code> will only be used to initialize <code>userOccurancies</code>, we can move the strings rather than copying them. Either of these is likely to be faster than copying the strings (if circumstances allow them, of course).</li>\n</ol>\n\n<p>A little here may also depend on what we're trying to optimize though. Storing references to the original strings may hurt cache locality a bit, so if we're <em>using</em> <code>userOccurancies</code> a lot, it may be faster overall to copy the strings rather than just storing references to them. This becomes especially true with short strings (for some definition of 'short') and a <code>std::string</code> that implements the short string optimization (which most modern implementations do).</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-20T20:53:04.853",
"Id": "242664",
"ParentId": "242569",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "242664",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-19T14:27:55.483",
"Id": "242569",
"Score": "-2",
"Tags": [
"c++",
"performance",
"c++11"
],
"Title": "emplace_back is faster than allocate once + move in c++11?"
}
|
242569
|
<p>I was rewriting some code from my colleague and I was questioning if I was improving the code at all.</p>
<p>My take at the code:</p>
<pre><code>if (account == null || (!account.Authorizations.Any(x =>
(x.Role.Name == RoleNames.ADMIN ||
x.Role.Name == RoleNames.SENDER ||
x.Role.Name == RoleNames.SENDERSADMIN) &&
x.TopicFilter.Name.ToLower() == item.Topic.Name.ToLower()) &&
!isCurrentUser))
{
return StatusCode(403);
}
</code></pre>
<p>Versus the original code:</p>
<pre><code>if (account == null)
return StatusCode(403);
bool isAuthorized = account.Authorizations.Any(x =>
(x.Role.Name == RoleNames.ADMIN || x.Role.Name == RoleNames.SENDER || x.Role.Name == RoleNames.SENDERSADMIN) &&
x.TopicFilter.Name.ToLower() == item.Topic.Name.ToLower());
bool isCurrentUser = message.Author.Username.ToLower() == UID.ToLower();
if (!isAuthorized && !isCurrentUser)
return StatusCode(403);
</code></pre>
<p>Even though the big linq query for "isAuthorized" is still rather bulky and there are two IF-statements with the same result, the code is still a lot more readable.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-19T15:01:23.270",
"Id": "476007",
"Score": "3",
"body": "The current question title, which states your concerns about the code, applies to too many questions on this site to be useful. The site standard is for the title to simply state the task accomplished by the code. Please see [How do I ask a good question?](https://codereview.stackexchange.com/help/how-to-ask) for examples, and revise the title accordingly."
}
] |
[
{
"body": "<p>I would argue that <em>neither</em> version is readable enough. <a href=\"https://sites.google.com/site/unclebobconsultingllc/one-thing-extract-till-you-drop\" rel=\"nofollow noreferrer\">Extract 'til you drop</a>. I would say in the grand scheme of things, you should wind up with very small bits of code that do atomic tests and almost reads like natural language when you're done. One possible example (I've created fake types to complete the parameters to the methods):</p>\n\n<pre><code> private static StatusCode CheckAccount(Account account, Item item, Message message, string UID)\n {\n const int HttpForbidden = 403;\n\n if (!ValidAccount(account))\n {\n return StatusCode(HttpForbidden);\n }\n\n if (!HasProperAuthorizations(account))\n {\n return StatusCode(HttpForbidden);\n }\n\n if (!TopicNameMatches(account, item) && !IsCurrentUser(message, UID))\n {\n return StatusCode(HttpForbidden);\n }\n\n // other stuff ?\n }\n\n private static bool ValidAccount(Account account) => account != null;\n\n private static bool HasProperAuthorizations(Account account) => account.Authorizations.Any(x =>\n x.Role.Name == RoleNames.ADMIN ||\n x.Role.Name == RoleNames.SENDER ||\n x.Role.Name == RoleNames.SENDERSADMIN);\n\n private static bool TopicNameMatches(Account account, Item item) => account.Authorizations.Any(x => string.Equals(\n x.TopicFilter.Name,\n item.Topic.Name,\n StringComparison.InvariantCultureIgnoreCase);\n\n private static bool IsCurrentUser(Message message, string UID) => string.Equals(\n message.Author.Username,\n UID,\n StringComparison.InvariantCultureIgnoreCase);\n\n private static StatusCode StatusCode(int statusCode) => new StatusCode(statusCode);\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-20T08:38:18.287",
"Id": "476103",
"Score": "1",
"body": "Thanks for the reply! Seeing this makes me kinda scratch my head why I have not thought about this myself. This makes it way more readable."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-19T16:12:35.253",
"Id": "242575",
"ParentId": "242572",
"Score": "5"
}
},
{
"body": "<p>Your colleague code is clearly focused on <code>readability</code> while your code is focused on <code>simplicity</code>. You both have a good points (excluding the <code>ToLower()</code>).</p>\n\n<p>You must keep in mind that some changes can't be <code>beneficial</code>, while others would not improve the performance much, but it would boost up code clarity and flexibility.</p>\n\n<p>First take the roles : </p>\n\n<pre><code>x.Role.Name == RoleNames.SENDERSADMIN || x.Role.Name == RoleNames.ADMIN\n</code></pre>\n\n<p>this seems to me a general user role, where it's used in multiple places. If that's the case it would more easier if it's converted into a role class where it can be used something like this : \n<code>UserRole.IsUserOrSenderAdmin(x.Role.Name)</code> or using extension <code>x.Role.Name.IsUserOrSenderAdmin()</code> Another way is to have a property inside the <code>Role</code> property like this <code>x.Role.IsAdmin || x.Role.IsSenderAdmin</code> So, you are defining the general roles conditions inside the model itself. Which would be accessed directly. This would make it easier to handle roles (or user permissions) instead of repeating the same condition or having long condition like this one. This would add clarity and simplification to the used conditions. </p>\n\n<p>The second part <code>ToLower</code>, you need to use <code>StringComparison</code> instead. \nso this : </p>\n\n<pre><code>x.TopicFilter.Name.ToLower() == item.Topic.Name.ToLower()\n</code></pre>\n\n<p>would be converted to this : </p>\n\n<pre><code>x.TopicFilter.Name.Equals(item.Topic.Name, StringComparison.OrdinalIgnoreCase);\n</code></pre>\n\n<p>This will avoid creating extra strings along with using the safe default for culture-agnostic string matching.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-20T08:39:44.700",
"Id": "476104",
"Score": "0",
"body": "Thanks! It is similar to @Jesse's approach to extrude the checks in seperate methods. The stringComparison is also something I should have thought about..."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-19T16:12:44.477",
"Id": "242576",
"ParentId": "242572",
"Score": "2"
}
},
{
"body": "<blockquote>\n <p>bool isAuthorized = account.Authorizations.Any(x =>\n (x.Role.Name == RoleNames.ADMIN || x.Role.Name == RoleNames.SENDER || x.Role.Name == RoleNames.SENDERSADMIN) &&\n x.TopicFilter.Name.ToLower() == item.Topic.Name.ToLower());</p>\n</blockquote>\n\n<ol>\n<li>I would place one check per line</li>\n<li>I would explicitly capture the 'item'</li>\n</ol>\n\n<blockquote>\n <p>bool isCurrentUser = message.Author.Username.ToLower() == UID.ToLower();</p>\n</blockquote>\n\n<p>if (!isAuthorized && !isCurrentUser)\n return StatusCode(403);</p>\n\n<p>I would check isAuthorized before calculating isCurrentUser for performance sake.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-19T17:40:17.200",
"Id": "242582",
"ParentId": "242572",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "242575",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-19T14:58:00.573",
"Id": "242572",
"Score": "-1",
"Tags": [
"c#"
],
"Title": "Less code vs More readable"
}
|
242572
|
<p>I have written the code for implementation of the cp program that prints the number of bytes copied when the user presses Ctrl-C. Could someone please review this code and provide feedback. Thanks a lot.</p>
<pre><code>
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<fcntl.h>
#include<error.h>
#include<signal.h>
#define buffer_size 512
void signal_handler(int num);
void write_buf(int des_fd, char *buffer, size_t rlen, int *bytes);
int flag = 0;
void signal_handler(int num)
{
printf("The caught signal number is : %d\n", num);
flag = 1;
}
void write_buf(int des_fd, char *buffer, size_t rlen, int *bytes)
{
int wlen;
while (1) {
wlen = write(des_fd, buffer, rlen);
if (wlen == -1)
error(1, 0, "error in writing the file\n");
*bytes = *bytes + wlen;
buffer = buffer + wlen;
rlen = rlen - wlen;
if (rlen == 0)
break;
}
}
int main()
{
int src_fd;
int des_fd;
int rlen;
int bytes;
char buffer[buffer_size];
signal(SIGINT, signal_handler);
src_fd = open("src_text", O_RDONLY);
if (src_fd == -1)
error(1, 0, "error in opening the source-file\n");
des_fd = open("des_txt", O_WRONLY);
while (1) {
rlen = read(src_fd, buffer, sizeof(buffer));
if (rlen == -1)
error(1, 0, "error in reading the file\n");
if (rlen == 0)
break;
write_buf(des_fd, buffer, rlen, &bytes);
if (flag == 1)
printf("The number of bytes copied is :%d\n", bytes);
flag = 0;
}
}
<span class="math-container">```</span>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-20T18:12:49.560",
"Id": "476185",
"Score": "0",
"body": "Vijay Antony, Why not print \"The number of bytes copied is :0\" when input file length is 0? Why that design choice?"
}
] |
[
{
"body": "<ul>\n<li><p>Do not call <code>printf</code> from the signal handler. It is not signal safe. <code>man sigaction</code> for details.</p></li>\n<li><p><code>write_buf</code> is somewhat convoluted. <code>while (rlen > 0)</code> seems more straightforward.</p>\n\n<p>Also, it is forced to write the entire buffer. It means that your program only pays attention to the <code>Ctrl-C</code> in between of writes. You may get more crispy resolution by testing <code>wlen < rlen</code> and inspecting <code>errno</code>; if <code>write</code> was interrupted, it would be <code>EINTR</code>.</p>\n\n<p><code>void</code> function with an in-out parameter (<code>bytes</code> in your case) is strange to say the least. The <code>void</code> function is not supposed to return anything, and in-out parameters are generally unclean. Just return <code>bytes</code>.</p></li>\n<li><p><code>error()</code> is a GNU extension and should not be used in programs intended to be portable. In any case, the pass <code>errno</code> as a second parameter. The user is very interested what exactly was wrong.</p></li>\n<li><p>If the program was <em>not</em> interrupted, it doesn't print number of bytes copied. Looks like a bug (or a very dubious design decision) to me.</p></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-19T17:20:28.633",
"Id": "242580",
"ParentId": "242577",
"Score": "1"
}
},
{
"body": "<h1>Avoid unnecessary forward declarations</h1>\n\n<p>The forward declarations of <code>signal_handler()</code> and <code>write_buf()</code> are unnecessary and can be removed. Try to avoid repeating code, the less chance there is for errors.</p>\n\n<h1>Make variables and functions <code>static</code> where appropriate</h1>\n\n<p>If variables and functions do not need to be used from other source files, you can mark them <code>static</code>. This will allow the compiler to better optimize the code.</p>\n\n<h1>Make <code>flag</code> an atomic variable</h1>\n\n<p>It is generally not safe to just set <code>flag = 1</code> in the signal handler and expect the <code>main()</code> function to see it change. That is because the compiler might in some circumstances be allowed to assume that nothing could change the variable <code>flag</code> between iterations in the <code>while</code>-loop, and thus optimize away the check. In this case it will work because the compiler cannot assume that the I/O functions you call in the loop won't change global variables. However, if you were not calling any library functions in the loop, the compiler would probably have elided the check.</p>\n\n<p>The quick way to fix this kind of issue is to make <code>flag</code> <code>volatile</code>. If you can use C11 or later, then you might want to use <a href=\"https://en.cppreference.com/w/c/atomic\" rel=\"nofollow noreferrer\">atomic operations</a> for this.</p>\n\n<h1>Use <code>unsigned long long</code> or <code>uint64_t</code> to store the total size read</h1>\n\n<p>An <code>int</code> typically only holds values up to 2 billion. Files can easily be larger than 2 gigabytes, so you want to use a type that can hold larger values. An <code>unsigned long long</code> will likely be 64 bits, but it is even better to be explicit and use <code>uint64_t</code> from <code>stdint.h</code>.</p>\n\n<h1>Avoid changing the behavior of common signals</h1>\n\n<p>The expectation is normally that <code>SIGINT</code> causes a program to exit immediately, not to print some information and continue. However, it is nice to handle <code>SIGINT</code> in your application and have it exit gracefully, in your case by exitting the loop, then printing the amount of bytes copied:</p>\n\n<pre><code>while (flag) {\n ...\n}\n\nprintf(\"The number of bytes copied is: %llu\\n\", bytes);\n</code></pre>\n\n<h1>Alternatives to signals</h1>\n\n<p>Using UNIX signals is always a bit tricky, since there are only a few things you can do in a signal handler that are <a href=\"http://man7.org/linux/man-pages/man7/signal-safety.7.html\" rel=\"nofollow noreferrer\">safe</a>. If you want to provide a progress indicator while copying something, and want the progress indicator to be updated once every second, then a possible way is to create a thread to do this. One issue is that creating a thread is easy, shutting it down properly is another matter.</p>\n\n<p>You can also try to use a buffer size that is so large that it takes about a second to read and write, so you can just print the progress indicator once every iteration in the loop. Or, if you want to keep the buffer small (or if you have another problem where each loop iteration is much faster than a second), you can just have a simple counter that increments for each iteration, and only update the progress indicator once so many iterations.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-20T18:07:46.557",
"Id": "476184",
"Score": "1",
"body": "Concerning file size, `uintmax_t` is a good alternative. `uint64_t` may be insufficient in say 30 years - by that time I expect `uintmax_t` to employ 128+ bits."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-19T20:16:21.120",
"Id": "242590",
"ParentId": "242577",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "242580",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-19T16:50:29.477",
"Id": "242577",
"Score": "4",
"Tags": [
"c",
"linux",
"unix"
],
"Title": "Implementation of cp program that prints the number of bytes copied"
}
|
242577
|
<blockquote>
<p>Write a Program that determines where to add periods to a decimal string so that
the resulting string is a valid IP address. There may be more than one valid IP address
corresponding to a string, in which case you should print all possibilities. For example, if the mangled string is "19216811" then some of the corresponding IP addresses are 192.168.1.1 and 19.216.81.1</p>
</blockquote>
<p><a href="https://books.google.co.ke/books?id=eErBDwAAQBAJ&lpg=PA82&ots=FosnBq2y_3&dq=Elements%20of%20Programming%20Interviews%206.9%20Compute%20Valid%20IPs&pg=PA82#v=onepage&q=Elements%20of%20Programming%20Interviews%206.9%20Compute%20Valid%20IPs&f=false" rel="nofollow noreferrer">Elements of Programming Interviews Section 6.9 See Bottom of Page 82</a>, asks the following as a variant to the above problem:</p>
<p><em>Now suppose we need to solve the analogous problem when the number of periods is a parameter <code>k</code> and the
string length <code>s</code> is unbounded</em>. </p>
<p>See attempt below, I am generating all permutations, see <code>permute(s)</code>, of the string and then filtering later hence I end up doing unnecessary work. Can I do better?</p>
<pre><code>def period_partition(s, k):
slen = len(s)
def is_valid_octet(s):
# section ranges 0 - 255 and `00` or `000`, `01` are not valid but 0 is
return slen == 1 or (s[0] != "0" and 0 <= int(s) <= 255)
def permute(s):
if len(s) > 0:
for i in range(1, slen + 1):
first, rest = s[:i], s[i:]
for p in permute(rest):
yield [first] + p
else:
yield []
results = set()
for s in filter(
lambda x: len(x) == k + 1 and all(is_valid_octet(i) for i in x), permute(s),
):
results.add(".".join(s))
return list(results)
if __name__ == "__main__":
for args in [
("", 1),
("1234", 2),
("19216811", 3),
("192168111234", 3),
("192168111234", 4),
]:
print(period_partition(*args))
print()
</code></pre>
<p>Output:</p>
<pre><code>[]
['1.23.4', '12.3.4', '1.2.34']
['1.92.168.11', '192.16.81.1', '19.216.81.1', '192.1.68.11', '192.16.8.11', '19.216.8.11', '19.2.168.11', '19.21.68.11', '192.168.1.1']
['192.168.111.234']
['192.16.81.11.234', '19.21.68.111.234', '19.2.168.111.234', '192.168.1.112.34', '192.168.11.12.34', '192.168.11.1.234', '192.168.111.23.4', '192.168.1.11.234', '192.1.68.111.234', '192.168.111.2.34', '19.216.81.112.34', '192.16.81.112.34', '19.216.81.11.234', '192.168.11.123.4', '192.16.8.111.234', '19.216.8.111.234', '1.92.168.111.234']
</code></pre>
<p><strong>NB</strong>:
This is just a toy problem and its connection to valid IP addresses, IPv4 and IPv6, I think, is just to provide constraints on valid octets as periods are assigned. So <code>1.23.4</code> is an unbounded string <code>s</code>, "1234", after being partitioned with periods <code>k=2</code> </p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-19T17:51:42.550",
"Id": "476026",
"Score": "0",
"body": "An IPv4 address is a 32 bit number, \"1.23.4\" is a 24bit number and \"192.16.81.11.234\" is a 40 bit number. It's not IPv6 because your output is neither a 128 bit number or using colons. ① Please can you provide the source for this problem. ② Does the code work the way the problem specifies?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-19T18:08:38.617",
"Id": "476027",
"Score": "0",
"body": "This is just a toy problem and its connection to valid IP addresses, IPv4 and IPv6, is just to provide constraints on valid octets as periods are assigned. Please see update to the question. So `1.23.4` is an unbounded string `s`, `1234`, after being partitioned with periods `k=2`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-19T18:16:49.877",
"Id": "476029",
"Score": "1",
"body": "Ok, that makes sense. Please could you [edit] your question to add that."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-19T18:27:57.260",
"Id": "476030",
"Score": "5",
"body": "As an aside I'm not sold on the validity of the book you're reading. I would take care to not trust the book too much. The following sentence is misleading at best and wrong at worst. \"The total number of IP addresses is a constant (\\$2^{32}\\$), implying an \\$O(1)\\$ time complexity for the above algorithm.\""
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-19T20:12:15.840",
"Id": "476042",
"Score": "1",
"body": "I copy pasted your code and got a RecursionError. I'm pretty sure your `slen = len(s)` at the beginning is a bug, since you use `slen` where you probably want the length of a string other than the outer `s`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-19T20:16:38.947",
"Id": "476043",
"Score": "0",
"body": "\"Can I do better e.g using a technique like backtracking, dfs?\" Yes, backtracking is a good idea. If that's what you really want to know, I'm not sure this question is a good idea, a lot of time will be spent on the details of your current brute force code."
}
] |
[
{
"body": "<h3>Use a generative approach</h3>\n\n<p>Iterating over all possible permutations and filtering out the invalid ones results in lots of wasted work. Move the filtering operation earlier so many invalid permutations are not generated in the first place. </p>\n\n<p>For example, <code>permute()</code> contains <code>for i in range(1, slen + 1)</code>, but we know that an octet can only be up to 3 digits long. Change the loop to <code>for i in range(1, min(4, len(s)+1))</code>. Also, if <code>first</code> is not a valid octet skip the recursive call (none will result in a valid address).</p>\n\n<p>Something like this:</p>\n\n<pre><code>def period_partition(s, k):\n\n def is_valid_octet(s):\n # section ranges 0 - 255 and `00` or `000`, `01` are not valid but 0 is\n return s == '0' or not s.startswith('0') and 0 < int(s) < 256\n\n if s and k:\n for i in range(1, min(4, len(s)+1)):\n first, rest = s[:i], s[i:]\n if is_valid_octet(first):\n yield from (f\"{first}.{p}\" for p in period_partition(rest, k-1))\n\n elif s and is_valid_octet(s):\n yield s\n\n\ntestcases = [\n (\"\", 1),\n (\"1234\", 2),\n (\"19216811\", 3),\n (\"192168111234\", 3),\n (\"192168111234\", 4),\n (\"19216811123444\", 4),\n (\"192168111234444\", 4),\n]\n\nfor s, k in testcases:\n print(f\"\\nperiod_partition({s!r}, {k})\")\n\n for partition in period_partition(s, k):\n print(f\" {partition}\")\n</code></pre>\n\n<p>Note: I modified <code>period_partition()</code> to be a generator yields all valid partitions. Use <code>list()</code> if you need an actual list.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-19T20:42:21.080",
"Id": "242591",
"ParentId": "242581",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "242591",
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-19T17:29:11.657",
"Id": "242581",
"Score": "4",
"Tags": [
"python",
"performance",
"algorithm",
"combinatorics",
"backtracking"
],
"Title": "Filter out unwanted substrings while generating all possible relevant substrings"
}
|
242581
|
<p>The following is the conclusion in a long chain of attempts to solve Project Euler problem #14 (Longest Collatz sequence) on HackerRank in the Haskell programming language.</p>
<hr />
<p>The problem is defined as follows:</p>
<blockquote>
<p>The following iterative sequence is defined for the set of positive integers:</p>
<p>n → n/2 (n is even)</p>
<p>n → 3n + 1 (n is odd)</p>
<p>Using the rule above and starting with 13, we generate the following sequence:</p>
<p>13 → 40 → 20 → 10 → 5 → 16 → 8 → 4 → 2 → 1</p>
<p>It can be seen that this sequence (starting at 13 and finishing at 1) contains 10 terms. Although it has not been proved yet (Collatz Problem), it is thought that all starting numbers finish at 1.</p>
<p>Which starting number, under a given N, produces the longest chain?</p>
</blockquote>
<p>An <a href="https://codereview.stackexchange.com/questions/27059/project-euler-14-longest-collatz-sequence-in-haskell">existing question</a> discusses the problem in the context of the original <a href="https://projecteuler.net" rel="nofollow noreferrer">Project Euler constraints</a>, namely:</p>
<blockquote>
<p>Each problem has been designed according to a "one-minute rule", which means that although it may take several hours to design a successful algorithm with more difficult problems, an efficient implementation will allow a solution to be obtained on a <strong>modestly powered computer in less than one minute</strong>.</p>
</blockquote>
<p>Note the ambiguous specification of the host machine's processing power, and the lack of any space (memory) constraints. For <a href="https://projecteuler.net/problem=14" rel="nofollow noreferrer">the problem itself</a>:</p>
<blockquote>
<p>Which starting number, <strong>under one million</strong>, produces the longest chain?</p>
</blockquote>
<p>Only one input value (1,000,000) is given, and one output value is requested.</p>
<p>On the other hand, the <a href="https://www.hackerrank.com/environment" rel="nofollow noreferrer">HackerRank website</a> gives the following constraints for Haskell programs:</p>
<blockquote>
<p>Runtime: 5 seconds</p>
<p>Memory: 512 MB</p>
</blockquote>
<p>And, for <a href="https://www.hackerrank.com/contests/projecteuler/challenges/euler014/problem" rel="nofollow noreferrer">the problem itself</a>:</p>
<blockquote>
<p>The first line contains an integer T, i.e. number of test cases. Next T lines will contain an integer N.</p>
<p>1 <= T <= 10^4</p>
<p>1 <= N <= 5*10^6 (i.e. 5,000,000)</p>
</blockquote>
<p>These constraints are significantly more strict, and the requested computations more resource-intensive.</p>
<hr />
<p>After dabbling (with no success) in binary-tree memoization (improved time, not space), bit manipulation (no significant improvements), tail recursion (avoiding stack overflow errors), and immutable arrays/vectors (decent runtime, but gratuitous space usage), I stumbled upon Haskell's <a href="https://hackage.haskell.org/package/base-4.14.0.0/docs/Control-Monad-ST.html" rel="nofollow noreferrer">State Thread</a> monad and <a href="https://hackage.haskell.org/package/vector-0.12.1.2/docs/Data-Vector-Unboxed-Mutable.html" rel="nofollow noreferrer">mutable vectors</a>.</p>
<p>Using these tools finally appeased HackerRank's testing process. However, due to my relative inexperience with such advanced Haskell libraries and language features, I want to receive the critiques of other developers with regard to efficiency, style, and (potentially) less advanced alternatives to achieve the same result.</p>
<p>My working code follows:</p>
<pre><code>import qualified Data.Vector.Unboxed.Mutable as M
import qualified Data.Vector.Unboxed as U
import Data.Vector.Generic ( iscanl' )
import Data.Bits ( shiftR )
import Control.Monad.ST ( runST )
import Control.Monad ( forM_
, forM
)
collatzLengthVector :: Int -> U.Vector Int
collatzLengthVector n = runST $ do
vec <- M.replicate n (-1)
M.write vec 0 0
M.write vec 1 1
let c x = if even x then shiftR x 1 else 3 * x + 1
let f x = do
-- (-1) means "unset." (-2) means "index out of bounds."
cache <- if x < n then M.read vec x else pure (-2)
result <- if cache < 0 then succ <$> f (c x) else pure cache
if cache == (-1) then M.write vec x result else pure ()
return result
forM_ [2 .. n - 1] f
U.freeze vec
chainScan :: U.Vector Int -> Int -> Int -> Int -> Int
chainScan vec i i' l = let l' = vec U.! i' in if l >= l' then i else i'
longestChains :: U.Vector Int -> U.Vector Int
longestChains vec = U.tail $ iscanl' (chainScan vec) 0 vec
main = do
inputSize <- getLine
let n = read inputSize :: Int
inputs <- forM [1 .. n] (const getLine)
let ints = map read inputs :: [Int]
let chains = longestChains . collatzLengthVector . succ . maximum $ ints
mapM_ (print . (chains U.!)) ints
</code></pre>
<p>Aside from general critiques, I am curious to hear:</p>
<ol>
<li>Is this scenario a good use case for mutable data structures in Haskell? Why or why not?</li>
<li>What best practices exist for distinguishing between the various different types of Vectors in Haskell's library offerings? I struggled to keep straight in my head whether I should be calling e.g. <code>freeze</code> from the Mutable package, Unboxed package, Generic package, etc.</li>
<li>Should I have simply abandoned Haskell altogether for HackerRank's version of this problem? I stuck with it because my goal is to learn Haskell. However, from a pragmatic perspective, I feel confident that I could have discerned the underlying inefficiencies of my old solutions and solved the problem elegantly in, say, C++, and gained the immediate benefits of mutable cache memory as a standard language construct.</li>
</ol>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-19T19:29:44.137",
"Id": "242587",
"Score": "2",
"Tags": [
"programming-challenge",
"haskell",
"immutability"
],
"Title": "Project Euler #14: Longest Collatz sequence on HackerRank"
}
|
242587
|
<blockquote>
<p>RNA can be broken into three nucleotide sequences called codons, and then translated to a polypeptide like so:</p>
<p>RNA: <code>"AUGUUUUCU"</code> => translates to</p>
<p>Codons: <code>"AUG", "UUU", "UCU"</code>
=> which become a polypeptide with the following sequence =></p>
<p>Protein: <code>"Methionine", "Phenylalanine", "Serine"</code></p>
<p>There are 64 codons which in turn correspond to 20 amino acids; however, all of the codon sequences and resulting amino acids are not important in this exercise. If it works for one codon, the program should work for all of them.
However, feel free to expand the list in the test suite to include them all.</p>
<p>There are also three terminating codons (also known as 'STOP' codons); if any of these codons are encountered (by the ribosome), all translation ends and the protein is terminated.</p>
<p>All subsequent codons after are ignored, like this:</p>
<p>RNA: <code>"AUGUUUUCUUAAAUG"</code> =></p>
<p>Codons: <code>"AUG", "UUU", "UCU", "UAA", "AUG"</code> =></p>
<p>Protein: <code>"Methionine", "Phenylalanine", "Serine"</code></p>
<p>Note the stop codon <code>"UAA"</code> terminates the translation and the final methionine is not translated into the protein sequence.</p>
<p>Learn more about <a href="http://en.wikipedia.org/wiki/Translation_(biology)" rel="nofollow noreferrer">protein translation on Wikipedia</a></p>
</blockquote>
<p>This was the task given. I originally did this some time ago in Python 3. </p>
<pre><code>def proteins(strand):
sub_len = 3
split_str = [strand[i:i+sub_len] for i in range(0, len(strand), sub_len)]
protein = []
for x in split_str:
if x == "UAA" or x == "UAG" or x == "UGA":
break
elif x == "AUG":
protein.append("Methionine")
elif x == "UUU" or x == "UUC":
protein.append("Phenylalanine")
elif x == "UUA" or x == "UUG":
protein.append("Leucine")
elif x == "UCU" or x == "UCC" or x == "UCA" or x == "UCG":
protein.append("Serine")
elif x == "UAU" or x == "UAC":
protein.append("Tyrosine")
elif x == "UGU" or x == "UGC":
protein.append("Cysteine")
elif x == "UGG":
protein.append("Tryptophan")
return protein
</code></pre>
<p>This time I did this in C#.</p>
<pre><code>// This file was auto-generated based on version 1.1.1 of the canonical data.
using System;
using System.Collections.Generic;
using System.Linq;
public static class ProteinTranslation
{
public static string[] Proteins(string strand)
{
// Create a list to house codons
List<string> protein = new List<string>();
// Convert string(RNA aka strand) to Array so we can iterate in chunks of 3's(codons)
IEnumerable<string> output = RnaToCodons(strand);
// Add codons to list and return results
return Codons(protein, output);
}
private static IEnumerable<string> RnaToCodons(string strand, int k = 0) => strand.ToLookup(c => Math.Floor(k++ / (double)3)).Select(e => new String(e.ToArray()));
private static string[] Codons(List<string> protein, IEnumerable<string> output)
{
foreach (var item in output)
{
switch (item)
{
case "UAA": case "UAG": case "UGA": return protein.ToArray();
case "UCU": case "UCC": case "UCA": case "UCG": protein.Add("Serine"); break;
case "UUU": case "UUC": protein.Add("Phenylalanine"); break;
case "UUA": case "UUG": protein.Add("Leucine"); break;
case "UAU": case "UAC": protein.Add("Tyrosine"); break;
case "UGU": case "UGC": protein.Add("Cysteine"); break;
case "UGG": protein.Add("Tryptophan"); break;
case "AUG": protein.Add("Methionine"); break;
}
}
return protein.ToArray();
}
}
</code></pre>
<p>Requiring me to pass these test.</p>
<pre><code>// This file was auto-generated based on version 1.1.1 of the canonical data.
using Xunit;
public class ProteinTranslationTests
{
[Fact]
public void Methionine_rna_sequence() => Assert.Equal(new[] { "Methionine" }, ProteinTranslation.Proteins("AUG"));
[Fact]
public void Phenylalanine_rna_sequence_1() => Assert.Equal(new[] { "Phenylalanine" }, ProteinTranslation.Proteins("UUU"));
[Fact]
public void Phenylalanine_rna_sequence_2() => Assert.Equal(new[] { "Phenylalanine" }, ProteinTranslation.Proteins("UUC"));
[Fact]
public void Leucine_rna_sequence_1() => Assert.Equal(new[] { "Leucine" }, ProteinTranslation.Proteins("UUA"));
[Fact]
public void Leucine_rna_sequence_2() => Assert.Equal(new[] { "Leucine" }, ProteinTranslation.Proteins("UUG"));
[Fact]
public void Serine_rna_sequence_1() => Assert.Equal(new[] { "Serine" }, ProteinTranslation.Proteins("UCU"));
[Fact]
public void Serine_rna_sequence_2() => Assert.Equal(new[] { "Serine" }, ProteinTranslation.Proteins("UCC"));
[Fact]
public void Serine_rna_sequence_3() => Assert.Equal(new[] { "Serine" }, ProteinTranslation.Proteins("UCA"));
[Fact]
public void Serine_rna_sequence_4() => Assert.Equal(new[] { "Serine" }, ProteinTranslation.Proteins("UCG"));
[Fact]
public void Tyrosine_rna_sequence_1() => Assert.Equal(new[] { "Tyrosine" }, ProteinTranslation.Proteins("UAU"));
[Fact]
public void Tyrosine_rna_sequence_2() => Assert.Equal(new[] { "Tyrosine" }, ProteinTranslation.Proteins("UAC"));
[Fact]
public void Cysteine_rna_sequence_1() => Assert.Equal(new[] { "Cysteine" }, ProteinTranslation.Proteins("UGU"));
[Fact]
public void Cysteine_rna_sequence_2() => Assert.Equal(new[] { "Cysteine" }, ProteinTranslation.Proteins("UGC"));
[Fact]
public void Tryptophan_rna_sequence() => Assert.Equal(new[] { "Tryptophan" }, ProteinTranslation.Proteins("UGG"));
[Fact]
public void Stop_codon_rna_sequence_1() => Assert.Empty(ProteinTranslation.Proteins("UAA"));
[Fact]
public void Stop_codon_rna_sequence_2() => Assert.Empty(ProteinTranslation.Proteins("UAG"));
[Fact]
public void Stop_codon_rna_sequence_3() => Assert.Empty(ProteinTranslation.Proteins("UGA"));
[Fact]
public void Translate_rna_strand_into_correct_protein_list() => Assert.Equal(new[] { "Methionine", "Phenylalanine", "Tryptophan" }, ProteinTranslation.Proteins("AUGUUUUGG"));
[Fact]
public void Translation_stops_if_stop_codon_at_beginning_of_sequence() => Assert.Empty(ProteinTranslation.Proteins("UAGUGG"));
[Fact]
public void Translation_stops_if_stop_codon_at_end_of_two_codon_sequence() => Assert.Equal(new[] { "Tryptophan" }, ProteinTranslation.Proteins("UGGUAG"));
[Fact]
public void Translation_stops_if_stop_codon_at_end_of_three_codon_sequence() => Assert.Equal(new[] { "Methionine", "Phenylalanine" }, ProteinTranslation.Proteins("AUGUUUUAA"));
[Fact]
public void Translation_stops_if_stop_codon_in_middle_of_three_codon_sequence() => Assert.Equal(new[] { "Tryptophan" }, ProteinTranslation.Proteins("UGGUAGUGG"));
[Fact]
public void Translation_stops_if_stop_codon_in_middle_of_six_codon_sequence() => Assert.Equal(new[] { "Tryptophan", "Cysteine", "Tyrosine" }, ProteinTranslation.Proteins("UGGUGUUAUUAAUGGUUU"));
}
</code></pre>
<p>I had issues on deciding how to iterate a string with Nth length of a substring. <strong>split_str</strong> and <strong>RnaToCodons</strong> was code I borrowed from post on StackOverflow. I'm not sure, but I have a feeling that a better way to do this exist. In C#, I wanted to decouple my code unlike the Python version I made. I wanted to make sure I only made one pass through the given string with <strong>Codons</strong>. Not sure if the switch case was the best way to go here, but in my opinion its easy to read. </p>
<p>It will be interesting to see if this can be sped up or more concise while still be readable along with learning if there is a better way to iterate a string with a substring.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-20T09:12:08.890",
"Id": "476107",
"Score": "0",
"body": "What should the behavior be, if an invalid RNA (e.g. 'UXU') sequence is found - is that a mutation or should it terminate the search?"
}
] |
[
{
"body": "<p>If you want a one-pass, then you can do something like this: </p>\n\n<pre><code>public static string[] Proteins(string strand)\n{\n return GetProteins(strand).ToArray();\n}\n\nprivate static IEnumerable<string> GetProteins(string strand)\n{\n if (string.IsNullOrEmpty(strand)) { throw new ArgumentNullException(nameof(strand)); }\n\n for (var i = 0; i < strand.Length; i += 3)\n {\n var condon = strand.Substring(i, Math.Min(3, strand.Length - i));\n\n if(!TryParseCodon(condon, out string protien)) { break; }\n\n yield return protien;\n }\n}\n\nprivate static string GetProteinName(string codon)\n{\n switch (codon)\n {\n case \"UCU\":\n case \"UCC\":\n case \"UCA\":\n case \"UCG\":\n return \"Serine\";\n case \"UUU\":\n case \"UUC\":\n return \"Phenylalanine\";\n case \"UUA\":\n case \"UUG\":\n return \"Leucine\";\n case \"UAU\":\n case \"UAC\":\n return \"Tyrosine\";\n case \"UGU\":\n case \"UGC\":\n return \"Cysteine\";\n case \"UGG\":\n return \"Tryptophan\";\n case \"AUG\":\n return \"Methionine\";\n default:\n return null;\n }\n}\n\nprivate static bool TryParseCodon(string codon, out string protien)\n{\n protien = GetProteinName(codon);\n return protien != null;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-19T22:57:52.733",
"Id": "476057",
"Score": "0",
"body": "`private static IEnumerable<string> RnaToCodons(string strand, int k = 0) => strand.ToLookup(c => Math.Floor(k++ / (double)3)).Select(e => new String(e.ToArray()));` I guess i'm not seeing it, but what about this did you not like? Is there multiple passes with this?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-19T23:12:05.253",
"Id": "476061",
"Score": "1",
"body": "@Milliorn yes, 3 passes (ToLookup, Select, and ToArray()). add that +2 passes on `Codons` and `Proteins`. I cut that into 2 passes, one for GetProtiens, and the other is `ToArray()` which you can element if you just change `string[]` to `IEnumerable<string> ` or change the return of `GetProtiens` to `string[]`, but I really encourage using `IEnumerable<T>` to have more generic approach which would give you access to any type of collection."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-20T05:51:07.133",
"Id": "476086",
"Score": "0",
"body": "Is a switch with fall-through the only option here? Could we use a hash in C# like in Ruby illustrated in the answers on [this question](https://codereview.stackexchange.com/q/128203/52915)?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-20T07:29:23.753",
"Id": "476097",
"Score": "1",
"body": "@Mast you could converted to `HashSet<(string,string[])>` but the switch would be faster though."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-20T08:40:56.523",
"Id": "476105",
"Score": "1",
"body": "A `Dictionary<string, string>` would be the obvious choice, but the domain specific nature would suggest there is little benefit in that abstraction."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-20T16:34:08.093",
"Id": "476165",
"Score": "0",
"body": "@VisualMelon actually, any type of collection that fits the requirement would be enough, any other suggestions on collection types is based on performance, scalability, readability, and common use. While the switch, in the other hand, the IL would convert it into a hash table (or Dictionary depends on .NET version) when there is a memory overhead."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-19T21:27:55.857",
"Id": "242594",
"ParentId": "242588",
"Score": "2"
}
},
{
"body": "<p>Your implementation doesn't seem to bother if the RNA-sequence contains invalid characters like: <code>\"UXGUGUUAUUA\"</code>. Is that on purpose? I think, I would expect an exception or at least some reporting in a log.</p>\n\n<hr>\n\n<p>An alternative to a <code>switch</code>-statement is often a dictionary - especially if the cases are going to vary or maybe should be localized - because a dictionary can be loaded at runtime from a file or database:</p>\n\n<pre><code>static readonly IDictionary<string, string> rnaProteinMap = new Dictionary<string, string>\n{\n { \"UAA\", null },\n { \"UAG\", null },\n { \"UGA\", null },\n\n { \"UCU\", \"Serine\" },\n { \"UCC\", \"Serine\" },\n { \"UCA\", \"Serine\" },\n { \"UCG\", \"Serine\" },\n\n { \"UUU\", \"Phenylalanine\" },\n { \"UUC\", \"Phenylalanine\" },\n\n { \"UUA\", \"Leucine\" },\n { \"UUG\", \"Leucine\" },\n\n { \"UAU\", \"Tyrosine\" },\n { \"UAC\", \"Tyrosine\" },\n\n { \"UGU\", \"Cysteine\" },\n { \"UGC\", \"Cysteine\" },\n\n { \"UGG\", \"Tryptophan\" },\n\n { \"AUG\", \"Methionine\" },\n};\n</code></pre>\n\n<p>Here more RNA-entries map to the same protein, but I don't think that's an issue in this context.</p>\n\n<hr>\n\n<blockquote>\n <p><code>private static string[] Codons(List<string> protein, IEnumerable<string> output)</code>\n I don't understand, why you have <code>protein</code> as an argument instead of just create it in <code>Codons()</code>?</p>\n</blockquote>\n\n<hr>\n\n<p>Below, I have refactored your code using the same bits an pieces in another fasion:</p>\n\n<pre><code> private static IEnumerable<string> RnaToCodons(string strand, int k = 0) => strand.ToLookup(c => Math.Floor(k++ / (double)3)).Select(e => new String(e.ToArray()));\n\n private static bool TryGetProtein(string rna, out string protein)\n {\n protein = null;\n\n switch (rna)\n {\n case \"UAA\": case \"UAG\": case \"UGA\": \n return false;\n case \"UCU\": case \"UCC\": case \"UCA\": case \"UCG\":\n protein = \"Serine\";\n break;\n case \"UUU\": case \"UUC\":\n protein = \"Phenylalanine\";\n break;\n case \"UUA\": case \"UUG\":\n protein = \"Leucine\";\n break;\n case \"UAU\": case \"UAC\":\n protein = \"Tyrosine\";\n break;\n case \"UGU\": case \"UGC\":\n protein = \"Cysteine\";\n break;\n case \"UGG\":\n protein = \"Tryptophan\";\n break;\n case \"AUG\":\n protein = \"Methionine\";\n break;\n default:\n // TODO log an invalid RNA\n return true;\n // OR throw new ArgumentException($\"Invalid RNA sequence: {rna}\", nameof(rna));\n }\n\n return true;\n }\n\n public static string[] Proteins(string strand)\n {\n List<string> proteins = new List<string>();\n\n foreach (var rna in RnaToCodons(strand))\n {\n if (!TryGetProtein(rna, out string protein))\n break;\n if (protein != null)\n proteins.Add(protein);\n }\n\n return proteins.ToArray();\n }\n</code></pre>\n\n<p>In TryGetProtein I return <code>true</code> for an invalid <code>RNA</code>-sequence after reporting it to the log in order to let the process proceed instead of terminate it with an exception. You should consider what to do in such situations.</p>\n\n<p><code>RnaToCodons()</code> seems to be the bottleneck performance wise. You should try stress tests it with a huge RNA-string.</p>\n\n<hr>\n\n<p>Below is another solution that handles everything in one iteration:</p>\n\n<pre><code>IEnumerable<string> Slice(string data, int size)\n{\n if (size <= 0) throw new ArgumentOutOfRangeException(nameof(size), \"Must be greater than zero\");\n\n\n char[] slice = new char[size];\n\n for (int i = 0; i <= data.Length; i++)\n {\n if (i > 0 && i % size == 0)\n {\n yield return new string(slice);\n }\n\n if (i == data.Length)\n yield break;\n\n slice[i % size] = data[i];\n }\n\n}\n\nIEnumerable<string> Proteins(string strand)\n{\n foreach (string rna in Slice(strand, 3))\n {\n if (rnaProteinMap.TryGetValue(rna, out string protein))\n {\n if (protein == null) yield break;\n yield return protein;\n }\n else\n {\n // throw, report an error or just let is pass, as you do?\n } \n }\n}\n</code></pre>\n\n<p>It uses the dictionary <code>rnaProteinMap</code> as shown above.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-20T19:12:45.027",
"Id": "476190",
"Score": "0",
"body": "`Your implementation doesn't seem to bother if the RNA-sequence contains invalid characters like: \"UXGUGUUAUUA\". Is that on purpose? I think, I would expect an exception or at least some reporting in a log.`\nCorrect, I did not factor that in or think about that.\n`private static string[] Codons(List<string> protein, IEnumerable<string> output) I don't understand, why you have protein as an argument instead of just create it in Codons()?`\nI let VSC do a refactor that turned it into that. I cannot recall what it was prior(I tried looking at the commit history on github)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-20T19:33:24.160",
"Id": "476191",
"Score": "0",
"body": "That is a very clever and unique way from what I have seen to slice up a string. I'm still working it out in my head how it works, but it makes the **foreach** easier to read. I had the idea to go with a dictionary originally but gave up after some trouble early on. I'm just a lot more familiar with switch/case."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-20T19:34:46.043",
"Id": "476192",
"Score": "0",
"body": "Trying to understand **Slice**. `if (i > 0 && i % size == 0)\n {\n yield return new string(slice);\n }` Is this simply returning an empty string/character if the **size** is 0? Guess I am just having trouble understanding how this function works step by step an how it feds the **foreach** a substring?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-20T19:45:55.487",
"Id": "476194",
"Score": "0",
"body": "@Milliorn: If `size` is zero, the a `DivideByZeroException` is thrown, so you should probably check `size` before using it. It should be greater than zero to give any meaning - see my update."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-20T20:57:36.707",
"Id": "476199",
"Score": "0",
"body": "`if (i > 0 && i % size == 0)\n {\n yield return new string(slice);\n }` So as long as size is greater than 0 then this yield will return the substring as character array?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-21T04:58:41.970",
"Id": "476242",
"Score": "1",
"body": "@Milliorn: not as a character array, but as a string `new string(slice);`"
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-20T12:06:58.463",
"Id": "242631",
"ParentId": "242588",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "242631",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-19T19:32:17.877",
"Id": "242588",
"Score": "1",
"Tags": [
"c#",
"beginner",
"strings",
"linq",
"bioinformatics"
],
"Title": "Protein Translation - Translate RNA sequences into proteins"
}
|
242588
|
<p>I wrote this code in order to return a http status of not found to my users in case the resource is not present in the DB.</p>
<pre><code>@RestController
public class ExampleController {
public final ExampleService exampleService;
@Autowired
public ExampleController(ExampleService exampleService) {
this.exampleService = exampleService;
}
@ResponseStatus(value = HttpStatus.NOT_FOUND)
public class ResourceNotFoundException extends RuntimeException {
}
@GetMapping("/api/mappings/get-by-id/{id}")
public ExampleDto getExampleById(@PathVariable String id) {
Example example = exampleService.findById(id).orElse(null );
if (example == null) throw new ResourceNotFoundException();
return new ExampleDto(example);
}
}
</code></pre>
<p>I would like to know if this code can be considered good and robust enough or if it can be improved and how.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-20T07:20:45.767",
"Id": "476096",
"Score": "1",
"body": "Please do not update the code in your question to incorporate feedback from answers, doing so goes against the Question + Answer style of Code Review. This is not a forum where you should keep the most updated version in your question. Please see *[what you may and may not do after receiving answers](//codereview.meta.stackexchange.com/a/1765)*."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-01T22:35:50.807",
"Id": "477391",
"Score": "0",
"body": "FYI, you don't need to type `@Autowired` on constructor injection. Cheers just saved 2 line of code in each Component"
}
] |
[
{
"body": "<p>Your URL path isn't very RESTlike. You have built the URL to describe an operation when a more common approach is to build the URL to describe a <a href=\"https://restfulapi.net/resource-naming/\" rel=\"nofollow noreferrer\">resource</a>.</p>\n\n<p>So instead of <code>https://example.com/api/mappings/get-by-id/42</code> one would build a URL like <code>https://example.com/api/mappings/42</code>.</p>\n\n<p>The name <code>get-by-id</code> is fully redundant in REST world as the \"get\" operation is already defined in the HTTP GET-method (the <code>@GetMapping</code> annotation in Spring Boot) and identifying resources by their identifier is always the default operation :).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-20T06:44:34.810",
"Id": "476088",
"Score": "0",
"body": "While that is correct this is a specific case where you can get an item by a property that I called id here but it was just to write an example.\nThe key part of my question if how to handle the 404. \n\nThanks for your contribution in any case!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-20T06:59:12.817",
"Id": "476093",
"Score": "0",
"body": "Ps \nI have made my pseudocode more precise regarding your observation.\nxxxId is a specific property of my object, therefore the route I specified."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-20T07:17:22.390",
"Id": "476095",
"Score": "0",
"body": "Still you have a very valid point, +1"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-20T04:22:39.890",
"Id": "242607",
"ParentId": "242589",
"Score": "4"
}
},
{
"body": "<p>As often happens after sleeping on it I had a better solution:</p>\n\n<pre><code>.orElseThrow(ResourceNotFoundException::new);\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-20T07:16:50.893",
"Id": "242614",
"ParentId": "242589",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "242607",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-19T20:07:34.870",
"Id": "242589",
"Score": "1",
"Tags": [
"java",
"rest",
"spring",
"spring-mvc"
],
"Title": "Return a 404 when a resource is not found in Spring Boot"
}
|
242589
|
<p>I got this script which work perfectly but I got some delays because of this 2 <code>for</code> loops <code>[i][j]</code> is there any way to do the same function but with a better and effective process like <code>foreach</code> or other.</p>
<pre><code>User.find({}).lean(true).exec((err, users) => {
let getTEvent = [];
//nested loops() //callbacks
for (let i =0 ; i < users.length; i++) {
if(users[i].events && users[i].events.length) {
const dt = datetime.create();
dt.offsetInDays(0);
const formatted = dt.format('d/m/Y');
// console.log(formatted)
for (let j = 0; j < users[i].events.length; j++) {
if(users[i].events[j].eventDate === formatted) {
getTEvent.push({events: users[i].events[j]});
}
}
}
}
return res.json(getTEvent)
});
</code></pre>
<p>The main role of this code is: </p>
<ol>
<li><p>find the data in Mongodb: find all users with or without events</p></li>
<li><p>loop through data and select events made by any users</p></li>
<li><p>push the results in an array which is <code>getEvent</code>in order to be useful later for the client side</p></li>
</ol>
<p>Details:</p>
<p>The <code>User</code> is the model: <code>const User = require('../models/users.model');</code>
and <code>events</code> is <code>[]</code> array.</p>
<p>This is Mongodb structure of that models:</p>
<p><a href="https://i.stack.imgur.com/OCgDO.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/OCgDO.png" alt="enter image description here"></a></p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-19T21:33:16.547",
"Id": "476047",
"Score": "2",
"body": "Welcome to Code Review! Welcome to Code Review! The current question title, which states your concerns about the code, is too general to be useful here. Please [edit] to the site standard, which is for the title to simply state the task accomplished by the code. Please see [How to get the best value out of Code Review: Asking Questions](https://codereview.meta.stackexchange.com/q/2436) for guidance on writing good question titles."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-19T22:33:54.983",
"Id": "476049",
"Score": "0",
"body": "Thank you for the welcome :D okey noted!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-19T22:39:32.173",
"Id": "476050",
"Score": "0",
"body": "@SᴀᴍOnᴇᴌᴀ I tried to explain the main role of my script :-D"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-19T22:56:10.870",
"Id": "476054",
"Score": "2",
"body": "`I got some delays` in *coding* or in execution of the code? Measurement results & method?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-20T00:19:13.113",
"Id": "476067",
"Score": "0",
"body": "@greybeard, Delays in execution of the code what I'm looking is if there something more efficient than this?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-20T18:29:32.800",
"Id": "476187",
"Score": "1",
"body": "What is `User`? Obviously it is a service/model class that has a `find` method... can that find method accept parameters like filters for events? Please [edit] your post to include as much detail as possible - this will help reviewers give better reviews"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-21T15:08:50.587",
"Id": "476293",
"Score": "1",
"body": "Yea, we're missing context here."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-21T21:51:21.487",
"Id": "476349",
"Score": "1",
"body": "@SᴀᴍOnᴇᴌᴀ I updated my question hope I clarified everything"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-21T21:51:35.367",
"Id": "476350",
"Score": "0",
"body": "@Mast , I updated my question"
}
] |
[
{
"body": "<p>I think the main cause of your delays is not a nested for but rather a fact that you extract all data from your mongodb collection into memory. What you can do is</p>\n\n<ol>\n<li><p>You can calculate formatted date once.</p></li>\n<li><p>Then you can query just those users that contain given event date instead of populating all users in memory. Here's the <a href=\"https://docs.mongodb.com/manual/tutorial/query-array-of-documents/\" rel=\"nofollow noreferrer\">guide</a></p></li>\n</ol>\n\n<p>This will look roughly like the following</p>\n\n<pre><code>const dt = datetime.create();\ndt.offsetInDays(0);\nconst formatted = dt.format('d/m/Y');\n\nUser.find({\n \"events\": {\n eventDate: formatted\n } \n }).lean(true).exec((err, users) => {\n let getTEvent = [];\n //nested loops() //callbacks\n\n for (let i = 0 ; i < users.length; i++) { \n if(users[i].events && users[i].events.length) { \n for (let j = 0; j < users[i].events.length; j++) {\n if(users[i].events[j].eventDate === formatted) {\n getTEvent.push({events: users[i].events[j]});\n } \n }\n }\n }\n\n\n return res.json(getTEvent)\n}); \n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-25T12:06:26.593",
"Id": "476715",
"Score": "0",
"body": "I think you are right I see, instead of populating all data user just fetch the data needed with only one connexion DB, so as per your answer my code is corrected the nested loops part?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-26T10:51:56.140",
"Id": "476796",
"Score": "0",
"body": "I'm not sure I've understood your comment correctly. My point is that you fetch from mongo only users that contain events in question. And that will reduce memory footprint"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-26T11:12:41.873",
"Id": "476798",
"Score": "0",
"body": "ok thank you so much, I asked something else of the code that I wrote is efficient no need for another modification ?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-26T11:25:21.183",
"Id": "476799",
"Score": "0",
"body": "I think that is the only modification that is needed. You can't eliminate nested loop completely, since you need to filter out only needed events."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-26T11:36:44.757",
"Id": "476801",
"Score": "0",
"body": "you're welcome :)"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-25T11:09:04.433",
"Id": "242893",
"ParentId": "242593",
"Score": "3"
}
},
{
"body": "<p>I was planning to suggest filtering the users in the query, as Bohdan suggested. Below are more suggestions.</p>\n<h3>Variable declarations</h3>\n<p>Another suggestion is to default to using <code>const</code> for all variables including arrays. This helps avoid <a href=\"https://softwareengineering.stackexchange.com/a/278653/244085\">accidental re-assignment and other bugs</a>. If you determine that you need to re-assign a variable then switch it to <code>let</code>.</p>\n<p>The variable <code>getTEvent</code> can be declared with <code>const</code> since it is never re-assigned. If you had to remove all elements the <code>length</code> property could be set to <code>0</code>.</p>\n<h3>looping apporach</h3>\n<p>Also you can use <a href=\"https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Statements/for...of\" rel=\"nofollow noreferrer\"><code>for...of</code></a> loops instead of <code>for</code> loops when the index is not used for anything other than selecting a current index. You could also consider a functional approach with <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter\" rel=\"nofollow noreferrer\"><code>array.filter()</code></a> - this would avoid the need to push filtered items manually.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-26T18:15:59.143",
"Id": "242962",
"ParentId": "242593",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "242893",
"CommentCount": "9",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-19T21:15:12.470",
"Id": "242593",
"Score": "5",
"Tags": [
"javascript",
"node.js",
"ecmascript-6",
"iteration"
],
"Title": "Delays using multiple for loops"
}
|
242593
|
<p>I'm making a MacOS app that will do some analysis on the user's calendar data. For now it only supports Apple's native calendar (<code>EventKit</code>), but I will later add support to Google, outlook, etc.</p>
<p><code>Models/Events/Base.swift</code>:</p>
<pre><code>import Foundation
struct EventData {
var title: String;
var startDate: Date;
var endDate: Date;
var organizerName: String;
var notes: String;
var location: String;
}
struct CalendarData {
var title: String;
var isSubscribed: Bool;
}
class Events {
init() {
checkForAuthorization();
}
func checkForAuthorization() {}
func requestAccess() {}
func getCalendars() -> [CalendarData] {
return [];
}
func getEvents(calendarName: String, from: Date, to: Date) -> [EventData] {
return [];
}
}
</code></pre>
<p><code>Models/Events/iCal.swift</code>:</p>
<pre><code>import Foundation
import EventKit
class iCal: Events {
let eventStore = EKEventStore();
var calendars: [EKCalendar]?;
override func checkForAuthorization() {
let status = EKEventStore.authorizationStatus(for: EKEntityType.event);
switch (status) {
case EKAuthorizationStatus.notDetermined:
self.requestAccess();
break;
case EKAuthorizationStatus.authorized:
break;
case EKAuthorizationStatus.restricted, EKAuthorizationStatus.denied:
break;
}
}
override func requestAccess() {
eventStore.requestAccess(to: EKEntityType.event, completion:{ (accessGranted: Bool, error: Error?) in
if accessGranted == true {
print("Granted")
} else {
print("Denied")
}
});
}
override func getCalendars() -> [CalendarData] {
let _cals = self.eventStore.calendars(for: .event);
var cals: [CalendarData] = [];
for cal: EKCalendar in _cals {
cals.append(CalendarData(title: cal.title, isSubscribed: cal.isSubscribed));
}
return cals;
}
override func getEvents(calendarName: String, from: Date, to: Date) -> [EventData] {
let cals = self.eventStore.calendars(for: .event);
var events: [EventData] = [];
if let calIndex: Int = cals.firstIndex(where: { $0.title == calendarName }) {
let selectedCalendar: EKCalendar = cals[calIndex];
let predicate = eventStore.predicateForEvents(withStart: from, end: to, calendars: [selectedCalendar])
let _events = eventStore.events(matching: predicate) as [EKEvent];
for ev: EKEvent in _events {
events.append(
EventData(
title: ev.title,
startDate: ev.startDate,
endDate: ev.endDate,
organizerName: ev.organizer?.name ?? "",
notes: ev.notes ?? "",
location: ev.location ?? ""
)
);
}
}
return events;
}
}
</code></pre>
<p>And I use this class like this:</p>
<pre><code>let calendar = iCal();
for cal in calendar.getCalendars() {
print("****** \(cal.title) *******\n");
print(calendar.getEvents(calendarName: cal.title, from: Calendar.current.date(byAdding: .day, value: -2, to: Date())!, to: Calendar.current.date(byAdding: .day, value: 1, to: Date())!))
}
</code></pre>
<p>This works, but it feels very wrong...
I know the semi-colons are not needed, but I always used it in other languages and the linting will delete them anyway after.</p>
<p>Questions:</p>
<ol>
<li>How can I improve this?</li>
<li>Would it be better to instantiate the class
<code>Events</code>, by passing the calendar type as an argument (eg. iCal,
outlook, etc)</li>
<li>Are those structs ok? As in should they go in another
file?</li>
</ol>
<p>Thank you</p>
|
[] |
[
{
"body": "<p>Please consider follow recommendations:</p>\n<ol>\n<li><p>Make habit of extracting each struct/class/enum in separate files which brings more readability and clarity. Code looks less cluttered.</p>\n</li>\n<li><p>Please try getting used to of not using semicolons :)</p>\n</li>\n<li><p>You have defined Events as a class with empty implementations of functions. Are you sure you want to do that, I think it could be converted as a protocol instead</p>\n<p>To be able to inject different type of calendar APIs, you should define your own protocol and make concrete implementations for each calendar (Adapter Pattern).</p>\n</li>\n<li><p>You must use dependency injection. For example even things like <code>EKEventStore()</code> should be injected.</p>\n<pre><code>final class iCal: Events {\n\n private let eventStore: EKEventStore\n\n init(with eventStore: EKEventStore = EKEventStore()) {\n self.eventStore = eventStore\n }\n}\n</code></pre>\n</li>\n<li><p>Using force unwrap is a bad practice, you should use <code>guard let</code> or <code>if let</code> to unwrap the optional value and only then use that unwrapped value for whatever purpose you want. By using forced unwrapping your app can crashes unexpectedly where it will find a nil value inside any optional variable.</p>\n</li>\n<li><p>Please make use of Swiftlint to make sure that your code is following standard convention. It will force you to think swift way :)</p>\n</li>\n<li><p>You should make class final when don't want to allow subclassing it (even if when you are not sure for now). If you do need subclassing later, you can remove <code>final</code> keyword.</p>\n</li>\n</ol>\n<p>All the best!</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-23T19:08:11.690",
"Id": "476566",
"Score": "0",
"body": "Thank you for your reply. Protocols is definitely the way to go. Could you please expand why I need to use dependency injection? Isn't it overkill?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-24T22:15:52.213",
"Id": "476670",
"Score": "0",
"body": "It is a choice. It can be considered overkill based on how you think. When I think about SOLID principles, the O in SOLID says that the class should be closed to changes and open for extension. I am not a Mac Developer but I see that there are 2 ways to instantiate EKEventStore and if for any reason you want to instantiate differently than how you have done now, it will violate Open Close Principle. By using DI, you will not need to change any code in class but you will just inject a differently instantiated object of EKEventStore."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-24T22:22:58.653",
"Id": "476671",
"Score": "0",
"body": "By using DI, same implementation can be used by instantiating the EKEventStore with init() and init(sources: [EKSource]). And because you will not need to do any change in your class, it will be closed to change and open to extension."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-26T15:17:24.233",
"Id": "476815",
"Score": "0",
"body": "you could do the following: `init(with eventStore: EKEventStore = EKEventStore())`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-26T15:18:16.203",
"Id": "476817",
"Score": "0",
"body": "By doing this, you can skip the parameter because default evenstore will be passed through parameter and also allow replacement when needed with other type through init."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-26T15:19:07.833",
"Id": "476818",
"Score": "0",
"body": "And change the property of class to be `let eventStore: EKEventStore`"
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-23T00:29:28.767",
"Id": "242781",
"ParentId": "242595",
"Score": "3"
}
},
{
"body": "<p>On the big picture question, you ask for the best OOP conventions, to which the answer is probably “don’t use OOP; use POP (protocol oriented programming)”. Use OOP where you really need hierarchies of concrete types, but that would not appear to the be case here. For example, you’re never instantiating what you called an <code>Events</code> object, but rather you are only instantiating <code>iCal</code> (and <code>GoogleCal</code>, etc.). So we should use a protocol rather than a concrete base type that you never use.</p>\n\n<p>For more information on POP, see WWDC 2015 video <a href=\"https://developer.apple.com/videos/play/wwdc2015/408/\" rel=\"nofollow noreferrer\">Protocol-Oriented Programming in Swift</a> or the equivalent WWDC 2016 video <a href=\"https://developer.apple.com/videos/play/wwdc2016/419/\" rel=\"nofollow noreferrer\">Protocol and Value Oriented Programming in UIKit Apps</a>.</p>\n\n<hr>\n\n<p>So, I would advise replacing <code>Base.swift</code> with:</p>\n\n<pre><code>struct Event {\n var title: String\n var startDate: Date\n var endDate: Date\n var organizerName: String?\n var notes: String?\n var location: String?\n}\n\nstruct Calendar {\n var title: String\n var isSubscribed: Bool\n}\n\nenum CalendarAuthorizationStatus {\n case authorized\n case notAuthorized\n case notDetermined\n}\n\nprotocol CalendarManager {\n func authorizationStatus() -> CalendarAuthorizationStatus\n func requestAuthorization(completion: @escaping (Result<Bool, Error>) -> Void)\n func calendars() -> [Calendar]\n func events(for calendarName: String, from: Date, to: Date) -> [Event]?\n}\n</code></pre>\n\n<p>I’m doing a few things there:</p>\n\n<ul>\n<li><p>I’ve renamed <code>Events</code> to be <code>CalendarManager</code>. The <code>Events</code> name suggests it’s a collection of event objects, but it’s not. It’s a protocol for interfacing with a calendar subsystem.</p></li>\n<li><p>If an event might not have an organizer name, notes, or a location, then those really should be optionals.</p></li>\n<li><p>I’ve eliminated the redundant/confusing <code>Data</code> suffix to the type names. <code>Data</code> is a very specific type (binary data), and using it as a suffix is unnecessarily confusing and adds cruft to our code.</p></li>\n<li><p>You really want to give <code>requestAuthorization</code> a completion handler (and not bury it in <code>checkAuthorization</code>) because the caller needs to know what to do in the UI if authorization is was not granted, which happens asynchronously. If you don’t supply a completion handler, the app has no way to defer requests until permission is granted, it has no way to present some meaningful error message in the UI if it wasn’t granted, etc.</p></li>\n<li><p>When retrieving events, it strikes me that “no matching data found” is different from “invalid calendar name supplied”, so I might use an optional and use <code>nil</code> to indicate some error.</p></li>\n</ul>\n\n<hr>\n\n<p>On stylistic matters, the code is unswifty. I’d suggest removing the semicolons, eliminate unnecessary enumeration type names, don’t use <code>break</code> in <code>switch</code> statements (this isn’t C, it’s Swift), remove redundant <code>self</code> references. For example, the following:</p>\n\n<pre><code>override func checkForAuthorization() {\n let status = EKEventStore.authorizationStatus(for: EKEntityType.event);\n\n switch (status) {\n case EKAuthorizationStatus.notDetermined:\n self.requestAccess();\n break;\n case EKAuthorizationStatus.authorized:\n break;\n case EKAuthorizationStatus.restricted, EKAuthorizationStatus.denied:\n break;\n }\n}\n</code></pre>\n\n<p>Can be reduced to:</p>\n\n<pre><code>func checkForAuthorization() {\n if EKEventStore.authorizationStatus(for: .event) == .notDetermined {\n requestAccess()\n }\n}\n</code></pre>\n\n<p>I’d also suggest using trailing closure syntax and not using <code>== true</code> syntax with booleans. Thus, for example, the following:</p>\n\n<pre><code>override func requestAccess() {\n eventStore.requestAccess(to: EKEntityType.event, completion:{ (accessGranted: Bool, error: Error?) in\n if accessGranted == true {\n print(\"Granted\")\n } else {\n print(\"Denied\")\n }\n });\n}\n</code></pre>\n\n<p>That might be better written as:</p>\n\n<pre><code>func requestAccess() {\n eventStore.requestAccess(to: .event) { granted, error in\n if !granted {\n print(\"Denied\", error ?? \"Unknown error\")\n }\n }\n}\n</code></pre>\n\n<p>Also, in Swift, if you want to get an array of <code>Event</code> from an array of <code>EKEvent</code>, you’d generally use <code>map</code>, eliminating that unnecessary local variable. Also, rather than big <code>if</code> statements that encompass nearly the whole function, you might use <code>guard</code> with early exit</p>\n\n<p>Thus this:</p>\n\n<pre><code>override func getEvents(calendarName: String, from: Date, to: Date) -> [EventData] {\n let cals = self.eventStore.calendars(for: .event);\n var events: [EventData] = [];\n\n if let calIndex: Int = cals.firstIndex(where: { $0.title == calendarName }) {\n let selectedCalendar: EKCalendar = cals[calIndex];\n\n let predicate = eventStore.predicateForEvents(withStart: from, end: to, calendars: [selectedCalendar])\n let _events = eventStore.events(matching: predicate) as [EKEvent];\n\n for ev: EKEvent in _events {\n events.append(\n EventData(\n title: ev.title,\n startDate: ev.startDate,\n endDate: ev.endDate,\n organizerName: ev.organizer?.name ?? \"\",\n notes: ev.notes ?? \"\",\n location: ev.location ?? \"\"\n )\n );\n }\n\n }\n\n return events;\n}\n</code></pre>\n\n<p>Might become:</p>\n\n<pre><code>func events(for calendarName: String, from: Date, to: Date) -> [Event] {\n let calendars = eventStore.calendars(for: .event)\n\n guard let calendar = calendars.first(where: { $0.title == calendarName }) else {\n return []\n }\n\n let predicate = eventStore.predicateForEvents(withStart: from, end: to, calendars: [calendar])\n\n return eventStore\n .events(matching: predicate)\n .map {\n Event(\n title: $0.title,\n startDate: $0.startDate,\n endDate: $0.endDate,\n organizerName: $0.organizer?.name,\n notes: $0.notes,\n location: $0.location\n )\n }\n}\n</code></pre>\n\n<hr>\n\n<p>Pulling that all together, you end up with a <code>iCal</code> implementation (which I’d call <code>AppleCalendar</code> because the “iCal” brand name isn’t used anymore and this name violates type naming conventions, namely that types should start with uppercase letter), that might look like:</p>\n\n<pre><code>class AppleCalendar: CalendarManager {\n let eventStore = EKEventStore()\n\n func authorizationStatus() -> CalendarAuthorizationStatus {\n switch EKEventStore.authorizationStatus(for: .event) {\n case .notDetermined:\n return .notDetermined\n\n case .authorized:\n return .authorized\n\n default:\n return .notAuthorized\n }\n }\n\n func requestAuthorization(completion: @escaping (Result<Bool, Error>) -> Void) {\n eventStore.requestAccess(to: .event) { granted, error in\n if let error = error {\n completion(.failure(error))\n } else {\n completion(.success(granted))\n }\n }\n }\n\n func calendars() -> [Calendar] {\n eventStore\n .calendars(for: .event)\n .map { Calendar(title: $0.title, isSubscribed: $0.isSubscribed) }\n }\n\n func events(for calendarName: String, from: Date, to: Date) -> [Event] {\n let calendars = eventStore.calendars(for: .event)\n\n guard let calendar = calendars.first(where: { $0.title == calendarName }) else {\n return []\n }\n\n let predicate = eventStore.predicateForEvents(withStart: from, end: to, calendars: [calendar])\n return eventStore\n .events(matching: predicate)\n .map {\n Event(title: $0.title,\n startDate: $0.startDate,\n endDate: $0.endDate,\n organizerName: $0.organizer?.name,\n notes: $0.notes,\n location: $0.location)\n }\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-03T01:12:51.877",
"Id": "243291",
"ParentId": "242595",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-19T21:34:51.883",
"Id": "242595",
"Score": "1",
"Tags": [
"object-oriented",
"design-patterns",
"swift",
"macos"
],
"Title": "Trying (and failing) to implement the best conventions on OOP Swift"
}
|
242595
|
<p>I attempted making a hashmap in python, and it was harder, due to some limitations but this is my version of dictionaries in python. Are there any way to simplify or do the same thing in less code along with tips and tricks?</p>
<pre><code>class HashMap:
def __init__(self, memory): # refers to the length of the bucket
self.data = [None] * memory
self.memory = memory
def _hash(self, key):
hashed_value = 0
bucket_length = self.memory
string_length = len(key)
i = 0
while i < string_length:
hashed_value += (ord(key[i]) * i) % bucket_length
if hashed_value > bucket_length-1:
hashed_value %= bucket_length-1
i += 1
return hashed_value
def set(self, key, value):
address = self._hash(key)
bucket = self.data[address]
if not bucket:
self.data[address] = [key, value, None] # None refers to next pointer
else:
while bucket[2] != None:
bucket = bucket[2]
bucket[2] = [key, value, None]
def get(self, key):
address = self._hash(key)
bucket = self.data[address]
if bucket:
while bucket[2] != None or key != bucket[0]:
bucket = bucket[2]
if bucket:
return bucket[1]
raise KeyError
def keys(self):
keys_list = []
bucket_list = self.data
for bucket in bucket_list:
current_bucket = bucket
if bucket:
while current_bucket != None:
keys_list.append(current_bucket[0])
current_bucket = current_bucket[2]
return keys_list
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-19T23:19:58.407",
"Id": "476062",
"Score": "0",
"body": "I'm missing a description of how the hash function **should** work. `%` with anything other than the size is usually wrong. And `> bucket_length - 1`? What about `>= bucket_length`? What's so special about `bucket[2]`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-19T23:41:05.353",
"Id": "476063",
"Score": "0",
"body": "bucket[2] is like a pointer from a linked list, for example when creating a new key value pair a bucket will be [key, value, None] but when collisions happen it will be [key, value, [key2, value2, None] ]"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-19T23:42:51.290",
"Id": "476064",
"Score": "0",
"body": "and the modulo operator is for making sure, that the index we get from the hash function is a possible index for the bucket array"
}
] |
[
{
"body": "<p>Your implementation of <code>get</code> is wrong. The code is:</p>\n\n<pre><code>def get(self, key):\n address = self._hash(key)\n bucket = self.data[address]\n if bucket:\n while bucket[2] != None or key != bucket[0]:\n bucket = bucket[2]\n if bucket:\n return bucket[1]\n raise KeyError\n</code></pre>\n\n<p>The line <code>while bucket[2] != None or key != bucket[0]</code> says \"keep traversing the link list as long as it's possible to do so, and if it's impossible, try to do it anyway if the key is wrong\". Because of the boolean <code>or</code>, the condition <code>bucket[2] != None</code> means the loop will always step forward in the linked list if it's possible to do so - <em>even if the current key is correct</em>. On top of that, once the loop gets to the last element, if the key at that position does not match the given key, the loop will attempt to iterate once more, giving us:</p>\n\n<pre><code>TypeError Traceback (most recent call last)\n<ipython-input-7-a5939dc0e83e> in <module>()\n----> 1 h.get(\"apple\")\n\n<ipython-input-1-4777e6d3506b> in get(self, key)\n 31 bucket = self.data[address]\n 32 if bucket:\n---> 33 while bucket[2] != None or key != bucket[0]:\n 34 bucket = bucket[2]\n 35 if bucket:\n\nTypeError: 'NoneType' object is not subscriptable\n</code></pre>\n\n<p>The result is <code>get</code> fails with this error in every case except when the requested key is the last one in its slot.</p>\n\n<p>The correct condition is of course <code>while bucket[2] != None and key != bucket[0]</code>. We then need to check afterwards that we got out of the loop because we found the right key, not because we ran out of buckets, giving us the implementation:</p>\n\n<pre><code>def get(self, key):\n address = self._hash(key)\n bucket = self.data[address]\n if bucket:\n while bucket[2] != None and key != bucket[0]:\n bucket = bucket[2]\n if bucket[0] == key:\n return bucket[1]\n raise KeyError\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-20T17:17:10.563",
"Id": "476171",
"Score": "0",
"body": "ahhh, that is very true, i couldn't test for these conditions and just assumed it works based on my first testcases, since generating the same memory place by hash, seemed very hard"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-20T17:18:20.910",
"Id": "476172",
"Score": "1",
"body": "@MahdeenSky You can test it by setting the memory to 1 when you create the hashmap"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-20T17:30:48.137",
"Id": "476177",
"Score": "0",
"body": "oh ill keep it mind, ty for taking your time fixing a mistake of mine, when it doesn't work as expected, since people tend to report the thread and downvote it for not working, on the other hand, people like you are what this stackexchange needs!!"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-20T00:49:25.803",
"Id": "242602",
"ParentId": "242596",
"Score": "4"
}
},
{
"body": "<p>Your implementation of <code>set</code> is also wrong. If you set the same key twice, the first value should be overwritten. Instead, the new key-value pair is added to the end of the bucket list, so memory usage will increase, the <code>keys</code> method will return multiple copies of the same key. </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-20T17:14:46.037",
"Id": "476170",
"Score": "0",
"body": "basically i should add change the condition of while bucket != None to while bucket != None and key != bucket[0]"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-20T17:21:29.557",
"Id": "476174",
"Score": "0",
"body": "... followed by doing different things depending on whether or not `key` was found. If you simply changed the condition, you'd lose any subsequent key-value pairs that were added to that `bucket` after that `key`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-20T17:25:38.870",
"Id": "476176",
"Score": "0",
"body": "oh a rather good point, so i basically only change the None if it loops through the whole keys in the memory, and change the value only if it isn't the above"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-20T17:36:07.477",
"Id": "476179",
"Score": "0",
"body": "Once you've fixed your code, you should [post a follow-up question](https://codereview.stackexchange.com/help/someone-answers) with the updated code, complete with test cases you've used test the new implementation. There is much more that can be improved in your implementation, but with an accepted answer, it is unlikely you will not garner any more feedback on this question."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-20T05:50:22.530",
"Id": "242610",
"ParentId": "242596",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "242602",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-19T21:53:43.810",
"Id": "242596",
"Score": "1",
"Tags": [
"python",
"python-3.x",
"hash-map",
"hashcode"
],
"Title": "HashMap Implementation (dictionary) in Python"
}
|
242596
|
<p>Suppose I have an <code>InputStream</code> that contains text data, and I want to detect all words and their <code>numLine</code>. I reach for every word in file and their <code>num</code> line and put the result in a map. This is my code:</p>
<pre><code>public class IndexerClassicRead {
private static Map<String, Map<String, Set<Integer>>> mapAllWordsPositionInFilesInFolder = new HashMap<>();
public static Map<String, Map<String, Set<Integer>>> getMap1() {
return mapAllWordsPositionInFilesInFolder;
}
public Map<String, Map<String, Set<Integer>>> showAllWordInFolder(String FolderPath) throws IOException {
ShowAllFiles showAllFiles = new ShowAllFiles();
Set<String> fileInFolder;
fileInFolder = showAllFiles.showfiles(FolderPath);
for (String filePath : fileInFolder) {
try {
BufferedInputStream bis=new BufferedInputStream(new FileInputStream(filePath));
int currentChar;
int numLine = 1;
StringBuilder word = new StringBuilder();
while ((currentChar = bis.read()) != -1 ) {
if ((char)currentChar == '\n'){
numLine++;
}
if(Character.isLetter((char)currentChar)){
word.append((char) currentChar);
}
if(!Character.isLetter((char)currentChar) || bis.available()==0 ){
if (word.length() > 0 ) {
mapAllWordsPositionInFilesInFolder.computeIfAbsent(word.toString(), v -> new HashMap<>())
.computeIfAbsent(filePath, val -> new HashSet<>())
.add(numLine);
}
word = new StringBuilder();
}
}
bis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return mapAllWordsPositionInFilesInFolder;
}
public static void main(String[] args) throws IOException {
System.out.println(new IndexerClassicRead().showAllWordInFolder("D:\\Files"));
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-20T01:18:17.283",
"Id": "476070",
"Score": "3",
"body": "You are missing the type & initialisation of `mapAllWordsPositionInFilesInFolder`. We can guess, but we might guess wrong. Missing the beginning of the `try`, too ... or is it a try-with-resources statement? Much more context is needed."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-06T14:05:57.077",
"Id": "477866",
"Score": "2",
"body": "@MaartenBodewes This is Code Review, not Stack Overflow. Asking for an MCVE will likely lead to people turning their code into example code, which is explicitly off-topic."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-07T20:37:57.687",
"Id": "477973",
"Score": "0",
"body": "@AJNeufeld the OP added the surrounding code- albeit in an answer, which has been merged into the original code. Hopefully this provides sufficient context."
}
] |
[
{
"body": "<h1>String Builder inefficiency</h1>\n<h2>Non-words</h2>\n<p>The first inefficiency deals with repeated non-letter characters:</p>\n<pre><code> if(!Character.isLetter((char)currentChar) || .... ){\n if (word.length() > 0 ) {\n mapAllWordsPositionInFilesInFolder. ... .add(...);\n }\n word = new StringBuilder();\n }\n</code></pre>\n<p>If you encounter a non-letter, you check to see if you have a word accumulated in the <code>word</code> buffer, and if so, you add to <code>mapAllWordsPositionInFilesInFolder</code>. Then, unconditionally, you create a new <code>StringBuilder</code> object.</p>\n<p>If you encounter a long string of non-letters, perhaps a table of numbers, only at the first non-letter could you have a word accumulated. But at each non-letter of this long series of non-letters, you create a new <code>StringBuilder</code> when you haven't even used the last one. You only need a clean <code>StringBuilder</code> after you've accumulated and processed a word:</p>\n<pre><code> if(!Character.isLetter((char)currentChar) || .... ){\n if (word.length() > 0 ) {\n mapAllWordsPositionInFilesInFolder. ... .add(...);\n word = new StringBuilder();\n }\n }\n</code></pre>\n<p>Small change, but huge improvement.</p>\n<h2>setLength</h2>\n<p>The second biggest inefficiency is the repeated construction of <code>StringBuilder</code> objects. A <code>StringBuilder</code> can be reused.</p>\n<p>Instead of</p>\n<pre><code> if (word.length() > 0 ) {\n mapAllWordsPositionInFilesInFolder. ... .add(...);\n word = new StringBuilder();\n }\n</code></pre>\n<p>simply reset the <code>StringBuilder</code> object to "empty":</p>\n<pre><code> if (word.length() > 0 ) {\n mapAllWordsPositionInFilesInFolder. ... .add(...);\n word.setLength(0);\n }\n</code></pre>\n<p>Now the same buffer is being reused to accumulate words. Bonus: If the buffer ever reallocates to a larger size for an extra long word, this reallocation will not need to be repeated for the next extra long word, since the <a href=\"https://docs.oracle.com/en/java/javase/14/docs/api/java.base/java/lang/StringBuilder.html#capacity()\" rel=\"nofollow noreferrer\"><code>capacity</code></a> is retained.</p>\n<p>For more efficiency, you could reuse the same <code>StringBuilder</code> for each file, instead of reallocating a new one every file.</p>\n<h1>try-with-resources</h1>\n<p>If an <code>IOException</code> occurs, you are not closing the <code>bis</code> stream. True, eventually the <code>bis</code> object will be garbage collected and the stream will be closed at that point, but that may take awhile and the operating system resources are held until that point.</p>\n<p>Simply adding a <code>bis.close()</code> statement inside the <code>catch</code> clause is not enough, since that statement can itself raise an <code>IOException</code>. It was hard to get the exception handling & closing of files correctly written, until Java 1.7's <code>try-with-resources</code> statement.</p>\n<p>Instead of:</p>\n<pre><code> try {\n BufferedInputStream bis=new BufferedInputStream(new FileInputStream(filePath));\n ...\n bis.close();\n } catch (IOException e) {\n e.printStackTrace();\n }\n</code></pre>\n<p>write:</p>\n<pre><code> try (BufferedInputStream bis=new BufferedInputStream(new FileInputStream(filePath))) {\n ...\n } catch (IOException e) {\n e.printStackTrace();\n }\n</code></pre>\n<p>Note that the <code>bis.close();</code> statement has gone away. Written this way, the <code>try ( ) { ... }</code> statement is responsible for closing the <a href=\"https://docs.oracle.com/en/java/javase/14/docs/api/java.base/java/lang/AutoCloseable.html\" rel=\"nofollow noreferrer\"><code>AutoCloseable</code></a> resources; you no longer have to.</p>\n<h1>Unused</h1>\n<pre><code>public static Map<String, Map<String, Set<Integer>>> getMap1() {\n return mapAllWordsPositionInFilesInFolder;\n}\n</code></pre>\n<p>Why does this function exist? Is the word map expected to be queried several times, and the same word map returned?</p>\n<p>The caller can modify this map. Perhaps an <a href=\"https://docs.oracle.com/en/java/javase/14/docs/api/java.base/java/util/Collections.html#unmodifiableMap(java.util.Map)\" rel=\"nofollow noreferrer\">unmodifiable map</a> should be returned. Ideally, an unmodifiable map of unmodifiable maps of an unmodifiable sets, though that would take much more work.</p>\n<h1>Usage</h1>\n<p><code>showAllWordInFolder(...)</code> is a non-static method that updates and returns the map. The map, however, is statically created.</p>\n<p>If a different folder path is given, and the function is called again, the files in the new location are merged into the map. If files are changed, and the function is called, the new file word/line information is merged into the sets along with the old and obsolete word/line information.</p>\n<p>Maybe a new <code>Map</code> should be created and returned? If each call returned a new object, then making the returned map unmodifiable wouldn't be as important.</p>\n<h1>Line by Line</h1>\n<p>Instead of processing the stream character by character, perhaps processing it line by line would be simpler.</p>\n<pre><code>for(String path : fileInFolder) {\n try (BufferedReader reader = Files.newBufferedReader(Path.of(path))) {\n int line = 1\n for(String line : reader.lines()) {\n ...\n line++;\n }\n }\n}\n</code></pre>\n<p>Words can be extracted from each line:</p>\n<pre><code>var regex = Pattern.compile("[^\\\\p{Alpha}]+"); // Split using non-letters\n...\n String[] words = regex.split(line);\n for (String word : words) {\n ...\n }\n...\n</code></pre>\n<p>Or using <code>.splitAsStream()</code> and collectors, for stream processing of results without constructing arrays of the words.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-09T16:19:24.073",
"Id": "243621",
"ParentId": "242597",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-19T22:39:18.187",
"Id": "242597",
"Score": "-1",
"Tags": [
"java"
],
"Title": "How can I optimise my code with BufferedInputStream"
}
|
242597
|
<p>Task: . Complete the following function that determines if two lists contain the same elements, but not necessarily in the same order. The function would return true if the first list contains 5, 1, 0, 2 and the
second list contains 0, 5, 2, 1. The function would return false if one list contains elements the other
does not or if the number of elements differ. This function could be used to determine if one list is a
permutation of another list. The function does not affect the contents of either list.</p>
<p>My code:</p>
<pre><code>def permutation(a,b):
if len(a) != len(b):
return False
n = len(a)
count = 0
for i in range(n):
for j in range(n):
if b[j] == a[i]:
count += 1
return count == n
def main():
lst_1 = [1,2,3,4]
lst_2 = [2,4,3,1]
lst_3 = [2,4,4,5,4,5]
lst_4 = [2,3,4,4,4,4]
print(permutation(lst_1,lst_2))
print(permutation(lst_2,lst_3))
print(permutation(lst_3,lst_4))
main()
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-20T11:11:39.983",
"Id": "476119",
"Score": "3",
"body": "There's a bug in this code because it allows each character in the first string to be counted against multiple copies of that character in the second. As such it returns False (count==4, n==2) for `permutation([2,2], [2,2])` which obviously should be True, and True (count==n==3) for `permutation([0,1,2], [1,2,2])` which should be False."
}
] |
[
{
"body": "<p>Just sort both lists and compare them:</p>\n\n<pre><code>lst1=[5,1,0,2]\nlst2=[0,5,2,1]\n\ndef comparelists(list1, list2):\n return(list1.sort()==list2.sort())\n\nprint(comparelists(lst1, lst2))\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-20T04:16:32.030",
"Id": "476079",
"Score": "2",
"body": "Won't this modify the input for the caller?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-20T06:55:27.427",
"Id": "476091",
"Score": "1",
"body": "@slepic, Yeah, which is probably unwanted behaviour, or at least [surprising](https://en.wikipedia.org/wiki/Principle_of_least_astonishment). Calling `sorted(lst)` will get rid of that, but using `set`s is likely a better approach."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-20T16:42:51.390",
"Id": "476168",
"Score": "0",
"body": "@AlexPovel I'm unfamiliar with Python, but if sets work same as Java (and math) then they don't allow duplicates -- but OP allows duplicates in their example: `[2,3,4,4,4,4]`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-20T17:23:14.477",
"Id": "476175",
"Score": "0",
"body": "@CaptainMan yes, sets don't allow duplicates in Python either. There was a now-deleted answer in this thread earlier that created sets but also compared the lengths of the initial lists. It seemed to be a valid attempt but did not work on closer inspection. So sets are not the way to go, you are right."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-18T17:47:05.777",
"Id": "512285",
"Score": "0",
"body": "@slepic I'd say the even bigger issue is that it's wrong. It returns `True` for *any* two lists, regardless of whether they're permutations of each other."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-20T02:39:01.350",
"Id": "242606",
"ParentId": "242603",
"Score": "1"
}
},
{
"body": "<p>You can also do:</p>\n\n<pre><code>from collections import Counter\n\ndef compare_lists(list1, list2): \n return Counter(list1) == Counter(list2)\n</code></pre>\n\n<p>While <code>list.sort</code> / <code>sorted</code> has <code>O(n log n)</code> time complexity, constructing a <code>Counter</code> (which is a <code>dict</code> internally) is <code>O(n)</code>. This is also an improvement over the solution in the question, which is <code>O(n ^ 2)</code>. </p>\n\n<p>There is also a more efficient memory allocation involved if you do not want to mutate <code>list1</code> and <code>list2</code>. Constructing the sorted list has <code>O(n)</code> space complexity, while constructing the <code>Counter</code> is <code>O(k)</code>, where <code>k</code> is the number of <em>unique</em> elements.</p>\n\n<p>If you wanted to make this function scalable to an arbitrary number of lists, you could do:</p>\n\n<pre><code>from collections import Counter\n\ndef compare_lists(*lists):\n counters = map(Counter, lists)\n\n try:\n first_counter = next(counters)\n except StopIteration:\n return True\n\n return all(first_counter == counter for counter in counters)\n</code></pre>\n\n<p>Now <code>compare_lists</code> takes a variable number of arguments, and would return <code>True</code> if all of the arguments are permutations of each other.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-20T14:50:02.600",
"Id": "476157",
"Score": "0",
"body": "I'm not a Python expert, but generally speaking, I believe inserting `n` items into a hash table is also `O(n log n)`. The constants are different, of course, between hash inserts and sorting, and sorting moves elements as well. Oddly enough, on a NUMA (Non-Uniform Memory Access) machine, sorting may well be faster than hashing, due to better cache usage."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-20T16:41:24.153",
"Id": "476167",
"Score": "0",
"body": "Just a reminder that when dealing with big-O for small values for n, it can often be better to use \"worse\" algorithms. One of my professors had us intentionally think of radix sorting as `k O(n)` due to the large overhead."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-20T09:47:49.493",
"Id": "242621",
"ParentId": "242603",
"Score": "8"
}
},
{
"body": "<p>This might be totally over engineered compared to what you need.</p>\n\n<p>Depending on what you input data actually is there are fast or faster metodes to find the difference.</p>\n\n<p>Untested pseudo code ahead</p>\n\n<p>All tests should start with a size comparison as that is a fast way to find out that they are not equal.\nIf you have large data structures and small keys you want to compare then make a new list with just the values you want to compare.\nUsing a kind of metode IntroSort a variant of QuickSort to quickly find out if they are equal.\nDepth is 2 times the Log2(size A).</p>\n\n<pre><code>bool IntroEqual (A,B, depth)\n if (size A != size B) // different size so not equal\n return false \n\n if (size A <= 16)\n insertion_sort(A)\n insertion_sort(B)\n return A == B\n\n if (dictionary size is small)\n return count_sort(A) == count_sort(B)\n\n pivot = cleverly selected\n PA = partition(A, pivot)\n PB = partition(B, pivot)\n\n depth = depth - 1;\n if (depth == 0) // using introspection we now know that we selected bad pivots.\n return sort(A) == sort(B)\n\n return IntroEqual (PA low, PB low) && IntroEqual (PA high, PB high)\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-20T11:33:36.743",
"Id": "242630",
"ParentId": "242603",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-20T01:49:45.197",
"Id": "242603",
"Score": "5",
"Tags": [
"python",
"python-3.x"
],
"Title": "Check if two lists are permutations of the one another ( Improvement)"
}
|
242603
|
<h2>Review Wanted</h2>
<h3>Application Summary</h3>
<p>The application is a simple screen scraper which is to notify the user when new items are posted.</p>
<p>The code is run as a CRON job every ten minutes. It will scrape the target page and return an array of ALL items matching the search criteria ( hard-coded ) by the user.</p>
<p>The results are compared to the results from the previous time the code was run. If there are any new items, the user is notified.</p>
<h3>My Challenges</h3>
<p>First of all, I have never used any of the technologies I had to use in the app ( NodeJS, Puppeteer, and Express ). More significant that is, how to track what constitutes a "new" item, an item that has been "seen", etc.</p>
<p>Currently, I added a column in the database, "seen". When the user hits the front end, I will mark those results as "seen".</p>
<p>Also, the way I am saving the items in general may need refactoring. I will leave that up to your opinion.</p>
<h3>WorkFlow</h3>
<p>Here is a breakdown of how the app works:</p>
<p><a href="https://i.stack.imgur.com/DKXxz.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/DKXxz.png" alt="WorkFlow" /></a></p>
<h3>Source Code</h3>
<p>Here is the complete source code of the app. It functions well, as far as I can tell. I am concerned about the Duplicate issue though.</p>
<pre><code>const puppeteer = require('puppeteer');
const _ = require("lodash");
var mysql = require('mysql');
var con = mysql.createConnection({
host: 'localhost',
user: 'root',
password: '',
database: 'mydatabase'
});
var oldItems; // Items already scraped
getSavedJeeps = function () {
return new Promise(function (resolve, reject) {
con.query(
"SELECT * FROM jeeps",
function (err, rows) {
if (err) {
reject(new Error("Error rows is undefined"));
} else {
resolve(rows);
}
}
)
})
}
const saveNewJeeps = async function (entity) {
let objLen = entity.length;
// FOR EACH OBJECT IN ARRAY...
for (var i = 0; i < objLen; i++) {
var savedJeeps = con.query('INSERT INTO newjeeps SET ?', entity[i], function (err, result) {
// Neat!
console.log("Save function complete");
});
}
removeDupes();
return true;
}
const updateAllItems = async function (entity) {
let objLen = entity.length;
// FOR EACH OBJECT IN ARRAY...
for (var i = 0; i < objLen; i++) {
var savedJeeps = con.query('INSERT INTO jeeps SET ?', entity[i], function (err, result) {
// Neat!
console.log("Save function complete");
});
}
}
// Gets current items Search Results
const getItems = async searchTerm => {
browser = await puppeteer.launch({
headless: true,
timeout: 0,
args: ["--no-sandbox"]
});
page = await browser.newPage();
await page.goto(`https://facebook.com/marketplace/tampa/search/?query=${encodeURI(searchTerm)}&sort=created_date_descending&exact=false`);
await autoScroll(page);
const itemList = await page.waitForSelector('div > div > span > div > a[tabindex="0"]')
.then(() => page.evaluate(() => {
const itemArray = [];
const itemNodeList = document.querySelectorAll('div > div > span > div > a[tabindex="0"]');
itemNodeList.forEach(item => {
const itemTitle = item.innerText;
const itemURL = item.getAttribute('href');
const itemImg = item.querySelector('div > div > span > div > a > div > div > div > div > div > div > img').getAttribute('src');
var obj = ['price', 'title', 'location', 'miles',
...itemTitle.split(/\n/)
]
.reduce((a, c, i, t) => {
if (i < 4) a[c] = t[i + 4]
return a
}, {});
obj.imgUrl = itemImg;
obj.itemURL = itemURL;
itemArray.push(obj);
});
return itemArray;
}))
.catch(() => console.log("Selector error."));
return itemList;
}
// This takes care of the auto scrolling problem
async function autoScroll(page) {
await page.evaluate(async () => {
await new Promise(resolve => {
var totalHeight = 0;
var distance = 100;
var timer = setInterval(() => {
var scrollHeight = document.body.scrollHeight;
window.scrollBy(0, distance);
totalHeight += distance;
if (totalHeight >= scrollHeight || scrollHeight > 9000) {
clearInterval(timer);
resolve();
}
}, 100);
});
});
}
const removeDupes = async function () {
// remove duplicates
sql = `DELETE
t1
FROM
jeeps t1
INNER JOIN jeeps t2 WHERE
t1.title < t2.title AND t1.price = t2.price `;
return new Promise(function (resolve, reject) {
con.query(
sql,
function (err, rows) {
if (err) {
reject(new Error("Error rows is undefined"));
} else {
resolve();
}
}
)
})
}
const getDifferences = async function (objNew, objOld) {
console.log("Inside Differences")
return _.difference(objNew, objOld);
}
const init = async function () {
var oldItems;
const newItems = await getItems("Jeep Wrangler");
getSavedJeeps()
.then(function (results) {
oldItems = results;
})
.catch(function (err) {
console.log("Promise rejection error: " + err);
})
const finalArray = await getDifferences(newItems, oldItems);
const saveSuccess = await saveNewJeeps(finalArray);
const saveSuccess2 = await updateAllItems(finalArray);
const changed = (finalArray.length > 0) ? true : false;
if (changed) {
// Fire Off Email
const page2 = await browser.newPage();
await page2.goto(`http://john.example.com/mail.php`);
}
}
init();
</code></pre>
<p>Thanks in advance for your suggestions or comments. I asked a similar question a while back, but the app wasn't ready for review. It is now, and I am ready for your review - whether good or bad.</p>
<p>Regards,
John</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-20T16:04:50.020",
"Id": "476164",
"Score": "2",
"body": "Your `init` function is not waiting for the `getSavedJeeps` function to finish before calling `getDifferences`; `oldItems` will always be `undefined`, so `getDifferences` will always return the `newItems` unaltered. There are also a whole bunch of improvements described in the prior answer on the code in the question: https://codereview.stackexchange.com/a/242044 that don't appear to have been implemented. (not that you have to implement them all, but many of them are concrete improvements without disadvantages or database restructuring)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-21T02:04:05.450",
"Id": "476228",
"Score": "0",
"body": "I just don't understand why it isn't waiting. What more can I do? It's already async. As far as the other improvements, I appreciated the suggestions, but I wanted to try to get it working before I refactor. I think I bit off more than I could chew for a first project. Ok, I will dig in and see why getSavedJeeps is not waiting. Thank you so much CP."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-21T12:10:49.327",
"Id": "476272",
"Score": "1",
"body": "The issue is similar to the one described in great detail [here](https://stackoverflow.com/q/23667086). In short, you should `await` the Promise in order for the current function to stop execution until the Promise resolves."
}
] |
[
{
"body": "<p>I can't comment, but I have a question for you. </p>\n\n<h1>Question</h1>\n\n<p>Why don't you use the jeep id of Facebook as a unique key, this way duplicates will not be a problem.</p>\n\n<h1>Now for the code review</h1>\n\n<p>Notes:</p>\n\n<ul>\n<li>I saw other responses told you you have bugs in your code, I didn't check your code for bugs. But please follow their advice.</li>\n<li>This is my add-on above all that was already been told by others.</li>\n</ul>\n\n<hr>\n\n<ol>\n<li><p>The first impression the code looks good for its purpose.\nWhat I mean - the code is a small CRON script and therefore using a <strong>single file</strong> might be ok for the use-case. Although code tends to grow or even infrastructure might change. </p></li>\n<li><p>The code is broken into meaningful functions and is easy to read. and it's ok because its a small CRON job otherwise another structure was required.</p>\n\n<ul>\n<li>For example the non-readable parts are some of the boilerplate code that is scattered around which is the misfortune of a single file.</li>\n<li>Another example of such misfortune is not needing to be object-oriented and have a clear responsibility structure embedded which makes the code less readable.</li>\n<li>Yet another - There is no sense of layers in your code, so it's just simple progressive programming. If it was part of a bigger project, I would expect it to use existing DB layers or other existing infrastructure and may be part of a single monorepo and layers would have been a must and different restructuring.</li>\n</ul></li>\n<li><p>Good use of promise & await, but why not stick with one method? promisify the endpoints and keep the consistency of async/await from there on to the top level.</p></li>\n<li><p>very important, I read another person told you the same thing, you didn't handle catch-all exception in one location.</p></li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-04T10:38:56.617",
"Id": "243370",
"ParentId": "242609",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-20T05:02:04.540",
"Id": "242609",
"Score": "0",
"Tags": [
"javascript",
"mysql",
"node.js"
],
"Title": "Scrape page and send user only new results"
}
|
242609
|
<p>This is modified from the general recursive solution here: <a href="https://stackoverflow.com/a/54544211/42346">https://stackoverflow.com/a/54544211/42346</a> to, more specifically, copy/move files with a given extension from one directory to another whilst preserving subdirectories.</p>
<p>I'm reluctant to use <code>.rename()</code> for this purpose as it seems slightly less intuitive than copying or moving.</p>
<p>Any other ideas you have about how to clean this up are greatly appreciated.</p>
<pre><code>import os, shutil
from pathlib import Path
def recur(path,destination,file_ext,is_subdir=False):
if not is_subdir:
os.chdir(path)
for entry in os.scandir(path):
if os.path.splitext(entry.name)[-1].lower() == file_ext:
subdir_path = entry.path.replace(os.getcwd() + os.sep,'')
new_path = Path(destination) / subdir_path
os.makedirs(os.path.dirname(new_path), exist_ok=True)
shutil.copy(entry.path,new_path)
if entry.is_dir():
recur(Path(path).joinpath(entry.name),destination,file_ext,is_subdir=True)
</code></pre>
|
[] |
[
{
"body": "<p>You use <code>pathlib.Path</code>, which is great, but it can do a lot more:</p>\n\n<ul>\n<li>Operations like <code>os.path.splitext</code> should be modernized using the <code>suffix</code> attribute of <code>Path</code> objects; for a full list of those designated replacements, see <a href=\"https://docs.python.org/3/library/pathlib.html#correspondence-to-tools-in-the-os-module\" rel=\"nofollow noreferrer\">the documentation</a>.</li>\n<li><code>os.scandir</code> can in this case be replaced by <code>Path.rglob</code>. This is where the recursion you mentioned comes into play. But that's it: Recursive globbing is an irrelevant implementation detail here. The point is that we do not have to do it \"manually\". <code>rglob</code> takes a pattern as its string argument, which can be the suffix you mentioned.</li>\n<li>Further, <code>os.makedirs</code> can be <code>Path.mkdir</code> with <code>parents=True</code> for the latter. This is not as big a win as the others, but nice.</li>\n</ul>\n\n<p>Eventually, it turns out the <code>os</code> import can be done without altogether, and recursion is neatly tucked away:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>from pathlib import Path\nfrom shutil import copy2 # \"identical to copy() but attempts to preserve to file metadata\"\n\nCOPY_FROM = Path(\"source\")\nCOPY_TO = Path(\"dest\")\n\nSUFFIX = \"*.py\"\n\nfor source in COPY_FROM.rglob(SUFFIX):\n subpath = source.relative_to(COPY_FROM)\n destination = COPY_TO.joinpath(subpath)\n destination.parent.mkdir(parents=True, exist_ok=True)\n copy2(source, destination)\n</code></pre>\n\n<p>Note the use of <code>copy2</code>, which is <a href=\"https://docs.python.org/3/library/shutil.html#shutil.copy2\" rel=\"nofollow noreferrer\">identical to <code>copy</code> but attempts to preserve metadata</a>.\nThis can be convenient for e.g. music files.</p>\n\n<p>The <code>parent</code> attribute is the logical parent path to the found file, so essentially all path elements except for the found file itself.\nLike in your solution, those path elements (directories) have to be created first.\nIn <code>mkdir</code>, <code>exist_ok=False</code> is the default and would prohibit us from most desired operations, like copying files in subdirectories.</p>\n\n<p>The above gives the following result, which is hopefully what you are aiming for:</p>\n\n<pre><code>~$ tree\n.\n├── dest\n│ ├── file1.py\n│ ├── test1\n│ │ ├── file2.py\n│ │ └── file3.py\n│ └── test2\n│ ├── file4.py\n│ └── test3\n│ └── file5.py\n└── source\n ├── file1.py\n ├── test1\n │ ├── file2.py\n │ └── file3.py\n └── test2\n ├── file4.py\n └── test3\n └── file5.py\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-20T08:00:37.283",
"Id": "476101",
"Score": "0",
"body": "Excellent answer, thank you!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-20T07:52:27.863",
"Id": "242616",
"ParentId": "242612",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "242616",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-20T07:00:08.867",
"Id": "242612",
"Score": "3",
"Tags": [
"python",
"recursion",
"file-system"
],
"Title": "Recursive os.scandir() for copying/moving files preserving subdirectories"
}
|
242612
|
<p><strong>Task:</strong></p>
<p>"Implement a method 'gruppiere', in a way that it can be invoked on all enumerable objects (Enumerable). The method receives a block and returns a hash. The items of the enumerable a grouped within the hash according to the return-value of the block."</p>
<p>What they like to have is an own implementation of Ruby's "#group_by"-method: <a href="https://ruby-doc.org/core-2.7.1/Enumerable.html#method-i-group_by" rel="nofollow noreferrer">Ruby-Docs Enumerable</a></p>
<p><strong>My solution:</strong></p>
<pre><code>module Enumerable
def gruppiere()
ret = {}
self.each { |item|
key = yield item
if ret[key] == nil
tmp = []
tmp << item
ret[key] = tmp
else
ret[key] << item
end
}
ret
end
end
puts [1, 2, 3, 4].gruppiere { |i| i % 2 == 0 } # Result: {false=>[1, 3], true=>[2, 4]}
</code></pre>
<p>Works well. But I'm sure it could be done better.</p>
<p><strong>Is there a less verbose way to solve the task?</strong></p>
<p><strong>Is my code written in a good way and manner? What could be improved?</strong></p>
|
[] |
[
{
"body": "<h1>Linting</h1>\n<p>You should run some sort of linter or static analyzer on your code. <a href=\"https://www.rubocop.org/\" rel=\"nofollow noreferrer\">Rubocop</a> is a popular one, but there are others.</p>\n<p>Rubocop was able to detect almost all of the style violations I am going to point out (and even some more), and was able to autocorrect almost all of them.</p>\n<h1>Testing</h1>\n<p>There is no automated testing in your code. Apart from the single example at the very end (which is not automated), there is no testing at all.</p>\n<p>You should always strive to have as close to 100% test coverage as possible. It doesn't really matter if you have unit tests, functional tests, integration tests, end-to-end tests, or a mix of them, but you should have tests, and they should be automated.</p>\n<p>In this particular case, since you are implementing a Ruby core method, there are already plenty of tests written for you in the <a href=\"https://github.com/ruby/spec/blob/master/core/enumerable/group_by_spec.rb\" rel=\"nofollow noreferrer\">Ruby/Spec project</a> as well as the <a href=\"https://github.com/ruby/ruby/blob/master/test/ruby/test_enum.rb#L288-L295\" rel=\"nofollow noreferrer\">YARV test suite</a>.</p>\n<p>Running the Ruby/Spec tests against your code yields 3 errors, 1 failure, and only 3/7 passing tests.</p>\n<p>The YARV test suite has 1/2 passing assertion and 1 error.</p>\n<h1>Indentation</h1>\n<p>The standard indentation style in the Ruby community is 2 spaces, not 4.</p>\n<h1>Empty parameter list</h1>\n<p>When you define a method without parameters, don't write out an empty parameter list. Just leave out the parameter list completely.</p>\n<p>Instead of</p>\n<pre class=\"lang-rb prettyprint-override\"><code>def gruppiere()\n</code></pre>\n<p>you should have</p>\n<pre class=\"lang-rb prettyprint-override\"><code>def gruppiere\n</code></pre>\n<h1>Naming</h1>\n<p><code>ret</code> and <code>tmp</code> aren't really good variable names. Try to make them more expressive so that they reveal their intent. Okay, so it's a temporary variable, but what does it do, what is it for, why is it there?</p>\n<p>Normally, the reason to introduce a temporary variable is to give an intention-revealing name to some sub-expression. But <code>tmp</code> is not very intention-revealing.</p>\n<p>At least, spell them out. You are not going to wear out your keyboard by writing <code>temp</code> instead of <code>tmp</code>, I promise.</p>\n<h1>Unnecessary <code>self</code></h1>\n<p><code>self</code> is the implicit receiver in Ruby if you don't explicitly provide one. There is no need to explicitly provide <code>self</code> as the receiver (except in some very limited special circumstances).</p>\n<p>Instead of</p>\n<pre class=\"lang-rb prettyprint-override\"><code>self.each\n</code></pre>\n<p>just write</p>\n<pre class=\"lang-rb prettyprint-override\"><code>each\n</code></pre>\n<h1>Block delimiters</h1>\n<p>The standard community style for block delimiters is to use <code>{</code> / <code>}</code> for single-line blocks and <code>do</code> / <code>end</code> for multi-line blocks.</p>\n<p>There is a small minority that follows a different style: <code>{</code> / <code>}</code> for functional blocks and <code>do</code> / <code>end</code> for imperative blocks</p>\n<p>Whichever style you follow, your block should use <code>do</code> / <code>end</code> since it is both multi-line and imperative.</p>\n<h1>Explicit equality check against <code>nil</code></h1>\n<p>You should not check for equality with <code>nil</code>. There is a method <a href=\"https://ruby-doc.org/core/Object.html#method-i-nil-3F\" rel=\"nofollow noreferrer\"><code>Object#nil?</code></a> which returns <code>false</code> for all objects, and the only override of this method is <a href=\"https://ruby-doc.org/core/NilClass.html#method-i-nil-3F\" rel=\"nofollow noreferrer\"><code>NilClass#nil?</code></a>, which returns <code>true</code>. In other words: the only object that will ever respond with <code>true</code> to <code>nil?</code> is <code>nil</code>.</p>\n<p>Instead of</p>\n<pre class=\"lang-rb prettyprint-override\"><code>ret[key] == nil\n</code></pre>\n<p>you should write</p>\n<pre class=\"lang-rb prettyprint-override\"><code>ret[key].nil?\n</code></pre>\n<h1>Unnecessary array mutation</h1>\n<p>In this piece of code:</p>\n<pre class=\"lang-rb prettyprint-override\"><code>tmp = []\ntmp << item\n</code></pre>\n<p>You assign an empty array to <code>tmp</code>, then immediately append <code>item</code> to the empty array. That's exactly the same as assigning an array with one item to <code>tmp</code> in the first place:</p>\n<pre class=\"lang-rb prettyprint-override\"><code>tmp = [item]\n</code></pre>\n<h1>Unnecessary temporary variable</h1>\n<p>Once we have made the above change, this piece of code:</p>\n<pre class=\"lang-rb prettyprint-override\"><code>tmp = [item]\nret[key] = tmp\n</code></pre>\n<p>doesn't really need the temporary variable anymore:</p>\n<pre class=\"lang-rb prettyprint-override\"><code>ret[key] = [item]\n</code></pre>\n<p>See? The reason why you didn't find a good name for that variable, is that it shouldn't even be there!</p>\n<h1><code>Hash</code> default value</h1>\n<p>Actually, we can get rid of that whole conditional expression by instead making sure our result hash automatically initialized non-existent keys with an empty array the first time the key is accessed:</p>\n<pre class=\"lang-rb prettyprint-override\"><code>def gruppiere\n ret = Hash.new {|hash, key| hash[key] = [] }\n\n each do |item|\n key = yield item\n ret[key] << item\n end\n\n ret\nend\n</code></pre>\n<p>This, by the way, also gets rid of one of the things Rubocop was complaining about but was unable to auto-correct: the method was too long.</p>\n<h1>Higher-level iteration methods</h1>\n<p><code>each</code> is a very low level iteration method. It is usually barely needed in Ruby. As a general rule, in Ruby</p>\n<ul>\n<li>When you are writing a loop, you are definitely doing something wrong.</li>\n<li>When you use <code>each</code>, you are very likely doing something wrong.</li>\n</ul>\n<p>The pattern you use in your code looks like this: you create a result object, then accumulate results in this object, and at the end return it. This pattern is actually a <a href=\"https://wikipedia.org/wiki/Fold_(higher-order_function)\" rel=\"nofollow noreferrer\"><em>Fold</em></a>. In Ruby, <em>fold</em> is provided by <a href=\"https://ruby-doc.org/core/Enumerable.html#method-i-inject\" rel=\"nofollow noreferrer\"><code>Enumerable#inject</code></a> (and its alias <a href=\"https://ruby-doc.org/core/Enumerable.html#method-i-reduce\" rel=\"nofollow noreferrer\"><code>Enumerable#reduce</code></a>) and <a href=\"https://ruby-doc.org/core/Enumerable.html#method-i-each_with_object\" rel=\"nofollow noreferrer\"><code>Enumerable#each_with_object</code></a>.</p>\n<p>Here is what the method would look like using <code>Enumerable#each_with_object</code>:</p>\n<pre class=\"lang-rb prettyprint-override\"><code>def gruppiere\n each_with_object(Hash.new { |hash, key| hash[key] = [] }) do |element, result|\n key = yield element\n result[key] << element\n end\nend\n</code></pre>\n<h1>Iteration protocol</h1>\n<p>It is standard that iterator methods return an <a href=\"https://ruby-doc.org/core/Enumerator.html\" rel=\"nofollow noreferrer\"><code>Enumerator</code></a> when called without a block. We can use the <a href=\"https://ruby-doc.org/core/Object.html#method-i-enum_for\" rel=\"nofollow noreferrer\"><code>Object#enum_for</code></a> method to create an <code>Enumerator</code> for our method. We just put the following code as the first line of our method:</p>\n<pre class=\"lang-rb prettyprint-override\"><code>return enum_for(__callee__) { size if respond_to?(:size) } unless block_given?\n</code></pre>\n<p>This actually fixes all of the test errors we had.</p>\n<h1>Test failures</h1>\n<p>Unfortunately, we have introduced one new test failure with our refactoring to auto-initialize the hash. <code>group_by</code> should not return a <code>Hash</code> that has <code>default_proc</code> set.</p>\n<p>We have two choices:</p>\n<ul>\n<li>Set <code>default_proc</code> to <code>nil</code>.</li>\n<li>Create a new hash.</li>\n</ul>\n<p>I opted for the latter, to create a new empty hash and <a href=\"https://ruby-doc.org/core/Hash.html#method-i-merge\" rel=\"nofollow noreferrer\"><code>Hash#merge</code></a> onto it, to be 100% sure that the <code>default_proc</code> as well as any internal flags are reset to defaults:</p>\n<pre class=\"lang-rb prettyprint-override\"><code>def gruppiere\n return enum_for(__callee__) { size if respond_to?(:size) } unless block_given?\n\n {}.merge(\n each_with_object(Hash.new { |hash, key| hash[key] = [] }) do |element, result|\n key = yield element\n result[key] << element\n end\n )\nend\n</code></pre>\n<h1><a href=\"https://ruby-doc.org/core/Hash.html#method-i-fetch\" rel=\"nofollow noreferrer\"><code>Hash#fetch</code></a></h1>\n<p>There is actually a better option than using a <code>default_proc</code>. <code>Hash#fetch</code> will get the value corresponding to the key if the key exists and otherwise return a value of our choosing:</p>\n<pre class=\"lang-rb prettyprint-override\"><code>def gruppiere\n return enum_for(__callee__) { size if respond_to?(:size) } unless block_given?\n\n each_with_object({}) do |element, result|\n key = yield element\n result[key] = result.fetch(key, []) << element\n end\nend\n</code></pre>\n<h1>Monkey patching core classes / modules</h1>\n<p>Monkey patching core modules is generally frowned upon. <em>If</em> you do it, it is good practice to put your monkey patches in a separate mixin with a clear name, and mix that into the class or module you want to monkey patch. That way, it shows up in the inheritance chain, and people can use the name in the inheritance chain to make a guess at the filename, when they find this strange method in their array that they have no idea where it comes from.</p>\n<h1>Refinements</h1>\n<p>NOTE! This advice is controversial.</p>\n<p>When monkey patching, it is a good idea to wrap your monkey patch into a <em>Refinement</em>, so that consumers can only pull it in when they need it, and it doesn't pollute other parts of your code.</p>\n<p>Unfortunately, most Ruby implementations don't implement Refinements, so as nice as the benefits are, it essentially makes your code non-portable.</p>\n<h1>The Result</h1>\n<p>If we put all of the above together, we end up with something roughly like this:</p>\n<pre class=\"lang-rb prettyprint-override\"><code>module EnumerableGruppiereExtension\n def gruppiere\n return enum_for(__callee__) { size if respond_to?(:size) } unless block_given?\n\n each_with_object({}) do |element, result|\n key = yield element\n result[key] = result.fetch(key, []) << element\n end\n end\nend\n\nmodule EnumerableWithGruppiere\n refine Enumerable do\n include EnumerableGruppiereExtension\n end\nend\n\nusing EnumerableWithGruppiere\n\nputs [1, 2, 3, 4].gruppiere(&:even?)\n#=> { false => [1, 3], true => [2, 4] }\n</code></pre>\n<h1>Addendum: Functional Programming</h1>\n<p>You tagged your question with <a href=\"/questions/tagged/functional-programming\" class=\"post-tag\" title=\"show questions tagged 'functional-programming'\" rel=\"tag\">functional-programming</a>, but there is nothing functional about your code. There's looping, there is mutation, there are side-effects.</p>\n<p>It is, however, not easy to program in a functional way in Ruby. Neither the core and standard library data structures nor the core and standard library algorithms really lend themselves to Functional Programming.</p>\n<p>Here is a purely functional version that does not use mutation, side-effects, or looping:</p>\n<pre class=\"lang-rb prettyprint-override\"><code>def gruppiere\n return enum_for(__callee__) { size if respond_to?(:size) } unless block_given?\n\n inject({}) do |result, element|\n key = yield element\n result.merge({ key => result.fetch(key, []) + [element] })\n end\nend\n</code></pre>\n<p>Now, you might ask yourself: that actually doesn't look that bad. Why did I say that Ruby is not amenable to Functional Programming?</p>\n<p>The reason for this is <em>performance</em>.</p>\n<p>Because <code>Hash</code> and <code>Array</code> are <em>mutable</em>, operations such as <code>Hash#merge</code> and <code>Array#+</code> can only be implemented by <em>copying the entire data structure</em>. Whereas if <code>Hash</code> and <code>Array</code> were <em>immutable</em>, as they are in a collections library for a functional language, these operations could be implemented by what is called <em>structural sharing</em>, which means that <code>Hash#merge</code> and <code>Array#+</code> would not return a full copy of the original but rather would return only the <em>updated</em> data and a reference to the old version. This is much more efficient.</p>\n<p>For example, here is what the same code would look like in <a href=\"https://scala-lang.org/\" rel=\"nofollow noreferrer\">Scala</a>:</p>\n<pre class=\"lang-scala prettyprint-override\"><code>def [A, B](seq: Iterable[A]).gruppiere(classifier: A => B): Map[B, Iterable[A]] = \n seq.foldLeft(Map.empty[B, IndexedSeq[A]]) {\n (result, element) => {\n val key = classifier(element)\n result updated(key, result.getOrElse(key, IndexedSeq.empty[A]) :+ element)\n }\n }\n\nIterable(1, 2, 3).gruppiere { _ % 2 == 0 }\n//=>Map(false -> Iterable(1, 3), true -> Iterable(2))\n</code></pre>\n<p>As you can see, it looks more or less identical. Some names are different (e.g. <code>foldLeft</code> instead of <code>inject</code>, <code>getOrElse</code> instead of <code>fetch</code>, etc.), and there are some static type annotations. But other than that, it is the same code. The main difference is in the performance: <code>Map.updated</code> does not copy the map, it returns a map which shares all its data except the one updated key-value-pair with the original. The same applies to <code>IndexedSeq.:+</code> (an alias for <code>IndexedSeq.append</code>).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-01T09:15:28.977",
"Id": "477329",
"Score": "0",
"body": "I know that votes are anonymous, and for a good reason, but if the downvoter would like to explain what is \"not useful\" about my answer, I would be happy to improve it! (Especially since it seems from the voting history that the person in question upvoted my answer, then a week later reversed their decision, which I assume means that they found a flaw in my answer after analyzing it.)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-23T14:08:22.327",
"Id": "242800",
"ParentId": "242618",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "242800",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-20T09:14:08.040",
"Id": "242618",
"Score": "1",
"Tags": [
"ruby",
"functional-programming"
],
"Title": "Ruby Exercise: Implement your own \"#group_by\" method"
}
|
242618
|
<p>Hi I am working on a complex application and currently adding two additional properties to objects that match the condition and returning it back. I was able to achieve the expected output, but just wanted to know if there is any other way which is more efficient than what I have tried.</p>
<p>Step 1 : Filtering the array to get only car objects.</p>
<p>Step 2 : Add firstlayer and lastlayer prop to car objects</p>
<p>Step 3 : </p>
<ul>
<li>If it is first car object in the filtered array then mark firstlayer
as true. If it is last car object in the filtered array then mark
lastlayer as true.</li>
</ul>
<p>Step 4 : concat it with the other non-car objects </p>
<p><a href="https://i.stack.imgur.com/Kfwr3.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Kfwr3.png" alt="enter image description here"></a></p>
<p>Original array:</p>
<pre><code>[{
id: 10,
name: "Truck",
status: "Cancelled"
}, {
id: 11,
name: "Bus",
status: "Approved"
}, {
id: 12,
name: "Car1",
status: "Approved"
}, {
id: 19,
name: "Car2",
status: "Cancelled"
}, {
id: 13,
name: "Car3",
status: "Cancelled"
}]
</code></pre>
<p>Expected array:</p>
<pre><code>[{
id: 10,
name: "Truck",
status: "Cancelled"
}, {
id: 11,
name: "Bus",
status: "Approved"
}, {
id: 12,
isFirstLayer: true,
isLastLayer: false,
name: "Car1",
status: "Approved"
}, {
id: 19,
isFirstLayer: false,
isLastLayer: false,
name: "Car2",
status: "Cancelled"
}, {
id: 13,
isFirstLayer: false,
isLastLayer: true,
name: "Car3",
status: "Cancelled"
}]
</code></pre>
<p>This is the code I have tried</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var array = [
{
"name": "Truck",
"status": "Cancelled",
"id": 10
},
{
"name": "Bus",
"status": "Approved",
"id": 11
},
{
"name": "Car1",
"status": "Approved",
"id": 12
},
{
"name": "Car2",
"status": "Cancelled",
"id": 19
},
{
"name": "Car3",
"status": "Cancelled",
"id": 13
}
];
var i=0;
var arrayLength=array.length;
var newArray = array.filter(function(a) {
if((a.name !='Bus'&&a.name!='Truck'))
{
if(i==0){
a.isFirstLayer=true;
a.isLastLayer=false;
}else if(i==arrayLength-i-1){
a.isFirstLayer=false;
a.isLastLayer=true;
} else{
a.isFirstLayer=false;
a.isLastLayer=false;
}
i++;
};
return a
});
console.log(newArray);</code></pre>
</div>
</div>
</p>
<p><a href="https://jsfiddle.net/fierce_trailblazer/q2uvf06r/24/" rel="nofollow noreferrer">https://jsfiddle.net/fierce_trailblazer/q2uvf06r/24/</a></p>
<p>Any suggestions to improve the code would be helpful</p>
|
[] |
[
{
"body": "<p>Some things I noticed:</p>\n\n<p><code>Array.prototype.filter</code> is intended to be used when you want to filter out elements from an array and construct a new array from certain elements of the other array, for example:</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>const arr = [0, 1, 2, 3, 4];\nconst evens = arr.filter(num => num % 2 === 0);\nconsole.log(evens);</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p>If you're not taking elements out to make a new array, then <code>.filter</code> isn't appropriate. If you're just looking to <em>iterate</em>over an array and perform side-effects (like mutate certain elements), use <code>Array.prototype.forEach</code> or <code>for..of</code> instead.</p>\n\n<p>That said - I think using <code>filter</code> <em>would</em> be the best way to approach this problem, by separating out the cars from non-cars. More on that later.</p>\n\n<p>You have</p>\n\n<pre><code>if((a.name !='Bus'&&a.name!='Truck')) \n</code></pre>\n\n<pre><code>if(i==0){\n</code></pre>\n\n<pre><code>}else if(i==arrayLength-i-1){\n</code></pre>\n\n<p>It would be better to never use sloppy comparison with <code>==</code> and <code>!=</code> - instead, use strict comparison with <code>===</code> and <code>!==</code>. The problem with sloppy comparison is that it has <a href=\"https://stackoverflow.com/q/359494\">so many weird rules</a> a developer has to memorize in order to be confident in its proper usage. See <a href=\"https://i.stack.imgur.com/35MpY.png\" rel=\"nofollow noreferrer\">this image</a>. If you're comparing items of the same type, using strict comparison instead will work just fine. (When comparing items of different types, you can check their types and then explicitly cast to the same type if needed, then perform the comparison.)</p>\n\n<p>I'd also recommend adding spaces between operators - it improves code readability. (Many decent IDEs can do this automatically.) Eg, compare</p>\n\n<pre><code>if((a.name !='Bus'&&a.name!='Truck')) \n</code></pre>\n\n<p>to</p>\n\n<pre><code>if (a.name !== 'Bus' && a.name !== 'Truck')\n</code></pre>\n\n<p>(There's no need for the extra <code>()</code>s around the condition)</p>\n\n<p>An even better method might be to check whether the item's name starts with <code>Car</code>:</p>\n\n<pre><code>if (a.name.startsWith('Car'))\n</code></pre>\n\n<p>You're missing a semicolon with <code>return a</code>. Occasionally forgetting semicolons can <a href=\"https://stackoverflow.com/questions/2846283/what-are-the-rules-for-javascripts-automatic-semicolon-insertion-asi\">result in confusing bugs</a>, especially if you aren't an expert. Consider using a linter to automatically prompt you to fix these sorts of potential mistakes.</p>\n\n<p>If I were approaching this problem, I'd prefer to separate out the cars into their own array. This separation can be achieved concisely with <code>Array.prototype.filter</code>. Then, iterate over the cars, and add the <code>isFirstLayer</code> and <code>isLastLayer</code> properties (as <code>false</code>) to each car. Then, take the <em>first</em> car and set its <code>isFirstLayer</code> to <code>true</code>. Similarly, take the <em>last</em> car and set its <code>isLastLayer</code> to <code>true</code>:</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>var array = [{\n \"name\": \"Truck\",\n \"status\": \"Cancelled\",\n \"id\": 10\n },\n {\n \"name\": \"Bus\",\n \"status\": \"Approved\",\n \"id\": 11\n },\n {\n \"name\": \"Car1\",\n \"status\": \"Approved\",\n \"id\": 12\n },\n {\n \"name\": \"Car2\",\n \"status\": \"Cancelled\",\n \"id\": 19\n },\n {\n \"name\": \"Car3\",\n \"status\": \"Cancelled\",\n \"id\": 13\n }\n];\nconst cars = array.filter(item => item.name.startsWith('Car'));\nfor (const car of cars) {\n car.isFirstLayer = false;\n car.isLastLayer = false;\n}\ncars[0].isFirstLayer = true;\ncars[cars.length - 1].isLastLayer = true;\nconsole.log(array);</code></pre>\r\n</div>\r\n</div>\r\n</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-06T05:48:25.853",
"Id": "477848",
"Score": "0",
"body": "Thanks for the review :)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-20T12:53:45.293",
"Id": "242636",
"ParentId": "242622",
"Score": "2"
}
},
{
"body": "<p>It may be a better idea to use a <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce\" rel=\"nofollow noreferrer\">reducer</a> to initially add the properties to a subset of the elements of the array. Finally you can change the last element from the new Array with a property <code>isLastLayer</code>. I used <code>Array.find</code> within the reducer lambda and a custom function <code>findLast</code> for finding the last array-element with property <code>isLastLayer</code>.</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"true\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code snippet-currently-hidden\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>const result = document.querySelector(\"#result\");\nconst log = (...txt) => result.textContent += txt.join(\"\\n\") + \"\\n\";\n\n// moved to function, so the relevant code is more visible\nconst array = getTestArray();\n\n// find the last element using the predicate lambda\nconst findLast = (array, predicate) => {\n for (let i = array.length - 1; i >= 0; --i) {\n if (predicate(array[i])) {\n return array[i];\n }\n }\n};\n\n// reduce the values, adding the layer props to \n// all elements where the name does not start \n// with 'bus' or 'truck'. Use Array.find within the \n// accumulated array to determine if isFirstLayer\n// is already in the set of elements\nlet newArray = array.reduce((acc, value) => {\n if (/^(bus|truck)/i.test(value.name)) {\n return [...acc, value];\n }\n const isFirst = !acc.find(el => \"isFirstLayer\" in el);\n value = { ...value,\n isFirstLayer: isFirst,\n isLastLayer: false\n };\n return [...acc, value];\n}, []);\n\n// use findLast to find the last element with\n// a property 'isLastLayer' in the array, and \n// change its value\nfindLast(newArray, el => \"isLastLayer\" in el).isLastLayer = true;\n\n// let's see if it worked\nlog(JSON.stringify(newArray, null, 2));\n\nfunction getTestArray() {\n return [{\n \"name\": \"Truck\",\n \"status\": \"Cancelled\",\n \"id\": 10\n },\n {\n \"name\": \"Bus\",\n \"status\": \"Approved\",\n \"id\": 11\n },\n {\n \"name\": \"Car1\",\n \"status\": \"Approved\",\n \"id\": 12\n },\n {\n \"name\": \"Car2\",\n \"status\": \"Cancelled\",\n \"id\": 19\n },\n {\n \"name\": \"Car3\",\n \"status\": \"Cancelled\",\n \"id\": 13\n }\n ];\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><pre id=\"result\"></pre></code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p>It can also be done without the extra <code>findLast</code> function</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"true\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code snippet-currently-hidden\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>const result = document.querySelector(\"#result\");\nconst log = (...txt) => result.textContent += txt.join(\"\\n\") + \"\\n\";\nconst array = getTestArray();\nlet accumulator = {\n newArr: [], \n // track first/last\n firstLayerSet: false,\n lastLastLayer: null\n};\nconst addPropsReducer = (acc, value, i) => {\n if (/^(bus|truck)$/i.test(value.name)) {\n return {\n newArr: [...acc.newArr, value]\n };\n }\n value = { ...value,\n isFirstLayer: !acc.firstLayerSet,\n isLastLayer: false\n };\n return {\n ...acc,\n newArr: [...acc.newArr, value],\n firstLayerSet: true,\n lastLayerIndex: i\n };\n};\n\nlet newArray = array.reduce(addPropsReducer, accumulator);\nnewArray.newArr[newArray.lastLayerIndex].isLastLayer = true;\n\n// ditch tracking values\nnewArray = newArray.newArr;\n\nlog(JSON.stringify(newArray, null, 2));\n\nfunction getTestArray() {\n return [{\n \"name\": \"Truck\",\n \"status\": \"Cancelled\",\n \"id\": 10\n },\n {\n \"name\": \"Bus\",\n \"status\": \"Approved\",\n \"id\": 11\n },\n {\n \"name\": \"Car1\",\n \"status\": \"Approved\",\n \"id\": 12\n },\n {\n \"name\": \"Car2\",\n \"status\": \"Cancelled\",\n \"id\": 19\n },\n {\n \"name\": \"Car3\",\n \"status\": \"Cancelled\",\n \"id\": 13\n }\n ];\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><pre id=\"result\"></pre></code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p>Play with this code in <a href=\"https://jsfiddle.net/KooiInc/Ltyknpwg/\" rel=\"nofollow noreferrer\">jsFiddle</a>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-06T05:48:40.330",
"Id": "477849",
"Score": "0",
"body": "Thanks for the review :)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-20T13:30:08.827",
"Id": "242640",
"ParentId": "242622",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "242636",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-20T09:51:49.373",
"Id": "242622",
"Score": "1",
"Tags": [
"javascript",
"array"
],
"Title": "Filtering and adding additional properties to array of objects"
}
|
242622
|
<p>i'm exercising <strong>Java multithreading</strong> on an example of simple banking funcions. The programm is able to perform multiple transactions at once on different threads.<br>All accounts transfer money to the following account, the last transferes money to the first. <br><br> I want some feedback so I can improve my coding standards and practices, specifically on multithreading.</p>
<p>Banking class:</p>
<pre><code>import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ThreadLocalRandom;
public class BankSystem
{
public static void main(String[] args)
{
List<Account> accounts = new ArrayList<>();
for (int i = 0; i < 5; i++)
{
accounts.add(new Account("user " + i, i, 100));
}
for (int i = 0; i < 5; i++)
{
if (i != 4)
{
accounts.get(i).setTransTarget(accounts.get(i + 1));
} else
{
accounts.get(i).setTransTarget(accounts.get(0));
}
accounts.get(i).start();
}
try
{
for (int i = 0; i < 5; i++)
{
accounts.get(i).join();
}
} catch (InterruptedException e)
{
e.printStackTrace();
}
accounts.forEach(n -> System.out.println(n.getBalance()));
}
public static void transactMoney(Account sender, Account receiver, float amountToTransfer)
{
Account firstLock = sender;
Account secondLock = receiver;
if (sender.accountNumber < receiver.accountNumber)
{
firstLock = receiver;
secondLock = sender;
}
System.out.println(Thread.currentThread().getName() + " waiting for first lock on user " + firstLock.accountNumber);
synchronized (firstLock)
{
System.out.println(Thread.currentThread().getName() + " got first lock on user " + firstLock.accountNumber);
System.out.println(Thread.currentThread().getName() + " waiting for second lock on user " + secondLock.accountNumber);
synchronized (secondLock)
{
System.out.println(Thread.currentThread().getName() + " got second lock on user " + secondLock.accountNumber);
sender.subtractBalance(amountToTransfer);
int delayTime = ThreadLocalRandom.current().nextInt(100, 600);
try
{
Thread.sleep(delayTime);
} catch (InterruptedException e)
{
e.printStackTrace();
}
receiver.addBalance(amountToTransfer);
System.out.println("\t" + Thread.currentThread().getName() + " withdraw $" + amountToTransfer);
}
System.out.println("\t" + Thread.currentThread().getName() + " released lock on user " + firstLock.accountNumber + " and " + secondLock.accountNumber);
}
}
}
</code></pre>
<p>Account class:</p>
<pre><code>public class Account extends Thread
{
volatile float balance;
Account target;
int accountNumber;
public Account(String name, int accountNumber, int balance)
{
super(name);
this.accountNumber = accountNumber;
this.balance = balance;
}
@Override
public void run()
{
for (int i = 0; i < 2; i++)
{
BankSystem.transactMoney(this, target, 100);
}
}
public void setTransTarget(Account target)
{
this.target = target;
}
private void setBalance(float balance)
{
this.balance = balance;
}
public float getBalance()
{
return balance;
}
public void addBalance(float balance)
{
setBalance(getBalance() + balance);
}
public void subtractBalance(float balance)
{
setBalance(getBalance() - balance);
}
}
</code></pre>
<p>Output of Console:</p>
<pre><code>user 4 waiting for first lock on user 4
user 0 waiting for first lock on user 1
user 1 waiting for first lock on user 2
user 2 waiting for first lock on user 3
user 3 waiting for first lock on user 4
user 1 got first lock on user 2
user 2 got first lock on user 3
user 0 got first lock on user 1
user 4 got first lock on user 4
user 1 waiting for second lock on user 1
user 2 waiting for second lock on user 2
user 0 waiting for second lock on user 0
user 4 waiting for second lock on user 0
user 0 got second lock on user 0
user 0 withdraw $100.0
user 4 got second lock on user 0
user 0 released lock on user 1 and 0
user 0 waiting for first lock on user 1
user 1 got second lock on user 1
user 4 withdraw $100.0
user 4 released lock on user 4 and 0
user 4 waiting for first lock on user 4
user 3 got first lock on user 4
user 3 waiting for second lock on user 3
user 1 withdraw $100.0
user 1 released lock on user 2 and 1
user 0 got first lock on user 1
user 1 waiting for first lock on user 2
user 2 got second lock on user 2
user 0 waiting for second lock on user 0
user 0 got second lock on user 0
user 0 withdraw $100.0
user 0 released lock on user 1 and 0
user 2 withdraw $100.0
user 2 released lock on user 3 and 2
user 1 got first lock on user 2
user 2 waiting for first lock on user 3
user 3 got second lock on user 3
user 1 waiting for second lock on user 1
user 1 got second lock on user 1
user 1 withdraw $100.0
user 1 released lock on user 2 and 1
user 3 withdraw $100.0
user 3 released lock on user 4 and 3
user 3 waiting for first lock on user 4
user 2 got first lock on user 3
user 4 got first lock on user 4
user 2 waiting for second lock on user 2
user 4 waiting for second lock on user 0
user 2 got second lock on user 2
user 4 got second lock on user 0
user 2 withdraw $100.0
user 2 released lock on user 3 and 2
user 4 withdraw $100.0
user 4 released lock on user 4 and 0
user 3 got first lock on user 4
user 3 waiting for second lock on user 3
user 3 got second lock on user 3
user 3 withdraw $100.0
user 3 released lock on user 4 and 3
user 0 balance 100.0
user 1 balance 100.0
user 2 balance 100.0
user 3 balance 100.0
user 4 balance 100.0
</code></pre>
|
[] |
[
{
"body": "<p>Hello and welcome to code review! I hope you don't mind me being direct, but your class structure is simply a mess. We need to fix that before we go to the concurrency control.</p>\n\n<p>Your <code>Account</code> is both an account and a single transaction from that account to some other account. This violates the <a href=\"https://en.wikipedia.org/wiki/Single-responsibility_principle\" rel=\"nofollow noreferrer\">single responsibility principle</a>. It also makes it impossible to transfer money from one account to two other accounts simultaneously. You need to remove the transaction responsibility from the Account class and have the account class only contain information that is relevant to the state of that account only. Optimally the <code>Account</code> would only hold the account balance and the account number.</p>\n\n<p>The account should not be a <code>Thread</code>. Accounts are not entities that act by themselves. They are just data containers. Instead you should have several instances of a <code>TestClient</code> class running concurrently as threads and a <code>TestRunner</code> that sets up and starts the clients.</p>\n\n<p><code>TestRunner</code> should initialize a single <code>AccountController</code> object and pass that reference to the <code>TestClients</code> during their construction. The <code>AccountController</code> provides the account transfer operation for transfering funds from one accout number to another.</p>\n\n<pre><code>public void transferFunds(String debtorIban, String creditorIban, int amount);\n</code></pre>\n\n<p><code>AccountController</code> manages acquiring write locks to accounts for each transaction and the debiting and crediting of funds from accounts. In the simplest example you don't need a class to represent a transaction. The parameters to the transferFunds method provide all the needed information.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-20T12:41:38.783",
"Id": "476139",
"Score": "0",
"body": "Thank you for your honest answer, I'm going to try to Implement it like you described. What do you think of my locking logic that I use atm ? Should I use the same in transferFunds ?"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-20T12:07:16.643",
"Id": "242632",
"ParentId": "242623",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-20T09:54:56.480",
"Id": "242623",
"Score": "2",
"Tags": [
"java",
"multithreading"
],
"Title": "Java multithreaded withdrawal and deposit banking"
}
|
242623
|
<p>I needed to draw border element according to scroll amount.
I made it work but I am not sure about optimization and performance.
There may have a better way? I am open to suggestion</p>
<p>you can see it in action here: <a href="https://codepen.io/a_prods/pen/PoPXQee" rel="nofollow noreferrer">enter link description here</a></p>
<p>here my js:</p>
<p>Thanks</p>
<pre><code>var el = document.querySelectorAll(".animateBorder");
document.addEventListener("scroll", (event) => {
for (var i = 0; i < el.length; i++) {
var mHeight = window.innerHeight / 2 || document.documentElement.clientHeight / 2;
var currentPos = document.documentElement.scrollTop + mHeight;
var elTop = el[i].offsetTop;
var elHeight = el[i].offsetHeight;
var count = el[i].dataset.count;
var partLenght = elHeight / count;
var elEnd = elTop + elHeight;
var spans = el[i].getElementsByTagName("span");
for (var s = 0; s < spans.length; s++) {
var offset = s * partLenght;
var _0 = elTop + offset;
var _100 = _0 + partLenght;
var direction = spans[s].dataset.direction;
// console.log("s", s);
// console.log("partLenght", partLenght);
// console.log("elTop", elTop);
// console.log("offset", offset);
// console.log("currentPos", currentPos);
// console.log("_0", _0);
// console.log("_100", _100);
if (_0 <= currentPos && currentPos <= _100) {
console.log("spans[s]", s);
console.log("direction", direction);
if (direction == "horizontal") {
spans[s].style.width = Math.round(((currentPos - _0) * 100) / partLenght) + "%";
}
if (direction == "vertical") {
spans[s].style.height = Math.round(((currentPos - _0) * 100) / partLenght) + "%";
}
}
if (currentPos >= _100) {
if (direction == "horizontal") {
spans[s].style.width = "100%";
}
if (direction == "vertical") {
spans[s].style.height = "100%";
}
}
if (currentPos <= _0) {
if (direction == "horizontal") {
spans[s].style.width = "0%";
}
if (direction == "vertical") {
spans[s].style.height = "0%";
}
}
}
}
});
</code></pre>
|
[] |
[
{
"body": "<p>When you have a collection that you want to iterate over, and you don't particularly care about the index of each element, iterating by going through the collection's <code>.length</code> and manually incrementing an index counter anyway is a bit tedious and ugly. Collections almost always have iterators or a <code>forEach</code> method - it's nice to use those instead, when possible. In other words, rather than</p>\n\n<pre><code>var el = document.querySelectorAll(\".animateBorder\");\nfor (var i = 0; i < el.length; i++) {\n // lots of lines referencing el[i]\n</code></pre>\n\n<p>you may use</p>\n\n<pre><code>const borderContainers = document.querySelectorAll(\".animateBorder\");\nfor (const borderContainer of borderContainers) {\n // lots of lines referencing borderContainer\n</code></pre>\n\n<p>Don't call the collection <code>el</code> - I, and most other developers, would ordinarily expect a variable named <code>el</code> to contain an <em>element</em>. Since what you have is a <em>collection</em> of elements, it would be good to be precise and make that clearer with the variable name, else a script reader or writer is more likely to get confused by it and make a mistake as a result.</p>\n\n<p>You define the <code>event</code> argument, but never use it:</p>\n\n<pre><code>document.addEventListener(\"scroll\", (event) => {\n</code></pre>\n\n<p>If you're not going to use an argument, it would be better to leave it out entirely, that way there's one less variable readers of the script have to be mindful of:</p>\n\n<pre><code>document.addEventListener(\"scroll\", () => {\n</code></pre>\n\n<p><code>scroll</code> events can sometimes fire <em>very</em> frequently (like 50 in a second or two):</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"true\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code snippet-currently-hidden\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>const div = document.querySelector('div');\nwindow.addEventListener('scroll', () => {\n div.textContent = Number(div.textContent) + 1;\n});</code></pre>\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>body {\n height: 2000px;\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><div>0</div></code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p>Given these sorts of events, and given that you might be iterating over a non-trivial number of <code>animateBorder</code> elements, <em>and</em> each of those <code>animateBorder</code>'s descendant <code><span></code>s, you might be right to consider the performance implications of your code.</p>\n\n<p>One way to improve would be to retrieve values only when necessary. For example, rather than doing <code>window.innerHeight / 2 || document.documentElement.clientHeight / 2;</code> <em>for every scroll</em>, and also <em>for every <code>animateBorder</code> item that exists</em> during that scroll event, you could retrieve the value just <em>once</em>, on pageload. You can also retrieve the <code>scrollTop</code> when a scroll event occurs, rather than <em>for every animateBorder element</em> in a scroll event. Another option would be to add a small debouncer - only iterate through the elements and change their styles once, say, 50ms has passed since the last style change has taken place.</p>\n\n<p>You define</p>\n\n<pre><code>partLenght\n</code></pre>\n\n<p>Spelling matters in programming. Misspelled words are a very easy source of bugs. Use <code>partLength</code> instead.</p>\n\n<p>Variables named <code>_0</code> and <code>_100</code> are pretty weird - it doesn't look like a normal variable name, but almost like a numeric literal with the new <code>_</code> optional separators, eg:</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>console.log(\n 1_000_000\n);</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p>Better to call the variables something easily understandable with English words instead, maybe <code>spanTopOffset</code> and <code>spanBotOffset</code>.</p>\n\n<p>You have</p>\n\n<pre><code>if (direction == \"horizontal\") {\n</code></pre>\n\n<p>and a few other uses of <code>==</code> as well. Always use strict equality with <code>===</code> and <code>!==</code> instead - otherwise, if you use loose equality, you'll be requiring everyone that reads the code (including you) to be sure of all of the <a href=\"https://i.stack.imgur.com/35MpY.png\" rel=\"nofollow noreferrer\">weird type coercion rules</a> invoked by loose equality.</p>\n\n<p>Since it's 2020, best to write <em>at least</em> in ES2015 syntax (which you're already partially doing with <code>=></code>). If you're going to use ES2015 syntax, use it everywhere - never use <code>var</code>, since it has too many problems. Define variables with <code>const</code> instead (or <code>let</code> if you have no choice but to reassign the variable).</p>\n\n<p>To clarify the logic in the comparisons against <code>currentPos</code>, consider using <code>else-if</code> and <code>else</code> instead, to make it clear that exactly one of the conditions may be fulfilled. I'd also add comments indicating what exactly each condition means.</p>\n\n<p>Or, an alternative would be to simply calculate the percentage required regardless, then constrain its values to between 0 and 100 - then set the width or height to that constrained percentage:</p>\n\n<pre><code>// 0 when current position before or at top of span section\n// between 0 and 100 when current position is between top and bottom of span section\n// 100 when current position is after bottom of span section\nconst percentScrolledThisElement = Math.min(\n 100,\n Math.max(\n 0,\n Math.round(((currentPos - spanTopOffset) * 100) / partLength)\n )\n);\nif (direction === \"horizontal\") {\n span.style.width = percentScrolledThisElement + \"%\";\n} else {\n span.style.height = percentScrolledThisElement + \"%\";\n}\n</code></pre>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"true\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code snippet-currently-hidden\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>const borderContainers = document.querySelectorAll(\".animateBorder\");\n// If screen size changes, you can add a resize event to reassign this:\nconst mHeight = window.innerHeight / 2 || document.documentElement.clientHeight / 2;\ndocument.addEventListener(\"scroll\", () => {\n const currentPos = document.documentElement.scrollTop + mHeight;\n for (const borderContainer of borderContainers) {\n const { offsetTop, offsetHeight } = borderContainer;\n const { count } = borderContainer.dataset;\n const partLength = offsetHeight / count;\n const elEnd = offsetTop + offsetHeight;\n borderContainer.querySelectorAll('span').forEach((span, i) => {\n const offset = i * partLength;\n const spanTopOffset = offsetTop + offset;\n const spanBotOffset = spanTopOffset + partLength;\n const { direction } = span.dataset;\n \n // 0 when current position before or at top of span section\n // between 0 and 100 when current position is between top and bottom of span section\n // 100 when current position is after bottom of span section\n const percentScrolledThisElement = Math.min(\n 100,\n Math.max(\n 0,\n Math.round(((currentPos - spanTopOffset) * 100) / partLength)\n )\n );\n if (direction === \"horizontal\") {\n span.style.width = percentScrolledThisElement + \"%\";\n } else {\n span.style.height = percentScrolledThisElement + \"%\";\n }\n });\n }\n});</code></pre>\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>#lipsum {\n max-width: 680px;\n margin: 0 auto;\n}\n\n.animateBorder {\n display: flex;\n outline: 1px solid red;\n height: 300px;\n width: 50%;\n align-items: center;\n justify-content: center;\n position: relative;\n}\n\nspan {\n display: block;\n background-color: green;\n position: absolute;\n}\nspan.b-top {\n top: 0;\n width: 0;\n height: 2px;\n}\nspan.b-top.d-right {\n left: 0;\n}\nspan.b-top.d-left {\n right: 0;\n}\nspan.b-right {\n right: 0%;\n height: 0;\n width: 2px;\n}\nspan.b-right.d-up {\n bottom: 0;\n}\nspan.b-right.d-down {\n top: 0%;\n}\nspan.b-bottom {\n top: 100%;\n width: 0;\n height: 2px;\n}\nspan.b-bottom.d-right {\n left: 0;\n}\nspan.b-bottom.d-left {\n right: 0;\n}\nspan.b-left {\n left: 0%;\n height: 0;\n width: 2px;\n}\nspan.b-left.d-up {\n bottom: 0;\n}\nspan.b-left.d-down {\n top: 0%;\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><div id=\"lipsum\">\n<p>\nLorem ipsum dolor sit amet, consectetur adipiscing elit. Nam lacinia mi eget efficitur pretium. Aliquam neque mauris, commodo sed leo quis, rutrum rhoncus dui. Nulla in sollicitudin magna. Aliquam at fermentum metus. Integer ac diam id urna placerat ornare. Integer consequat condimentum sem, quis finibus mi hendrerit non. Morbi quis fringilla purus, consequat imperdiet mauris. Sed dictum pretium tellus, eget euismod sem.\n</p>\n<p>\nMorbi suscipit magna nibh, vel tempus justo fermentum non. Nullam metus sapien, viverra quis viverra ac, ullamcorper ut neque. Maecenas eget orci quis libero aliquam gravida id in ligula. Mauris molestie consectetur erat, sed pharetra magna. Fusce consequat luctus libero sit amet posuere. Aliquam ultricies purus a nunc molestie elementum. Aliquam erat volutpat.\n</p>\n <div class=\"animateBorder\" data-count=\"3\">\n <span data-direction=\"horizontal\" class=\"b-top d-right\"></span>\n <span data-direction=\"vertical\" class=\"b-right d-down\"></span>\n <span data-direction=\"horizontal\" class=\"b-bottom d-left\"></span>\n top,right,bottom</div>\n <div class=\"animateBorder\" data-count=\"2\">\n <span data-direction=\"vertical\" class=\"b-left d-down\"></span>\n <span data-direction=\"horizontal\" class=\"b-bottom d-right\"></span>\n left,bottom</div>\n<p>\nNam at ligula leo. Integer eu ante vitae nisi pellentesque feugiat in vitae neque. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia curae; Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum ante odio, placerat eu tincidunt in, luctus a diam. Aenean sed elit nunc. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur a ullamcorper orci. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia curae; Proin finibus elit sed urna tempus, in volutpat ipsum volutpat.\n</p>\n<p>\nPraesent nunc elit, aliquam id sagittis in, ornare a dui. Vestibulum aliquam sem sit amet risus porttitor, ornare fringilla ex tristique. Vivamus quis augue id enim placerat finibus. In ullamcorper, tortor eu finibus euismod, sapien felis eleifend urna, feugiat convallis metus purus sed ante. Pellentesque volutpat egestas mi, in luctus mauris. Suspendisse pellentesque sed enim eu maximus. Donec vestibulum orci nunc, sed egestas mauris iaculis vel. Aenean malesuada bibendum turpis eget lobortis. Sed et ex non lorem varius interdum. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Praesent ultrices vehicula pretium. Aliquam mollis dolor ut commodo viverra. Nam nibh mauris, hendrerit et ipsum sed, aliquet auctor lacus. Maecenas tincidunt neque sed enim facilisis sagittis.\n</p>\n <div class=\"animateBorder\" data-count=\"3\">\n <span data-direction=\"horizontal\" class=\"b-top d-right\"></span>\n <span data-direction=\"vertical\" class=\"b-right d-down\"></span>\n <span data-direction=\"horizontal\" class=\"b-bottom d-left\"></span>\n top,right,bottom</div>\n<p>\nUt ornare, metus eu consectetur pulvinar, mi ipsum egestas nibh, et rhoncus odio nulla quis massa. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Duis tincidunt turpis nunc, vitae pretium velit condimentum non. Nunc eleifend ipsum porttitor ligula mattis faucibus. Etiam ac neque vitae nibh finibus lobortis. Morbi laoreet auctor metus, quis sagittis lectus posuere at. Aenean quis gravida lorem. Mauris aliquam, purus nec congue blandit, erat ligula ornare erat, eu malesuada augue nunc in dolor. Mauris vestibulum condimentum suscipit. Suspendisse id nibh sed ex ornare tempus vel vitae velit. Quisque sem enim, sodales nec leo et, fermentum finibus lacus. Suspendisse sit amet rutrum arcu.\n</p>\n<p>\nMorbi nec efficitur nibh, a condimentum justo. Nunc enim nunc, gravida sed convallis eget, pulvinar nec ex. Pellentesque vitae feugiat massa. Phasellus fermentum orci eu commodo pulvinar. Ut eget porttitor purus. Nam posuere, tortor eleifend condimentum fermentum, lacus quam luctus diam, id congue tortor tortor vel nulla. Vivamus iaculis luctus mauris et dictum. Curabitur rutrum felis eros, vitae tempus risus pellentesque in.\n</p>\n<p>\nUt tempor feugiat efficitur. Donec cursus sem consequat malesuada malesuada. Curabitur eu turpis quis tortor aliquet lobortis. Aliquam venenatis, nibh at porttitor faucibus, ex tortor viverra elit, vitae egestas ante augue ut tellus. Phasellus venenatis finibus blandit. Suspendisse sit amet eros vitae odio iaculis accumsan. Pellentesque eu nunc dolor. Vestibulum sed massa at orci ornare bibendum.\n</p>\n<p>\nPellentesque nec justo ornare, iaculis turpis ut, vestibulum orci. Integer vel sem sed justo dapibus tempor. Nam hendrerit at sem eu lobortis. Duis id urna ac odio lobortis aliquet. Praesent id porttitor purus. Quisque et nibh in diam accumsan congue ac in velit. Proin libero mauris, interdum sollicitudin mauris id, dignissim ultrices metus. Etiam lacinia augue vitae suscipit euismod. Aliquam pulvinar dui semper lectus accumsan, auctor sagittis erat convallis. Donec faucibus id velit a consectetur.\n</p>\n<p>\nSuspendisse sodales pretium molestie. Morbi vulputate posuere porta. Duis dictum ultrices facilisis. Sed lobortis libero ipsum, eget tempus turpis blandit sed. Curabitur egestas dolor metus, quis iaculis dolor mattis vitae. Donec ac accumsan leo. Aenean maximus sapien eros.\n</p>\n<p>\nPraesent leo risus, sagittis ut sapien eget, convallis aliquam lacus. Donec posuere, mauris nec fringilla dictum, purus velit imperdiet purus, vel aliquam magna dui sit amet urna. Phasellus consequat purus id erat ornare congue quis non neque. Donec odio lectus, tincidunt eu sapien sit amet, fringilla dignissim felis. Nunc blandit vehicula ligula quis suscipit. Aenean nec auctor augue. Integer semper mauris eleifend, luctus est sit amet, hendrerit tellus. Donec at erat nec nulla convallis aliquam. Donec laoreet sit amet arcu at pretium. Sed et consequat augue, eget ultricies massa. Suspendisse luctus nulla at eros elementum fringilla.\n</p>\n<p>\nDuis volutpat erat nec feugiat lacinia. Praesent eget consectetur arcu. Duis fringilla imperdiet libero, eget tincidunt metus tincidunt vel. Suspendisse dignissim quis velit a tempor. Curabitur finibus nec tellus ac aliquet. Cras porttitor efficitur tristique. Maecenas bibendum lacus dui, in mattis tortor aliquam vel. Vestibulum quis tortor semper, consequat nulla eget, lacinia ante. Phasellus ornare vel massa nec eleifend. In aliquet ultricies augue.\n</p>\n<p>\nNam ante augue, condimentum non nulla in, imperdiet dignissim augue. Curabitur sodales ullamcorper turpis, vitae convallis lacus vulputate eget. In mollis ipsum eleifend porttitor egestas. Aenean orci mi, scelerisque euismod justo id, luctus hendrerit tortor. Orci varius natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. In lobortis vitae dui ac efficitur. Nullam iaculis vulputate mi, sed pharetra turpis ultrices non. Pellentesque vitae sodales orci, non vulputate odio. Aliquam eu molestie ex. Maecenas pellentesque lorem est, quis lacinia odio tincidunt nec. Suspendisse pharetra est et magna tincidunt scelerisque.\n</p>\n<p>\nVestibulum eu finibus orci. Sed non egestas felis. Vestibulum et nisi vel metus faucibus mattis. Vivamus at ligula sodales, commodo nisl vitae, pharetra tellus. Phasellus quis magna blandit, suscipit magna ac, interdum sem. Cras facilisis dui eu dolor efficitur, sed commodo velit placerat. Sed tempus tortor sit amet nunc dignissim, sit amet vestibulum mi luctus. Donec eget elit ex. Aenean sodales viverra est. Sed accumsan mauris turpis, eu rhoncus lacus volutpat eu. Curabitur et consectetur felis. Nullam at nulla vestibulum, eleifend quam ac, tristique odio. Phasellus sapien ante, blandit ultricies eros at, semper viverra elit.\n</p>\n<p>\nSed dictum accumsan efficitur. Sed convallis lobortis porttitor. Nullam vitae lorem sed felis semper tincidunt. Mauris ut ipsum purus. Cras ultricies pharetra tellus sit amet accumsan. Quisque sed nulla lorem. Aliquam pulvinar a nisi sit amet semper. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla aliquam scelerisque erat et facilisis.\n</p>\n<p>\nCras ac varius odio, in sollicitudin sapien. Nunc tincidunt vulputate tortor ac euismod. Phasellus dignissim et orci sit amet malesuada. Sed suscipit lectus libero. Maecenas ac aliquam diam, sit amet feugiat nibh. Duis vehicula sem nec tincidunt viverra. Donec non dolor nulla. Curabitur iaculis justo vitae vehicula egestas. Phasellus efficitur volutpat faucibus. Morbi ligula nisl, porttitor nec lectus non, accumsan ornare augue. Nullam imperdiet nisl eu urna bibendum finibus nec vel augue. Phasellus vestibulum dui at interdum sollicitudin. Etiam ac commodo metus. Vestibulum augue metus, commodo vitae felis venenatis, aliquet feugiat mauris. Duis consequat dui enim, in posuere lorem aliquet vitae.\n</p></div></code></pre>\r\n</div>\r\n</div>\r\n</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-20T16:35:34.500",
"Id": "476166",
"Score": "0",
"body": "Thank A LOT!\nThere is a miscalculation of `partLength` it should be \n\n`const partLength = offsetHeight / count;`\ninstead of \n`const partLength = offsetTop / count;`"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-20T14:52:01.243",
"Id": "242645",
"ParentId": "242625",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "242645",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-20T10:22:10.900",
"Id": "242625",
"Score": "3",
"Tags": [
"javascript",
"animation"
],
"Title": "Draw element border according to scroll amount"
}
|
242625
|
<p>I'm trying to give one Controller one operation. However, some Controllers exists of 2 or more operations. I'm not sure whats the best way to structure this part of the app.</p>
<p>For example, I have 2 Controller Functions, each doing their independent thing <br />
<strong>1. attemptGetUserById</strong> (checks input, calls database provider, returns user or error) <br />
<strong>2. attemptVerifyToken</strong> (checks input, tries to verify token, returns valid/invalid)</p>
<p>Then, there is another Controller "<strong>attemptCheckUser</strong>" which is essentially calling <br />
<strong>--> attemptVerifyToken --> if token valid --> attemptGetUserById</strong> <br /> </p>
<p>This Controller is called via a route.</p>
<p>Now, I have 3 variants which might be acceptable.</p>
<p><strong>Variant1</strong> <br />
This variant is the one described above. When the API endpoint is accessed, it will call <strong>attemptCheckUser</strong>, which is calling the 2 other controllers. No logic in Endpoint. </p>
<pre><code>// routes.ts
{
path: '/api/core/users/check',
method: 'post',
handler: [
async ({ headers: { authorization } }: Request, res: Response, next: NextFunction) => {
const { error, user } = await attemptCheckUser(authorization)
if (error) return next(error);
return res.status(200).send(user);
},
],
},
...
// auth.controller.ts
export const attemptVerifyToken = (token: string) => {
if (token) {
const secret = "xxx";
// only provider - no logic in verifyToken
const { error, userId } = verifyToken(token, secret);
if(error) return { error };
return { userId, token };
}
return { error: new HTTP400Error() };
};
// user.controller.ts
export const attemptGetUserById = async (_id: string) => {
if (_id) {
try {
// only provider - no logic in getFullUserById only db operation
const user = await getUserById(_id);
if (user) return { user };
return { error: new HTTP404Error() };
} catch (e) {
return { error: new HTTP400Error(e) };
}
}
return { error: new HTTP400Error() };
};
export const attemptCheckUser = async (token: string) => {
const { error, userId} = attemptVerifyToken(token);
if (error) return { error };
if (userId) {
const { error, user } = await attemptGetUserById(userId);
if (error) return { error };
return { user };
}
return { error: new HTTP400Error() };
}
</code></pre>
<p><strong>Variant2</strong> <br />
Instead of having <strong>attemptCheckUser</strong>, move logic into Endpoint/Route so each Controller remains to have only one operation. <strong>attemptVerifyToken</strong> and <strong>attemptGetUserById</strong> remain the same as in Variant1</p>
<pre><code>// routes.ts
{
path: '/api/core/users/check',
method: 'post',
handler: [
async ({ headers: { authorization } }: Request, res: Response, next: NextFunction) => {
const { error, userId } = attemptVerifyToken(authorization);
if (error) return next(error);
if (userId) {
const { error, user } = await attemptGetUserById(userId);
if (error) return next(error);
return res.status(200).send(user);
}
return next();
},
],
},
...
// auth.controller.ts
export const attemptVerifyToken = (token: string) => {
if (token) {
const secret = "xxx";
// only provider - no logic in verifyToken
const { error, userId } = verifyToken(token, secret);
if(error) return { error };
return { userId, token };
}
return { error: new HTTP400Error() };
};
// user.controller.ts
export const attemptGetUserById = async (_id: string) => {
if (_id) {
try {
// only provider - no logic in getFullUserById only db operation
const user = await getUserById(_id);
if (user) return { user };
return { error: new HTTP404Error() };
} catch (e) {
return { error: new HTTP400Error(e) };
}
}
return { error: new HTTP400Error() };
};
</code></pre>
<p><strong>Variant3</strong> <br />
This variant is nearly identical to Variant1, however, the route injects the dependencies (the other 2 controllers) into <strong>attemptCheckUser</strong>. This Controller gets a new Interface.</p>
<pre><code>// routes.ts
{
path: '/api/core/users/check',
method: 'post',
handler: [
async ({ headers: { authorization } }: Request, res: Response, next: NextFunction) => {
const { error, user } = await attemptCheckUser(
{
attemptVerifyToken,
attemptGetUserById,
},
authorization,
);
if (error) return next(error);
return res.status(200).send(user);
},
],
},
...
// auth.controller.ts
export const attemptVerifyToken = (token: string) => {
if (token) {
const secret = "xxx";
// only provider - no logic in verifyToken
const { error, userId } = verifyToken(token, secret);
if(error) return { error };
return { userId, token };
}
return { error: new HTTP400Error() };
};
// user.controller.ts
export const attemptGetUserById = async (_id: string) => {
if (_id) {
try {
// only provider - no logic in getFullUserById only db operation
const user = await getUserById(_id);
if (user) return { user };
return { error: new HTTP404Error() };
} catch (e) {
return { error: new HTTP400Error(e) };
}
}
return { error: new HTTP400Error() };
};
interface OptionsCheckUser {
attemptVerifyToken: (token: string, skipToken?: boolean) => any;
attemptGetFullUserById: (userId: string, organisationId: string) => any;
}
export const attemptCheckUser = async (dependencies: OptionsCheckUser, token: string) => {
const { error, userId} = dependencies.attemptVerifyToken(token);
if (error) return { error };
if (userId) {
const { error, user } = await dependencies.attemptGetUserById(userId);
if (error) return { error };
return { user };
}
return { error: new HTTP400Error() };
</code></pre>
<p>I'm creating this question here on codereview, because I came up with the idea of <strong>Variant 3</strong>. I wanted to decouple those controllers calling other controllers, however, it just doesn't feel right. The reason I feel unsure about is that the interface needs to describe the injected functions quite precisely, which means it's likely there are no other functions I can inject since those functions would theoretically be doing the same job, so they simply don't exist (as they would be duplicates).</p>
<p><strong>Note:</strong> Please consider that this is a simplified example. The app will have multiple services, and one Controller will need to call other Controller Functions of a different service. That's why I found I need some kind of decoupling of those Controllers and how they call other Controller functions inside.</p>
<p><strong>What variant would you choose (if any) and why?</strong> </p>
<p>Thanks a lot in advance!</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-20T11:13:07.763",
"Id": "242628",
"Score": "1",
"Tags": [
"typescript",
"dependency-injection",
"express.js",
"controller"
],
"Title": "Typescript Express - Controller in Controller via dependency Injection or logic in routes"
}
|
242628
|
<p>I am trying to create stacked inputs using flexbox, with the additional ability to also set rows. Here is the code:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>.stacked-inputs,
.stacked-inputs .row {
display: -ms-flexbox;
display: flex;
-ms-flex-flow: row wrap;
flex-flow: row wrap;
-ms-flex-align: center;
align-items: center;
}
.stacked-inputs .row {
width: 100%;
margin-bottom: 10px;
}
.stacked-inputs > input,
.stacked-inputs .row > input {
position: relative;
-ms-flex: 1 1 0%;
flex: 1 1 0%;
min-width: 0;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="stacked-inputs">
<input type="text" placeholder="First name">
<input type="text" placeholder="Last name">
</div>
<br /><br />
<div class="stacked-inputs">
<div class="row">
<input type="text" placeholder="First name">
<input type="text" placeholder="Last name">
</div>
<div class="row">
<input type="text" placeholder="Job title">
<input type="text" placeholder="Year started">
</div>
</div></code></pre>
</div>
</div>
</p>
<p>When inputs are stacked without using rows, they will all be stacked horizontally. However, if a row is used, then obviously the rows of stacked inputs can be divided up nicely. Would love a review of this code from someone. Thanks in advance.</p>
|
[] |
[
{
"body": "<p>The following is my opinion on how to improve your code.</p>\n\n<ol>\n<li>You don't need write <code>flex-flow: row-wrap</code> because <code>flex</code> by default set row, then you can use another property of css <code>flex-wrap: wrap</code>.</li>\n<li>If you want to use flex in the whole of your code, you can set flex properties for <code>.row</code> class.</li>\n<li>Care about responsiveness, because flex is very good for making your page responsive. Due to this, we use <code>flex-wrap</code> and <code>min-width</code> to our input.</li>\n</ol>\n\n\n\n<pre><code>.stacked-inputs,.stacked-inputs .row {\n display: -ms-flexbox;\n display: flex;\n -ms-flex-wrap: wrap;\n flex-wrap: wrap;\n\n}\n.stacked-inputs .row {\n display: flex;\n flex-grow: 1;\n flex-shrink: 1;\n flex-basis: 100%;\n margin-bottom: 10px;\n}\n.stacked-inputs > input,\n.stacked-inputs .row > input {\n -ms-flex: 1 1 0%;\n flex: 1 1 0%;\n min-width: 200px;\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-01T07:57:47.437",
"Id": "243209",
"ParentId": "242629",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "243209",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-20T11:28:54.847",
"Id": "242629",
"Score": "3",
"Tags": [
"html",
"css"
],
"Title": "Stacked inputs with rows using flexbox"
}
|
242629
|
<pre><code>using System;
using System.Collections.Generic;
namespace Function_JosephusSurvivor
{
class Program
{
static void Main(string[] args)
{
//Debug purposes
Console.WriteLine(JosSurvivor(7, 3));
Console.ReadKey();
}
//Actual function:
public static int JosSurvivor(int n, int k)
{
// n = amount of people(array size)
// k = every k'th index will be yeeted
List<int> list = new List<int>();
int iCounter = 1; //always count till the size of the list
int iWatcher = 1; //always count till the size of k
for (int i = 1; i <= n; i++)
{
list.Add(i);
}
do
{
if (iWatcher+1 == k)
{
list.RemoveAt(iCounter);
iWatcher = 0;
}
iWatcher++;
iCounter++;
if (iCounter == list.Count) // -1 because index
{
iCounter = 0;
}
else if (iCounter > list.Count)
{
iCounter = 1; //if one is jumped due to deleteting
}
} while (list.Count != 1);
return list[0]; //winner
}
}
}
</code></pre>
<p>My question is: </p>
<h2>how could you make this more efficient? What could I do better?</h2>
<p>I'm trying to submit this as my solution on a practicing page. Unfortunately, it always times out. Therefore I need to make this more efficient I believe.</p>
<p>Thanks in advance :)!</p>
<p>Also feel free to add fitting Tags :)!</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-20T12:26:22.770",
"Id": "476131",
"Score": "0",
"body": "From what aspect are you looking for a more efficient solution? It was executed less than a sec on dotnetfiddle."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-20T12:29:09.593",
"Id": "476133",
"Score": "0",
"body": "@PeterCsala Maybe something that is better practice, or just any hints on what I could do better :). Also, could it be then, that the website could just have problems at the moment?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-20T13:19:49.260",
"Id": "476148",
"Score": "0",
"body": "Sorry but I still don't get it. From what perspective are you looking for some better solution? Better for maintainability / portability / readability / robustness / more efficient memory usage / ... / ???"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-20T13:44:48.457",
"Id": "476149",
"Score": "0",
"body": "More efficient :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-20T14:06:04.323",
"Id": "476150",
"Score": "0",
"body": "Generally speaking you can opt either for time or for resource consumption. What resource consumption is too high in your case?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-20T14:55:23.513",
"Id": "476158",
"Score": "0",
"body": "There's no need to work through an elimination process. See: https://www.exploringbinary.com/powers-of-two-in-the-josephus-problem/"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-21T14:47:47.033",
"Id": "476288",
"Score": "0",
"body": "@RickDavin thx for the info! :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-21T14:47:52.593",
"Id": "476289",
"Score": "0",
"body": "@PeterCsala what is good practice in order to have a little less memory consumption? And maybe also a faster way of doing this?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-22T06:45:59.947",
"Id": "476374",
"Score": "1",
"body": "@JeremiasT. Generally speaking in order to reduce the memory usage you have several techniques. Here are some well-known: 1) If possible prefer `Array`s over `List`s, because of double capacity allocation. Or it might be even better to use `IEnumerable`s 2) Try to use `struct`s instead of `class`es for short-living small data objects. 3) Try to avoid to allocate space more than 85000 bytes for a single object, because they will be allocated on the LargeObjectHeap. 4) Try to use allocation optimised structures like `Span`, `Memory`, `ArrayPool`, `StringBuilder`, etc."
}
] |
[
{
"body": "<blockquote>\n<pre><code> List<int> list = new List<int>();\n int iCounter = 1; //always count till the size of the list\n int iWatcher = 1; //always count till the size of k\n for (int i = 1; i <= n; i++)\n {\n list.Add(i);\n }\n</code></pre>\n</blockquote>\n\n<p>You can initialize <code>list</code> more elegantly:</p>\n\n<pre><code>List<int> list = Enumerable.Range(1, n).ToList();\n</code></pre>\n\n<hr>\n\n<p>For <code>n = 2; k = 1</code> it runs infinitely?</p>\n\n<hr>\n\n<p>Your counting and indexing seem ok, but are a little difficult to comprehend. It can be done a lot easier using modular operations:</p>\n\n<pre><code>static int JosSurvivor(int n, int k)\n{\n List<int> positions = Enumerable.Range(1, n).ToList();\n int index = k % n - 1; // %n is important for k > n\n\n while (positions.Count > 1)\n {\n if (index < 0) index += positions.Count; // when (index + k) % poisitons.Count == 0 then index becomes -1 from the line below\n positions.RemoveAt(index);\n index = (index + k) % positions.Count - 1;\n }\n\n return positions[0];\n}\n</code></pre>\n\n<hr>\n\n<p>Another approach building on the same principle is to maintain a fixed array of indices and then left-shift the reminder of the indices for each found index while decrement n by 1:</p>\n\n<pre><code>static int JosSurvivor(int n, int k)\n{\n int[] positions = Enumerable.Range(1, n).ToArray();\n int index = k % n - 1;\n\n while (n > 1)\n {\n if (index < 0) index += n;\n Array.Copy(positions, index + 1, positions, index, n - index - 1);\n n--;\n index = (index + k) % n - 1;\n }\n\n return positions[0];\n}\n</code></pre>\n\n<p>There seems to be a little performance gain - but not significant.</p>\n\n<hr>\n\n<p>Yet another version that uses a fixed array of flags, that are set for each found index:</p>\n\n<pre><code>static int JosSurvivor(int n, int k)\n{\n int counter = 0;\n int index = -1;\n int runner = 0;\n bool[] positions = new bool[n];\n\n while (counter < n - 1)\n {\n runner += k;\n int temp = 0;\n do\n {\n index = (index + 1) % n;\n } while (positions[index] || ++temp < k);\n\n if (runner > 0 && runner % k == 0)\n {\n positions[index] = true;\n counter++;\n }\n }\n\n for (int i = 0; i < n; i++)\n {\n if (!positions[i])\n return i + 1;\n }\n\n throw new InvalidOperationException(\"No last position found\");\n}\n</code></pre>\n\n<p>This is very fast for small <code>k</code>s - even for large <code>n</code>s - but becomes slower when <code>k</code> increases.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-21T11:45:59.763",
"Id": "476268",
"Score": "0",
"body": "You may have missed my comment to OP, but there is no to work through an elimination process. A formula may be used instead. See https://www.exploringbinary.com/powers-of-two-in-the-josephus-problem/"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-21T12:46:39.983",
"Id": "476275",
"Score": "0",
"body": "@RickDavin: I havn't missed your comment, but as far as I can read, it's about eliminating every other person (k = 2) only - not an arbitrary interval - for instance k = 3, og maybe I have missed something?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-21T15:19:27.943",
"Id": "476294",
"Score": "0",
"body": "@HenrikHansen Thank you! That helped a lot :)!"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-21T07:04:47.560",
"Id": "242685",
"ParentId": "242633",
"Score": "3"
}
},
{
"body": "<p>As a beginner you do need to practice the loop-based method, but I'd like to add that when you want to optimize code to the maximum, it's worth looking for mathematical rules that will help you predict things - if something is predictable then there's no need to simulate all the intermediate steps.</p>\n\n<p>For <code>k = 1</code> the result is always <code>n</code>.</p>\n\n<p>I found a great explanation about the math of this problem for <code>k = 2</code> (<a href=\"https://www.exploringbinary.com/powers-of-two-in-the-josephus-problem/\" rel=\"nofollow noreferrer\">link</a>):</p>\n\n<p><span class=\"math-container\">$$(2(n-2^{\\lfloor\\log_2n\\rfloor})+1) \\mod n$$</span></p>\n\n<p>In binary, powers of 2 have only one 1-bit, so the part of the formula that finds the greatest power of 2 that is less than or equal to <code>n</code> can be replaced with code that finds the left most 1-bit of <code>n</code>. It's a micro-optimization but it's related to the point I want to make.</p>\n\n<p>I failed generalizing it to work with any <code>k</code>, but it was still worth a shot, my goal is to illustrate that you can use math can optimize some of your code.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-21T13:12:22.920",
"Id": "476276",
"Score": "1",
"body": "In case `k > n` or even `k < 0`, I would use `k = k % n;`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-21T13:34:49.450",
"Id": "476277",
"Score": "0",
"body": "Have you actually tested your formula against different steps (k's) - for instance if n = 7 and k = 3? Be aware, that k in OP's algorithm is not the same as k in this formula. Please show the formula implemented in C# with some working examples :-)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-21T13:48:22.417",
"Id": "476280",
"Score": "0",
"body": "Or I mean the k from the explanation of the formula rather."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-21T13:54:25.693",
"Id": "476281",
"Score": "0",
"body": "@HenrikHansen I just tested it and it doesn't work, troubleshooting it right now."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-21T14:37:03.613",
"Id": "476284",
"Score": "1",
"body": "Turns out I made a big mistake when trying to generalize it to cases where `k ≠ 2`, so I replaced it with the cases of `k=1` and `k=2`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-21T14:41:20.390",
"Id": "476285",
"Score": "0",
"body": "@potato: [There are 10 types of people...](https://www.exploringbinary.com/there-are-10-types-of-people/) :-)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-21T14:43:25.563",
"Id": "476286",
"Score": "1",
"body": "@HenrikHansen haha I'd like to think I'm type 1 but sometimes I slip up and act like type 10"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-21T14:54:42.400",
"Id": "476290",
"Score": "0",
"body": "@potato Thank you for the tipp! I will redo this with a formula :)."
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-21T12:42:29.097",
"Id": "242696",
"ParentId": "242633",
"Score": "1"
}
},
{
"body": "<p>I just found a really clever solution to this (not mine):</p>\n\n<p>All credit goes to ViolaCrellin:</p>\n\n<pre><code>using System;\nusing System.Linq;\nusing System.Collections.Generic;\n\npublic class JosephusSurvivor\n{\n public static int JosSurvivor(int n, int k)\n {\n if (n == 1)\n return 1;\n else\n return (JosSurvivor(n - 1, k) + k-1) % n + 1;\n }\n}\n</code></pre>\n\n<p>Very nice solution :)! </p>\n\n<p><strong>Thanks for the answers everyone!</strong></p>\n\n<hr>\n\n<p><strong>Updated</strong> by Henrik Hansen</p>\n\n<p>This is an implementation of the <a href=\"https://en.wikipedia.org/wiki/Josephus_problem\" rel=\"nofollow noreferrer\">formula on wiki</a></p>\n\n<p>Recursive functions always has the potential to overflow the stack, so whenever you can, you should convert it to an iterative approach, which is also almost faster than using recursion:</p>\n\n<pre><code>public static int JosSurvivor(int n, int k)\n{\n int result = 1;\n for (int i = 2; i <= n; i++)\n {\n result = (result + k - 1) % i + 1;\n }\n return result;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-21T16:55:29.897",
"Id": "476309",
"Score": "1",
"body": "You have presented an alternative solution, but you did not review the original code at all. Reviewing code is all this site is about."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-21T17:17:00.703",
"Id": "476312",
"Score": "0",
"body": "The person who replied here with the alternative solution IS the OP."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-21T15:29:35.577",
"Id": "242700",
"ParentId": "242633",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "242685",
"CommentCount": "9",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-20T12:13:31.017",
"Id": "242633",
"Score": "3",
"Tags": [
"c#",
"beginner"
],
"Title": "finished Josephus-Problem in C#, how to make this more efficient?"
}
|
242633
|
<p>I'm trying to create functions in Python that would update calculations for a matrix only for new entries. These functions are created within a Design class, where users would submit a design into an existing database of designs. The distance between each design should be calculated, but ideally not by brute force every time so as to optimize for larger sized matrices (e.g. if there were 100+ designs). Here's what I have so far:</p>
<pre><code>def compute_matrix(self, all_design, new_design):
M = {}
count = 0
#Does the design already exist?
existing_design = None
#Do not calculate every time
update_distance = None
for i in self.designs:
for j in self.designs:
if i not in M:
M[i] = {}
current_design = M[i]
count += 1
if i == j:
continue
#need to test - only update based on new entries
for current_design in all_design:
update_distance = self._distance(new_design, current_design)
#Is calculation exactly the same?
if update_distance is None or current_distance == update_distance:
continue
##M[i][j] = self._distance(i, j)
return current_distance
def _distance(self, i, j):
p1 = self.designs[i].values()
p2 = self.designs[j].values()
##Using pdist to calculate distance matrix
dm = pdist(M, reduce(lambda a,x: (x[1]-x[0])**2 + a, zip(p1,p2), 0))
return dm
</code></pre>
<p>Designs are of 3D models where displacement forces are calculated on each model. Distances would evaluate how similar or dissimilar each collection of measured forces are from one another. So in a matrix of collected information of 100+ designs, a user would ideally be able to determine the top 5 most similar or dissimilar designs from a submitted one based on the distance between stored values within each design.</p>
<p>M is a matrix defined within compute_matrix and is the initialized matrix where submitted designs with their values will be stored. Time would probably be the primary concern with these calculations. E.g. if a row is added into a matrix of 100*100 designs, I would not want a 101*101 calculation to be done - rather just the distance between the 101st design and the rest of the designs to be updated instead of iterating through all the designs again.</p>
<p>How could I think about formatting the code properly? And might something like <code>scipy.spatial.cKDTree</code> be usable for a scenario like this? Or would that be more appropriate for finding the nearest vector in a matrix, and not the distance between each and every vector in a matrix? </p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-20T12:25:49.970",
"Id": "242635",
"Score": "1",
"Tags": [
"python",
"matrix"
],
"Title": "Efficiently update matrix calculations in Python"
}
|
242635
|
<p>hi guys this script recursively searches for files with a certain extension and possibly in a directory passed by the terminal ....(In case no directory has been passed, search from the current one) I believe it works correctly but I wanted to ask you if you noticed any flaws and report them to me or just tell me that everything is ok ...thanksss</p>
<pre><code> #include<stdio.h>
#include<sys/stat.h>
#include<errno.h>
#include<stdlib.h>
#include<dirent.h>
#include<stdarg.h>
#include<limits.h>
#include<string.h>
#include<time.h>
char * scrivi(const char * a, char * B) {
char *targetdir = malloc(2048);
strcpy(targetdir,a);
strcat(targetdir,"/");
strcat(targetdir,B);
return targetdir;
}
void ricor1(const char estensione[],const char nomedirectory[]){
struct stat attr;
char dbuf[PATH_MAX+1];
DIR * fh ;
struct dirent *fdata;
struct stat buf;
if((fh=opendir(nomedirectory))==NULL){
perror("ERRORE 1");
exit(errno);
}
while((fdata = readdir (fh))!=NULL){
if(strcmp(fdata->d_name,".")==0){
continue;
}
if(strcmp(fdata->d_name,"..")==0){
continue;
}
char *percorso;
percorso = scrivi(nomedirectory,fdata->d_name);
if (fdata->d_type==DT_DIR){
ricor1(estensione,percorso);
}
if (fdata->d_type == DT_REG && strstr(fdata->d_name, estensione)) {
realpath(percorso, dbuf);
printf("[%s]", dbuf);
stat(percorso, &attr);
printf("%s\n", ctime(&attr.st_mtime));
}
free(percorso);
}
closedir(fh);
}
int main(int argc, char *argv[]) {
if(argc==3){
printf("Checking existence directory.. \n");
DIR* dir=opendir(argv[2]);
if(dir){
closedir(dir);
ricor1(argv[1],argv[2]);
}
else if (ENOENT==errno){
printf("Directory doesn't exist\n");
}
else{
printf("error");
}
}
else if(argc==2){
ricor1(argv[1],"./");
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-20T14:57:49.013",
"Id": "476159",
"Score": "2",
"body": "_\"I believe it works correctly\"_ What do you mean? Didn't you test your code?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-20T15:07:06.050",
"Id": "476160",
"Score": "0",
"body": "it works, I wanted to know if there could be any errors that I had not considered ..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-20T15:30:19.440",
"Id": "476162",
"Score": "4",
"body": "At least you should indent your code correctly to enhance readability."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-20T16:43:33.470",
"Id": "476169",
"Score": "0",
"body": "Please keep in mind that the C programming language is not a scripting language, it is a compiled language, scripts run through an interpreter, compilers generate an executable file that can be run more quickly and efficiently."
}
] |
[
{
"body": "<blockquote>\n <p>... if you noticed any flaws ....</p>\n</blockquote>\n\n<p>Problems with <code>scrivi()</code></p>\n\n<pre><code>char * scrivi(const char * a, char * B) {\n\n char *targetdir = malloc(2048);\n strcpy(targetdir,a);\n strcat(targetdir,\"/\");\n strcat(targetdir,B);\n return targetdir;\n } \n</code></pre>\n\n<p><strong>Magic number</strong></p>\n\n<p>Why 2048? Big enough - who knows? Makes more sense to find the size needed and allocate rather than risk <em>undefined behavior</em> of a buffer overflow with <code>strcpy(targetdir,a);</code></p>\n\n<p><strong><code>strcpy(), strcat(), strcat()</code></strong></p>\n\n<p>Walking down the string 3 times. Bad enough to do twice. (With a larger code re-write, we could avoid all repetitive walks down <code>a</code>, that is far below.)</p>\n\n<p><strong><code>char * B</code> better as <code>const char * b</code></strong></p>\n\n<p>Use <code>const</code>.</p>\n\n<p><strong>No error checking</strong></p>\n\n<p>With a recursion function, out-of-memory is a concern.</p>\n\n<p><strong>Alternative</strong></p>\n\n<pre><code>char * scrivi(const char *a, const char *b) {\n size_t a_len = strlen(a); \n size_t b_len = strlen(b); \n char *targetdir = malloc(a_len + 1 + b_len + 1);\n\n if (targetdir) {\n memcpy(targetdir, a, a_len);\n targetdir[a_len] = '/';\n memcpy(targetdir + a_len + 1, b, b_len + 1);\n }\n return targetdir;\n} \n</code></pre>\n\n<hr>\n\n<p><strong>Re-write trick</strong></p>\n\n<p>Rather than repetitive <code>malloc()/free()</code>, allocate <strong>once</strong> ever for a working file path buffer.</p>\n\n<pre><code>size_t file_path_size = PATH_MAX * 2; // Let us be generous.\nchar file_path = mallloc(file_path_size); \n</code></pre>\n\n<p>Before code calls <code>ricor1()</code> the first time, fill in the directory path and pass how much used, how much total.</p>\n\n<pre><code>strcpy(file_path, argv[2]);\nricor1(argv[1], file_path, strlen(argv[2]), file_path_size);\n</code></pre>\n\n<p>When forming the the full path, rather than <code>percorso = scrivi(nomedirectory, fdata->d_name);</code> with its allocations, write at the right place.</p>\n\n<pre><code>int length = snprintf(file_path + used, file_path_size - used, \"/%s\", fdata->d_name);\n</code></pre>\n\n<p>When recursing, append the sub-directory name and re-curse with an updated length</p>\n\n<pre><code>ricor1(estensione, file_path, used + length, file_path_size);\n</code></pre>\n\n<p>Include ample size error checking.</p>\n\n<p>Consider code only ever needs 1 <code>file_path[]</code> at a time.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-21T22:03:36.683",
"Id": "476353",
"Score": "0",
"body": "`stpcpy` also works."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-21T22:17:55.940",
"Id": "476355",
"Score": "0",
"body": "@S.S.Anne Yes - could use that approach. Yet a crucial attribute of forming the file path in a _recursive_ function is 1) never overwriting the buffer and 2) detecting when the buffer was insufficient. I find `snprintf()` useful in insuring #1 and useful to detecting #2 and more convenient than the `strcpy()` route. I also find compilers more often these days emit efficient code with `*printf()` and friends due to analyzability and so less concern about a tedious format string interpretation that is no longer there. IAC, it is big O that I watch."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-21T22:19:02.560",
"Id": "476356",
"Score": "0",
"body": "No, `st` **p** `cpy`. There's also `stpncpy`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-21T22:24:18.157",
"Id": "476358",
"Score": "0",
"body": "@S.S.Anne Aha, Yes. could use `stpcpy()` to remove the [painter problem](https://wiki.c2.com/?ShlemielThePainter), That like `strcpy()`, `strcat()` still obliges other code to avoid buffer overflow and insufficient size detection. I'll look more into `stpncpy()`. They also has the short-coming of not existing in the standard C library - but of course neither does `opendir()` and friends."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-21T02:42:42.237",
"Id": "242681",
"ParentId": "242641",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-20T13:35:50.107",
"Id": "242641",
"Score": "1",
"Tags": [
"c",
"recursion",
"file",
"search"
],
"Title": "recursive file search, C , linux"
}
|
242641
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.