body
stringlengths 25
86.7k
| comments
list | answers
list | meta_data
dict | question_id
stringlengths 1
6
|
|---|---|---|---|---|
<p><strong>Updates</strong>: I kept the original code here, while performed some changes on my machine, including:</p>
<ol>
<li>fixed the incorrect return documentation for <code>clear()</code></li>
<li>made the closing functions recursive too (to be more clear and order-safe)</li>
<li>moved the static inner classes into separate files</li>
<li>extracted the API into an interface</li>
<li>use <code>.addSuppressed(e)</code> for handling more closing exceptions</li>
</ol>
<hr>
<p>This is a simple resource storage with basic dependency management. When we open a resource, its dependencies will be also opened (and vica versa when closing).</p>
<p>I post this here because the resulted code is surprisingly long (to me), and I also placed several <code>NOSONAR</code> flags because of the (necessarily) wildcarded result types.</p>
<p>I obfuscated the package name.</p>
<pre class="lang-java prettyprint-override"><code>package lorem.ipsum;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.Set;
/**
* Storage for openable and closeable resources with basic dependency handling.
*
* When opening a resource, its dependencies will also be opened.
* When closing a resource, its dependants will also be closed.
*/
public class ResourceManager {
private final String label;
private final Map<Key<?>, Entry<?>> entries = new LinkedHashMap<>();
private final Map<Key<?>, Set<Key<?>>> dependants = new HashMap<>();
/**
* Creates a new empty resource manager
*/
public ResourceManager() {
this("Resources");
}
/**
* Creates a new empty resource manager with the specified label
*
* @param label
*/
public ResourceManager(String label) {
this.label = label;
}
/**
* Gets the storage label
*
* @return The label
*/
public String getLabel() {
return label;
}
@Override
public String toString() {
return label;
}
/**
* Registers a new resource under the specified key
*
* @param key The key
* @param factory The resource factory
* @param dependencies Optional dependencies
* @throws CyclicDependencyException is dependency cycle is detected
*/
public <T extends AutoCloseable> void register(
Key<T> key,
Factory<T> factory,
Key<?>... dependencies) {
register(key, factory, createAutoCloser(), Arrays.asList(dependencies));
}
/**
* Registers a new resource under the specified key
*
* @param key The key
* @param factory The resource factory
* @param closer Custom closer code
* @param dependencies Optional dependencies
* @throws CyclicDependencyException is dependency cycle is detected
*/
public <T> void register(
Key<T> key,
Factory<T> factory,
Closer<T> closer,
Key<?>... dependencies) {
register(key, factory, closer, Arrays.asList(dependencies));
}
/**
* Registers a new resource under the specified key
*
* @param key The key
* @param factory The resource factory
* @param dependencies Dependencies
* @throws CyclicDependencyException is dependency cycle is detected
*/
public <T extends AutoCloseable> void register(
Key<T> key,
Factory<T> factory,
Collection<? extends Key<?>> dependencies) {
register(key, factory, createAutoCloser(), dependencies);
}
/**
* Registers a new resource under the specified key
*
* @param key The key
* @param factory The resource factory
* @param closer Custom closer code
* @param dependencies Dependencies
* @throws CyclicDependencyException is dependency cycle is detected
*/
public synchronized <T> void register(
Key<T> key,
Factory<T> factory,
Closer<T> closer,
Collection<? extends Key<?>> dependencies) {
if (entries.containsKey(key)) {
throw new DuplicateKeyException(key);
}
checkCycle(key, dependencies);
entries.put(key, new Entry<>(key, factory, closer, dependencies));
for (Key<?> dependency : dependencies) {
dependants.computeIfAbsent(dependency, k -> new HashSet<>()).add(key);
}
}
private static <C extends AutoCloseable> Closer<C> createAutoCloser() {
return (resourceManager, key, value) -> value.close();
}
/**
* Checks if this manager is empty
*
* @return <code>true</code> if there are no resource, <code>false</code> otherwise
*/
public synchronized boolean isEmpty() {
return entries.isEmpty();
}
/**
* Gets the number of resources in this manager
*
* @return The number of resources
*/
public synchronized int size() {
return entries.size();
}
/**
* Gets the set of registered keys
*
* @return The set of registered keys
*/
public synchronized Set<Key<?>> keySet() { // NOSONAR
return new LinkedHashSet<>(entries.keySet());
}
/**
* Checks if the specified key is registered
*
* @param key The key
* @return <code>true</code> if the key is registered, <code>false</code> otherwise
*/
public synchronized boolean containsKey(Key<?> key) {
return entries.containsKey(key);
}
/**
* Gets resource under the specified key.
*
* Returns with null if <code>key</code> is not registered
* or the resource is not open.
*
* @param key The key
* @return The resource or <code>null</code>
*/
public synchronized <T> T get(Key<T> key) {
@SuppressWarnings("unchecked")
Entry<T> entry = (Entry<T>) entries.get(key);
if (entry == null) {
return null;
}
return entry.resource;
}
/**
* Returns with open resource with the specified key.
*
* Opens the resource and its dependencies if it is not open.
* Does not return with <code>null</code>. Throws exception if <code>key</code> is missing.
*
* @param key The key
* @throws NoSuchElementException if <code>key</code> or any dependency is missing
* @throws OpeningFailedException if opening of this resource or any dependency was failed
* @return The open resource
*/
public synchronized <T> T open(Key<T> key) {
Entry<T> entry = getEntry(key);
if (entry.resource != null) {
return entry.resource;
}
for (Key<?> dependency : entry.dependecies) {
open(dependency);
}
return entry.get();
}
/**
* Closes resource under the specified key.
*
* If <code>key</code> is missing, then exception will be thrown.
* If resource is already open, no operation will be performed.
* If closing was failed (because of this resource or any dependant),
* throws an exception and stops closing,
* so this close variant is non aggressive (see {@link #close(Key, boolean)}).
*
* @throws NoSuchElementException if <code>key</code> is missing
* @throws ClosingFailedException if closing of this resource or any dependant was failed
* @param key The key
*/
public synchronized void close(Key<?> key) {
close(key, false);
}
/**
* Closes resource under the specified key.
*
* If <code>key</code> is missing, then exception will be thrown.
* If resource is already open, no operation will be performed.
* If closing was failed (because of this resource or any dependant),
* then throws an exception, and in aggressive mode does not stop and
* tries to close each dependency (including this resource).
*
* @throws NoSuchElementException if <code>key</code> is missing
* @throws ClosingFailedException if closing of this resource or any dependant was failed
* @param key The key
* @param aggressive Enables aggressive mode
*/
public synchronized void close(Key<?> key, boolean aggressive) {
closeInternal(key, aggressive);
}
/**
* Closes all resources in this manager.
*
* This is non aggressive (see {@link #close(Key, boolean)}).
*
* @throws ClosingFailedException if closing of any resource was failed
*/
public synchronized void closeAll() {
closeAll(false);
}
/**
* Closes all resources in this manager.
*
* This is possibly aggressive (see {@link #close(Key, boolean)}).
*
* @throws ClosingFailedException if closing of any resource was failed
* @param aggressive Enables aggressive mode
*/
public synchronized void closeAll(boolean aggressive) {
if (aggressive) {
closeAllInternalAggressive();
} else {
closeAllInternalNonAggressive();
}
}
private synchronized void closeAllInternalNonAggressive() {
for (Key<?> key : entries.keySet()) {
closeInternal(key, false);
}
}
private synchronized void closeAllInternalAggressive() {
ClosingFailedException exception = null;
for (Key<?> key : entries.keySet()) {
try {
closeInternal(key, true);
} catch (ClosingFailedException e) {
exception = e;
}
}
if (exception != null) {
throw exception;
}
}
/**
* Closes and removes resource at the specified key.
*
* Dependants will kept, so calling this method can leave this manager
* in a non consistent state, in which you can register an alternative
* dependency instead of this. For instant consistency use {@link #remove(Key, boolean)}.
* See {@link #close(Key, boolean)}. This is non aggressive,
* and resource will be kept in case of a closing related exception.
*
* @param key The key
* @throws NoSuchElementException if <code>key</code> is missing
* @throws ClosingFailedException if closing of this resource or any dependant was failed
* @return The resource removed from this key
*/
public synchronized <T> T remove(Key<T> key) {
return remove(key, false);
}
/**
* Closes and removes resource at the specified key and possibly its dependencies.
*
* See {@link #close(Key, boolean)}. This is non aggressive,
* and no resource will be removed in case of a closing related exception.
*
* @param key The key
* @param removeDependants Remove dependants too or not
* @throws NoSuchElementException if <code>key</code> is missing
* @throws ClosingFailedException if closing of this resource or any dependant was failed
* @return The resource removed from this key
*/
public synchronized <T> T remove(Key<T> key, boolean removeDependants) {
T resource = getEntry(key).resource;
List<Key<?>> allDependants = closeInternal(key, false);
if (removeDependants) {
for (Key<?> dependant : allDependants) {
entries.remove(dependant);
dependants.remove(dependant);
}
}
entries.remove(key);
dependants.remove(key);
return resource;
}
private synchronized List<Key<?>> closeInternal(Key<?> key, boolean aggressive) { // NOSONAR
if (aggressive) {
return closeInternalAggressive(key);
} else {
return closeInternalNonAggressive(key);
}
}
private synchronized List<Key<?>> closeInternalNonAggressive(Key<?> key) { // NOSONAR
List<Key<?>> allDependants = getAllDependants(key);
int countOfDependants = allDependants.size();
for (int i = countOfDependants - 1; i >= 0; i--) {
Key<?> dependantKey = allDependants.get(i);
getEntry(dependantKey).close();
}
getEntry(key).close();
return allDependants;
}
private synchronized List<Key<?>> closeInternalAggressive(Key<?> key) { // NOSONAR
List<Key<?>> allDependants = getAllDependants(key);
int countOfDependants = allDependants.size();
ClosingFailedException exception = null;
for (int i = countOfDependants - 1; i >= 0; i--) {
Key<?> dependantKey = allDependants.get(i);
try {
getEntry(dependantKey).close();
} catch (ClosingFailedException e) {
exception = e;
}
}
getEntry(key).close();
if (exception != null) {
throw exception;
}
return allDependants;
}
/**
* Closes and removes all resources.
*
* See {@link #closeAll()}.
*
* @throws ClosingFailedException if closing of any resource was failed
* @return The resource removed from this key
*/
public synchronized void clear() {
closeAll();
entries.clear();
dependants.clear();
}
private Set<Key<?>> getDependants(Key<?> key) {
Set<Key<?>> result = dependants.get(key);
return result == null ? new HashSet<>() : result;
}
private List<Key<?>> getAllDependants(Key<?> key) {
List<Key<?>> allDependants = new ArrayList<>();
Set<Key<?>> currentDependants = getDependants(key);
while (!currentDependants.isEmpty()) {
allDependants.addAll(currentDependants);
Set<Key<?>> newDependants = new HashSet<>();
for (Key<?> currentKey : currentDependants) {
newDependants.addAll(getDependants(currentKey));
}
newDependants.removeAll(allDependants);
currentDependants = newDependants;
}
return allDependants;
}
/**
* Checks if resource under the specified key is registered and is open.
*
* @param key The key
* @throws NoSuchElementException if key is missing
* @return <code>true</code> if the resource is open, <code>false</code> otherwise
*/
public synchronized boolean isOpen(Key<?> key) {
return getEntry(key).resource != null;
}
/**
* Checks if there is any open resource
*
* @return <code>true</code> is any open resource found, <code>false</code> otherwise
*/
public synchronized boolean hasOpen() {
for (Entry<?> entry : entries.values()) {
if (entry.resource != null) {
return true;
}
}
return false;
}
/**
* Gets the number of open resources in this manager
*
* @return The number of open resources
*/
public synchronized int countOpen() {
int result = 0;
for (Entry<?> entry : entries.values()) {
if (entry.resource != null) {
result++;
}
}
return result;
}
/**
* Gets the set of keys of open resources in this manager
*
* @return The set of open keys
*/
public synchronized Set<Key<?>> openKeySet() { // NOSONAR
Set<Key<?>> result = new LinkedHashSet<>();
for (Entry<?> entry : entries.values()) {
if (entry.resource != null) {
result.add(entry.key);
}
}
return result;
}
/**
* Gets the set of closed of open resources in this manager
*
* @return The set of closed keys
*/
public synchronized Set<Key<?>> closedKeySet() { // NOSONAR
Set<Key<?>> result = new LinkedHashSet<>();
for (Entry<?> entry : entries.values()) {
if (entry.resource == null) {
result.add(entry.key);
}
}
return result;
}
private <T> Entry<T> getEntry(Key<T> key) {
@SuppressWarnings("unchecked")
Entry<T> entry = (Entry<T>) entries.get(key);
if (entry == null) {
throw new NoSuchElementException(String.format("Key not found: %s", key));
}
return entry;
}
private void checkCycle(Key<?> key, Collection<? extends Key<?>> dependencies) {
Set<Key<?>> currentDependencies = new HashSet<>(dependencies);
Set<Key<?>> allDependencies = new HashSet<>(dependencies);
while (!currentDependencies.isEmpty()) {
Set<Key<?>> nextDependencies = new HashSet<>();
for (Key<?> dependency : currentDependencies) {
if (dependency.equals(key)) {
throw new CyclicDependencyException();
}
Entry<?> entry = entries.get(key);
if (entry != null) {
nextDependencies.addAll(entry.dependecies);
}
}
nextDependencies.removeAll(allDependencies);
allDependencies.addAll(nextDependencies);
currentDependencies = nextDependencies;
}
}
/**
* Key for resources to store under
*
* @param <T> Resource type
*/
public static class Key<T> implements Serializable {
private static final long serialVersionUID = 1L;
private final String name;
private final Class<T> resourceType;
/**
* Constructs a key.
*
* You can store resources with this key with the specified type only.
* You can use the same <code>name</code> multiple times with different <code>type</code>s.
*
* @param name Name of this key
* @param resourceType Resource type
*/
public Key(String name, Class<T> resourceType) {
this.name = name;
this.resourceType = resourceType;
}
/**
* Gets the key name
*
* @return The name
*/
public String getName() {
return name;
}
/**
* Gets the associated resource type
*
* @return The resource type
*/
public Class<T> getResourceType() {
return resourceType;
}
/**
* Checks if this key is equal to the given object.
*
* If <code>obj</code> is not a {@link Key}, then returns with false.
* Thwo key are equal, iff their names and types are both equal.
*
* @return <code>true</code> if equals, <code>false</code> otherwise
*/
@Override
public boolean equals(Object obj) {
if (!(obj instanceof Key)) {
return false;
}
Key<?> otherKey = (Key<?>) obj;
return name.equals(otherKey.name) && resourceType == otherKey.resourceType;
}
/**
* Generates hash code for this key
*
* @return The hash code
*/
@Override
public int hashCode() {
return (name.hashCode() * 31) + resourceType.hashCode();
}
/**
* Generates string representation for this key.
*
* Format of the string is: &lt;name&gt; ":" &lt;type&gt; .
*
* @return The string representation
*/
@Override
public String toString() {
return String.format("%s:%s", name, resourceType.getName());
}
}
/**
* Functional interface for resource factory lambdas
*
* @param <T> Resource type
*/
public interface Factory<T> {
public T create(ResourceManager resourceManager, Key<T> key) throws Exception; // NOSONAR
}
/**
* Functional interface for custom resource closer lambdas
*
* @param <T> Resource type
*/
public interface Closer<T> {
public void close(ResourceManager resourceManager, Key<T> key, T value) throws Exception; // NOSONAR
}
/**
* Exception, thrown when a duplicated key given
*/
public static class DuplicateKeyException extends RuntimeException {
private static final long serialVersionUID = 1L;
private final Key<?> key;
private DuplicateKeyException(Key<?> key) {
super(String.format("Duplicate key: %s", key));
this.key = key;
}
/**
* Gets the key tried to duplicate
*
* @return The key
*/
public Key<?> getKey() { // NOSONAR
return key;
}
}
/**
* Exception, thrown when cyclic dependencies detected
*/
public static class CyclicDependencyException extends RuntimeException {
private static final long serialVersionUID = 1L;
private CyclicDependencyException() {
super("Cyclic dependency detected");
}
}
/**
* Exception, thrown when opening of a resource failed
*/
public static class OpeningFailedException extends RuntimeException {
private static final long serialVersionUID = 1L;
private final Key<?> key;
private OpeningFailedException(Key<?> key, Exception e) {
super(String.format("Opening failed: %s", key), e);
this.key = key;
}
/**
* Gets the key of the unopenable resource
*
* @return The key
*/
public Key<?> getKey() { // NOSONAR
return key;
}
}
/**
* Exception thrown when closing of a resource failed
*/
public static class ClosingFailedException extends RuntimeException {
private static final long serialVersionUID = 1L;
private final Key<?> key;
public ClosingFailedException(Key<?> key, Exception e) {
super(String.format("Closing failed: %s", key), e);
this.key = key;
}
/**
* Gets the key of the uncloseable resource
*
* @return The key
*/
public Key<?> getKey() { // NOSONAR
return key;
}
}
private class Entry<T> {
final Key<T> key;
final Factory<T> factory;
final Closer<T> closer;
final List<Key<?>> dependecies;
T resource = null;
Entry(
Key<T> key,
Factory<T> factory,
Closer<T> closer,
Collection<? extends Key<?>> dependecies) {
this.key = key;
this.factory = factory;
this.closer = closer;
this.dependecies = new ArrayList<>(dependecies);
}
T get() {
if (resource == null) {
try {
resource = factory.create(ResourceManager.this, key);
} catch (Exception e) {
throw new OpeningFailedException(key, e);
}
}
return resource;
}
void close() {
if (resource != null) {
try {
closer.close(ResourceManager.this, key, resource);
} catch (Exception e) {
throw new ClosingFailedException(key, e);
}
resource = null;
}
}
}
}
</code></pre>
<p>And here are the tests:</p>
<pre class="lang-java prettyprint-override"><code>package lorem.ipsum;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import java.io.Closeable;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.NoSuchElementException;
import java.util.Set;
import java.util.function.Consumer;
import org.junit.jupiter.api.Test;
class ResourceManagerTest {
@Test
void testBasicsOfEmpty() {
ResourceManager resourceManager = createEmptyResourceManager();
String label = resourceManager.getLabel();
assertThat(resourceManager.toString()).as("string").isEqualTo(label);
assertThat(resourceManager).matches(r -> r.isEmpty(), "should be empty");
assertThat(resourceManager.size()).as("size").isZero();
assertThat(resourceManager.keySet()).as("keys").isEmpty();
assertThat(resourceManager.containsKey(key("foo"))).as("contains foo").isFalse();
assertThat(resourceManager.hasOpen()).as("has open").isFalse();
assertThat(resourceManager.countOpen()).as("open count").isZero();
assertThat(resourceManager.openKeySet()).as("open keys").isEmpty();
assertThat(resourceManager.closedKeySet()).as("closed keys").isEmpty();
}
@Test
void testBasicsOfFilled() {
ResourceManager resourceManager = createFilledResourceManager();
assertThat(resourceManager).matches(r -> !r.isEmpty(), "should not be empty");
assertThat(resourceManager.size()).as("size").isEqualTo(10);
assertThat(resourceManager.keySet()).as("keys").isEqualTo(keys(
"light", "camera", "cameraman", "shot", "movie",
"fire", "cookbook", "chef", "cooking", "cookingshow"));
assertThat(resourceManager.containsKey(key("foo"))).as("contains foo").isFalse();
assertThat(resourceManager.containsKey(key("light"))).as("contains foo").isTrue();
assertThat(resourceManager.hasOpen()).as("has open").isFalse();
assertThat(resourceManager.countOpen()).as("open count").isZero();
assertThat(resourceManager.openKeySet()).as("open keys").isEmpty();
assertThat(resourceManager.closedKeySet()).as("closed keys").isEqualTo(keys(
"light", "camera", "cameraman", "shot", "movie",
"fire", "cookbook", "chef", "cooking", "cookingshow"));
}
@Test
void testKeyDuplication() {
ResourceManager resourceManager = createFilledResourceManager();
assertThatThrownBy(() -> resourceManager.register(key("light"), this::create)).as("duplicate light")
.isInstanceOf(ResourceManager.DuplicateKeyException.class);
}
@Test
void testOpen() {
ResourceManager resourceManager = createFilledResourceManager();
String label = resourceManager.getLabel();
ResourceManager.Key<TestResource> lightKey = key("light");
ResourceManager.Key<TestResource> fireKey = key("fire");
resourceManager.open(lightKey);
assertThat(resourceManager.toString()).as("string").isEqualTo(label);
assertThat(resourceManager.hasOpen()).as("has open").isTrue();
assertThat(resourceManager.countOpen()).as("open count").isEqualTo(1);
assertThat(resourceManager.openKeySet()).as("open keys").isEqualTo(keys("light"));
assertThat(resourceManager.closedKeySet()).as("closed keys").isEqualTo(keys(
"camera", "cameraman", "shot", "movie",
"fire", "cookbook", "chef", "cooking", "cookingshow"));
assertThat(resourceManager.isOpen(lightKey)).as("light is open").isTrue();
assertThat(resourceManager.isOpen(fireKey)).as("light is open").isFalse();
assertThat(resourceManager.get(lightKey).isClosed()).as("light is off").isFalse();
}
@Test
void testOpenComplex1() {
ResourceManager resourceManager = createFilledResourceManager();
resourceManager.open(key("movie"));
assertThat(resourceManager.openKeySet()).as("open keys").isEqualTo(keys(
"light", "camera", "cameraman", "shot", "movie"));
assertThat(resourceManager.closedKeySet()).as("closed keys").isEqualTo(keys(
"fire", "cookbook", "chef", "cooking", "cookingshow"));
assertThat(resourceManager.hasOpen()).as("has open").isTrue();
assertThat(resourceManager.countOpen()).as("open count").isEqualTo(5);
}
@Test
void testOpenComplex2() {
ResourceManager resourceManager = createFilledResourceManager();
resourceManager.open(key("cookingshow"));
assertThat(resourceManager.openKeySet()).as("openKeys").isEqualTo(keys(
"light", "camera", "cameraman", "shot",
"fire", "cookbook", "chef", "cooking", "cookingshow"));
assertThat(resourceManager.closedKeySet()).as("closed keys").isEqualTo(keys("movie"));
assertThat(resourceManager.hasOpen()).as("has open").isTrue();
assertThat(resourceManager.countOpen()).as("open count").isEqualTo(9);
}
@Test
void testOpenNonExisting() {
ResourceManager resourceManager = createFilledResourceManager();
assertThatThrownBy(() -> resourceManager.open(key("foo"))).as("openNonExisting")
.isInstanceOf(NoSuchElementException.class);
}
@Test
void testOpeningOrder() {
List<ResourceManager.Key<?>> openingOrder = new ArrayList<>();
ResourceManager resourceManager = createFilledResourceManager(
key -> openingOrder.add(key), key -> {});
resourceManager.open(key("movie"));
assertThat(openingOrder)
.containsSubsequence(key("shot"), key("movie"))
.containsSubsequence(key("light"), key("shot"))
.containsSubsequence(key("camera"), key("shot"))
.containsSubsequence(key("cameraman"), key("shot"));
}
@Test
void testGetUnopened() {
ResourceManager resourceManager = createFilledResourceManager();
assertThat(resourceManager.get(key("light"))).as("light").isNull();
}
@Test
void testGetOpened() {
ResourceManager resourceManager = createFilledResourceManager();
ResourceManager.Key<TestResource> key = key("light");
resourceManager.open(key);
assertThat(resourceManager.get(key)).as("light").isInstanceOf(TestResource.class);
}
@Test
void testGetNonExisting() {
ResourceManager resourceManager = createFilledResourceManager();
assertThat(resourceManager.get(key("foo"))).as("light").isNull();
}
@Test
void testOpenWithDirectException() {
ResourceManager resourceManager = createFilledResourceManager();
ResourceManager.Key<TestResource> key = key("unopenable");
resourceManager.register(key, this::createUnopenable);
assertThatThrownBy(() -> resourceManager.open(key)).as("openingException")
.isInstanceOf(ResourceManager.OpeningFailedException.class)
.extracting(e -> ((ResourceManager.OpeningFailedException) e).getKey()).as("failedKey")
.isEqualTo(key);
}
@Test
void testOpenWithDependencyException() {
ResourceManager resourceManager = createFilledResourceManager();
ResourceManager.Key<TestResource> dependencyKey = key("unopenable");
ResourceManager.Key<TestResource> key = key("dependantOfUnopenable");
resourceManager.register(dependencyKey, this::createUnopenable);
resourceManager.register(key, this::create, dependencyKey);
assertThatThrownBy(() -> resourceManager.open(key)).as("openingException")
.isInstanceOf(ResourceManager.OpeningFailedException.class)
.extracting(e -> ((ResourceManager.OpeningFailedException) e).getKey()).as("failedKey")
.isEqualTo(dependencyKey);
}
@Test
void testSingleOpenAndClose() {
ResourceManager resourceManager = createFilledResourceManager();
ResourceManager.Key<TestResource> key = key("light");
TestResource resource = resourceManager.open(key);
assertThat(!resource.isClosed()).as("really opened").isTrue();
resourceManager.close(key);
assertThat(resource.isClosed()).as("really closed").isTrue();
assertThat(resourceManager.hasOpen()).as("has open").isFalse();
}
@Test
void testComplexOpenAndSingleClose() {
ResourceManager resourceManager = createFilledResourceManager();
ResourceManager.Key<?> key = key("movie");
resourceManager.open(key);
resourceManager.close(key);
assertThat(resourceManager.openKeySet()).as("open keys").isEqualTo(keys(
"light", "camera", "cameraman", "shot"));
assertThat(!resourceManager.get(key("light")).isClosed()).as("light is on").isTrue();
}
@Test
void testComplexOpenAndClose() {
ResourceManager resourceManager = createFilledResourceManager();
ResourceManager.Key<?> movieKey = key("movie");
ResourceManager.Key<?> lightKey = key("light");
resourceManager.open(movieKey);
resourceManager.close(lightKey);
assertThat(resourceManager.openKeySet()).as("open keys").isEqualTo(keys(
"camera", "cameraman"));
}
@Test
void testClosingOrder() {
List<ResourceManager.Key<?>> closingOrder = new ArrayList<>();
ResourceManager resourceManager = createFilledResourceManager(
key -> {}, key -> closingOrder.add(key));
resourceManager.open(key("cookingshow"));
resourceManager.close(key("cooking"));
resourceManager.close(key("camera"));
assertThat(closingOrder).isEqualTo(keyList("cookingshow", "cooking", "shot", "camera"));
}
@Test
void testCloseAllOnEmptyWithoutException() {
createEmptyResourceManager().closeAll();
}
@Test
void testCloseNonExisting() {
ResourceManager resourceManager = createFilledResourceManager();
assertThatThrownBy(() -> resourceManager.close(key("foo"))).as("closeNonExisting")
.isInstanceOf(NoSuchElementException.class);
}
@Test
void testCloseWithDirectException() {
ResourceManager resourceManager = createFilledResourceManager();
ResourceManager.Key<TestResource> key = key("uncloseable");
resourceManager.register(key, this::createUncloseable);
resourceManager.open(key);
assertThatThrownBy(() -> resourceManager.close(key)).as("closingException")
.isInstanceOf(ResourceManager.ClosingFailedException.class)
.extracting(e -> ((ResourceManager.ClosingFailedException) e).getKey()).as("failedKey")
.isEqualTo(key);
}
@Test
void testCloseWithDependantException() {
ResourceManager resourceManager = createFilledResourceManager();
ResourceManager.Key<TestResource> dependencyKey = key("dependency");
ResourceManager.Key<TestResource> uncloseableKey = key("uncloseable");
ResourceManager.Key<TestResource> leafDependantKey = key("leafDependant");
resourceManager.register(dependencyKey, this::create);
resourceManager.register(uncloseableKey, this::createUncloseable, dependencyKey);
resourceManager.register(leafDependantKey, this::create, uncloseableKey);
resourceManager.open(leafDependantKey);
assertThatThrownBy(() -> resourceManager.close(dependencyKey)).as("closingException")
.isInstanceOf(ResourceManager.ClosingFailedException.class)
.extracting(e -> ((ResourceManager.ClosingFailedException) e).getKey()).as("failedKey")
.isEqualTo(uncloseableKey);
assertThat(resourceManager.openKeySet()).as("open keys").isEqualTo(
new HashSet<>(Arrays.asList(dependencyKey, uncloseableKey)));
}
@Test
void testCloseAggressiveWithException() {
ResourceManager resourceManager = createFilledResourceManager();
ResourceManager.Key<TestResource> dependencyKey = key("dependency");
ResourceManager.Key<TestResource> uncloseableKey = key("uncloseable");
ResourceManager.Key<TestResource> leafDependantKey = key("leafDependant");
resourceManager.register(dependencyKey, this::create);
resourceManager.register(uncloseableKey, this::createUncloseable, dependencyKey);
resourceManager.register(leafDependantKey, this::create, uncloseableKey);
resourceManager.open(leafDependantKey);
assertThatThrownBy(() -> resourceManager.close(dependencyKey, true)).as("closingException")
.isInstanceOf(ResourceManager.ClosingFailedException.class)
.extracting(e -> ((ResourceManager.ClosingFailedException) e).getKey()).as("failedKey")
.isEqualTo(uncloseableKey);
assertThat(resourceManager.openKeySet()).as("open keys").isEqualTo(
new HashSet<>(Arrays.asList(uncloseableKey)));
}
@Test
void testRemove() {
ResourceManager resourceManager = createFilledResourceManager();
ResourceManager.Key<TestResource> key = key("light");
resourceManager.remove(key);
assertThat(resourceManager.containsKey(key)).as("contains light").isFalse();
}
@Test
void testRemoveOpen() {
ResourceManager resourceManager = createFilledResourceManager();
ResourceManager.Key<TestResource> key = key("light");
TestResource resource = resourceManager.open(key);
assertThat(!resource.isClosed()).as("light is really open").isTrue();
resourceManager.remove(key);
assertThat(resourceManager.containsKey(key)).as("contains light").isFalse();
assertThat(resource.isClosed()).as("light is really closed").isTrue();
}
@Test
void testRemoveWithException() {
ResourceManager resourceManager = createFilledResourceManager();
ResourceManager.Key<TestResource> key = key("uncloseable");
resourceManager.register(key, this::createUncloseable);
resourceManager.open(key);
assertThatThrownBy(() -> resourceManager.remove(key)).as("closing failed while removing")
.isInstanceOf(ResourceManager.ClosingFailedException.class);
assertThat(resourceManager.containsKey(key)).as("contains uncloseable").isTrue();
}
@Test
void testRemoveWithDependantException() {
ResourceManager resourceManager = createFilledResourceManager();
ResourceManager.Key<TestResource> dependencyKey = key("dependency");
ResourceManager.Key<TestResource> uncloseableKey = key("uncloseable");
resourceManager.register(dependencyKey, this::create);
resourceManager.register(uncloseableKey, this::createUncloseable, dependencyKey);
resourceManager.open(uncloseableKey);
assertThatThrownBy(() -> resourceManager.remove(dependencyKey)).as("closing failed while removing")
.isInstanceOf(ResourceManager.ClosingFailedException.class)
.extracting(exception -> ((ResourceManager.ClosingFailedException) exception).getKey())
.as("uncloseable key").isEqualTo(uncloseableKey);
assertThat(resourceManager.get(dependencyKey).isClosed()).as("dependency is closed").isFalse();
}
@Test
void testCloseAll() {
ResourceManager resourceManager = createFilledResourceManager();
ResourceManager.Key<TestResource> testKey = key("shot");
ResourceManager.Key<TestResource> dependantKey = key("movie");
resourceManager.open(dependantKey);
assertThat(resourceManager.isOpen(testKey)).as("shot is open before").isTrue();
resourceManager.closeAll();
assertThat(resourceManager.isOpen(testKey)).as("shot is open after").isFalse();
}
@Test
void testCloseAllWithException() {
ResourceManager resourceManager = createFilledResourceManager();
ResourceManager.Key<TestResource> uncloseableKey = key("uncloseable");
ResourceManager.Key<TestResource> dependantKey = key("dependant");
resourceManager.register(uncloseableKey, this::createUncloseable, key("movie"));
resourceManager.register(dependantKey, this::create, key("uncloseable"));
resourceManager.open(dependantKey);
assertThatThrownBy(() -> resourceManager.closeAll()).as("close all exception")
.isInstanceOf(ResourceManager.ClosingFailedException.class)
.extracting(exception -> ((ResourceManager.ClosingFailedException) exception).getKey())
.as("uncloseable key").isEqualTo(uncloseableKey);
assertThat(resourceManager.get(key("light")).isClosed()).as("light is off").isFalse();
}
@Test
void testCloseAllAggressiveWithException() {
ResourceManager resourceManager = createFilledResourceManager();
ResourceManager.Key<TestResource> uncloseableKey = key("uncloseable");
ResourceManager.Key<TestResource> dependantKey = key("dependant");
resourceManager.register(uncloseableKey, this::createUncloseable, key("movie"));
resourceManager.register(dependantKey, this::create, key("uncloseable"));
resourceManager.open(dependantKey);
assertThatThrownBy(() -> resourceManager.closeAll(true)).as("closing all exception")
.isInstanceOf(ResourceManager.ClosingFailedException.class)
.extracting(exception -> ((ResourceManager.ClosingFailedException) exception).getKey())
.as("uncloseable key").isEqualTo(uncloseableKey);
assertThat(resourceManager.openKeySet()).as("open keys").isEqualTo(keys("uncloseable"));
}
@Test
void testClear() {
ResourceManager resourceManager = createFilledResourceManager();
resourceManager.clear();
assertThat(resourceManager.isEmpty()).as("manager is empty").isTrue();
assertThat(resourceManager.keySet()).as("keys").isEmpty();
}
@Test
void testClearWithOpen() {
ResourceManager resourceManager = createFilledResourceManager();
ResourceManager.Key<TestResource> lightKey = key("light");
TestResource light = resourceManager.open(lightKey);
resourceManager.open(key("light"));
resourceManager.clear();
assertThat(resourceManager.isEmpty()).as("manager is empty").isTrue();
assertThat(resourceManager.keySet()).as("keys").isEmpty();
assertThat(light.isClosed()).as("light is off").isTrue();
}
@Test
void testClearWithException() {
ResourceManager resourceManager = createFilledResourceManager();
ResourceManager.Key<TestResource> key = key("uncloseable");
resourceManager.register(key, this::createUncloseable);
resourceManager.open(key);
assertThatThrownBy(() -> resourceManager.clear()).as("clearing exception")
.isInstanceOf(ResourceManager.ClosingFailedException.class)
.extracting(exception -> ((ResourceManager.ClosingFailedException) exception).getKey())
.as("uncloseable key").isEqualTo(key);
assertThat(resourceManager.size()).as("size: all should be kept").isEqualTo(11);
}
private ResourceManager createEmptyResourceManager() {
return new ResourceManager("No resources");
}
private ResourceManager createFilledResourceManager() {
return createFilledResourceManager(key -> {}, key -> {});
}
private ResourceManager createFilledResourceManager(
Consumer<ResourceManager.Key<?>> onOpen, Consumer<ResourceManager.Key<?>> onClose) {
ResourceManager resourceManager = new ResourceManager();
ResourceManager.Factory<TestResource> factory = (manager, key) -> {
onOpen.accept(key);
return this.create();
};
ResourceManager.Closer<TestResource> closer = (manager, key, value) -> {
onClose.accept(key);
value.close();
};
resourceManager.register(key("light"), factory, closer);
resourceManager.register(key("camera"), factory, closer);
resourceManager.register(key("cameraman"), factory, closer);
resourceManager.register(key("shot"), factory, closer, keys("light", "camera", "cameraman"));
resourceManager.register(key("movie"), factory, closer, keys("shot"));
resourceManager.register(key("fire"), factory, closer);
resourceManager.register(key("cookbook"), factory, closer);
resourceManager.register(key("chef"), factory, closer);
resourceManager.register(key("cooking"), factory, closer, keys("light", "fire", "cookbook", "chef"));
resourceManager.register(key("cookingshow"), factory, closer, keys("cooking", "shot"));
return resourceManager;
}
private Set<ResourceManager.Key<TestResource>> keys(String... names) {
Set<ResourceManager.Key<TestResource>> result = new HashSet<>();
for (String name : names) {
result.add(key(name));
}
return result;
}
private List<ResourceManager.Key<TestResource>> keyList(String... names) {
List<ResourceManager.Key<TestResource>> result = new ArrayList<>();
for (String name : names) {
result.add(key(name));
}
return result;
}
private ResourceManager.Key<TestResource> key(String name) {
return new ResourceManager.Key<>(name, TestResource.class);
}
private TestResource create(
ResourceManager resourceManager, ResourceManager.Key<TestResource> key) {
return create();
}
private TestResource create() {
return new TestResource();
}
private TestResource createUnopenable(
ResourceManager resourceManager, ResourceManager.Key<TestResource> key) {
return createUnopenable();
}
private TestResource createUnopenable() {
throw new IllegalStateException("This is unopenable!");
}
private TestResource createUncloseable(
ResourceManager resourceManager, ResourceManager.Key<TestResource> key) {
return createUncloseable();
}
private TestResource createUncloseable() {
return new TestResource(true);
}
static class TestResource implements Closeable {
private final boolean uncloseable;
private boolean closed = false;
TestResource() {
this(false);
}
TestResource(boolean uncloseable) {
this.uncloseable = uncloseable;
}
@Override
public synchronized void close() throws IOException {
if (uncloseable) {
throw new IllegalStateException("I am uncloseable!");
}
closed = true;
}
public boolean isClosed() {
return closed;
}
}
}
<span class="math-container">```</span>
</code></pre>
|
[] |
[
{
"body": "<p>I noticed a few things briefly scanning your code. I'de be happy to share.</p>\n\n<h2>Exception State</h2>\n\n<p>Note the below snippet.</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>ClosingFailedException exception = null;\nfor (Key<?> key : entries.keySet()) {\n try {\n closeInternal(key, true);\n } catch (ClosingFailedException e) {\n exception = e;\n }\n}\nif (exception != null) {\n throw exception;\n}\n</code></pre>\n\n<p>I understand that you want to continue closing resources even if a resource failed to close, but currently as is, only the last failing resource to close will be thrown. It is possible that multiple resources could fail to close. Maybe it would be a good idea to maintain all closure failures, not just the last.</p>\n\n<p>Also, the <code>CyclicDependencyException</code> could probably contain more information detailing which dependencies are cyclic. The current message is not very helpful to a consumer.</p>\n\n<h2>Nested Classes</h2>\n\n<p>I would definitely pull the exceptions and interfaces out side of this implementation. Especially if you decide to make use of more abstractions, such as a <code>ResourceManager</code> interface. This implementation will no longer be the only class having a dependency on all your cool classes. Also, might be a good idea to give your interfaces more descriptive names, especially if they become standalone files.</p>\n\n<h2>Consistency</h2>\n\n<p>Just to keep things consistent, the <code>Entry</code> class should have explicit access modifiers on fields, methods and constructors.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-05T15:58:07.830",
"Id": "452517",
"Score": "0",
"body": "Only the last exception thrown: Hm, this bothers me too, but this is a general practice ([see this, for example](https://github.com/confluentinc/schema-registry/blob/f08138d67868c9d7783f38af1d1b46fbb129238f/client/src/main/java/io/confluent/kafka/schemaregistry/client/rest/RestService.java#L312)). Probably I should create CompoundClosingFailedException."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-05T16:07:14.650",
"Id": "452518",
"Score": "0",
"body": "Entry class should have explicit access modifiers: My convention is to not use modifiers in private inner classes. This is the result of experimentation of long years. What are the arguments against this?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-05T17:38:40.553",
"Id": "452542",
"Score": "0",
"body": "@DávidHorváth In regards to access modifiers, the best argument I can muster is when you override some superclass method, e.g toString(). It MUST be explicitly denoted public. Could look strange having access modifiers on somethings and not others, might as well explicitly state all modifiers. Obviously not the case here but definitely worth the discussion."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-05T04:45:08.310",
"Id": "231872",
"ParentId": "231473",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-29T15:58:18.973",
"Id": "231473",
"Score": "3",
"Tags": [
"java",
"object-oriented",
"generics"
],
"Title": "Resource manager class with basic dependency handling in java"
}
|
231473
|
<p>Write a function that returns a string length N of alternating strings: "A" and "B", starting with the 1st string. How could this be improved for be more performance or efficiency?</p>
<p>Eg: num = 5, should return "ABABA" & given num = 2, should return "AB".</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>function solution(num) {
const str1 = 'A', str2 = 'B';
let res = [];
for(let i = 1; res.length < num; i++ ) {
res.push(i % 2 ? str1 : str2);
}
console.log(res.join(''))
}
solution(5) // return "ABABA"</code></pre>
</div>
</div>
</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-29T16:56:47.460",
"Id": "451519",
"Score": "0",
"body": "Welcome to CodeReview. Check the [help page](https://codereview.stackexchange.com/help) to get tips to improve your submission."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-30T08:36:24.407",
"Id": "451599",
"Score": "2",
"body": "Welcome to Code Review! I have rolled back your last edit. 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": "2019-10-30T11:45:50.857",
"Id": "451611",
"Score": "0",
"body": "Thanks for your feedback @Heslacher, make sense!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-31T10:53:43.787",
"Id": "451762",
"Score": "1",
"body": "@mdiiorio I have rolled back your two last edits for the same reason as Heslacher"
}
] |
[
{
"body": "<p>No need to use abbreviation when you can use meaningful name. For example, use <code>result</code> instead of <code>res</code>. \n\nAlso if you can find a better name for your function, it will improve the readability. I will use <code>alternateLetters</code> but I think we can do better :)</p>\n\n<p>To achieve your problem, you can use a for loop or a generate a range then use <code>map</code> to assign the letter.</p>\n\n<pre><code>function alternateLetters(num) {\n const a = 'A', b = 'B';\n const result = [...Array(num)].map((_, i) => i % 2 ? b : a);\n console.log(result.join(''))\n}\n\nalternateLetters(5) // return \"ABABA\"\n</code></pre>\n\n<p>if you prefer, you can also generate <code>result</code> with <code>keys()</code>:</p>\n\n<pre><code>const result = [...Array(num).keys()].map(i => i % 2 ? b : a);\n</code></pre>\n\n<p>By the way I would make it more generic by passing 'A' and 'B' as parameter:</p>\n\n<pre><code>function alternateLetters(num, a, b) {\n const result = [...Array(num)].map((_, i) => i % 2 ? b : a);\n return result.join('');\n}\n\nconsole.log(alternateLetters(5, 'A', 'B')) // return \"ABABA\"\n</code></pre>\n\n<p>If we have more context about this problem, we may even do better. For example, are \"A\" and \"B\" always constant?</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-29T17:53:15.613",
"Id": "451530",
"Score": "0",
"body": "Why did you passed the underscore on the arrow function before i ?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-29T18:17:19.737",
"Id": "451534",
"Score": "1",
"body": "Using underscore is a convention to show that we can ignore this value. In this case we are looking for the index. Read https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-30T11:50:39.253",
"Id": "451614",
"Score": "0",
"body": "I read and used map() before but in MDN didn't mention this specific convention. But its okey, thanks any way!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-30T13:05:57.760",
"Id": "451637",
"Score": "0",
"body": "@mdiiorio this is a general programming convention. Read the 3rd point [here](https://stackoverflow.com/questions/5893163/what-is-the-purpose-of-the-single-underscore-variable-in-python) for Python or [here](https://docs.microsoft.com/en-us/dotnet/csharp/discards) in C# or even [Go, Dart, Ruby, F#, etc.](https://stackoverflow.com/a/41085252/1248177)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-30T13:57:19.140",
"Id": "451649",
"Score": "0",
"body": "thanks for clarify! I never hear about it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-30T15:32:43.900",
"Id": "451667",
"Score": "0",
"body": "@mdiiorio you are welcome. Always happy to share knowledge :)"
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-29T16:46:23.817",
"Id": "231477",
"ParentId": "231475",
"Score": "1"
}
},
{
"body": "<p>Optimization tips with <em>benchmark</em> demo tests:</p>\n\n<p>Initial approach <em>\"issues\"</em>:</p>\n\n<ul>\n<li><code>for(let i = 1; res.length < num; i++ )</code>. Instead of calculation the resulting array length <code>res.length</code> on each loop iteration, you can just replace it with <code>i <= num</code></li>\n<li><p><code>let res = []; ... res.push() ... res.join()</code>. While the final result should eventually be a string we can declare the result holder as string and perform simple concatenation: </p>\n\n<pre><code>let res = '';\n...\nfor (let i = 1; i <= num; i++ ) { \n res += (i % 2 ? str1 : str2);\n}\n</code></pre></li>\n</ul>\n\n<hr>\n\n<p>The below approach is a bit more performant, in my opinion (as well as benchmarks shown that), using the mentioned improvements:</p>\n\n<pre><code>function cycle(num) {\n const str1 = 'A', str2 = 'B';\n let res = '';\n\n for (let i=1; i <= num; i++) { \n res += (i % 2 ? str1 : str2);\n }\n console.log(res)\n}\n</code></pre>\n\n<hr>\n\n<p>In prepared benchmarks I've named</p>\n\n<ul>\n<li>the initial function (<code>for</code> loop + <code>res</code> array) as <code>cycle1</code></li>\n<li>my approach - as <code>cycle2</code> </li>\n<li>and the function from previous answer <code>alternateLetters</code> - named accordingly</li>\n</ul>\n\n<p>Shared link on <code>http://jsbench.github.io</code>: <a href=\"http://jsbench.github.io/#be710bc0a4b288e024d5bd67286b1c8c\" rel=\"nofollow noreferrer\">http://jsbench.github.io/#be710bc0a4b288e024d5bd67286b1c8c</a></p>\n\n<p>Another benchmark were run on <a href=\"https://i.stack.imgur.com/cZI57.jpg\" rel=\"nofollow noreferrer\">https://jsbench.me/</a> and the results are as below:</p>\n\n<p><a href=\"https://i.stack.imgur.com/cZI57.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/cZI57.jpg\" alt=\"enter image description here\"></a></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-30T11:57:20.647",
"Id": "451620",
"Score": "0",
"body": "Perfect approach! This is just what I was looking for."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-29T19:26:15.437",
"Id": "231487",
"ParentId": "231475",
"Score": "1"
}
},
{
"body": "<p>Why not use doubling to get a logarithmic number of steps?</p>\n\n<pre><code> const str1 = 'A', str2 = 'B';\n let res = '';\n\n if (num >= 1)\n res = str1; // 'A'\n if (num >= 2)\n res += str2; // 'AB'\n\n while (2 * res.length < num) { \n res += res; // 'ABAB', 'ABABABAB', ...\n }\n if (res.length < num) {\n res += res.substring(0, num - res.length)\n }\n console.log(res)\n</code></pre>\n\n<p><strong>EDIT</strong></p>\n\n<p>In the above code I try do create the resulting string of exactly the length required, which costs an additional conditional. We can also get rid of that at the cost of creating the string too long temporarily. The central part would then look like:</p>\n\n<pre><code> while (res.length < num) { \n res += res; // 'ABAB', 'ABABABAB', ...\n }\n res = res.substring(0, num)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-30T11:48:25.350",
"Id": "451613",
"Score": "0",
"body": "@CianPan This could be an other point of resolution, but with the function alternative we can reused it only invoking it. Thanks!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-30T13:29:33.887",
"Id": "451642",
"Score": "0",
"body": "@mdiiorio You're perfectly right: that's precisely \"an other point of resolution\" – an example of another algorithm solving the same problem. And that's it. I don't care about embedding it in a function, it's entirely the user's buisness to decide _IF_ and _HOW_ to incorporate this algo into the actual code (e.g. whether to return the resulting string from a function, or explicitly print it to a virtual console, or show it in some alert window, or save in some output file, etc., depending on limitations of the destination environment and predefined requirements for the solution.)"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-29T22:00:30.697",
"Id": "231494",
"ParentId": "231475",
"Score": "2"
}
},
{
"body": "<p>A short code review;</p>\n\n<ul>\n<li>Your code does not work, it should <code>return</code> something instead it calls <code>console.log</code></li>\n<li><p>Your <code>for</code> loop is icky, either update <code>i</code> and check <code>i</code></p>\n\n<p><code>for(let i = 0; i < num; i++ )</code>) </p>\n\n<p><em>or</em> check <code>res.length</code> </p>\n\n<p><code>while(res.length < num)</code></p></li>\n<li><p><code>solution</code> is too generic for this function name</p></li>\n<li><code>console.log()</code> is missing a semi-colon</li>\n<li><p>Performance;</p>\n\n<ul>\n<li>Checking whether <code>i</code> is odd every time seems like much, you can avoid that</li>\n<li>Remember<code>String.repeat()</code>, you could repeat by calling <code>\"AB\".repeat(num/2)</code> and add an <code>\"A\"</code> if <code>num</code> is odd.</li>\n</ul></li>\n</ul>\n\n<p>Obligatory rewrite</p>\n\n<pre><code> //repeatAB(5) => \"ABABA\"\n function repeatAB(n) {\n return \"AB\".repeat(n/2) + (n%2 ? \"A\" : \"\");\n }\n\n console.log(repeatAB(5)) // returns \"ABABA\"\n</code></pre>\n\n<p>I ran this approach against the other approaches for the heck of it, this approach destroys the other approaches (at least visually):</p>\n\n<p><a href=\"http://jsbench.github.io/#11a2b8507a7f9290c6ef6cda596f8179\" rel=\"nofollow noreferrer\">http://jsbench.github.io/#11a2b8507a7f9290c6ef6cda596f8179</a></p>\n\n<p><a href=\"https://i.stack.imgur.com/Df02C.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/Df02C.png\" alt=\"enter image description here\"></a></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-30T15:55:10.817",
"Id": "451674",
"Score": "0",
"body": "@konjin my code works. I just console log the specific result and don't use a return statement to be more explicit here, as a use case. Then I checked res.length so what do you mean? I personally like avoiding using semicolons in my code, and is not a bad practice.... Thanks for your suggestion and please be more polite with the community."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-30T16:59:14.360",
"Id": "451687",
"Score": "0",
"body": "Greetings, your description says `Write a function that returns a string length N `, either your description is wrong or your code is wrong. For semicolons, you are missing only one, so you are inconsistent in applying semicolons, I assumed you prefer to put semicolons. The `for` comment is style, to make it easier for the reader. As for politeness, I am open to reading how you would rephrase parts or all of my answer, as I dont see impoliteness there. (though that feedback should happen on chat)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-31T09:44:05.143",
"Id": "451755",
"Score": "0",
"body": "@konijn I would disagree that not adding semi colons is not bad practice. The rules for automatic semi colon insertion are not particularly simple and when working on a project with multiple developers with differing skill-sets it is unlikely that everyone will know the rules. This would then lead to an inconsistent programming approach which over time makes the code less readable."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-31T13:10:54.170",
"Id": "451783",
"Score": "0",
"body": "@Magrangs Agreed, but not a hill to die on in this answer ;)"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-30T11:36:28.953",
"Id": "231524",
"ParentId": "231475",
"Score": "5"
}
},
{
"body": "<p>Try using this,</p>\n\n<pre><code>if n == 1:\n print \"A\"\nelif n%2 == 0:\n temp = (n/2);\n print \"AB\"*temp\nelse:\n temp = (n-1)/2\n print \"AB\"*temp + \"A\"\n</code></pre>\n\n<p>In above pseudo code, you can see if n is even then print \"AB\" * (n/2) times and if odd reduce one number and print \"AB\" divided by 2 times and add \"A\"</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-30T12:04:08.130",
"Id": "231529",
"ParentId": "231475",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-29T16:25:16.593",
"Id": "231475",
"Score": "3",
"Tags": [
"javascript",
"algorithm"
],
"Title": "Alternating chars N times"
}
|
231475
|
<p>I am verifying certain codes that work well and I don't know what else to optimize in them or what other tests to do: in this case it is a php script that takes the data of the <code>$_POST</code> variable analyzes them and converts them into an array, this is since in some cases the post field may contain a <code>JSon</code> string.</p>
<p>I leave a functional example where I have manually set the <code>$_POST</code> variable to do the Demonstration:</p>
<p><a href="https://wtools.io/php-sandbox/bqsT" rel="nofollow noreferrer">https://wtools.io/php-sandbox/bqsT</a></p>
<p>Original Code example:</p>
<pre><code><?php
#Example Array
$_POST = array(
"valor1" => 1200,
"valor2" => "texto",
"valor3" => true,
"valor4" => '{"seclvl_text":"datp","seclvl_boolean":"false"}',
);
#Validate Function for Json
function ValidateJson($Var) {
if (!is_array($Var)) {
return ((json_decode($Var) != null) AND (is_object(json_decode($Var)) OR is_array(json_decode($Var)))) ? true : false;
} else {
return false;
}
}
#Parse Function
function buildVirtualData($data) {
if (is_array($data)) {
$result = [];
foreach ($data as $key1 => $val1) {
$valJson = ValidateJson($val1);
if ($valJson) {
$jsonObj = json_decode($val1, true);
$result[$key1] = buildVirtualData($jsonObj);
} elseif ($valJson == false && is_array($val1)) {
foreach ($val1 as $key2 => $val2) {
$result[$key1][$key2] = buildVirtualData($val2);
}
} else {
if ($val1 === 'true') {
$val1 = true;
} else if ($val1 === 'false') {
$val1 = false;
}
$result[$key1] = $val1;
}
}
return $result;
} else {
if (ValidateJson($data)) {
$jsonObj = json_decode($data, true);
return buildVirtualData($jsonObj);
} else {
return $data;
}
}
}
# call to Function:
$data = buildVirtualData($_POST);
echo '<pre>';
echo var_dump($data);
echo '</pre>';
</code></pre>
<p>this parse have the feature that convert any text true or false to Boolean.</p>
|
[] |
[
{
"body": "<p>I think you're are definitely on the right track here. I spent a good deal of time trying to refactor, here's what I came up with </p>\n\n<pre><code>#Validate Function for Json\nfunction jsonDecodeAndValidate($var, $assoc = false) {\n if(!is_string($var))\n return false;\n if(!$decoded = json_decode($var, $assoc))\n return false;\n if(!is_object($decoded) && !is_array($decoded))\n return false;\n return $decoded;\n}\n#Parse Function\nfunction buildVirtualData($data) {\n if (is_array($data) || is_object($data)) {\n foreach ($data as $key1 => $val1) {\n\n if(is_array($val1)){\n foreach ($val1 as $key2 => $val2) {\n $result[$key1][$key2] = buildVirtualData($val2);\n }\n }\n else if($decoded = jsonDecodeAndValidate($val1)){\n $result[$key1] = buildVirtualData($decoded);\n } else {\n if(in_array($val1, ['true', 'false']))\n $val1 = filter_var($val1, FILTER_VALIDATE_BOOLEAN);\n $result[$key1] = $val1;\n }\n }\n return $result;\n } else {\n if ($decoded = jsonDecodeAndValidate($data, true)) {\n return buildVirtualData($decoded);\n } else {\n return $data;\n }\n }\n}\n</code></pre>\n\n<p>At the very least this will save you some calls to <code>json_decode</code> as the decoding is done once per iteration.</p>\n\n<p>EDIT: I took another stab at it. I think you can boil it down to this.</p>\n\n<pre><code>#decodeand validate\nfunction jsonDecodeAndValidate($var) {\n if(!is_string($var))\n return $var;\n if(!$decoded = json_decode($var, true))\n return $var;\n if(!is_array($decoded))\n return $var;\n return $decoded;\n}\n#Parse Function\nfunction buildVirtualData($data, &$build) {\n $data = jsonDecodeAndValidate($data);\n if(is_array($data) || is_object($data)){\n foreach($data as $key => $value){\n buildVirtualData($value, $build[$key]);\n }\n } else {\n if ($data === 'true')\n $data = true;\n if ($data === 'false')\n $data = false;\n $build = $data;\n }\n}\n# call to Function:\n$build = [];\nbuildVirtualData($_POST, $build);\necho '<pre>';\necho json_encode($build, JSON_PRETTY_PRINT);\necho '</pre>';\n</code></pre>\n\n<p>You just have to declare your array outside of the function.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-30T21:08:28.717",
"Id": "451710",
"Score": "0",
"body": "this trown error: filter_var($data, FILTER_VALIDATE_BOOLEAN);"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-30T21:13:06.463",
"Id": "451711",
"Score": "0",
"body": "is and error of the website sandbox test... sorry"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-30T21:18:03.583",
"Id": "451712",
"Score": "1",
"body": "I love it when I see this: `&$build` optimizing memory usage with pointers."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-30T21:42:49.783",
"Id": "451713",
"Score": "0",
"body": "I changed that part back to what it was. Seems you need a module installed to use `filter_var`"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-30T15:02:15.457",
"Id": "231548",
"ParentId": "231479",
"Score": "3"
}
},
{
"body": "<p>I don't think your JSON validation function is very useful because it does more or less what does the <code>json_decode</code> function itself, except that it tests if the result is an array or an object (that is useless too, since <code>buildVirtualData</code> always uses <code>json_decode</code> with the second parameter set to <code>true</code> and since the <code>$_POST</code> variable can't contain an object but only strings and arrays.).</p>\n\n<p>Always use a strict comparison with null when you want to check the return of <code>json_decode</code> for validity. As a counter-example, elements like an empty string, 0 or <code>false</code> that are valid JSON themselves, return <code>true</code> in this non-strict comparison: <code>var_dump(json_decode('\"\"') == null);</code></p>\n\n<p>Manualy replacing the strings \"true\" or \"false\" with a boolean isn't needed since <code>json_decode</code> does that automatically.</p>\n\n<p>You can rewrite your function like that:</p>\n\n<pre><code>function buildVirtualData($var) {\n\n if ( is_string($var) ) {\n\n $json = json_decode($var, true);\n\n if ( $json !== null )\n $var = $json;\n\n }\n\n if ( is_array($var) )\n return array_map('buildVirtualData', $var);\n\n return $var;\n}\n</code></pre>\n\n<p><a href=\"https://3v4l.org/JZ0i4\" rel=\"nofollow noreferrer\">demo</a></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-01T12:47:08.227",
"Id": "451985",
"Score": "0",
"body": "This wouldn't work if a php object were passed. Or rather, it wouldn't parse it into an array."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-01T15:42:45.293",
"Id": "452022",
"Score": "1",
"body": "@Rager: a POST variable doesn't contain php object."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-01T17:50:03.303",
"Id": "452040",
"Score": "0",
"body": "$_POST = json_decode(\n<<<JSON\n {\n \"valor1\" : 1200,\n \"valor2: : \"texto\",\n \"valor3\" : true,\n \"valor4\" : \"{\\\"seclvl_text\\\":\\\"datp\\\",\\\"seclvl_boolean\\\":\\\"false\\\"}\"\n }\nJSON\n);"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-01T17:53:00.187",
"Id": "452043",
"Score": "0",
"body": "@Rager: are you serious?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-01T18:00:31.657",
"Id": "452044",
"Score": "0",
"body": "I guess you're right. $_POST cannot be object."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-01T18:01:48.037",
"Id": "452045",
"Score": "0",
"body": "Unless someone were to get the raw data and decode themselves."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-01T18:02:53.583",
"Id": "452046",
"Score": "0",
"body": "@Rager: Even if it is possible to use it as any variable, it's highly recommended to not modify the `$_POST` or the `$_GET` variables and to work with copies if needed."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-05T07:33:04.803",
"Id": "452458",
"Score": "0",
"body": "@Rager even though you are right that $_POST cannot be object. Nothing implies that the function only works with $_POST. It actualy has no idea where it is coming from. If it feels like it can handle objects as well as arrays, then why not?"
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-01T11:41:45.883",
"Id": "231667",
"ParentId": "231479",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "231548",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-29T16:53:03.887",
"Id": "231479",
"Score": "3",
"Tags": [
"php",
"array",
"parsing"
],
"Title": "POST variable analysis contains JSON format string PHP"
}
|
231479
|
<p>I have multiple inputs that each one has an increment and decrement button </p>
<p>The buttons will be pressed multiple times so i am looking to optimize my selector:</p>
<p>So should i keep the first one (which selects by attribute) or the second? Or anything more optimized.</p>
<pre><code>$("[data-id-col="+thisID+"]")
$("input:tel#"+thisID+")
$("body").on('click','.incButton',e=>{
let thisID = e.currentTarget.getAttribute("d-id");
let colInput = $("[data-id-col="+thisID+"]");
colInput.val( parseInt( colInput.val())+1);
colInput.change();
});
</code></pre>
<p>Html:</p>
<p><strong>Input</strong></p>
<pre><code><div class="handle-counter" id="handleCounter3">
<input type="tel" data-id-col="8900" id="qty_inputCol" class="qty_col">
</div>
</code></pre>
<p><strong>Button</strong></p>
<pre><code><button type="button" d-id="8888" class="btn btn-primary btn-block inc"></button>
</code></pre>
<p><a href="https://learn.jquery.com/performance/optimize-selectors/" rel="nofollow noreferrer">https://learn.jquery.com/performance/optimize-selectors/</a></p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-30T05:47:30.017",
"Id": "451580",
"Score": "2",
"body": "Unless you see this code taking a noticeable amount of time in devtools profiler, there's no need to optimize it. What you're doing now is premature optimization, which is pointless. If you really insist you can simply remember the element reference as an expando property on the clicked element."
}
] |
[
{
"body": "<p>Your second selector doesn't work with the data provided <code>input:tel#8888</code> is not the <code>id=</code> of the input. </p>\n\n<p>IDs <em>should</em> start with a letter (for compatibility), so if you changed your input to <code><input id=\"inp8888\"></code> then you could use <code>input:tel#inp8888</code> in which case, you can use <code>$(\"#inp8888\")</code> as long as your IDs are unique (which they should be).</p>\n\n<p>Selecting by ID is the fastest selection method. </p>\n\n<blockquote>\n <p>jQuery uses document.getElementById(), which is faster</p>\n</blockquote>\n\n<p><a href=\"https://learn.jquery.com/performance/optimize-selectors/#id-based-selectors\" rel=\"nofollow noreferrer\">https://learn.jquery.com/performance/optimize-selectors/#id-based-selectors</a></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-30T09:05:39.037",
"Id": "231520",
"ParentId": "231480",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-29T17:02:24.283",
"Id": "231480",
"Score": "0",
"Tags": [
"javascript",
"jquery",
"dom"
],
"Title": "Jquery Selector optimization for multiple clicks"
}
|
231480
|
<p>My database:</p>
<p><a href="https://i.stack.imgur.com/8OP3r.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/8OP3r.png" alt="Database"></a></p>
<p>Class:</p>
<pre><code>Class Category {
function __construct($db) {
$this->db = $db;
}
public function groupByUnderCategoryName() {
$query = $this->db->prepare("SELECT categoryName, id, title FROM test2");
$query->execute();
return $query->fetchAll(PDO::FETCH_GROUP);
}
}
</code></pre>
<p>Seeing picture above, probably first thing comes to mind is, creating another table for categories and JOIN them. Actually that is what I already did, please see above picture as a result of joining two tables.</p>
<p>This is result of above query:</p>
<pre><code>array (size=3)
'Action' =>
array (size=2)
0 =>
object(stdClass)[5]
public 'id' => string '1' (length=1)
public 'title' => string 'Action#1' (length=8)
1 =>
object(stdClass)[7]
public 'id' => string '3' (length=1)
public 'title' => string 'Action#2' (length=8)
'Drama' =>
array (size=2)
0 =>
object(stdClass)[6]
public 'id' => string '2' (length=1)
public 'title' => string 'Drama#1' (length=7)
1 =>
object(stdClass)[9]
public 'id' => string '5' (length=1)
public 'title' => string 'Drama#1' (length=7)
'Comedy' =>
array (size=1)
0 =>
object(stdClass)[8]
public 'id' => string '4' (length=1)
public 'title' => string 'Comedy#1' (length=8)
</code></pre>
<p>As very proud I am to use <code>PDO::FETCH_GROUP</code> to get result above, I am not sure if it's a good idea to print it like that, and I would like you to review and help with me better practice:</p>
<pre><code>$category = new Category($db);
foreach ($category->groupByUnderCategoryName() as $key => $value) {
echo "<h3>{$key}</h3>";
foreach ($value as $t_value) {
echo "<h4>{$t_value->title}</h4>";
}
}
</code></pre>
<p>Result:</p>
<p><a href="https://i.stack.imgur.com/G97K1.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/G97K1.png" alt="result"></a></p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-29T19:21:04.870",
"Id": "451538",
"Score": "0",
"body": "Why do you think it's not a good idea?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-29T19:47:46.990",
"Id": "451543",
"Score": "0",
"body": "@YourCommonSense, foreach loop inside of another foreach loop seemed only solution to me, but I think avoiding the nesting would be better. maybe."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-29T19:50:31.227",
"Id": "451544",
"Score": "1",
"body": "If you have an array, the only way to iterate it over is a loop. It means that if you have a nested array, then a nested loop is the only way."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-29T19:57:13.313",
"Id": "451545",
"Score": "0",
"body": "Glad to hear that from your side, so just leaving code here since I believe it can be very helpful for future visitors."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-29T17:32:45.700",
"Id": "231481",
"Score": "1",
"Tags": [
"php",
"mysql"
],
"Title": "Printing nested arrays"
}
|
231481
|
<p>I like to request a review of the code below, which is my attempt at answering the question <a href="https://leetcode.com/problems/longest-palindromic-substring/" rel="nofollow noreferrer">here</a> on LeetCode site. The code passes 43 tests, but it times out on the next one. I copied and ran the test on my machine using visual studio and it seems to give me an answer. I wonder if there is something about the site LeetCode that I should know like a config setting somewhere.</p>
<p>Regardless the problem asks to find the longest palindrome in a string. I have seen and read other posts about this problem, like <a href="https://codereview.stackexchange.com/questions/47181/longest-palindrome-in-a-string">this</a> one, but I would really like to see answers in C#, because I originally converted my code from Java to C# and found out about the slight difference in the <code>.Substring()</code> method between the two languages. I tried to address it by creating my own method, and wonder if the time out is due to this adjustment.</p>
<pre><code>private static string LongestPalindrome(string s)
{
int length = s.Length;
if (s.Length < 2 || s == null)
{
return s;
}
Boolean[,] isPalindrome = new Boolean[length, length];
int left = 0;
int right = 0;
for (int j = 0; j < length; j++)
{
for (int i = 0; i < j; i++)
{
Boolean isInnerWordPalindrome = isPalindrome[i + 1, j - 1] || j - i <= 2;
if (s.ElementAt(i) == s.ElementAt(j) && isInnerWordPalindrome)
{
isPalindrome[i, j] = true;
if (j - i > right - left)
{
left = i;
right = j;
}
}
}
}
return JavaStyleSubstring(s, left, right + 1);
}
private static string JavaStyleSubstring(string s, int beginIndex, int endIndex)
{
// simulates Java substring function
int len = endIndex - beginIndex;
return s.Substring(beginIndex, len);
}
</code></pre>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-29T17:48:16.857",
"Id": "231483",
"Score": "3",
"Tags": [
"c#",
"performance",
"programming-challenge",
"palindrome"
],
"Title": "Longest palindrome code in C# takes time out on LeetCode"
}
|
231483
|
<p>I have an application which requests data from a REST endpoint 50 items at a time and displays results in the UI. I would like to paginate each API response into <em>smaller</em> arrays for display and then request a <em>new</em> API resource when the user reaches the end of the children arrays.</p>
<p><a href="https://codepen.io/bbennett/pen/NWWaPaX?editors=0010" rel="nofollow noreferrer">I have a working CodePen demo</a> using the SWAPI and paginating results (5 at a time) and I'm wondering if there is a better/more efficient way to achieve the same result. </p>
<pre class="lang-js prettyprint-override"><code>// See the CodePen for a working demo using these HTMl elements
const container = document.querySelector('#container');
const start = document.querySelector('#button');
let planetArrays = [];
let nextPage;
let refresh = true;
async function request(url) {
// Call specific page of results if provided
url = url || 'https://swapi.co/api/planets';
var data = await fetch(url);
var json = await data.json();
return json;
}
async function getData() {
let data = await request(nextPage)
// Store the next page for future calls
nextPage = data.next;
// Split the big array into smaller arrays
for(var d of data.results) {
planetArrays.push(data.results.splice(0, 5));
}
// Return the spliced Array
return planetArrays;
}
async function next() {
var childPage, response;
// Define which child array in smallArrays to display
var inSmallArray = isNaN(parseInt(start.dataset.page));
childPage = (!inSmallArray) ? parseInt(start.dataset.page) : 0;
// hit the API if it's a refresh call
if(refresh) {
var response = await getData(nextPage);
refresh = false;
} else {
// if it's NOT the first call, get the stored array
response = planetArrays;
}
// Do a check to see if we're on the last page in memory
if(childPage >= planetArrays.length-1) {
// Make a refresh call on the next click
refresh = true;
}
container.innerText = "";
for(var c = 0; c < response[childPage].length; c++) {
var p = document.createElement('p');
p.innerText = response[childPage][c].name;
container.appendChild(p);
}
// iterate the planetArrays
var newPage = childPage + 1;
start.dataset.page = newPage;
}
start.addEventListener("click", next)
</code></pre>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-29T18:44:01.767",
"Id": "231485",
"Score": "1",
"Tags": [
"javascript",
"pagination"
],
"Title": "Paginating a paginated API response"
}
|
231485
|
<p>I'm new with Ruby and am trying to improve my coding skills. This program gets personal information for three people, and then prints them.</p>
<p>It works, but I'm sure it's not the best and certainly not the fanciest way to do it.</p>
<p>I was hoping to get some advice here on how to do it faster/shorter/better/smarter...It is really hard to improve without knowing your mistakes.</p>
<h2>The code:</h2>
<pre><code># Define a person with name, age, origin
class Person
def input(count)
puts "Hi, let\'s create three new Person. Start with number #{count}"
puts "What\'s your name?"
@name = gets
@name = @name.delete("\n")
puts "How old are you?"
@age = gets
@age = @age.delete("\n")
puts "Where are you from?"
@origin = gets
@origin = @origin.delete("\n")
puts "I summarize! You are #{@name} and #{@age} years old from #{@origin}"
puts "Is that correct? \nEnter \"0=Yeah\" or \"Nah\""
@antwort = gets
if @antwort.to_i == 0
puts "Sweet #{@name}, let us get to the next one"
person_return = [@name, @age,@origin]
return person_return
else
puts "Get off. Let us try again" # How to go retry?
end
end
end
person_one = Person.new
var_person_one = person_one.input(1)
puts "Press Enter for next Person\n"
gets
person_two = Person.new.input(2)
var_person_two = person_two
puts "Press Enter for next Person\n"
gets
person_three = Person.new.input(3)
var_person_three = person_three
p var_person_one
p var_person_two
p var_person_three
</code></pre>
<h3>Output:</h3>
<pre class="lang-none prettyprint-override"><code>Hi, let's create three new Person. Start with number 1
What's your name?
Kevin
How old are you?
29
Where are you from?
Hamburg
I summarize! You are Kevin and 29 years old from Hamburg
Is that correct?
Enter "0=Yeah" or "Nah"
0
Sweet Kevin, let us get to the next one
Press Enter for next Person
Hi, let's create three new Person. Start with number 2
What's your name?
Steven
How old are you?
22
Where are you from?
London
I summarize! You are Steven and 22 years old from London
Is that correct?
Enter "0=Yeah" or "Nah"
0
Sweet Steven, let us get to the next one
Press Enter for next Person
Hi, let's create three new Person. Start with number 3
What's your name?
Mike
How old are you?
33
Where are you from?
Tampa,FL
I summarize! You are Mike and 33 years old from Tampa,FL
Is that correct?
Enter "0=Yeah" or "Nah"
1
Get off. Let us try again
["Kevin", "29", "Hamburg"]
["Steven", "22", "London"]
nil
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-29T19:21:54.353",
"Id": "451539",
"Score": "2",
"body": "Functionality *missing* is something that should be handled via StackOverflow because you don't know how to implement it and the implementation bits of that are not on topic for Code Review. General code review *also* requires that the code behave the way you expect it to, which it sounds like it doesn't, so it may be skirting the line of 'on-topicness' because you indicate you are missing functionality that you desire. (I'll leave that up to the community to determine however)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-29T19:25:51.700",
"Id": "451540",
"Score": "0",
"body": "Also, it sounds like you should be looking into how loops in Ruby work. (Literally, that's what you need, a loop around the inquiry until you get a valid message, before continuing or exiting)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-29T19:26:02.737",
"Id": "451541",
"Score": "2",
"body": "Hi Thomas, thanks for the quick answer! I might put it in wrong words. The code snippet works fine, it does what it should do! I'm just looking for a way to improve and write better code. I deleted the question for goto-function/loop to make it more clear. (You already solved that question by mentioning a loop around the inquiry)"
}
] |
[
{
"body": "<p>I have a few suggestions. Some high-level and then I'll go through your code.</p>\n\n<p>My first suggestion would be to focus on readability. That means:</p>\n\n<ul>\n<li>good use of spacing</li>\n<li>descriptive names for modules, classes, methods, variables, everything</li>\n<li>think about the different concepts involved</li>\n<li>extract into simple modules, classes and methods</li>\n<li>start small</li>\n<li>read the documentation (<a href=\"https://ruby-doc.org/\" rel=\"nofollow noreferrer\">here</a>), particularly string, hash, array</li>\n</ul>\n\n<p>For example, look at a subsection of your code with a little spacing:</p>\n\n<pre><code>class Person\n def input(count) \n puts \"Hi, let\\'s create three new Person. Start with number #{count}\"\n\n puts \"What\\'s your name?\"\n @name = gets\n @name = @name.delete(\"\\n\")\n\n puts \"How old are you?\"\n @age = gets\n @age = @age.delete(\"\\n\")\n\n puts \"Where are you from?\"\n @origin = gets\n @origin = @origin.delete(\"\\n\")\n end\nend\n</code></pre>\n\n<p>I would argue you can clearly see the structure of the 3 questions, and all it took was 3 blank lines in the right place.</p>\n\n<p>Next up is <strong>proper naming</strong>. You look good for the most part. You have <code>@name</code>, <code>@age</code>, <code>@origin</code>.. you have <code>@antwort</code>. From what I understand that is German for answer. Up to you if you want to mix German and English, but be aware of the native language of other people who will be reading your code. I would do the safe thing and use <code>@answer</code> instead.</p>\n\n<p>Avoid redundancy in naming. For example, you have <code>return person_return</code>. Instead, just use <code>return person</code>. Instead of <code>var_person_one</code> just use <code>person_one</code> (note: this is still not descriptive enough, but better).</p>\n\n<p>Now let's have a <strong>look at the different concepts involved, turn them into classes</strong>.</p>\n\n<p>You have a <code>Person</code>.. but the question and answer format doesn't really suit the person itself. Think about what you could do if you introduced a <code>Question</code> class and an <code>Answer</code> class.</p>\n\n<p>You have <code>name</code>, <code>age</code> and <code>origin</code> as answers to your questions about person, then you build up an array of those instance variables and call that array a person, but those are <code>attributes</code> of the <code>Person</code> class, so add them to it:</p>\n\n<pre><code>class Person\n attr_accessor :age, :name, :origin\nend\n</code></pre>\n\n<p>You also have this concept of a QA session being interacted with through the console. So, you could create a <code>QuestionAnswerSession</code>.</p>\n\n<p>To not complicate things too much you could get quite far by using just a <code>Person</code> and <code>QuestionAnswerSession</code> and forget the separate <code>Question</code> and <code>Answer</code> classes.</p>\n\n<p>The qa session is responsible for outputting questions to the console and listening for answers, then using those answers to create <code>Person</code> objects.</p>\n\n<p>My next suggestion would be to <strong>start small</strong>. Just introduce a couple of attributes and questions at first and forget about the multiple persons. Try to figure out the overall structure. It will be fewer lines and will be easier to take in and allow to focus on the design.</p>\n\n<p>Let's say we have a <code>Person</code> with a <code>name</code> and <code>age</code> attribute, and we have corresponding questions. From that we want to assign <code>name</code> and <code>age</code> to a <code>Person</code> and, finally, output the <code>Person</code> to the console.</p>\n\n<p>Let's create the person:</p>\n\n<pre><code>class Person\n attr_accessor :name, :age\nend\n\n# usage\n# Person.new(name: 'Dave', age: 20)\n# or\n# person = Person.new\n# person.name = 'Dave'\n# person.age = 20\n</code></pre>\n\n<p>Now let's build the QA session.</p>\n\n<pre><code>class QuestionAnswerSession\n def start\n puts \"Hi, let's create a new Person\"\n\n person = Person.new\n\n puts \"What's your name?\"\n person.name = gets.strip\n\n puts \"What's your age?\"\n person.age = gets.strip\n\n puts person\n end\nend\n\nqa = QuestionAnswerSession.new\nqa.start\n</code></pre>\n\n<p>Few minor things first. Notice I've removed <code>What\\'s</code> which is now simply <code>What's</code>. This is an escape character and is only required if the enclosing quote is the same. Since you are using double quotes you do not need to escape it.</p>\n\n<p>Also note I have replaced <code>@age.delete(\"\\n\")</code> with <code>String#strip</code> (<a href=\"https://ruby-doc.org/core-2.6/String.html#method-i-strip\" rel=\"nofollow noreferrer\">docs here</a>). This will remove the newline character for you.</p>\n\n<p>The qa session itself is fairly simple. You instantiate it first, then you call the <code>start</code> method which outputs a question and starts listening for input. It then builds up attributes for a person object and outputs the final result.</p>\n\n<p>I would add one small aspect to this to give you an idea on how to expand the behaviour. Let us say we wanted the person to be able to speak for itself. When we do <code>puts person</code> this is what we get:</p>\n\n<p><code>#<Person:0x0000000002572518 @name=\"Dave\", @age=\"20\"></code></p>\n\n<p>Not very nice. If you wanted to output something cleaner, you could add it to the qa session class (<code>puts \"Hi, my name is #{person.name}\"</code>), but you could also add a simple method to the <code>Person</code> class such as:</p>\n\n<pre><code>class Person\n def introduce_self\n \"Hi, my name is #{name} and I'm #{age}\"\n end\nend\n</code></pre>\n\n<p>Then in the qa session, instead of <code>puts person</code> you could do <code>puts person.introduce_self</code>.</p>\n\n<p>Extracting different responsibilities into simple, descriptive methods is a great way to keep things manageable, rather than dumping everything into the same method.</p>\n\n<p>Though there are other ways you could improve your code and it could be designed with numerous approaches, I'd urge you to focus on these important aspects first as outlined above, then tackle multiple <code>Person</code> objects later.</p>\n\n<p>Hope that helps! If you have any questions leave a comment.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-14T14:37:13.203",
"Id": "232385",
"ParentId": "231486",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "232385",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-29T19:11:54.133",
"Id": "231486",
"Score": "3",
"Tags": [
"performance",
"ruby"
],
"Title": "Store personal data for later use"
}
|
231486
|
<p>I am trying to get equal number of records in both columns, even if that means that first column doesn't fill page to bottom on the second page. The only way I was able to do this was by using a maxrow count and breaking when it is equal to the max row count.</p>
<pre><code> public List<DataForExcelExport> GetData()
{
var list = new List<DataForExcelExport>();
int ROWS_PER_PAGE = 41;
int MaxRow = 0;
SqlDataAdapter dataAdapter = new SqlDataAdapter(selectCommandText, connectionString);
DataTable dataTable = new DataTable();
dataAdapter.Fill(dataTable);
bool flgLastPage = false;
for (int i = 0; i < dataTable.Rows.Count; i++)
{
DataRow dr = dataTable.Rows[i];
var item = new DataForExcelExport();
SetItemData(dr, item, true);
if (i + ROWS_PER_PAGE < dataTable.Rows.Count)
{
SetItemData(dataTable.Rows[i + ROWS_PER_PAGE], item, false);
}
list.Add(item);
if (flgLastPage == false)
{
if ((i + 1) % ROWS_PER_PAGE == 0)
{
i += ROWS_PER_PAGE;
int remaining = dataTable.Rows.Count - (i + 1);
if (remaining < 2 * ROWS_PER_PAGE)
{
ROWS_PER_PAGE = remaining / 2 + remaining % 2;
flgLastPage = true;
}
}
}
int maxrow = i + ROWS_PER_PAGE;
if (maxrow == dataTable.Rows.Count)
{
break;
}
}
return list;
}
</code></pre>
<p>expected output: when there are a total of 118 rows</p>
<pre><code>- page 1
_________
1 | 41
... |...
38 | 78
39 | 79
40 | 80
_________
- page 2
_________
81 | 99
82 | 100
... | ...
98 |118
_________
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-01T15:57:16.703",
"Id": "452025",
"Score": "0",
"body": "It is not easy to understand this code. I think there is too many variables changing their values while you are loading your data. My advice is - as you know `dataTable.Rows.Count` and `ROWS_PER_PAGE` you can calculate the number of pages, and number of rows on the given page in advance, then process things with 2 loops. One for pages, one for rows"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-04T20:57:51.637",
"Id": "452431",
"Score": "0",
"body": "This would be a lot easier if you posted the whole program. So am I correct in now assuming you want 80 entries per page?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-04T21:24:48.410",
"Id": "452434",
"Score": "0",
"body": "Hey there, looks like you're having login issues; feel free to [contact the community team](https://codereview.stackexchange.com/contact) if you would like your two accounts merged."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-05T15:22:28.557",
"Id": "452510",
"Score": "0",
"body": "@T145 correct page 1 should display 80 rows and then the remaining should display on page 2"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-18T17:05:40.627",
"Id": "454260",
"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>Try following some simple rules: Avoid setting flags in loops. Try calculating the data you need before taking action. Only increment counters inside loop declaration. This way even if something gets broken - you will not have to wonder \"how did we end up here?\". Instead you will be able to tell \"this index / limit is not calculated correctly\".</p>\n\n<p>Also when saying </p>\n\n<blockquote>\n <p>even if that means that first column doesn't fill page to bottom on the second page</p>\n</blockquote>\n\n<p>Did you mean:</p>\n\n<blockquote>\n <p>even if that means both columns don't fill the last page to the bottom</p>\n</blockquote>\n\n<p>This is how I understood it.</p>\n\n<pre><code>int ROWS_PER_PAGE = 41;\nint totalDataCount = dataTable.Rows.Count;\nint pagesToProcess = (int)Math.Ceiling(totalDataCount / 2.0 / ROWS_PER_PAGE);\nint itemsPerPage = ROWS_PER_PAGE * 2;\n\nfor(int pageIdx = 0; pageIdx < pagesToProcess; pageIdx++)\n{\n int itemsOnThisPage = (pageIdx + 1) * itemsPerPage >= totalDataCount ? totalDataCount - pageIdx * itemsPerPage : itemsPerPage;\n int rowsOnThisPage = (int)Math.Ceiling( itemsOnThisPage / 2.0 );\n for( int rowIdx = 0; rowIdx < rowsOnThisPage; rowIdx++)\n {\n var item = new DataForExcelExport();\n int itemIdx1 = pageIdx * itemsPerPage + rowIdx;\n int itemIdx2 = itemIdx1 + rowsOnThisPage;\n SetItemData(dataTable.Rows[itemIdx1], item, true);\n if(totalDataCount > itemIdx2)\n SetItemData(dataTable.Rows[itemIdx2], item, false);\n }\n}\n</code></pre>\n\n<p>Ah yes, and try to name variables in a meaningful way. Names like <code>i</code> or <code>maxrow</code> do not tell what the variable is really used for.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-01T20:04:04.750",
"Id": "452057",
"Score": "0",
"body": "I get an error about can't convert double to int on the second line"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-02T07:42:23.700",
"Id": "452099",
"Score": "0",
"body": "On the `Math.Ceiling`? There might be a cast needed, try `=(int)Math.Ceiling(...)`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-14T16:08:53.433",
"Id": "453803",
"Score": "0",
"body": "@jakubiszon I dont get out of the innter for loop? when do I add the item to the list?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-14T16:29:11.297",
"Id": "453807",
"Score": "0",
"body": "After processing page 1 it set itemsOnThisPage back to 82 and rowsOnThisPage to 41 should that just be the remaining because then itemIdx1 should be 42 it goes back to 0"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-15T17:23:15.873",
"Id": "453955",
"Score": "0",
"body": "1) What do you mean by not getting out of the inner for loop? Not using `break`? No it is not needed. Break is used when you meet an unforseen condition. There is nothing unforseen to happen here."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-15T17:30:02.420",
"Id": "453957",
"Score": "0",
"body": "2) adding an item to the list - you mean this part `var item = new DataForExcelExport`? It happens per each two items, so it should be added in the inner loop."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-18T16:52:00.760",
"Id": "454257",
"Score": "0",
"body": "When the app starts the values of the objects are totalDataCount = 124, pagesToProcess = 2 and itemsPerPage = 82, that looks correct for page 1. But then on page 2 loop pagesToProcess is increase to 3 is that correct?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-19T09:56:52.563",
"Id": "454319",
"Score": "0",
"body": "Oh my. You are right. It is `pageIdx` which should be incremented. Correcting it now."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-19T18:59:36.603",
"Id": "454415",
"Score": "0",
"body": "hmmm from record 52 to 62 it just fills in ColumnOne"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-20T19:50:09.737",
"Id": "454553",
"Score": "0",
"body": "This `int itemIdx1 = pageIdx * itemsPerPage + rowIdx * 2;` should be `int itemIdx1 = pageIdx * itemsPerPage + rowIdx;` I just corrected it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-20T19:54:27.620",
"Id": "454554",
"Score": "0",
"body": "btw. If it was difficult to figure out how my quickly skeched up code should work - this is why programmers need to write readable code and give variables good names."
}
],
"meta_data": {
"CommentCount": "11",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-01T16:21:43.620",
"Id": "231688",
"ParentId": "231488",
"Score": "3"
}
},
{
"body": "<p>Because this function is presented w/out a context to adequately test the code in, i.e. with sample data, a <code>Main</code> function, etc., the best way to critique this presently is against the design.</p>\n\n<p>Let us apply some basic formatting so we can actually get a better idea of what's going on:</p>\n\n<pre><code>public List<DataForExcelExport> GetData()\n{\n var list = new List<DataForExcelExport>();\n int ROWS_PER_PAGE = 41;\n int MaxRow = 0;\n\n var dataAdapter = new SqlDataAdapter(selectCommandText, connectionString);\n var dataTable = new DataTable();\n dataAdapter.Fill(dataTable);\n bool flgLastPage = false;\n\n for (int i = 0; i < dataTable.Rows.Count; i++)\n {\n DataRow dr = dataTable.Rows[i];\n var item = new DataForExcelExport();\n SetItemData(dr, item, true);\n\n if (i + ROWS_PER_PAGE < dataTable.Rows.Count)\n {\n SetItemData(dataTable.Rows[i + ROWS_PER_PAGE], item, false);\n }\n\n list.Add(item);\n\n if (flgLastPage == false)\n {\n if ((i + 1) % ROWS_PER_PAGE == 0)\n {\n i += ROWS_PER_PAGE;\n\n int remaining = dataTable.Rows.Count - (i + 1);\n if (remaining < 2 * ROWS_PER_PAGE)\n {\n ROWS_PER_PAGE = remaining / 2 + remaining % 2;\n flgLastPage = true;\n }\n }\n }\n\n int maxrow = i + ROWS_PER_PAGE;\n\n if (maxrow == dataTable.Rows.Count)\n {\n break;\n }\n }\n\n return list;\n}\n</code></pre>\n\n<p>Ah, that's better. Now, to me, the orphaned variables <code>selectCommandText</code> and <code>connectionString</code> appear as though they're global constants since they are not parameters. If they are, they should look like <code>COMMAND_TEXT</code> and <code>CONNECTION</code> to align w/ C# standards. There are also other instances of poor variable casing and naming throughout this function. <code>ROWS_PER_PAGE</code> is cased as a local constant, which should hopefully sound like an oxymoron. This variable is even modified later on. It should be named something like <code>pageCap</code> or <code>pageLim</code>. Up next, we have <code>MaxRow</code>, which isn't even used. If it were, rather than being PascalCase, it should be CamelCase to align w/ C# standards for variables. I'd say <code>dataAdapter</code> and <code>dataTable</code> should just be <code>adapter</code> and <code>table</code>, since we already know what they're doing in this context. Now, applying these changes, we get:</p>\n\n<pre><code>public List<DataForExcelExport> GetData()\n{\n var list = new List<DataForExcelExport>();\n int pageLim = 41;\n\n var adapter = new Sqladapter(selectCommandText, connectionString);\n var table = new table();\n adapter.Fill(table);\n bool flgLastPage = false;\n\n for (int i = 0; i < table.Rows.Count; i++)\n {\n DataRow dr = table.Rows[i];\n var item = new DataForExcelExport();\n SetItemData(dr, item, true);\n\n if (i + pageLim < table.Rows.Count)\n {\n SetItemData(table.Rows[i + pageLim], item, false);\n }\n\n list.Add(item);\n\n if (flgLastPage == false)\n {\n if ((i + 1) % pageLim == 0)\n {\n i += pageLim;\n\n int remaining = table.Rows.Count - (i + 1);\n if (remaining < 2 * pageLim)\n {\n pageLim = remaining / 2 + remaining % 2;\n flgLastPage = true;\n }\n }\n }\n\n if ((i + pageLim) == table.Rows.Count)\n {\n break;\n }\n }\n\n return list;\n}\n</code></pre>\n\n<p>The looping is pretty straightforward; you just want to get a certain number of data entries w/in a page limit. To that extent, you could just do something like this:</p>\n\n<pre><code>int pageLim = 80;\n\nfor (int i = 0; i < pageLim && i < table.Rows.Count; ++i)\n{\n // set up `item` var using `row`\n list.Add(item);\n}\n</code></pre>\n\n<p>This will create a single item page. Now, if you want multiple pages, I'd suggest looking into a <a href=\"https://docs.microsoft.com/en-us/dotnet/api/system.collections.generic.dictionary-2?view=netframework-4.8\" rel=\"nofollow noreferrer\">Dictionary</a> rather than using index-modulo magic in a flat list. This way, you can have page names rather than just page numbers, or any other object. If all you'll use are page numbers, a multi-dimensional list should suffice. That would look something like this:</p>\n\n<pre><code>int i = -1;\nint pageLim = 80;\nList pages = new List();\nList page = new List();\n\nforeach (var row in table.Rows)\n{\n ++i;\n\n // set up `item` var using `row`\n\n if (i < pageLim) {\n page.Add(item);\n } else if (i == (pageLim - 1) || i == (table.Rows.Count - 1)) {\n page.Add(item); // add the last item\n pages.Add(page);\n page.clear();\n i = -1;\n }\n}\n</code></pre>\n\n<p>Then just return <code>pages</code>, a list of lists w/ at most 80 items per page, and access a page like <code>pages[0]</code>. If pages have a lot of metadata, creating a <code>Page</code> object and just having a flat list of that is also possible. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-04T18:39:37.267",
"Id": "231847",
"ParentId": "231488",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-29T19:37:05.223",
"Id": "231488",
"Score": "5",
"Tags": [
"c#",
".net-datatable"
],
"Title": "Building equal number of records list object"
}
|
231488
|
<p>So I'm trying to implement the following problem in a couple of different languages to get a rough idea of how different languages work & feel. I'm completely new to C, and this is the first code I've cobbled together using the C reference and Google/SO.</p>
<p>The problem is this:</p>
<ul>
<li>Generate a list of n random doubles in (0, 1) and sort it</li>
<li>Create n "nodes" or points, so a Node is just a type with three doubles x,y,z</li>
<li>set x of each node to the corresponding entry in the list</li>
<li>generate a list of "elements", called a "mesh", where each element has two nodes</li>
<li>compute the Jacobian for each element (see <code>jacobian</code> below)</li>
<li>print the largest Jacobian of all elements</li>
</ul>
<p>The following code works, I think. Since I have no experience in C, I want to know:</p>
<ul>
<li>How can the code be made more idiomatic?</li>
<li>How can the code be made more performant?</li>
</ul>
<pre><code>#include <stdlib.h>
#include <math.h>
#include <stdio.h>
struct Node
{
double x, y, z;
};
struct Element
{
struct Node node1, node2;
};
struct Mesh
{
struct Element* elements;
int num_elements;
};
int compare_doubles(const void* a, const void* b)
{
double arg1 = *(const double*)a;
double arg2 = *(const double*)b;
if (arg1 < arg2) return -1;
if (arg1 > arg2) return 1;
return 0;
}
double* generate_coordinates(int num_nodes)
{
double* coordinates = malloc(num_nodes * sizeof(double));
for (int i=0; i < num_nodes; i++)
{
coordinates[i] = (double) rand() / RAND_MAX;
}
qsort(coordinates, num_nodes, sizeof(double), compare_doubles);
return coordinates;
}
struct Mesh generate_mesh(double* coordinates, int num_nodes, int num_elements)
{
struct Node* nodes = malloc(num_nodes * sizeof *nodes);
for (int i=0; i < num_nodes; i++)
{
nodes[i].x = coordinates[i];
nodes[i].y = 0.0;
nodes[i].z = 0.0;
}
struct Element* elements = malloc(num_elements * sizeof *elements);
for (int i=0; i < num_nodes; i++)
{
elements[i].node1 = nodes[i];
elements[i].node2 = nodes[i+1];
}
struct Mesh mesh;
mesh.elements = elements;
mesh.num_elements = num_elements;
return mesh;
}
double jacobian(struct Element elem)
{
double dx = elem.node2.x - elem.node1.x;
double dy = elem.node2.y - elem.node1.y;
double dz = elem.node2.z - elem.node1.z;
return 0.5 * sqrt(dx*dx + dy*dy + dz*dz);
}
double find_max_jacobian(struct Mesh mesh)
{
double max = 0.0;
for (int i=0; i < mesh.num_elements; i++)
{
double jac = jacobian(mesh.elements[i]);
if (jac > max)
max = jac;
}
return max;
}
int main()
{
int num_elements = 5000000;
int num_nodes = num_elements + 1;
double* coordinates = generate_coordinates(num_nodes);
struct Mesh mesh = generate_mesh(coordinates, num_nodes, num_elements);
printf("Max jacobian: %e\n", find_max_jacobian(mesh));
return 0;
}
</code></pre>
<hr>
<p><strong>Edit:</strong> I just realised that I'm storing the nodes twice (right?). So I've made the nodes in the element just pointers, and modified the access in <code>jacobian</code>, so</p>
<pre class="lang-c prettyprint-override"><code>struct Element
{
struct Node *node1, *node2;
};
// ...
elements[i].node1 = &nodes[i];
elements[i].node2 = &nodes[i+1];
// ...
double dx = elem.node2->x - elem.node1->x;
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-29T21:10:00.590",
"Id": "451548",
"Score": "0",
"body": "Did you write this in a language you know well first and get the expected output? Does the answer provided by the code meet the expected output?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-29T21:11:26.677",
"Id": "451549",
"Score": "2",
"body": "Yes, I did. Yes, it does."
}
] |
[
{
"body": "<p>Welcome to the wonderful world of C programming where you have to do everything yourself.</p>\n\n<p>The C programming language is basically a high level assembly language, there is no garbage collection and the programmer has to manage the memory themselves.</p>\n\n<h2>The Good</h2>\n\n<p>Before I start discussing what can be improved, I'll mention the good things:<br>\n - The code is quite readable<br>\n - No casts from <code>malloc()</code> to the receiving variable<br>\n - The code follows the Single Responsibility and KISS principles, lots of nice small functions, although the function <code>struct Mesh generate_mesh(double* coordinates, int num_nodes, int num_elements)</code> could have 2 sub-functions to implement it, each of the for loops could be a function.<br>\n - There is only one Magic Number, and that one is forgivable, the <code>5000000</code> used to initalize the variable <code>num_elements</code></p>\n\n<h2>Error Checking</h2>\n\n<p>The allocation functions <code>malloc()</code>, <code>calloc()</code> and <code>realloc()</code> have been known to fail. This happens less often now than historically because computers generally have more memory than they used to, but there are still cases of limited memory such as in embedded programming. </p>\n\n<p>When an allocation function fails it returns <code>NULL</code>. Reference through a NULL pointer causes unknown behavior, and generally the program will terminate without an explanation. It is a good habit to test the results of the allocation before using the pointer in code:</p>\n\n<pre><code> double* coordinates = malloc(num_nodes * sizeof(double));\n if (!coordinates)\n {\n fprintf(stderr, \"Allocation of coordinates failed, exiting program\\n\");\n exit(EXIT_FAILURE);\n }\n\n for (int i=0; i < num_nodes; i++)\n {\n coordinates[i] = (double) rand() / RAND_MAX;\n }\n</code></pre>\n\n<p>There are other ways to handle this error, you might want to learn about <a href=\"https://en.wikipedia.org/wiki/Setjmp.h\" rel=\"nofollow noreferrer\">setjmp and longjmp</a>. There is a discussion about setjmp and longjmp in this <a href=\"https://stackoverflow.com/questions/14685406/practical-usage-of-setjmp-and-longjmp-in-c\">stackoverflow question</a>. There are problems using <code>exit()</code> in some cases.</p>\n\n<h2>Prevent Memory Leaks</h2>\n\n<p>As mentioned above, C doesn't have garbage collection, the programmer is responsible for de-allocating memory through the use of <code>free()</code>. If this program was part of a larger more complex program there would be memory leaks because none of the allocated memory is ever freed. This could lead to other memory allocation failing.</p>\n\n<p>In reference to the edit, you could <code>free</code> the <code>nodes</code> array after the content of the <code>nodes</code> were copied into the <code>elements</code>.</p>\n\n<h2>Prefer <code>calloc</code> Over <code>malloc</code> for Arrays</h2>\n\n<p>The function <a href=\"https://en.cppreference.com/w/c/memory/calloc\" rel=\"nofollow noreferrer\">calloc(size_t num, size_t size)</a> is generally preferred over <code>malloc(size_t size)</code> for arrays. The first parameter is the number of items to allocate, the second number is the size of the items. The parameters obviously make sense for arrays. One of the benefits of <code>calloc()</code> is that it zeros out each element of the array when the memory is allocated.</p>\n\n<p>When allocating memory the code become more maintainable when the <code>sizeof()</code> function contains the variable the memory is being assigned to rather than the actual type. This allows the programmer or maintainer t change the type of the variable without having to change the code of the allocation itself. An example is :</p>\n\n<pre><code> double* coordinates = calloc(num_nodes, sizeof(*coordinates));\n if (!coordinates)\n {\n fprintf(stderr, \"Allocation of coordinates failed, exiting program\\n\");\n exit(EXIT_FAILURE);\n }\n</code></pre>\n\n<p>In the code above changing the type of the variable <code>coordinates</code> automatically changes the size of the items being allocated.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-30T08:21:37.253",
"Id": "451596",
"Score": "0",
"body": "Thank you very much! One question: if `calloc` sets all the entries to zero, is it slower than allocating an uninitialized array?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-30T12:57:36.623",
"Id": "451634",
"Score": "1",
"body": "@Psirus calloc is slightly slower than malloc, however, the major part of the time for both calloc and malloc is the memory allocation that calls a system function and gets the program swapped out."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-29T22:51:23.273",
"Id": "231496",
"ParentId": "231489",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-29T21:04:28.380",
"Id": "231489",
"Score": "5",
"Tags": [
"performance",
"c",
"memory-management"
],
"Title": "Finding the largest jacobian in a finite element mesh"
}
|
231489
|
<p>I have the following code:</p>
<pre><code> member this.ProcessEvent(sourceStream: OrderResponse) =
match sourceStream.Action with
| Action.Partial
| Action.Insert ->
sourceStream.Data
|> Seq.iter (fun x -> this.orderState.[x.OrderId] <- this.ConvertFullOrder x)
| Action.Update ->
sourceStream.Data
|> Seq.iter (fun x -> this.orderState.[x.OrderId] <- this.UpdateOrder x this.orderState.[x.OrderId])
| Action.Delete ->
sourceStream.Data
|> Seq.iter (fun x -> this.orderState.Remove(x.OrderId) |> ignore)
| _ -> ()
</code></pre>
<p>It is processing a list of events and an action. The data is processed and stored in a dictionary. The action tells to insert, update or delete some of the records and applies to all the events received in the same message.</p>
<p>For each case, I iterate through the sourceStream.Data list.</p>
<p>Is there a better / more readable way where I can declare I am going to process that list and then, based on the Action, have different code? this would allow to remove the multiple <code>sourceStream.Data |></code> bits and specify it only once.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-30T12:40:59.420",
"Id": "451632",
"Score": "1",
"body": "Whoever VTCd this question, please explain."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-30T16:47:31.417",
"Id": "451685",
"Score": "1",
"body": "I didn't VTC but my presumption is that it would be helpful to have sample usage of this function so reviewers can have a better sense of how it is utilized"
}
] |
[
{
"body": "<p>You have probably found a good solution long time ago, but here is my suggestion:</p>\n<pre><code>member this.ProcessEvent(sourceStream: OrderResponse) = \n let handler: (Order -> unit) = \n match sourceStream.Action with\n | Action.Partial\n | Action.Insert -> (fun x -> this.orderState.[x.OrderId] <- this.ConvertFullOrder x)\n | Action.Update -> (fun x -> this.orderState.[x.OrderId] <- this.UpdateOrder x this.orderState.[x.OrderId])\n | Action.Delete -> (fun x -> this.orderState.Remove(x.OrderId) |> ignore)\n | _ -> (fun x -> ())\n\n sourceStream.Data |> Seq.iter handler\n</code></pre>\n<p>I'm not sure. what type <code>x</code> has, so for the illustration I just call it <code>Order</code> in the handler definition.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-05T16:26:59.160",
"Id": "481125",
"Score": "0",
"body": "yes, by now I have a solution, but this is elegant, I like it."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-05T12:16:07.170",
"Id": "245032",
"ParentId": "231491",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "245032",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-29T21:25:55.143",
"Id": "231491",
"Score": "4",
"Tags": [
"f#",
"crud"
],
"Title": "F# method to insert, update, or delete events in a dictionary"
}
|
231491
|
<p>At the company i work we have a system where an user is presented with a question and some alternatives to choose from. The question and answers are generated at runtime. In order to simplify the process among the sent payload is an encrypted JSON string that contains some "sensitive" (but not that much) information and which of the alternatives is the correct one. </p>
<p>This might seem weird at first but keep in mind that this is not business critical and therefore if an user can cheat on some questions, that's ok. </p>
<p>So i designed the following "encryption protocol":</p>
<ol>
<li>Generate hundreds of random keys and store them</li>
<li>When the question and answers are selected, choose one key at random, encrypt all the necessary information and put the key index at the beginning</li>
</ol>
<p>So when the user submit his answer we take the key index, retrieve the key, decrypt the payload and check if the answer is the correct one. </p>
<p>My first option was to use some existing and tested encryption library (we use PHP internally) and my first implementation used <a href="https://paragonie.com/project/halite" rel="nofollow noreferrer">Halite</a>. Things worked great, but it was too slow for our use case (also i think it's really overkill to this simple use case). So i decided to find some simpler encryption algorithm and ended up discovering the <a href="https://en.wikipedia.org/wiki/XXTEA" rel="nofollow noreferrer">XXTEA</a> cipher it seemed simple and fast. Perfect for our use case. </p>
<p>So i started looking for some library for PHP that implemented it and while i did find some i wasn't very satisfied with them (either performance wise or code quality wise).</p>
<p>So i used this given all that i decided to use this opportunity to create my own XXTEA implementation (yeah, i'm aware of the "don't implement your own crypto" mantra, but it seemed easy enough) in C++ and create a PHP extension of it. And this sort of became a pet project for me, so i decided i was going to publish it and open-source it. And where we are. </p>
<p>What i'm looking for in CodeReview is: </p>
<ol>
<li>Can my code be made more reusable ? Is the API i designed good?</li>
<li>Are there any (obvious?) performance optimizations that i missed?</li>
<li>Is my implementation correct? it's working great so far, but you never know</li>
<li>Is my code idiomatic, can i make it better? if so how?</li>
<li>Comments on the whole process, some new ideas maybe.</li>
<li>Bonus: Can i use SIMD instructions to improve performance? I know very little about it but always wanted an excuse to read up on it and use it</li>
</ol>
<p>The whole code can be seem here: <a href="https://github.com/menezes-/xxtea/blob/master/xxtea.hpp" rel="nofollow noreferrer">Github repo</a></p>
<p>The whole library is contained in a single header: <code>xxtea.hpp</code> and all necessary functions are inside the xxtea namespace. </p>
<p>The whole API is <code>std::string</code> base because that was the requirement, but i do plan on implementing a binary interface.</p>
<p>So after all that to the code:</p>
<p>The first function provided is the <code>encrypt</code>, which as the name states encrypts the passed string.</p>
<pre><code>/**
* Encrypts text using Corrected Block TEA (aka xxtea) algorithm
* @param plaintext String to be encrypted. Handles utf-8.
* @param password Password to be used for encryption (only 128 bits are used).
* @return Encrypted text as uint32_t vector
*/
inline bytes encrypt(const std::string &plaintext, const std::string &password) {
auto text = internal::to_blocks<std::uint32_t>(plaintext);
auto key = internal::to_blocks<std::uint32_t>(password);
encode(text, key);
return text;
}
</code></pre>
<p>The first thing it does is to convert both strings to a <code>std::vector</code> of 32 bits integers, as required by the XXTEA cipher.
I tried to make this function as portable as possible, because i think it can be used for other projects:</p>
<pre><code>template<class BlockType>
std::vector<BlockType> to_blocks(std::string string) {
constexpr unsigned short block_size = std::numeric_limits<BlockType>::digits;
static_assert(block_size >= CHAR_BIT, "Can't be smaller than CHAR_BIT");
string.resize(round_up(string.size(), block_size), '\x03');
auto number_of_bits = string.size() * CHAR_BIT;
std::vector<BlockType> blocks{};
auto n_blocks = std::max(number_of_bits / block_size, 1UL);
blocks.resize(n_blocks, 0);
constexpr auto fit_size = block_size / CHAR_BIT;
for (std::size_t i = 0; i < string.size(); ++i) {
auto bucket = (i * CHAR_BIT) / block_size;
auto shift = CHAR_BIT * (i % fit_size);
auto c = static_cast<unsigned int>(string[i]);
blocks[bucket] += c << shift;
}
return blocks;
}
</code></pre>
<p>The main idea here is to splice the string characters into groups of 32bits.
Also if the string passed isn't a multiple of the <code>block_size</code> the string is padded with the <code>ETX</code> character. The round_up function just returns the first argument rounded up to the next multiple of the second argument.</p>
<p>The <code>to_blocks</code> function has a sister function that takes a <code>std::vector</code> of <code>std::uint32_t</code> blocks and transforms them into a string:</p>
<pre><code>template<class BlockType>
std::string to_string(const std::vector<BlockType> &blocks) {
constexpr unsigned short block_size = std::numeric_limits<BlockType>::digits;
constexpr auto fit_size = block_size / CHAR_BIT;
std::string s;
s.reserve(fit_size * blocks.size());
for (const auto &i : blocks) {
for (std::size_t j = 0; j < fit_size; ++j) {
auto shift = CHAR_BIT * (j % fit_size);
auto c = static_cast<char >(i >> shift);
if (c != '\x03') {
s.push_back(c);
} else {
break;
}
}
}
return s;
}
</code></pre>
<p>Pretty much the same idea, but reversed: figure out how many chars can fit into the block size and shift-left them to produce a string, stop when the padding character is found or the blocks end </p>
<p>After that comes the main encryption routine:</p>
<pre><code>// acording to this stackexchange https://crypto.stackexchange.com/a/12997 comment
// xxtea security can be increase by increasing the number of mixes,
// so i've put this as a definibable constant
#ifndef XXTEA_NUMBER_OF_MIXES
#define XXTEA_NUMBER_OF_MIXES 6
#endif
#define XXTEA_MX (((z>>5U^y<<2U) + (y>>3U^z<<4U)) ^ ((sum^y) + (k[(p&3U)^e] ^ z)))
using bytes = std::vector<std::uint32_t>; // probably not the best name, but at the time i couldn't think of another
/**
* encodes an array of unsigned 32-bit integers using 128-bit key.
* @param v vector of uint32
* @param k 128-bit key, if smaller the vector will be padded
*/
inline void encode(bytes &v, const bytes &k) {
if (v.empty()) {
return;
}
auto n = v.size();
unsigned long z{v[n - 1]};
unsigned long y{v[0]};
unsigned long sum = 0;
long rounds = XXTEA_NUMBER_OF_MIXES + 52 / n;
std::size_t p;
while (rounds-- > 0) {
sum += internal::delta; // constant defined as constexpr unsigned long delta{0x9E3779B9};
unsigned long e = (sum >> 2U) & 3U;
for (p = 0; p < n - 1; ++p) {
y = v[p + 1];
v[p] += XXTEA_MX;
z = v[p];
}
y = v[0];
v[n - 1] += XXTEA_MX;
z = v[n - 1];
}
}
</code></pre>
<p>In my first try i tried to replace the <code>XXTEA_MX</code> macro with a <code>constexpr</code> function, but that didn't work because of the vector access(<code>k[(p&3U)^e]</code>) in it.</p>
<p>I also think that i can replace the while loop with some sort of <code>for</code> loop (to improve readability)</p>
<p>You will notice that this code is <em>really</em> based on the implementation on the Wikipedia page. There are a few things that i would like to change about it, for example all those definitions before the while, maybe i could put it more closely to the actual variable use? The worst offender there is the <code>p</code> variable.</p>
<p>The decryption routine: </p>
<pre><code>/**
* Decrypts text using Corrected Block TEA (xxtea) algorithm
* @param encrypted_string @see encrypt
* @param password password used to encrypt the string
* @return utf8 encoded string
*/
inline std::string decrypt(bytes &encrypted_string, const std::string &password) {
auto key = internal::to_blocks<std::uint32_t>(password);
decode(encrypted_string, key);
return internal::to_string<std::uint32_t>(encrypted_string);
}
</code></pre>
<p>Take the encrypted vector, transform the key into blocks, decrypt the blocks, transform said blocks into string again.</p>
<p>And the main decryption function:</p>
<pre><code>/**
* decodes an array of unsigned 32-bit integers using 128-bit key.
* @param v array to be decoded
* @param k 128-bit key
*/
inline void decode(bytes &v, const bytes &k) {
if (v.empty()) {
return;
}
auto n = v.size();
unsigned long z{v[n - 1]};
unsigned long y{v[0]};
long rounds = XXTEA_NUMBER_OF_MIXES + 52 / n;
unsigned long sum = rounds * internal::delta;
std::size_t p;
for (; sum != 0; sum -= internal::delta) {
unsigned long e = (sum >> 2U) & 3U;
for (p = n - 1; p > 0; --p) {
z = v[p - 1];
v[p] -= XXTEA_MX;
y = v[p];
}
z = v[n - 1];
v[0] -= XXTEA_MX;
y = v[0];
}
}```
Again, what bothers me the most is the long list of declarations.
I could put the `sum` variable into the for loop constructor but i think would become way to long.
Initially i used `auto` for all the `unsigned long`s but changed it out of fear that the compiler deduced some smaller int and my code would break in some weird edge case.
Last part:
The PHP extension. Not much to discuss is just a simple wrapper that uses the [PHP-CPP][4] library to generate the PHP bindings. To compile it it's just a matter of using the standard CMake commands `cmake; make;` and then copy the generated .so to the appropriate location and enable it on php.ini
But there's something that I'm unsure about:
This is the PHP wrapper function:
```C++
Php::Value xxtea_encrypt(Php::Parameters &params) {
std::string plaintext = params[0];
std::string key = params[1];
if (plaintext.empty()) {
return std::string{""};
}
if (key.empty()) {
throw Php::Exception("key parameter cannot be empty");
}
auto encrypted = xxtea::encrypt(plaintext, key);
std::stringstream result;
std::copy(encrypted.begin(), encrypted.end(), std::ostream_iterator<std::uint32_t>(result, " "));
return result.str();
}
</code></pre>
<p>I wanted to return an encrypted string to PHP, not a vector so in the last two lines i concatenated the encrypted blocks separated by a space. Usually I've seem people encode it with base64 or something like that, but i think it's overkill for something simple. The main advantage of base64 is that it's <a href="https://en.wikipedia.org/wiki/8-bit_clean" rel="nofollow noreferrer">8-bit clean</a> but so it's concatenating all numbers. Still i'm a little bit unsure about it</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-29T21:40:44.907",
"Id": "451554",
"Score": "0",
"body": "Funny how in the process of writing this question i ended up noticing a bug (that was fixed prior to post) and made some small improvements (also prior to posting)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-29T23:22:43.057",
"Id": "451559",
"Score": "0",
"body": "That is quite a bundle to read. Putting your hopes upfront (or even at the end) would make them easier to spot. Can you tell how *performance* has been identified as an issue?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-29T23:46:04.123",
"Id": "451562",
"Score": "0",
"body": "It looks bad for SIMD, the main computation is not data-parallel. `to_blocks` could be done with SIMD, but that's because it's a roundabout way to do a `memcpy`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-30T03:20:02.683",
"Id": "451574",
"Score": "0",
"body": "@harold what do mean it's a roundabout way to do a memcpy? I could just cast the entirety char vector of the string to a vector of uint32 but that's different of what I'm doing"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-30T03:21:11.707",
"Id": "451575",
"Score": "0",
"body": "@greybeard I haven't profiled it enough, I was just asking in case I was missing something obvious. Trying to get a second pair of eyes into this"
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-29T21:33:46.327",
"Id": "231492",
"Score": "2",
"Tags": [
"c++",
"performance",
"cryptography"
],
"Title": "XXTEA encryption implemented in modern C++"
}
|
231492
|
<p>I'm trying to filter items from an ecommerce site.The project on the local server was running smoothly.However, I noticed significant delays since the project was published on the global server.Most often happens when changes are made to the price range.</p>
<p>Here is the <code>Ajax</code> code:</p>
<pre><code> productFilter = {
catId: $('#catId').val(),
subcatId: $('#catSubId').val(),
markaId: null,
}
$(".filter-button").click(function () {
let filterPrice = $(this).val()
let maxPrice = $("input[name='maxProPrice']").val();
let minPrice = $("input[name='minProPrice']").val();
updateAllData(filterPrice, productFilter.markaId, minPrice, maxPrice, productFilter.subcatId,
productFilter.catId)
})
$(".btnRangePrice").click(function () {
let maxPrice = $("input[name='maxProPrice']").val();
let minPrice = $("input[name='minProPrice']").val();
updateAllData(productFilter.markaId, minPrice, maxPrice, productFilter.subcatId, productFilter
.catId)
})
$("#markaId").click(() => {
$('input[name="marka"]').change(function () {
if ($(this).prop('checked')) {
productFilter.markaId = $(this).val()
}
})
})
function updateAllData(markaId, minPrice, maxPrice, subcatId, catId) {
$.ajax({
url: "/api/getpromarka",
type: "Get",
data: {
'catId': catId,
'subCatId': subcatId,
'markaId': markaId,
'minPrice': minPrice,
'maxPrice': maxPrice,
//'price':filtprice
},
success: function (res) {
$("#prdcFor").empty();
res.forEach(resf => {
document.querySelector("#prdcFor").insertAdjacentHTML('beforeend',
`
<div class="col-lg-3 col-md-4 col-sm-12 col-12">
<div
class="shopImg mb-3" style="height:400px;">
<div class="ImgDiv" style="height:200px">
<img class="shop-img pro_image" style="height:100%; width:100%" src="${resf.Image}" alt="">
</div>
<div class="img-text mt-3">
<span class="pro_name">${resf.Name}</span>
</div>
<p class="pro_price">${resf.Price} AZN</p>
<input class="hidePId" type="hidden" value="${resf.Id}" />
<div class="">
<button type="button" data-action="Add_To_Cart" class="btn btn-warning mb-5 add-to-cart">Səbətə Əlavə Et</button>
</div>
</div>
</div>
`)
})
}
})
}
</code></pre>
<p><code>Web Api 2 Controller</code> :</p>
<pre><code> public IQueryable<Product> GetProduct(int? catId, int? subCatId, int? markaId,int? minPrice,int? maxPrice)
{
if (subCatId == null)
return db.Products.Where(pr => pr.SubCategory.CategoryId == catId && pr.Price >= minPrice && pr.Price <= maxPrice && pr.MarkaId == markaId);
if (markaId == null)
{
return db.Products.Where(pr => pr.SubCategory.CategoryId == catId && pr.SubCategoryId == subCatId && pr.Price >= minPrice && pr.Price <= maxPrice);
}
return db.Products.Where(pr=>pr.SubCategoryId==subCatId && pr.MarkaId==markaId && pr.Price>=minPrice && pr.Price<=maxPrice);
}
</code></pre>
<p>Product <code>cshtml</code></p>
<pre><code><section id="Shop" class="mt-5 mb-5">
<input id="catId" type="hidden" data-catid="subId" value="@catId" />
<input id="catSubId" type="hidden" data-subcatid="subCatId" value="@subId" />
<div class="container-fluid">
<div class="row">
<div class="mob-category col-md-4 col-lg-3">
<div class="ShopCategory" data-aos="fade-right">
@foreach (var item in Model.SubCategoryName.Where(sb=>sb.CategoryId==catId))
{
<div class="col-md-12">
<div class="row">
<div class="col-md-10 col-10">
<a id="@item.Id" class="sub_cat_name accordion" href="@Url.Action("product","product",new { subId=item.Id})">
<span>
@item.Name
</span>
</a>
</div>
</div>
</div>
}
<div class="col-md-12">
<a class="accordion" href="@Url.Action("PcTopla","Product")">
<span>
Pc Topla+
</span>
</a>
</div>
<br>
<h3 class="mt-5 text-center pt-1" style="border-top:1px solid #ccc;">Qiymət</h3>
<div class="price_range">
<div class="row mr-2 ml-2 mb-5">
<div class="col-md-5">
<div class="from">
<input name="minProPrice" class="num" type="number" id="price_from" min="@ViewBag.proMin" max="@ViewBag.proMax"
value="@ViewBag.proMin"/>
</div>
</div>
<div class="col-md-2">
<span>__</span>
</div>
<div class="col-md-5">
<div class="to">
<input class="num" name="maxProPrice" type="number" id="price_to" min="@ViewBag.proMin" max="@ViewBag.proMax" value="@ViewBag.proMax">
</div>
</div>
</div>
<h3 class="mt-3 text-center">İstehsalçı</h3>
<div class="company ml-5 mb-5">
<ul class="list-unstyled">
@foreach (var item in Model.marka)
{
<li>
<input id="markaId" type="radio" name="marka" value="@item.Id">
@item.MarkaName
</li>
}
</ul>
</div>
</div>
<div class="col d-flex justify-content-center">
<button type="submit" class="btnRangePrice btn btn-warning mb-3" >Seçimi göstər</button>
</div>
</div>
</div>
<div class="col-12 col-sm-12 col-md-8 col-lg-9">
<div id="prdcFor" class="row">
@foreach (var item in Model.productList)
{
<div class="col-xl-3 col-lg-4 col-md-6 col-sm-6 col-6">
<div class="shopImg mb-3" style="height:400px;">
<div class="ImgDiv" style="height:200px">
<img class="shop-img pro_image" style="height:100%; width:100%" src="@item.Image" alt="">
</div>
<div class="img-text mt-3">
<span class="pro_name">@item.Name</span>
</div>
<p class="pro_price">@item.Price AZN</p>
<input class="hidePId" type="hidden" value="@item.Id" />
<div class="addtocart">
<button type="button" data-action="Add_To_Cart" class="btn btn-warning mb-5 add-to-cart">Səbətə Əlavə Et</button>
</div>
</div>
</div>
}
</div>
</div>
</div>
</div>
</code></pre>
<p></p>
|
[] |
[
{
"body": "<p>You should not pass an <code>IQueryable</code> as a result. Convert it into an object or list of object and close the existing connection before passing it as a result. <code>IQueryable</code> is used to query the data before fetching it and hence the connection will stay open.</p>\n\n<p>Basically, it's similar to \n<code>Connection.open()</code>\n and then not closing the connection.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-02T12:25:01.243",
"Id": "234944",
"ParentId": "231497",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-29T23:31:22.137",
"Id": "231497",
"Score": "1",
"Tags": [
"c#",
"asp.net-mvc",
"asp.net-web-api"
],
"Title": "Filtering items in an ecommerce site with asp.net mvc and ajax"
}
|
231497
|
<p>The purpose of the code is to allow the user to select directories that will be crawled recursively in order to find particular files or file types to analyze en masse. The thing to bear in mind is that if <code>C:\</code> is already selected, then any child path of <code>C:\</code> that the user tries to select will be discarded. The entire process of the script can be broken down into the following steps:</p>
<ol>
<li>The user selects a directory or directories via a dialog box.</li>
<li>The script then compares the selection to whatever directories might already be stored in an array in the configuration file, which is a JSON object.</li>
<li>If the selection is invalid, the selection is discarded. / If the selection is valid, the configuration file is modified accordingly.</li>
</ol>
<p>Obviously promises are ideal, so I'm using Node's <code>fs.promises</code>. However, the tricky bit is that, although they're asynchronous, parts of the code must behave synchronously. For example, it would be a waste of resources to retrieve the array from the configuration file if the dialog box is cancelled by the user.</p>
<p>I'm completely new to promises and everything else that entails, so I'm wondering whether or not there's an even better way to structure the asynchronous code or the code in general? <strong>The code works fine the way it is, but can its structure/readability and or efficiency be improved?</strong></p>
<pre><code>async function userSelectsArchives()
{
try {
const r1 = await dialog.showOpenDialog(remote.getCurrentWindow(), {
title: 'Select Archives to Analyze',
buttonLabel: 'Select Archives',
defaultPath: 'c:\\',
properties: [ 'openDirectory', 'multiSelections' ]
})
if (r1.canceled) throw new Error('Dialog cancelled.')
const
r2 = await fsp.readFile('./config.json', 'utf8'),
config = JSON.parse(r2),
archivesOG = config.archives
for (const dir of r1.filePaths){
// Disregard user input if parent path or exact match already exists.
if (
config.archives.reduce((a, v) => {
return a || dir.indexOf(v.slice(-1) === '\\' ? v : (v + '\\')) === 0
}, false)
|| config.archives.includes(dir)
) continue
// Remove child paths of user input in config.
config.archives = config.archives.filter(
v => v.indexOf(dir.slice(-1) === '\\' ? dir : (dir + '\\')) !== 0
)
// Add user input to archive.
config.archives.push(dir)
}
// Verify that changes have occurred or throw error.
if (archivesOG === config.archives) throw new Error('Invalid selection.')
await fsp.writeFile('./config.json', JSON.stringify(config, null, 2), 'utf8')
displayDirs(config.archives)
}
catch (error) {
console.error(error)
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-30T00:01:50.897",
"Id": "451564",
"Score": "2",
"body": "Welcome to CR! Please [edit] your post to tell reviewers about the purpose of this code, and make the title summarize that. What we want to avoid, is a home page that reads \"how can I improve this code?\" 50 times over. Thanks!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-30T02:22:51.310",
"Id": "451571",
"Score": "0",
"body": "Is this code working as expected? It seems as if (archivesOG === config.archives) will always evaluate to true and throw as you as these reference the same object (you are not cloning this array)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-30T03:49:42.413",
"Id": "451576",
"Score": "0",
"body": "@MathieuGuindon Thanks. I will do that as soon as i get a free minute sometime in the next 24 hours."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-30T03:52:59.357",
"Id": "451578",
"Score": "2",
"body": "@MikeBrant yes, code is working as expected. no, `archivesOG === config.archives` evaluates to `false` if or rather when `config.archives` is modified, which is typically the case, since `archivesOG` is simply a cached version of `config.archives` before potential modifications are acted out"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-30T05:50:11.050",
"Id": "451581",
"Score": "1",
"body": "It's fine as is, but you should use .some() instead of .reduce() here."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-30T07:16:07.250",
"Id": "451587",
"Score": "0",
"body": "@wOxxOm youre right. no ideas on how to improve the structure of the code?"
}
] |
[
{
"body": "<p><em>Tips</em> for <em>JS</em> code optimization:</p>\n\n<p><strong><em>Variable names</em></strong></p>\n\n<p>Give your variables meaningful names:</p>\n\n<ul>\n<li><code>const r1 = await dialog.showOpenDialog(...)</code> can be renamed to <strong><code>dirs</code></strong> or <strong><code>dirList</code></strong> (representing selected directories)</li>\n<li><code>const r2 = await fsp.readFile('./config.json', 'utf8'), config = JSON.parse(r2),</code> where <code>r2</code> is supposed to be a config file path. Let's rename it to say <br><code>const config_file = await fsp.readFile('./config.json', 'utf8'), config = JSON.parse(config_file)</code> </li>\n</ul>\n\n<p><strong><em>Extract function:</em></strong></p>\n\n<p>Repeated expression <code><string>.slice(-1) === '\\\\' ? <string> : (<string> + '\\\\')</code> can be extracted into a reusable routine (named or anonymous function):</p>\n\n<pre><code>var asDirPath = function(path) {\n return path.slice(-1) === '\\\\' ? path : (path + '\\\\');\n};\n</code></pre>\n\n<p><strong><em>Substitute algorithm:</em></strong></p>\n\n<p>The whole condition (combination of <code>array.reduce</code> and <code>array.includes</code>) can be easily substituted with a more efficient <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/some\" rel=\"nofollow noreferrer\"><code>Array.some()</code></a> approach (to check for <strong>any</strong> match between current directory path <code>dir</code> and <code>config.archives</code> file/dir paths):</p>\n\n<pre><code>for (const dir of dirList.filePaths){\n // Disregard user input if parent path or exact match already exists.\n if (config.archives.some(path => {\n return dir.indexOf(asDirPath(path)) === 0 || path === dir\n })) continue\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-30T07:11:12.123",
"Id": "231510",
"ParentId": "231498",
"Score": "3"
}
},
{
"body": "<p>Some suggestions:</p>\n\n<ol>\n<li><p>Since this is an <code>async</code> function, it seems likely the caller may want to know when it's done and if it succeeded. To do that, you need to reject upon error. That means rethrow after logging inside your catch. This allows the error to get back to the caller as a rejected promise.</p></li>\n<li><p>Simplify by changing <code>config.archives.reduce()</code> to <code>config.archives.some()</code>. This will also be faster in cases where there is a match because <code>.some()</code> will short-circuit the iteration as soon as a match is found.</p></li>\n<li><p>Change <code>return dir.indexOf(v.slice(-1) === '\\\\' ? v : (v + '\\\\')) === 0;</code> to <code>return dir.indexOf(v) === 0;</code>. It appears the point of this code is to allow partial matches where <code>v</code> is a subset of <code>dir</code>, but starts matching at the beginning. If that's the case and if I understood what you're trying to do here, then you don't need to make sure that <code>v</code> has a trailing slash on it as that won't change the outcome.</p></li>\n<li><p>Remove <code>|| config.archives.includes(dir)</code>. It appears that is redundant since a full match will have already been found in the previous iteration through <code>config.archives</code>.</p></li>\n<li><p>Coding style. I prefer <code>if (condition) { do something }</code> rather than <code>if (condition) continue</code> as I just think it's easier to read and follow.</p></li>\n<li><p>You have a lot of references to <code>config.archives</code>. I would suggest either just using archivesOG instead or make a shorter named local variable such as just <code>archives</code> that you can refer to everywhere except when assigning back to it.</p></li>\n<li><p><code>r1</code> and <code>r2</code> could have much more meaningful names.</p></li>\n<li><p>The code <code>dir.indexOf(v.slice(-1) === '\\\\' ? v : (v + '\\\\')) === 0;</code> begs to be put in a function with a meaningful name. It takes a bit of a pause when reading this code to figure out what that's doing. If it has a meaningful function name such as <code>normalizePathEnd()</code> or something like that, the code will be a lot easier to read without having to follow the detail of the string manipulation. Also, your code as you show it has two copies of this concept which also begs to be in a utility function.</p></li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-01T23:10:05.310",
"Id": "452076",
"Score": "0",
"body": "unfortunately `3.` isn't possible due to comparisons between similar paths like `C:\\\\User` and `C:\\\\Users`, thus `4.` is also out of the question. thanks for your suggestions nonetheless"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-31T00:16:26.163",
"Id": "231573",
"ParentId": "231498",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-29T23:44:15.210",
"Id": "231498",
"Score": "3",
"Tags": [
"javascript",
"asynchronous",
"async-await",
"promise"
],
"Title": "Cleaner Way to Structure Asynchronous Code"
}
|
231498
|
<p>This is a follow up to this <a href="https://codereview.stackexchange.com/questions/231453/manage-excel-styles-with-vba-oop-approach">question</a></p>
<p>Code incorporates Mathieu's comments and it works. As some parts of the review left some code to my knowledge, I ask for another review to see if I implemented them correctly.</p>
<p>Objectives:</p>
<ul>
<li><p>Load the current Styles list (name and type=builtin or custom) in an Excel Structured Table (ListObject)</p></li>
<li><p>Allow users to:</p>
<ol>
<li><p>Delete</p></li>
<li><p>Duplicate (create a new style based on another)</p></li>
<li><p>Replace (one style with another)</p></li>
</ol></li>
</ul>
<hr>
<p>Main suggestions from previous review:</p>
<ul>
<li><p>Apply naming conventions</p></li>
<li><p>Add <em>factory method</em></p></li>
<li><p>Add Actions by composition</p></li>
</ul>
<hr>
<p>Note: My current level couldn't understand well how to apply the dependency injection concept</p>
<hr>
<p>GUI:</p>
<p><a href="https://i.stack.imgur.com/HOxVe.png" rel="noreferrer"><img src="https://i.stack.imgur.com/HOxVe.png" alt="enter image description here"></a></p>
<hr>
<p>Module: Macros</p>
<pre><code>'@Folder("Styles")
Option Explicit
Public Sub LoadStyles()
Dim myStyleProcessor As StyleProcessor
Set myStyleProcessor = New StyleProcessor
myStyleProcessor.LoadToTable
End Sub
Public Sub ProcessStyles()
Dim myStyleProcessor As StyleProcessor
Set myStyleProcessor = New StyleProcessor
myStyleProcessor.LoadFromTable
myStyleProcessor.Process
myStyleProcessor.LoadToTable
End Sub
</code></pre>
<hr>
<p>Class: StyleInfo</p>
<pre><code>'@Folder("Styles")
'@PredeclaredID
Option Explicit
Public Enum Action
DeleteStyle
DuplicateStyle
ReeplaceStyle
RenameStyle
End Enum
Private Type TStyleInfo
Style As Style
Name As String
Action As String
Target As String
Exists As Boolean
End Type
Private this As TStyleInfo
Public Property Let Name(ByVal value As String)
this.Name = value
End Property
Public Property Get Name() As String
Name = this.Name
End Property
Public Property Let Action(ByVal value As String)
this.Action = value
End Property
Public Property Get Action() As String
Action = this.Action
End Property
Public Property Let Target(ByVal value As String)
this.Target = value
End Property
Public Property Get Target() As String
Target = this.Target
End Property
Public Property Set Style(ByVal Style As Style)
Set this.Style = Style
End Property
Public Property Get Style() As Style
Set Style = this.Style
End Property
Public Property Get Self() As StyleInfo
Set Self = Me
End Property
Public Function Create(ByVal Name As String, ByVal Action As String, ByVal Target As String) As StyleInfo
With New StyleInfo
.Name = Name
.Action = Action
.Target = Target
If Exists(Name) Then
Set .Style = ThisWorkbook.Styles(Name)
End If
Set Create = .Self
End With
End Function
Public Function Exists(ByVal Name As String) As Boolean
' Returns TRUE if the named style exists in the target workbook.
On Error Resume Next
Exists = Len(ThisWorkbook.Styles(Name).Name) > 0
On Error GoTo 0
End Function
</code></pre>
<p>Class: StyleProcessor</p>
<pre><code>'@Folder("Styles")
Option Explicit
Private infos As Collection
Private StyleActions As Collection
Private Sub Class_Initialize()
Set infos = New Collection
Set StyleActions = New Collection
StyleActions.Add New StyleActionDelete, "Delete"
StyleActions.Add New StyleActionDuplicate, "Duplicate"
StyleActions.Add New StyleActionReplace, "Replace"
End Sub
Private Sub Class_Terminate()
Set infos = Nothing
End Sub
'TODO Public Sub Add(obj As StyleInfo) : infos.Add obj : End Sub
'TODO Public Sub Remove(Index As Variant) : infos.Remove Index : End Sub
'@DefaultMember
Public Property Get Item(ByVal Index As Variant) As StyleInfo
Set Item = infos.Item(Index)
End Property
Public Property Get Count() As Long
Count = infos.Count
End Property
Public Sub LoadToTable()
Dim stylesTable As ListObject
Dim currentStyle As Style
Dim tempStyleInfo() As Variant
Dim counter As Long
Dim counterStyles As Long
counter = 0
counterStyles = ThisWorkbook.Styles.Count
ReDim tempStyleInfo(counterStyles + 1, 3)
Set stylesTable = MStyles.ListObjects("TableStyles")
If Not stylesTable.DataBodyRange Is Nothing Then stylesTable.DataBodyRange.Delete
For Each currentStyle In ThisWorkbook.Styles
tempStyleInfo(counter, 0) = currentStyle.Name
tempStyleInfo(counter, 1) = IIf(currentStyle.BuiltIn, "BuiltIn", "Custom")
counter = counter + 1
Next currentStyle
stylesTable.Resize stylesTable.Range.Resize(RowSize:=UBound(tempStyleInfo, 1))
stylesTable.DataBodyRange = tempStyleInfo
End Sub
Public Sub LoadFromTable()
Dim stylesTable As ListObject
Dim styleCell As Range
Set stylesTable = MStyles.ListObjects("TableStyles")
For Each styleCell In stylesTable.DataBodyRange.Columns(1).Cells
If styleCell.Offset(ColumnOffset:=2) <> vbNullString Then
infos.Add StyleInfo.Create(styleCell.Value2, styleCell.Offset(ColumnOffset:=2).Value2, styleCell.Offset(ColumnOffset:=3).Value2)
End If
Next styleCell
End Sub
Public Sub Process()
Dim info As StyleInfo
For Each info In infos
Dim strategy As IStyleInfoAction
Set strategy = StyleActions(info.Action)
strategy.Run info
Next
End Sub
</code></pre>
<p>Class (Interface): IStyleInfoAction</p>
<pre><code>'@Folder("Styles")
Option Explicit
Public Sub Run(ByVal newStyleInfo As StyleInfo)
End Sub
</code></pre>
<p>Class: StyleActionDelete</p>
<pre><code>'@Folder("Styles.Action")
Option Explicit
Implements IStyleInfoAction
Private Sub IStyleInfoAction_Run(ByVal newStyleInfo As StyleInfo)
If Not newStyleInfo.Style Is Nothing Then newStyleInfo.Style.Delete
End Sub
</code></pre>
<p>Class: StyleActionDuplicate</p>
<pre><code>'@Folder("Styles.Action")
Option Explicit
Implements IStyleInfoAction
Private Sub IStyleInfoAction_Run(ByVal newStyleInfo As StyleInfo)
Dim styleCell As Range
Dim newName As String
Set styleCell = MStyles.Range("E1")
styleCell.Style = newStyleInfo.Name
newName = newStyleInfo.Target
ThisWorkbook.Styles.Add newName, styleCell
styleCell.Clear
End Sub
</code></pre>
<p>Class: StyleActionReplace</p>
<pre><code>'@Folder("Styles.Action")
Option Explicit
Implements IStyleInfoAction
Private Sub IStyleInfoAction_Run(ByVal newStyleInfo As StyleInfo)
Dim evalCell As Range
Dim newStyle As Style
Dim replaceSheet As Worksheet
Set newStyle = ThisWorkbook.Styles(newStyleInfo.Target)
For Each replaceSheet In ThisWorkbook.Worksheets
For Each evalCell In replaceSheet.UsedRange.Cells
If evalCell.Style = newStyleInfo.Style And evalCell.MergeCells = False Then evalCell.Style = newStyle
Next evalCell
Next replaceSheet
End Sub
</code></pre>
<p><a href="https://1drv.ms/x/s!ArAKssDW3T7wnK5dMeiQoorsWRBQtA" rel="noreferrer">Link to current file</a></p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-30T00:34:37.387",
"Id": "451566",
"Score": "2",
"body": "Well done! Dependency Injection (DI) would be e.g. treating the collection of `IStyleInfoAction` objects as a dependency, and *providing* them to the processor class via a `Property Set` member, a factory method, or as an argument to the `Process` method. That way adding new actions doesn't require modifying the processor class. If you inject *all* the dependencies of your class, you're able to write code that tests its functionality (and injects test-controlled dependencies) - unit tests."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-30T00:54:33.957",
"Id": "451568",
"Score": "2",
"body": "Actually the only DI techniques available to VBA are *property injection* and *method injection*; the normally preferred *constructor injection* is ruled out, for lack of constructors in the language ...but property injection *via* a factory method gets pretty close - see [here](https://stackoverflow.com/a/46414650/1188513) and [here](https://rubberduckvba.wordpress.com/2018/04/24/factories-parameterized-object-initialization/) =)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-30T02:43:40.823",
"Id": "451572",
"Score": "0",
"body": "@MathieuGuindon Thank you for all the insights. For DI is it good practice if I place a Private Sub InitializeStyleProcessor(ByVal processor As StyleProcessor) where I add the StyleActions and use processor.Create styleActions in the Macros module?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-30T02:54:29.683",
"Id": "451573",
"Score": "1",
"body": "My previous question was based on your post [here](https://codereview.stackexchange.com/questions/133871/finding-the-cheapest-hotel)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-01T02:38:49.593",
"Id": "451930",
"Score": "0",
"body": "Another compelling reason to union the ranges before changing the Styles in in the case of Swapping Styles. Say for instance you wanted to change all the Accent1 to Accent 2 and all the Accent2 to Accent1. This will not be possible unless you create all the unions before you change the styles."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-01T03:17:34.713",
"Id": "451932",
"Score": "0",
"body": "You're right. I had to change the logic because I was swapping the styles after I have the styles listed. I collected the styles cells and sheets (where they appear) and added them to the StyleInfo object. Nice touch!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-01T03:43:14.753",
"Id": "451933",
"Score": "0",
"body": "@TinMan Last comment ended with a collection of FastUnion items because you can't union ranges from different sheets."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-01T04:11:51.000",
"Id": "451935",
"Score": "0",
"body": "@RicardoDiaz it looks like you have `FastUnions ` working. Very Nice!"
}
] |
[
{
"body": "<p>Over all the code is really good but <code>LoadToTable()</code> could be tweaked.</p>\n\n<pre><code>Public Sub LoadToTable()\n\n1 Dim stylesTable As ListObject\n2 Dim currentStyle As Style\n\n3 Dim tempStyleInfo() As Variant\n4 Dim counter As Long\n5 Dim counterStyles As Long\n\n6 counter = 0\n\n7 counterStyles = ThisWorkbook.Styles.Count\n8 ReDim tempStyleInfo(counterStyles + 1, 3)\n\n\n9 Set stylesTable = MStyles.ListObjects(\"TableStyles\")\n\n10 If Not stylesTable.DataBodyRange Is Nothing Then stylesTable.DataBodyRange.Delete\n\n11 For Each currentStyle In ThisWorkbook.Styles\n\n12 tempStyleInfo(counter, 0) = currentStyle.name\n13 tempStyleInfo(counter, 1) = IIf(currentStyle.BuiltIn, \"BuiltIn\", \"Custom\")\n14 counter = counter + 1\n\n15 Next currentStyle\n\n16 stylesTable.Resize stylesTable.Range.Resize(RowSize:=UBound(tempStyleInfo, 1))\n\n17 If stylesTable.DataBodyRange Is Nothing Then stylesTable.ListRows.Add\n\n18 stylesTable.DataBodyRange = tempStyleInfo\n\n End Sub\n</code></pre>\n\n<blockquote>\n <p>Line 6 counter = 0</p>\n</blockquote>\n\n<p>This is the first time counter is used there is no reason to initiate a variable to its default value.</p>\n\n<blockquote>\n <p>Line 7 counterStyles = ThisWorkbook.Styles.Count</p>\n</blockquote>\n\n<p><code>counterStyles</code> does little to add to the readability of the code. It's clear what <code>ThisWorkbook.Styles.Count</code> does <code>counterStyles</code> is just adding 2 extra lines to the subroutines body.</p>\n\n<blockquote>\n <p>Line 8 ReDim tempStyleInfo(counterStyles + 1, 3)\n <code>counterStyles + 1</code> is wrong. It causing <code>tempStyleInfo</code> to be created with 2 extra rows. </p>\n</blockquote>\n\n<p>I prefer to work with 1 based arrays when writing data to a range. Using</p>\n\n<blockquote>\n<pre><code> ReDim tempStyleInfo(1 to counterStyles, 1 to 4)\n</code></pre>\n</blockquote>\n\n<p>Here is the correct declaration for the 0 based array:</p>\n\n<blockquote>\n<pre><code> ReDim tempStyleInfo(0 to counterStyles - 1, 0 to 3)\n</code></pre>\n</blockquote>\n\n<p>Although not necessary it is recommended to include the array base size when declaring an array.</p>\n\n<blockquote>\n <p>Line 9 Set stylesTable = MStyles.ListObjects(\"TableStyles\")</p>\n</blockquote>\n\n<p>Consider passing in the<code>stylesTable</code> as a parameter of the Create method.</p>\n\n<blockquote>\n<pre><code>9 Set stylesTable = MStyles.ListObjects(\"TableStyles\")\n10 If Not stylesTable.DataBodyRange Is Nothing Then \n</code></pre>\n</blockquote>\n\n<p>Lines 9 and 10 should appear after the Line 15. There is no reason to modify the table before the data is compiled. As a rule, I gather the data in a separate sub or function. This allows me to test the two tasks independently. </p>\n\n<blockquote>\n <p>Line 16 stylesTable.Resize stylesTable.Range.Resize(RowSize:=UBound(tempStyleInfo, 1))</p>\n \n <p>Line 17 If stylesTable.DataBodyRange Is Nothing Then stylesTable.ListRows.Add</p>\n</blockquote>\n\n<p>Line 17 never triggers because Line 16 already added the correct number of rows.</p>\n\n<blockquote>\n <p>Line 11 For Each currentStyle In ThisWorkbook.Styles</p>\n</blockquote>\n\n<p>Using <code>ThisWorkbook</code> severely limits the usefulness of the code. It would be far better to set the target workbook in the Create method. Other classes are also limited by <code>ThisWorkbook</code>. I would set a reference to the parent <code>StyleProcessor</code> class in these class's Create methods so you can reference the parent's target workbook (e.g. <code>Parent.TargetWorkbook</code>).</p>\n\n<h2>Refactored Code</h2>\n\n<pre><code>Public Sub LoadToTable()\n Dim Values\n Values = getStyleInfo()\n\n If Not stylesTable.DataBodyRange Is Nothing Then stylesTable.DataBodyRange.Delete\n stylesTable.ListRows.Add\n stylesTable.DataBodyRange.Resize(UBound(Values, 1)) = Values\n\nEnd Sub\n\nPrivate Function getStyleInfo()\n Dim Results\n ReDim Results(1 To TargetWorkbook.Styles.Count, 1 To stylesTable.ListColumns.Count)\n\n Dim n As Long\n Dim currentStyle As Style\n For Each currentStyle In TargetWorkbook.Styles\n n = n + 1\n Results(n, 1) = currentStyle.name\n Results(n, 2) = IIf(currentStyle.BuiltIn, \"BuiltIn\", \"Custom\")\n Next\n\n getStyleInfo = Results\nEnd Function\n</code></pre>\n\n<p><code>Application.ScreenUpdating</code> should be turned off when updating styles. You should also test changing name of individual cells styles versus Union the range for large number of cells.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-31T12:09:47.857",
"Id": "451772",
"Score": "0",
"body": "This is awesome and very illustrative feedback. Thank you! Could you elaborate more on this suggestion: \"You should also test changing name of individual cells styles versus Union the range for large number of cells\" ?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-31T13:53:48.143",
"Id": "451788",
"Score": "0",
"body": "@RicardoDiaz Here is my answer to [Brute force looping & formatting Or Create Union range & Format? Which is efficient and when?](https://codereview.stackexchange.com/a/226296/171419). The question does a good job of explaining the performances of formatting individual versus groups of cells."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-31T13:55:08.403",
"Id": "451789",
"Score": "0",
"body": "@RicardoDiaz Another thing that I forgot to mention, you should add a `Restore Default Styles` button."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-31T14:19:27.013",
"Id": "451795",
"Score": "0",
"body": "Thank you. You 're right about the restore button. Checking the link right now."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-31T06:23:01.987",
"Id": "231584",
"ParentId": "231499",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "231584",
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-30T00:13:00.130",
"Id": "231499",
"Score": "5",
"Tags": [
"object-oriented",
"vba",
"excel",
"interface",
"polymorphism"
],
"Title": "Manage Excel Styles with VBA OOP Approach (Follow up)"
}
|
231499
|
<p>This is the task's description. My code gets 100% task score. Is it good code yet? (I think I'm getting a lot better, since I started solving this codility's exercises and posting here, but I always get important things to improve -which help me A LOT!- from reviewers)</p>
<blockquote>
<p><strong><em>N voracious fish are moving along a river. Calculate how many fish are alive.</em></strong></p>
</blockquote>
<hr>
<blockquote>
<p>You are given two non-empty zero-indexed arrays A and B consisting of
N integers. Arrays A and B represent N voracious fish in a river,
ordered downstream along the flow of the river.</p>
<p>The fish are numbered from 0 to N − 1. If P and Q are two fish and P <
Q, then fish P is initially upstream of fish Q. Initially, each fish
has a unique position.</p>
<p>Fish number P is represented by A[P] and B[P]. Array A contains the
sizes of the fish. All its elements are unique. Array B contains the
directions of the fish. It contains only 0s and/or 1s, where:</p>
<p>0 represents a fish flowing upstream, 1 represents a fish flowing
downstream. If two fish move in opposite directions and there are no
other (living) fish between them, they will eventually meet each
other. Then only one fish can stay alive − the larger fish eats the
smaller one. More precisely, we say that two fish P and Q meet each
other when P < Q, B[P] = 1 and B[Q] = 0, and there are no living fish
between them. After they meet:</p>
<p>If A[P] > A[Q] then P eats Q, and P will still be flowing downstream.
If A[Q] > A[P] then Q eats P, and Q will still be flowing upstream. We
assume that all the fish are flowing at the same speed. That is, fish
moving in the same direction never meet. The goal is to calculate the
number of fish that will stay alive.</p>
<p>For example, consider arrays A and B such that:</p>
<pre><code>A[0] = 4 B[0] = 0
A[1] = 3 B[1] = 1
A[2] = 2 B[2] = 0
A[3] = 1 B[3] = 0
A[4] = 5 B[4] = 0
</code></pre>
<p>Initially all the fish are alive and all except fish number 1 are
moving upstream. Fish number 1 meets fish number 2 and eats it, then
it meets fish number 3 and eats it too. Finally, it meets fish number
4 and is eaten by it. The remaining two fish, number 0 and 4, never
meet and therefore stay alive.</p>
<p>Write a function:</p>
<pre><code>class Solution { public int solution(int[] A, int[] B); }
</code></pre>
<p>that, given two non-empty zero-indexed arrays A and B consisting of N
integers, returns the number of fish that will stay alive.</p>
<p>For example, given the arrays shown above, the function should return
2, as explained above.</p>
<p>Assume that:</p>
<p>N is an integer within the range [1..100,000]; each element of array A
is an integer within the range [0..1,000,000,000]; each element of
array B is an integer that can have one of the following values: 0, 1;
the elements of A are all distinct.</p>
<p>Complexity:</p>
<p>Expected worst-case time complexity is O(N); expected worst-case space
complexity is O(N), beyond input storage (not counting the storage
required for input arguments).</p>
</blockquote>
<pre><code>using System;
using System.Collections.Generic;
using System.Linq;
class Solution
{
public int solution(int[] A, int[] B)
{
const int UpstreamFloater = 0;
const int DownstreamFloater = 1;
Stack<int> downstreamersStack = new Stack<int>();
int topStackDownstreamer;
int aliveFishesCounter = 0;
for (int fish = 0; fish < B.Length; fish++)
{
if (downstreamersStack.Count == 0 && B[fish] == UpstreamFloater)
{
aliveFishesCounter++;
}
else if (B[fish] == DownstreamFloater)
{
downstreamersStack.Push(fish);
}
else if (B[fish] == UpstreamFloater)
{
topStackDownstreamer = downstreamersStack.Peek();
while (downstreamersStack.Count > 0 && A[fish] > A[topStackDownstreamer])
{
downstreamersStack.Pop();
if (downstreamersStack.Count > 0)
{
topStackDownstreamer = downstreamersStack.Peek();
}
}
if (downstreamersStack.Count == 0)
{
aliveFishesCounter++;
}
}
}
aliveFishesCounter += downstreamersStack.Count;
return aliveFishesCounter;
}
}
</code></pre>
|
[] |
[
{
"body": "<p>Your solution is good. There are a couple bits you could change, sure. Some of them boil down to personal preferences.</p>\n\n<p>Give the arrays more useful names:</p>\n\n<pre><code>public int solution(int[] size, int[] direction)\n</code></pre>\n\n<p>Declare <code>topStackDownstreamer</code> when you need it. Keeping the scope of a variable minimal gives you less things to remember. What is <code>topStackDownstreamer</code>? How is it used? What was it's value when we assign a new one? Should we do something with the old value first?</p>\n\n<p>But you might as well not need <code>topStackDownstreamer</code> at all.</p>\n\n<p>As you use <code>if</code> and two <code>else if</code> your code looks like it is missing something - the last <code>else</code>. I'd recommend using one <code>if</code> and <code>else</code> for clarity. You could also restructure the stack looping a little bit and check for stacksize=0 only once:</p>\n\n<pre><code> if (direction[fish] == DownstreamFloater)\n {\n downstreamersStack.Push(fish);\n }\n else // must be UpstreamFloater\n {\n while (downstreamersStack.Count > 0)\n {\n if(size[fish] > size[downstreamersStack.Peek()])\n {\n downstreamersStack.Pop();\n }\n else\n {\n break;\n }\n }\n\n if (downstreamersStack.Count == 0)\n {\n aliveFishesCounter++;\n }\n }\n</code></pre>\n\n<p>Another little bit - you could return without storing the added variables:</p>\n\n<pre><code>return aliveFishesCounter + downstreamersStack.Count;\n</code></pre>\n\n<p>The last bit - maybe you could use shorter identifiers. e.g. <code>direction[fish] == DownstreamFloater</code> would look better if it was <code>direction[fish] == Downstream</code>. Another example <code>aliveFishesCounter</code> could be <code>survivors</code>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-02T09:08:25.030",
"Id": "231725",
"ParentId": "231500",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-30T01:54:00.500",
"Id": "231500",
"Score": "3",
"Tags": [
"c#",
"performance",
"beginner",
"array",
"stack"
],
"Title": "Codility voracious fish are moving along a river, solution in C#"
}
|
231500
|
<p>I'm new to R and have created a dictionary function. A user will input a phrase into a text field and the server will read it and see if there's a match in a back-end data table and if so, output the abbreviation of the phrase.</p>
<p>This dictionary data table does not have a 1 to 1 mapping. The dictionary has <code>logical_word</code> and <code>abbreviation</code> columns; here's a small sample:</p>
<pre><code>238 abstract ABST NA NA NA
239 abstraction ABSTN NA NA NA
383 aggregate consumer economic ACE NA NA NA
876 business-to-consumer B2C NA NA NA
1309 consumer CNSMR NA NA NA
1310 Consumer Credit Counseling Service CCCS NA NA NA
1311 Consumer Indebtedness Index CII NA NA NA
1312 Consumer Lending CNL NA NA NA
1313 consumer loan application CLAPP NA NA NA
1314 consumer operating as business CSOAB NA NA NA
1315 Consumer Price Index
5582 time zone TZN NA NA NA
6041 Wholesale Consumer Information System WCIS NA NA NA
6119 zone ZONE NA NA NA
6121 ZORRO ZR NA NA NA
</code></pre>
<p>Suppose a user inputs "Consumer Credit Counseling Service zorro zone".
This program will take the input and switch it to upper case and same w/dictionary DT.</p>
<p>I split the user input on whitespace into a vector, then run a loop and grep for the first word (<code>CONSUMER</code>) to see if there's a match in the dictionary. If there is a match, then I keep going and grep for 2 words (<code>CONSUMER CREDIT</code>). I do the same for all words until there's no match returned from the grep or if the match returned is == 1; in that case I pull the abbreviation value using <code>merge()</code> and the phrase <code>(searchStringDT[i])</code>.</p>
<p>When looking for <code>"CONSUMER CREDIT COUNSELING SERVICE ZORRO"</code> the search result comes back as empty, so then I run a <code>merge()</code> on the last iterated phrase <code>"CONSUMER CREDIT COUNSELING SERVICE"</code>
and the dictionary and get back the abbreviation <code>"CCCS"</code>.</p>
<p>Then I set a flag (<code>reset <- true</code>) and run the loop against <code>"ZORRO"</code> and see if there's a match; since there is, I keep going and grep <code>"ZORRO ZONE"</code> again. There's no value returned and I run a <code>merge()</code> on <code>"ZORRO"</code> and the dictionary and get back <code>"ZR"</code>.</p>
<p>Then I run the loop on <code>"ZONE"</code>, and since it's the last value, I run the <code>merge()</code> and get back <code>"ZONE"</code>.</p>
<p>I have a couple of questions: </p>
<ol>
<li><p>Can someone recommend different approaches to improve speed/accuracy and make my code cleaner? Right now, it seems like a mess IMO.</p>
<p>If not, can someone recommend a way to fix my current approach, since this doesn't completely work.</p></li>
<li><p>In the grep I added <code>"^"</code> to make sure that I only return values that start with the user input, but when I tested with <code>"abstract"</code> the grep returned
both <code>"abstract"</code> and <code>"abstraction"</code> since the patterns match. My logic is based on only 1 value being returned to pull the abbreviation using the <code>merge()</code>.</p>
<p>If I add <code>"$"</code> to the grep then my code breaks since <code>"CONSUMER CREDIT"</code> doesn't have an exact match. Is there some other condition I can add to see if the dictionary contains a phrase? So if I search <code>"CONSUMER CREDIT"</code> I should get back <code>"CONSUMER CREDIT COUNSELING SERVICE"</code> and if I search <code>"ABSTRACT"</code> I should only get <code>"ABSTRACT"</code> and not <code>"ABSTRACTION"</code>?</p></li>
</ol>
<h2>The code:</h2>
<pre><code> searchDictionary <- function(userInput=NULL,dictionary=NULL){
userInput <- data.table(logical_word=userInput)
listTest <- data.frame(matrix(ncol = 5, nrow = nrow(userInput)))
names(listTest) <- c("logical_word","abbreviation","V3","V4","V5")
searchString <- ""
reset <- "FALSE"
searchStringDT <- data.table(matrix(ncol = 1, nrow = nrow(userInput)))
names(searchStringDT) <- c("logical_word")
i <- 1
while(i <= nrow(userInput)){
if(i==1){
searchString <- userInput[i]
searchStringDT$logical_word[i] <- unlist(searchString)
}
else if(reset == "TRUE"){
searchString <- userInput[i]
searchStringDT$logical_word[i] <- unlist(searchString)
}
else{
searchString <- paste(searchString,userInput[i])
searchStringDT$logical_word[i] <- unlist(searchString)
}
reset <- "FALSE"
searchResult <- dictionary[grep( paste0("^",searchStringDT[i]), dictionary$logical_word), ]
if(nrow(searchResult) == 0){
if( grepl("\\s", searchStringDT[i]) ){
listTest[i-1,] <- merge(searchStringDT[i-1], dictionary, "logical_word", all.x = TRUE, sort = FALSE)
i <- i
}
else{
listTest[i,] <- searchStringDT[i]
i <- i+1
}
reset <- "TRUE"
}
else if(nrow(searchResult) == 1){
listTest[i,] <- merge(searchStringDT[i], dictionary, "logical_word", all.x = TRUE, sort = FALSE)
i <- i+1
}
else{
i <-i+1
}
}
print("out for loop listTest")
print(listTest)
}
<span class="math-container">```</span>
</code></pre>
|
[] |
[
{
"body": "<p>R supports Perl-compatible regular expressions, and these support <code>\\b</code>, which matches at word boundaries. You can use this to avoid matching <code>abstraction</code>:</p>\n\n<pre><code>grep(paste0(\"^\", word, \"\\\\b\"), haystack, perl = TRUE)\n</code></pre>\n\n<p>Instead of the string literals <code>\"TRUE\"</code> and <code>\"FALSE\"</code>, you should use the logical literals for the <code>reset</code> variable, just remove the quotes.</p>\n\n<p>The spacing in your code is inconsistent. Have a look at <a href=\"https://style.tidyverse.org/\" rel=\"nofollow noreferrer\">https://style.tidyverse.org/</a> and either apply these rules manually to your code, or use an automatic formatter. RStudio certainly has one, and since a few days IntelliJ has an R plugin with a good formatter.</p>\n\n<p>Instead of printing the result at the end of the function, you should rather just return it by leaving out the <code>print</code> and the parentheses. This makes it easier to write unit tests for it. If you haven't done so already, have a look at the <code>testthat</code> package.</p>\n\n<p>The <code>if</code> branches for <code>i == 1</code> and for <code>reset == TRUE</code> are the same. You should merge them by making the condition <code>i == 1 || reset</code> (after you removed the quotes, as I suggested above).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-30T19:49:59.313",
"Id": "451706",
"Score": "0",
"body": "thank you! Worked like a charm. But I still have a doubt: when searching for \"consumer\" the grep returns vals 1309-1315 but I would like to only return the exact match. If I add \"$\" then when searching for \"consumer credit\" I wouldn't get anything back. \n\nBasically what I'm trying to do is search the dictionary DT one word at a time and if there is only 1 match then retrieve that abbreviation, if not then add the next word to the existing and search for the new val. \n\nIf this is out of scope, can you recommend documentation to look into? I looked into some but still struggling with regex"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-30T19:55:38.207",
"Id": "451707",
"Score": "0",
"body": "As I suggested in my answer, you should write `testthat` tests. You already know how the code should behave in all the situations, therefore it makes sense to write down your expectations so that they can be checked automatically. Next, use Git or another version control system, so that you cannot lose any code that worked in the past. With that done, it's no longer risky to throw away your code, completely rewrite it or try out new ideas."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-30T07:16:18.843",
"Id": "231512",
"ParentId": "231503",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "231512",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-30T03:03:34.280",
"Id": "231503",
"Score": "2",
"Tags": [
"beginner",
"algorithm",
"hash-map",
"r"
],
"Title": "Dictionary function for R"
}
|
231503
|
<p>I am trying to build a fast cryptography algorithm. The algorithm works fine, but I am worried if there are any potential flaws that might make the algorithm vulnerable to any kind of attack. Here is my code.</p>
<h2><code>Encryptor.cpp</code></h2>
<pre class="lang-cpp prettyprint-override"><code>#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
using namespace std;
class Encryptor
{
private:
unsigned char *key; //256 byte
unsigned char key16[16]; //16 byte
public:
Encryptor(unsigned char *k)
{
key = k;
for (int i = 0; i < 256; i += 16)
{
for (int j = 0; j < 16; j++)
{
if (i < 16)
{
key16[j] = key[j];
}
else
{
key16[j] = key16[j] ^ key[i + j];
}
}
}
srand(time(0));
}
string encrypt(string txt)
{
int totalRounds = (txt.size() / 256);
if (txt.size() % 256)
totalRounds++;
string cipher(totalRounds * 16 + txt.size(), 0);
for (int i = 0; i < totalRounds; i++)
{
unsigned char randKey[16];
int txtIndex = i * 256;
int cipherIndex = i * (16 + 256);
int txtSize = (i == (totalRounds - 1)) ? txt.size() % 256 : 256;
for (int j = 0; j < 16; j++)
{
randKey[j] = random(1, 254);
cipher[cipherIndex] = key16[j] ^ randKey[j];
cipherIndex++;
}
for (int j = 0; j < txtSize; j++)
{
cipher[cipherIndex] = key[j] ^ randKey[j % 16] ^ txt[txtIndex];
cipherIndex++;
txtIndex++;
}
}
return cipher;
}
string decrypt(string cipher)
{
int totalRounds = (cipher.size() / (256 + 16));
if (cipher.size() % (256 + 16))
totalRounds++;
string txt(cipher.size() - totalRounds * 16, 0);
for (int i = 0; i < totalRounds; i++)
{
unsigned char randKey[16];
int txtIndex = i * 256;
int cipherIndex = i * (16 + 256);
int txtSize = (i == (totalRounds - 1)) ? (cipher.size() % (256 + 16)) - 16 : 256;
for (int j = 0; j < 16; j++)
{
randKey[j] = cipher[cipherIndex] ^ key16[j];
cipherIndex++;
}
for (int j = 0; j < txtSize; j++)
{
txt[txtIndex] = cipher[cipherIndex] ^ key[j] ^ randKey[j % 16];
cipherIndex++;
txtIndex++;
}
}
return txt;
}
int random(int lower, int upper)
{
return (rand() % (upper - lower + 1)) + lower;
}
};
</code></pre>
<h2><code>main.cpp</code></h2>
<pre class="lang-cpp prettyprint-override"><code>#include <iostream>
#include "Encryptor.cpp"
using namespace std;
int main()
{
unsigned char key[256] = {239, 222, 80, 163, 48, 26, 182, 101, 123, 51, 145, 28, 106, 157, 105, 1, 51, 129, 222, 124, 80, 254, 118, 220, 208, 75, 225, 127, 180, 192, 125, 149, 22, 140, 218, 162, 89, 45, 237, 250, 71, 85, 245, 75, 59, 122, 146, 95, 68, 130, 33, 62, 124, 11, 203, 252, 72, 141, 140, 12, 241, 218, 89, 147, 58, 124, 209, 177, 71, 254, 201, 3, 166, 10, 179, 89, 194, 72, 150, 32, 97, 197, 119, 50, 185, 11, 202, 164, 175, 115, 239, 113, 146, 7, 84, 62, 49, 124, 25, 108, 111, 107, 250, 168, 75, 137, 87, 219, 115, 242, 237, 23, 79, 53, 95, 45, 180, 59, 243, 138, 37, 219, 174, 13, 188, 19, 62, 104, 176, 154, 183, 242, 177, 19, 215, 42, 197, 88, 149, 246, 40, 54, 184, 31, 187, 9, 115, 152, 128, 165, 116, 105, 179, 242, 145, 195, 250, 153, 139, 247, 96, 51, 225, 237, 86, 97, 97, 196, 146, 67, 73, 88, 30, 135, 192, 29, 64, 189, 123, 95, 152, 22, 31, 5, 71, 38, 136, 6, 68, 247, 93, 206, 200, 229, 243, 140, 11, 137, 60, 197, 22, 92, 118, 44, 3, 47, 121, 249, 88, 27, 101, 242, 222, 36, 112, 45, 188, 46, 170, 201, 244, 90, 115, 224, 88, 157, 109, 136, 228, 134, 186, 124, 154, 3, 78, 49, 225, 57, 249, 172, 103, 44, 74, 84, 158, 48, 139, 185, 207, 9, 58, 143, 211, 177, 62, 32};
Encryptor e(key);
for (int i = 0; i < 100; i++)
{
string c = e.encrypt("my secret");
cout << "cipher: " << c << endl;
cout << "After decryption: " << e.decrypt(c) << endl;
}
return 0;
}
</code></pre>
<hr>
<h1>Algorithm:</h1>
<ul>
<li>user provides 256 byte key where the value of any byte can't be 0 or 255 </li>
<li>16 byte internal key is generated from the user provided key </li>
</ul>
<h1>encryption:</h1>
<ul>
<li>plain text is processed in 256-byte blocks (same as the key length) except the last one which depends on the length of the plain text. </li>
<li>16-byte random key is generated for every block where the value of each byte is between 1,254.</li>
<li>for each plain text block additional 16 byte is added in the beginning of cipher text block that increases the cipher text block size to 256+16 byte</li>
<li>the first 16 bytes of each cipher text block contains the XOR result of the block random key and the internal key</li>
<li>the 17th byte of the cipher text = key[first byte] xor random key[first byte] xor plain text block[first byte]</li>
<li>the 18th byte of the cipher text = key[second byte] xor random key[second byte] xor plain text block[second byte]<br>
....</li>
<li>when the random key reaches its last byte, as it is shorter than the block size, it repeats from the beginning. </li>
</ul>
<p>The decryption process is reverse of the encryption process.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-30T14:42:06.010",
"Id": "451659",
"Score": "1",
"body": "By the way, your \"rounds\" are what most cryptographers would call \"blocks\"."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-30T15:08:03.987",
"Id": "451662",
"Score": "5",
"body": "Recommended reading: https://security.stackexchange.com/q/18197/218173 - TLDR: It's better to grab a well-tested open-source library and use that. Algorithms like AES-256 are not \"slow\". These public libraries are made from the combined efforts of legions of people, including many who are much more qualified than you or I."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-30T20:06:00.263",
"Id": "451708",
"Score": "0",
"body": "@Gloweye is correct. Don't use this for anything important. If this is just meant to be a fun exercise and learn about cryptography then by all means please continue. But if this is something you mean to encrypt anything meaningful with then please take pause."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-31T09:42:00.923",
"Id": "451754",
"Score": "0",
"body": "You're effectively using a simple substitution cipher with (slightly less than) 128 bits of key information. Although the cryptanalysis won't fit in a comment, that's criminally weak, and far from \"unrealistic\" to attack if any message structure is known (e.g. if it's known to contain ASCII or Unicode text; if it's a RFC-822 message, or an XML document, or a PNG image, or almost any other kind of useful data)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-31T09:52:10.320",
"Id": "451756",
"Score": "0",
"body": "I know this is a very simple encryption technique, but what making me crazy is that why can't I find a way of retiving any sensitive data. please try the cryptanalysis and lets assume that you have access to not only the encoding of the text but also n number of plain text and cipher text. @Toby Speight"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-31T10:50:19.353",
"Id": "451761",
"Score": "11",
"body": "It's not surprising that you can't find how to crack it. To quote Bruce Schneier, [in 1998](https://www.schneier.com/crypto-gram/archives/1998/1015.html#cipherdesign), ***Anyone, from the most clueless amateur to the best cryptographer, can create an algorithm that he himself can't break. It's not even hard. What is hard is creating an algorithm that no one else can break, even after years of analysis.*** IOW, being unable to crack it yourself says very little about its strength."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-31T11:07:27.620",
"Id": "451764",
"Score": "0",
"body": "That's the reason I am requesting you to try and break. If I can't find anyone who can break this algorithm for a long time then I want to use this in my project because this is faster than most of the popular algorithms. @Toby Speight"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-31T12:01:54.910",
"Id": "451771",
"Score": "2",
"body": "I think that's more than you can reasonably expect a volunteer reviewer to be able to do for you, for free."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-31T13:19:14.063",
"Id": "451784",
"Score": "3",
"body": "In 99.9[...]9% of the cases where someone thinks _\"I know, I'll write my own encryption algorithm, It's [faster|safer|...] than existing ones\"_, they're at the [unconsciously incompetent](https://en.wikipedia.org/wiki/Four_stages_of_competence) stage of learning. You don't know what you need to know in order to know whether you're doing a good job. Regarding cryptography, I know I myself am consciously incompetent; I do know what I don't know, and therefore I won't attempt to roll my own. You should do more reading on the subject and abandon this current attempt."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-31T17:32:35.473",
"Id": "451859",
"Score": "3",
"body": "Someone might break your algorithm if they think it's fun and they have spare time. But I wouldn't rely on it. I agree that it's probably easy to break if you put in some work to actually figure out how to break it. I have broken a similar algorithm before using automated frequency analysis. I did that because I thought it was fun to show that person how broken their algorithm was, and I had spare time. I think this one will be harder than the one I previously broke, but not unbreakable at all."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-31T18:21:26.427",
"Id": "451885",
"Score": "0",
"body": "I have borken the algorithm. The main problem here is that I am using the same random key to encrypt multiple blocks. This makes Known Plaintext Attack possible on messages more than 16 bytes long."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-30T14:12:29.977",
"Id": "451898",
"Score": "0",
"body": "I want to point you at another question over on Information Security: [Why shouldn't we roll our own?][1] [1]://security.stackexchange.com/q/18197 I'm not in the position to point out security flaws in your code but the gist of the other question is: Don't roll your own if you're concerned about security."
}
] |
[
{
"body": "<p>Here are a number of things you could do to improve the code.</p>\n\n<h2>Separate interface from implementation</h2>\n\n<p>The interface goes into a header file and the implementation (that is, everything that actually emits bytes including all functions and data) should be in a separate <code>.cpp</code> file. The reason is that you might have multiple source files including the <code>.h</code> file but only one instance of the corresponding <code>.cpp</code> file. In other words, split your existing <code>Encryptor.cpp</code> file into a <code>.h</code> file and a <code>.cpp</code> file.</p>\n\n<h2>Use C++-style includes</h2>\n\n<p>Instead of including <code>stdio.h</code> you should instead use <code>#include <cstdio></code>. The difference is in namespaces as you can <a href=\"http://stackoverflow.com/questions/10460250/cstdio-stdio-h-namespace\">read about in this question</a>.</p>\n\n<h2>Don't abuse <code>using namespace std</code></h2>\n\n<p>Putting <code>using namespace std</code> at the top of every program is <a href=\"http://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice\">a bad habit</a> that you'd do well to avoid. Know when to use it and when not to (as when writing include headers). </p>\n\n<h2>Make sure you have all required <code>#include</code>s</h2>\n\n<p>The code uses <code>std::string</code> but doesn't <code>#include <string></code>. Also, carefully consider which <code>#include</code>s are part of the interface (and belong in the <code>.h</code> file) and which are part of the implementation per the earlier advice. </p>\n\n<h2>Don't use unnecessary <code>#include</code>s</h2>\n\n<p>The code has <code>#include <stdio.h></code> but nothing from that include file is actually in the code. For that reason, that <code>#include</code> should be eliminated. </p>\n\n<h2>Don't use <code>std::endl</code> if you don't really need it</h2>\n\n<p>The difference betweeen <code>std::endl</code> and <code>'\\n'</code> is that <code>'\\n'</code> just emits a newline character, while <code>std::endl</code> actually flushes the stream. This can be time-consuming in a program with a lot of I/O and is rarely actually needed. It's best to <em>only</em> use <code>std::endl</code> when you have some good reason to flush the stream and it's not very often needed for simple programs such as this one. Avoiding the habit of using <code>std::endl</code> when <code>'\\n'</code> will do will pay dividends in the future as you write more complex programs with more I/O and where performance needs to be maximized.</p>\n\n<h2>Use a better random number generator</h2>\n\n<p>You are currently using </p>\n\n<pre><code>(rand() % (upper - lower + 1)) + lower;\n</code></pre>\n\n<p>There are a number of problems with this approach. This will generate lower numbers more often than higher ones -- it's not a uniform distribution. Another problem is that the low order bits of the random number generator are not particularly random, so neither is the result. On my machine, there's a slight but measurable bias toward 0 with that. See <a href=\"http://stackoverflow.com/questions/2999075/generate-a-random-number-within-range/2999130#2999130\">this answer</a> for details.</p>\n\n<h2>Study cryptography</h2>\n\n<p>If you're interested in this sort of thing, it would be good for you to study cryptography. One book you might like is <em>Modern Cryptanalysis</em> by Christopher Swenson. It's quite understandable and may help you answer your own questions. Here's a brief analysis of your scheme:</p>\n\n<p>First, some nomenclature. I'm going to be referring to <em>blocks</em> (16-byte chunks) hereafter. Let <span class=\"math-container\">\\$m\\$</span> be a single block message we're encrypting, and the 256-byte key is <span class=\"math-container\">\\$k[0] \\cdots k[15]\\$</span>. Let's also say the random key is <span class=\"math-container\">\\$r\\$</span> and your <code>key16</code> is <span class=\"math-container\">\\$b\\$</span>. Using standard notation, <span class=\"math-container\">\\$\\oplus\\$</span> is the block-sized exclusive or operator. Your scheme does this:</p>\n\n<p><span class=\"math-container\">$$ b = k[0] \\oplus k[1] \\oplus \\cdots \\oplus k[14] \\oplus k[15] $$</span></p>\n\n<p>The generated message has two parts which I'll call <span class=\"math-container\">\\$p\\$</span> and <span class=\"math-container\">\\$q\\$</span>: </p>\n\n<p><span class=\"math-container\">$$ p = b \\oplus r $$</span>\n<span class=\"math-container\">$$ q = k[0] \\oplus r \\oplus m $$</span></p>\n\n<p>If we combine those into a new quantity <span class=\"math-container\">\\$m'\\$</span>, we get this:</p>\n\n<p><span class=\"math-container\">$$ m' = p \\oplus q = b \\oplus r \\oplus k[0] \\oplus r \\oplus m $$</span>\n<span class=\"math-container\">$$ m' = p \\oplus q = b \\oplus k[0] \\oplus m $$</span></p>\n\n<p>So we can easily already see that the random key has no useful effect. Further, we can say that <span class=\"math-container\">\\$b' = b \\oplus k[0]\\$</span>, so from the definition of <span class=\"math-container\">\\$b\\$</span> we get:</p>\n\n<p><span class=\"math-container\">$$ b' = k[1] \\oplus k[2] \\oplus \\cdots \\oplus k[14] \\oplus k[15] $$</span></p>\n\n<p>And so <span class=\"math-container\">\\$m' = b' \\oplus m\\$</span> and we can now see that the first block of the key also doesn't need to be derived. All that we need to get is <span class=\"math-container\">\\$b'\\$</span> and we can decode any message encrypted with that key. If we know or can guess that the encrypted text is ASCII, for example, it's not at all hard to guess at the top few bits of each of the bytes of <span class=\"math-container\">\\$b'\\$</span> and in essence, your scheme is no better (and no different) than choosing a randomly generated single key and exclusive-or-ing it with the message. That's a very, very weak scheme that even amateur cryptographers like me would have little difficulty breaking.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-30T13:19:13.617",
"Id": "231538",
"ParentId": "231507",
"Score": "23"
}
},
{
"body": "<h1>File naming</h1>\n\n<p>It's a long-standing convention in C++, as in C, that files meant to be included as part of another translation unit (headers) are given names with a <code>.h</code> suffix. It's a good idea to follow such conventions, as it makes the code easier for everyone to understand.</p>\n\n<h1>Includes</h1>\n\n<p>Don't use the C compatibility headers in new code; use the C++ versions, which declare their identifiers in the <code>std</code> namespace, whence they can be used unambiguously:</p>\n\n<pre><code>#include <cstdio>\n#include <cstdlib>\n#include <ctime>\n</code></pre>\n\n<h1><code>using</code> directive</h1>\n\n<p>Don't bring the whole of <code>std</code> into the global namespace - especially not in a header file, which will inflict the harm onto the entire translation unit. Just use the minimum set of identifiers you need into the smallest reasonable scope, and fully qualify names where reasonable.</p>\n\n<h1>Use initializers</h1>\n\n<p>Instead of writing <code>key = k;</code> in the body of the constructor, it's much better practice to use an initializer for this. That makes it easier for the compiler to determine whether the class is properly initialized:</p>\n\n<pre><code>Encryptor(unsigned char *k)\n : key{k}\n</code></pre>\n\n<h1>Mark conversion constructor as explicit</h1>\n\n<p>We don't want <code>Encryptor</code> to be considered as an implicit promotion from <code>unsigned char*</code>, so it should be marked <code>explicit</code>.</p>\n\n<h1>Avoid mutable non-owning pointers</h1>\n\n<p>We never modify the values in <code>k[]</code>, so don't store a mutable pointer:</p>\n\n<pre><code>class Encryptor\n{\n unsigned char const *key;\n\npublic:\n explicit Encryptor(unsigned char const *k)\n : key{k}\n {\n</code></pre>\n\n<h1>Validate arguments</h1>\n\n<p>There's a documented constraint that <code>k[n]</code> is not 0 or 255, but this is never checked. The constructor should validate that constraint and throw <code>std::invalid_argument</code> if it's violated. However, there's no justification for that constraint - I see no reason not to accept all values from 0 to <code>UCHAR_MAX</code>.</p>\n\n<h1>Use the full keyspace</h1>\n\n<p>The <code>key16</code> array contains only values from 1 to 254. We actually need it to be uniformly distributed across the full range 0 to <code>UCHAR_MAX</code>.</p>\n\n<h1>Initialise the random seed only once</h1>\n\n<p><code>std::srand()</code> doesn't give very good randomness if reseeded every time we create a new <code>Encryptor</code> - it's best called exactly once per process (generally in <code>main()</code>, where we can't accidentally link in another call).</p>\n\n<h1>Don't pass <code>std::string</code> by value</h1>\n\n<p>We can pass inputs by reference to <code>const</code>:</p>\n\n<pre><code> std::string encrypt(const std::string& txt);\n std::string decrypt(const std::string& cipher);\n</code></pre>\n\n<h1>Don't pass mutable <code>this</code> unnecessarily</h1>\n\n<p><code>encrypt()</code> and <code>decrypt()</code> require only read access; <code>random()</code> doesn't use any members at all:</p>\n\n<pre><code> std::string encrypt(const std::string& txt) const;\n std::string decrypt(const std::string& cipher) const;\nprivate:\n static int random(int lower, int upper);\n</code></pre>\n\n<h1>Don't mix signed and unsigned arithmetic</h1>\n\n<p>Strings are measured and indexed using <code>std::size_t</code>, which is unsigned, so don't access them using <code>int</code>, which is signed and may be too small.</p>\n\n<h1>Scrub key data after use</h1>\n\n<p>Don't leave secrets in memory unnecessarily, as they could be exposed to an attacker (e.g. in core dumps).</p>\n\n<pre><code>~Encryptor()\n{\n std::fill(std::begin(key16), std::end(key16), 0u);\n}\n</code></pre>\n\n<h1>Improve the encryption</h1>\n\n<p>The encryption algorithm is extremely weak, as some elementary cryptanalysis would reveal. Avoid any encryption that isn't based on proven mathematical difficulty.</p>\n\n<p>The only positive thing I could find is that the code doesn't seem to have any obvious data dependencies in its timing or power consumption.</p>\n\n<p>Ciphertexts are more than 6% larger than plaintexts, making this algorithm inefficient for storage or transmission of secret data.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-30T13:50:11.753",
"Id": "231541",
"ParentId": "231507",
"Score": "7"
}
},
{
"body": "<p>Please do not roll your own encryption outside of an academic context.</p>\n\n<p>If you would like a fast algorithm that can be easily implemented in C/C++ take a look at <a href=\"https://en.wikipedia.org/wiki/Salsa20#ChaCha_variant\" rel=\"noreferrer\">ChaCha or Salsa</a>. Runs great on most general purpose CPUs and has been verified by the cryptographic community at large. I've seen it outpace AES accelerators in constrained devices.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-30T15:51:20.170",
"Id": "231553",
"ParentId": "231507",
"Score": "13"
}
},
{
"body": "<p>Regarding the cryptographic algorithm only:</p>\n\n<h1>Important observations</h1>\n\n<p>This is equivalent to an XOR cipher with a repeating 256-byte key. The key16 stuff adds no security. The randKey stuff adds no security. The following is working decryption code for one round (I'll use your terminology), if you know the key:</p>\n\n<pre><code>unsigned char key16[16] = {0};\nfor(int k = 0; k < 256; k++) key16[k % 16] ^= key[k];\nfor(int k = 0; k < 256; k++) key[k] ^= key16[k % 16];\n\n// everything above this line adds no security,\n// because we could just take the modified key HERE\n// and pretend that's the real key.\n// Then we wouldn't need key16.\n\nstring decrypted = encrypted.substr(16);\nfor(int i = 0; i < decrypted.length(); i++) {\n // This line adds no security, because the attacker\n // knows what encrypted[i % 16] is.\n decrypted[i] ^= encrypted[i % 16];\n\n // This is the only part where we need to know the key.\n // It's a standard XOR cipher.\n decrypted[i] ^= key[i % 256];\n}\nstd::cout << decrypted << std::endl;\n</code></pre>\n\n<p>This does the same as your decryption code (try it and see), but I've rearranged it for easier analysis.</p>\n\n<p><em>In the rest of this answer, I will ignore key16 and randKey because they are easily reversed (see code above) and concentrate on the XOR cipher.</em></p>\n\n<p>So with that in mind, what are the problems?</p>\n\n<h1>It is vulnerable to statistical analysis, to get key16</h1>\n\n<p>The bytes in randKey are never 0 or 255. This means that after you XOR them with key16, they'll never be equal to key16 or key16^255. If the attacker sees a lot of rounds, this means the attacker can guess the bytes in key16, by narrowing each byte down to 2 possibilities.</p>\n\n<p>If you did discover key16, then you can combine it with 240 key bytes to work out the other 16. So it's not <em>much</em> of a breakthrough. </p>\n\n<h1>It might be vulnerable to statistical analysis, to get the message</h1>\n\n<p>Because the key bytes are never 0 or 255, once you have recovered key16 (see above), you can XOR that with the ciphertext (along with the randKey^key16) and then you'll never get bytes equal to the original message, or the message XOR 255. If you had enough copies of the same message encrypted with different keys, you could figure out which bytes you <em>aren't</em> getting, which is the message.</p>\n\n<p>To use this attack, you'd need to have a very long message (so that it contains enough rounds to figure out key16 for each key) and you'd need to see it encrypted with a lot of different keys (so that you can figure out the message).</p>\n\n<h1>It is vulnerable to <a href=\"https://en.wikipedia.org/wiki/Known-plaintext_attack\" rel=\"noreferrer\">known plaintext attacks</a>.</h1>\n\n<p>If you know the plaintext (decrypted text), or part of it, you can XOR the plaintext with the ciphertext (encrypted text), and you get the key.</p>\n\n<h1>It is vulnerable to <a href=\"https://en.wikipedia.org/wiki/Chosen-ciphertext_attack\" rel=\"noreferrer\">chosen ciphertext attacks</a></h1>\n\n<p>If I can give you some ciphertext (encrypted text) and get you to decrypt it, and show me the plaintext (decrypted text), then I can work out the key by XORing them.</p>\n\n<p>In particular, if I just give you a bunch of 0 bytes, and ask you to decrypt them, the plaintext will be the key XOR key16. That's really lame. </p>\n\n<h1>It is vulnerable to <a href=\"https://en.wikipedia.org/wiki/Frequency_analysis\" rel=\"noreferrer\">frequency analysis</a></h1>\n\n<p>The most common letter in English is 'e' (ASCII 0x65) or possibly a space (ASCII 0x20). If you see that 0x8F as the most common first byte of a round, you can guess that the first byte of the key XOR key16 is 0xEA (which would make them 'e') or 0xAF (which would make them spaces). Same for the second byte, and the third byte, and all the other bytes. For this to work, the message has to be quite long.</p>\n\n<h1>It is vulnerable to XORing two messages</h1>\n\n<p>Once you undo the random keys, you can XOR the ciphertext for two messages (or blocks) and it will be the same as XORing the plaintext for those two messages (or blocks). This can give you lots of information about the plaintext, but it's very specific to the situation. I'm not sure if this attack has a standard name.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-31T20:47:36.067",
"Id": "451906",
"Score": "1",
"body": "This looks like a great first post, good job!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-31T20:18:38.223",
"Id": "231635",
"ParentId": "231507",
"Score": "11"
}
}
] |
{
"AcceptedAnswerId": "231538",
"CommentCount": "12",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-30T06:39:34.790",
"Id": "231507",
"Score": "13",
"Tags": [
"c++",
"cryptography"
],
"Title": "Fast symmetric key cryptography class"
}
|
231507
|
<p>I have these queries written in Entity Framework where I try to get:</p>
<ul>
<li>Name of the customer</li>
<li>Most Recent Invoice Ref</li>
<li>Most Recent Invoice Amount (£)</li>
<li>Number of outstanding invoices (#)</li>
<li>Total of all outstanding invoices (£)</li>
</ul>
<p>I use these two tables:</p>
<pre><code>CREATE TABLE Customers
(
CustomerId INT,
Name NVARCHAR(100),
Address1 NVARCHAR(100),
Address2 NVARCHAR(100),
Postcode NVARCHAR(100),
Telephone NVARCHAR(15),
CONSTRAINT Customers_PK PRIMARY KEY (CustomerId)
)
CREATE TABLE Invoices
(
InvoiceId INT,
CustomerId INT, -- FK
Ref NVARCHAR(10),
InvoiceDate DATETIME,
IsPaid BIT,
Value DECIMAL,
CONSTRAINT Invoices_PK PRIMARY KEY (InvoiceId)
)
</code></pre>
<p>And the queries I make are:</p>
<pre><code>public PaginatedList<CustomerListEntity> GetCustomers(int pageIndex, int pageSize, out int totalRecords)
{
var customers = _customerRepository.AllIncluding(x => x.Invoices).OrderBy(x => x.CustomerId).Select(x => new
CustomerListEntity {
Name = x.Name,
CustomerID=x.CustomerId,
RecentInvoiceRef = x.Invoices.OrderByDescending(t => t.InvoiceDate).FirstOrDefault() != null ? x.Invoices.OrderByDescending(t => t.InvoiceDate).FirstOrDefault().Ref : string.Empty,
RecentInvoiceAmount = x.Invoices.OrderByDescending(t=>t.InvoiceDate).FirstOrDefault()!=null? x.Invoices.OrderByDescending(t => t.InvoiceDate).FirstOrDefault().Value:null,
UnpaidInvoicesNumber=x.Invoices.Where(t=>t.IsPaid==false).Count(),
UnpaidInvoicesTotalAmount = x.Invoices.Where(t => t.IsPaid == false).Sum(k=>k.Value)
});
totalRecords = customers.Count();
return customers.ToPaginatedList(pageIndex, pageSize);
}
</code></pre>
<p>Here is the implementation of AllINcluding:</p>
<pre><code>public virtual IQueryable<T> AllIncluding(params Expression<Func<T, object>>[] includeProperties)
{
IQueryable<T> query = _entitiesContext.Set<T>();
foreach (var includeProperty in includeProperties)
{
query = query.Include(includeProperty);
}
return query;
}
</code></pre>
|
[] |
[
{
"body": "<p>First off, the <code>Include</code> is ignored because you project the result to a new result (<code>Select(x => new{ ... }</code>). So you may as well remove it.</p>\n\n<p>Then, there is some room for improvement by eliminating the repetitive parts. It's much easier to do this in query syntax:</p>\n\n<pre class=\"lang-cs prettyprint-override\"><code>var customers = from cst in _customerRepository.All() // Assuming this method exists\n let lastInvoice = cst.Invoices.OrderByDescending(t => t.InvoiceDate).FirstOrDefault()\n let upaidInvoices = cst.Invoices.Where(t => !t.IsPaid)\n select new\n CustomerListEntity {\n Name = cst.Name,\n CustomerID = cst.CustomerId,\n RecentInvoiceRef = lastInvoice.Ref ?? string.Empty,\n RecentInvoiceAmount = lastInvoice.Value,\n UnpaidInvoicesNumber = upaidInvoices.Count(),\n UnpaidInvoicesTotalAmount = upaidInvoices.Sum(k => k.Value)\n });\n</code></pre>\n\n<p>The <code>let</code> keyword defines a local variable that can be reused in the LINQ statement. As you see, this greatly improves the readability of the code.</p>\n\n<p>It <em>also</em> slightly improves the generated SQL query, because <code>Ref</code> and <code>Value</code> will now be retrieved in one subquery instead of two. Unfortunately, this doesn't apply to <code>Count</code> and <code>Sum</code>, because aggregates require separate subqueries.</p>\n\n<p>Also, note that the null checks are removed. The LINQ statement is translated into SQL and executed in the database. SQL doesn't have this null reference concept.</p>\n\n<p>One last point is that there is broad consensus on the additional repository layer being totally redundant. Consider removing and query directly on the context.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-06T11:45:48.730",
"Id": "452662",
"Score": "0",
"body": "While this is a case where I have to (begrudgingly) agree that LINQ's query syntax is better, if OP is working in a codebase that only uses method syntax, I'd suggest sticking to conformity unless there is significant impact (which there IMO isn't in this case)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-06T11:50:00.047",
"Id": "452664",
"Score": "0",
"body": "_\"there is broad consensus on the additional repository layer being totally redundant\"_ I very much disagree. Unless you're advocating the leaking of EF outside of the DAL (which is a massive red flag that I can't tackle in a mere comment), your DAL will always need some way to not leak EF to consumers. Which pattern/interface/construct you use for that separation is up for debate, but the \"repository\" name tends to persist regardless of pattern/interface/construct due to this separation's functional purpose of providing access to the data store."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-06T11:52:39.487",
"Id": "452665",
"Score": "0",
"body": "**If** EF were to step away from inheriting from its context and instead allow for a composition-over-inheritance approach, then your custom db context would be able to be exposed publically without needing to leak EF itself. But as far as I'm aware that is not the case, your custom db context currently needs to inherit EF's `DbContext` which leads to requiring a reference to the EF library in order to work with your custom db context."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-06T12:03:47.673",
"Id": "452667",
"Score": "0",
"body": "@Flater If really necessary this can be converted into method syntax, throwing away the readability (big time) but retaining the slight SQL improvement. About leaky abstractions: they are [inevitable](https://blog.ploeh.dk/2012/03/26/IQueryableTisTightCoupling/) in any data layer based on `IQueryable`. As for composition-over-inheritance, I can only agree, it's a far better pattern. How to tell EF though?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-06T12:06:02.983",
"Id": "452668",
"Score": "0",
"body": "You're right about IQueryables always being a leaky abstraction, hence the good practice suggestion of _not_ leaking IQueryables. OP is indeed leaking IQueryables at the moment, but that's still _less_ of a transgression than leaking EF is. (EF leak = EF library dependency in consumers; IQueryable leak = needing to know which expressions EF cannot convert to SQL for you, but no EF library dependency in consumers) It's not an improvement to throw the baby out with the bathwater and start leaking EF altogether."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-06T11:36:25.423",
"Id": "231948",
"ParentId": "231518",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-30T08:59:36.067",
"Id": "231518",
"Score": "1",
"Tags": [
"c#",
"entity-framework"
],
"Title": "Entity Framework invoice queries"
}
|
231518
|
<p>The following code is designed to cache a <code>(UTCTime, Text)</code> value that keeps the <code>Text</code> token around until it expires, preventing needing to re-fetch the token each time this third party API is called. I feel like this duplication in <code>APIDefaults</code> and <code>APIEnv</code> could be removed, perhaps through a type parameter, though there may be a better way of doing this than storing the <code>MVar</code> inside <code>APIDefaults</code>.</p>
<p><code>APIError</code> and <code>getApiToken</code> are just stubbed out as their detail is not relevant here, but in my code these are not implemented as they are below, so you can just ignore those.</p>
<pre><code>data APIDefaults = APIDefaults
{ apidefManager :: Manager
, apidefPool :: ConnectionPool
, apidefTokenRef :: MVar (UTCTime, Text)
}
data APIEnv = APIEnv
{ apienvManager :: Manager
, apienvPool :: ConnectionPool
, apienvToken :: Text
}
data APIToken = APIToken
{ apiTokenAccessToken :: Text
, apiTokenExpiresIn :: Int
}
data APIError
fireApiRequest
:: MonadLogger m
=> MonadUnliftIO m
=> ReaderT APIEnv m (Either APIError a)
-> ReaderT APIDefaults m (Either APIError a)
fireApiRequest req = runExceptT $ do
env <- do
t <- lift readCachedToken
case t of
Nothing -> fetchToken
Just (savedExpiry, token) -> lift $ do
updateTokenRef (savedExpiry, token)
apd <- ask
return (createAPIEnv apd token)
ExceptT $ lift (runReaderT req env)
readCachedToken
:: MonadUnliftIO m
=> ReaderT APIDefaults m (Maybe (UTCTime, Text))
readCachedToken = runMaybeT $ do
mv <- lift (asks apidefTokenRef)
(savedExpiry, token) <- MaybeT $ liftIO (tryTakeMVar mv)
now <- getCurrentTime
guard (savedExpiry > now)
return (savedExpiry, token)
updateTokenRef
:: MonadUnliftIO m
=> (UTCTime, Text)
-> ReaderT APIDefaults m ()
updateTokenRef value = do
tokenRef <- asks apidefTokenRef
void $ liftIO (tryPutMVar tokenRef value)
fetchToken
:: MonadLogger m
=> MonadUnliftIO m
=> ExceptT APIError (ReaderT APIDefaults m) APIEnv
fetchToken = do
now <- getCurrentTime
adef <- lift ask
token <- getApiToken
let expiration = addUTCTime (fromIntegral $ apiTokenExpiresIn token) now
lift $ updateTokenRef (expiration, apiTokenAccessToken token)
return $ createAPIEnv adef (apiTokenAccessToken token)
getApiToken :: Monad m => m APIToken
getApiToken =
return undefined
createAPIEnv :: APIDefaults -> Text -> APIEnv
createAPIEnv adef token =
APIEnv (apidefManager adef) (apidefPool adef) token
</code></pre>
|
[] |
[
{
"body": "<p>I think the type of <code>apidefTokenRef</code> unnecessarily exposes internal details. Perhaps it would better to parameterize <code>APIDefaults</code> with a monad and hide the code that gets the token behind a monadic action, like this:</p>\n\n<pre><code>data APIDefaults m = APIDefaults\n { apidefManager :: Manager\n , apidefPool :: ConnectionPool\n , apidefTokenAction :: m APIToken \n }\n</code></pre>\n\n<p>I'm also making it return the <code>APIToken</code> type instead of <code>Text</code>. It's good to have a more precise type for it than <code>Text</code>, let's not fall prey to <a href=\"https://refactoring.guru/smells/primitive-obsession\" rel=\"nofollow noreferrer\">primitive obsession</a>!</p>\n\n<p>Now <code>APIEnv</code> seems a bit redundant. Instead of reading the token from <code>APIEnv</code>, functions in need of it can simply execute the token action each time. Or perhaps we could define a function like</p>\n\n<pre><code>sequenceToken :: Monad m => APIDefaults m -> m (APIDefaults Identity)\nsequenceToken r = do\n token <- apidefTokenAction r\n pure (r { apidefTokenAction = Identity token })\n</code></pre>\n\n<hr>\n\n<p>But how to define the token action itself? Here I will indulge in a bit of over-abstraction and define this typeclass:</p>\n\n<pre><code>class Perishable p where\n lifetime :: p -> NominalDiffTime\n</code></pre>\n\n<p>for values which have a certain <a href=\"http://hackage.haskell.org/package/time-1.9.3/docs/Data-Time-Clock.html#t:NominalDiffTime\" rel=\"nofollow noreferrer\">lifetime</a> during which they are valid. Of course, <code>APIToken</code> will have an instance.</p>\n\n<p>What type should the function which creates the token action have? It will be something like </p>\n\n<pre><code>makeRefresher :: Perishable p => IO p -> IO (IO p)\n</code></pre>\n\n<p>(Working in <code>IO</code> for simplicity, the real function would likely work in <code>MonadUnliftIO</code>.)</p>\n\n<p>The argument is an action that obtains the perishable value. But why the outer <code>IO</code> in the result? because <code>makeRefresher</code> will have to set up some reference—like an <code>MVar</code>—that will be used across successive invocations of the resulting action:</p>\n\n<pre><code>makeRefresher obtain = do\n ref <- newMVar _initialValueHole\n return $ _actualTokenActionHole\n</code></pre>\n\n<p>What should be on the <code>MVar</code>? Perhaps a <code>Maybe (UTCTime, p)</code>. It would be <code>Nothing</code> initially to signify that no perishable value has been obtained yet, and later it would become <code>Just (someTime,somePerishable)</code>. We have the time of creation and the expected lifetime of the <code>Perishable</code>, so we can decide whether to return the current value or invoke <code>obtain</code> again.</p>\n\n<p>Instead of <code>Maybe</code>, I would perhaps use my own type, for clarity:</p>\n\n<pre><code>data PerishableState p = NoPerishableYet\n | PerishableObtainedAt UTCTime p\n</code></pre>\n\n<p>Also, I would try to manipulate the <code>MVar</code> with functions like <a href=\"http://hackage.haskell.org/package/base-4.12.0.0/docs/Control-Concurrent-MVar.html\" rel=\"nofollow noreferrer\"><code>modifyMVar_</code></a> to avoid deadlocks if there's an exception while obtaining the token.</p>\n\n<hr>\n\n<p>One potential disadvantage of this solution is that the token \"state\" becomes harder to inspect because it's hidden behind an opaque action. Perhaps some logging effect should be added.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-08T09:53:39.140",
"Id": "238557",
"ParentId": "231519",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-30T08:59:51.670",
"Id": "231519",
"Score": "3",
"Tags": [
"haskell",
"state"
],
"Title": "Haskell - Caching third party API token across requests"
}
|
231519
|
<p>I have an attachment uploading feature in my web app.</p>
<p>File can have type- <code>image/png</code> or <code>image/jpg</code> or <code>image/jpeg</code> or <code>application/pdf</code></p>
<p>For images, I need to return <code>Photo</code>, for pdf <code>Document</code>.</p>
<p>Documents will be only <code>pdf</code>, but images can be extended to <code>images/ico</code>, etc.</p>
<p>Now my code looks like this.</p>
<pre><code>getAttachmentType(attachmentTypeHeader: string): string {
if (
attachmentTypeHeader === 'image/png' ||
attachmentTypeHeader === 'image/jpg' ||
attachmentTypeHeader === 'image/jpeg'
) {
return 'Photo';
}
if (attachmentTypeHeader === 'application/pdf') {
return 'Document';
}
}
</code></pre>
<p>How I can make it check like <code>image/*</code>?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-30T11:24:38.900",
"Id": "451610",
"Score": "1",
"body": "if (attachmentTypeHeader.startsWith('image/'))"
}
] |
[
{
"body": "<p>Usually if I have a big list of mappings from one <code>string</code> to another, that is <em>likely</em> to be later enhanced on, I use a <em>generic</em> mapping method, that is fed a <em>static</em> mapping constant.</p>\n\n<p>So the first iteration would be something like:</p>\n\n<pre class=\"lang-js prettyprint-override\"><code>type ExpectedMimeTypes =\n 'image/png' |\n 'image/jpg' |\n 'image/jpeg' |\n 'application/pdf' |\n never;\n\ntype ExpectedMagicOutput =\n 'Photo' |\n 'Document' |\n 'Unknown' |\n never;\n\ntype MimeTypeMapping = {\n [key in ExpectedMimeTypes]?: ExpectedMagicOutput \n}\n\nconst MAP_MIME_TYPE_TO_MAGIC_STRING: MimeTypeMapping = {\n 'image/png': 'Photo',\n 'image/jpg': 'Photo',\n 'image/jpeg': 'Photo',\n 'application/pdf': 'Document'\n}\n\nfunction getAttachmentType(attachmentTypeHeader: ExpectedMimeTypes): ExpectedMagicOutput {\n if (attachmentTypeHeader in MAP_MIME_TYPE_TO_MAGIC_STRING) {\n return MAP_MIME_TYPE_TO_MAGIC_STRING[attachmentTypeHeader]!; \n } else {\n return 'Unknown';\n } \n}\n</code></pre>\n\n<p>If you are using TypeScript, go <em>all in</em>, meaning be <em>as specific as possible</em>. You do not expect <em>arbitrary</em> <code>string</code> as a result from <code>getAttachmentType()</code> but <em>specific</em> ones. You should explicitly model them, either by using <em>unions</em> or <em>string-based</em> enums. This fosters <em>reusability</em>.</p>\n\n<p>The above solution gives you full type-safety, while being easily enhanced for other types; simply add them to the ExpectedMimeTypes and then you can easily add them to the constant <code>MAP_MIME_TYPE_TO_MAGIC_STRING</code> and vice versa, you <em>cannot</em> add mappings there, that have not been mentioned in the types above.</p>\n\n<p>You could make <code>ExpectedMimeTypes</code> configurable by putting them into a dedicated file and let that be generated via a config and a simple script. That way you get both - configurable mime types and static compile type safety.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-14T16:44:01.097",
"Id": "235615",
"ParentId": "231521",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-30T09:37:56.453",
"Id": "231521",
"Score": "1",
"Tags": [
"javascript",
"typescript",
"angular-2+"
],
"Title": "Return value related to file content header"
}
|
231521
|
<p>I solved an online judge problem named Jollo.
The full description of the problem can be found here:
<a href="https://www.urionlinejudge.com.br/judge/en/problems/view/1321" rel="nofollow noreferrer">https://www.urionlinejudge.com.br/judge/en/problems/view/1321</a></p>
<p>It's a card game between 2 players.</p>
<p>Each player is given 3 cards.</p>
<p>Each round a player shows one card and removes it from hand.</p>
<p>The player who shows the highest card wins the round.</p>
<p>Prince and Princess play but Prince is really bad and cries loudly so the servant who deals the cards, after dealing Princess her 3 cards, and dealing Prince 2 cards, he deals Prince the lowest higher card available that no matter how badly he plays he ends up winning. If there is none return -1.</p>
<p>My logical approach is that:</p>
<ol>
<li>If Princess wins first 2 rounds, there's nothing to be done return -1</li>
<li>If Prince wins first 2 rounds, return the lowest available card on deck</li>
<li>If each wins 1 of the first 2 rounds, if there is an available card on deck higher than princess' remaining card return it, if not return -1</li>
</ol>
<p>Each round logic, so that Prince always plays the worst possible game is achived via:</p>
<ol>
<li>Prince will always show his card first, he will play his highest card on hand</li>
<li>If Princess does not have a higher card than Prince played she will play her lowest. If she does, she will player her lowest higher card.</li>
</ol>
<p>E.g:</p>
<p>Princess cards: <code>5, 4, 3</code></p>
<p>Prince cards: <code>6, 1</code></p>
<p>Prince plays: <code>6</code> - Princess doesn't have a higher, play lowest: <code>3</code></p>
<p>Prince plays: <code>1</code>- Princess has two higher cards, play lowest higher card: <code>4</code>.</p>
<p>Tie: Princess remaining card is <code>5</code> therefore the next card available on deck to beat her is <code>7</code>.</p>
<p>Now for the code review part. What could I do better? Is this code somewhat similar in what would be used in a professional environment? </p>
<p>(I know there is some hard coding to this since it's only being used to a very specific problem and that instead of having 2 hardcoded players <code>prince</code> and <code>princess</code> a more general approach would be to have a <code>vector</code> of players etc. I'm asking about the general code design/organization overall).</p>
<pre><code>#include <iostream>
#include <sstream>
#include <array>
#include <algorithm>
#include <numeric>
#include <utility>
//used as flags
enum JolloPlayer
{
PRINCE = 100,
PRINCESS = 101,
NONE = 102
};
template<int C> struct Player
{
std::array<int,C>cards;
friend std::istream& operator>>(std::istream& is, Player& p)
{
for(auto& i : p.cards){
is >> i;
}
return is;
}
int amountOfCards = C;
};
template<unsigned int N>
class Jollo
{
private:
//amount of cards, not player number
Player<2> prince;
Player<3> princess;
std::array<int, N> deck;
const int roundsToWin {2};
public:
Jollo<N>(){
static_assert(N>4, "Jollo: deck size must be higher than 4");
}
bool ReadCards();
int GetPrinceMinimumWinningCard();
private:
int GetNextAvailableCard(JolloPlayer ePlayer, int lastPlayedCard = 0); //gets next card and flips deck
};
template<unsigned int N>bool Jollo<N>::ReadCards()
{
std::string line;
std::getline(std::cin, line);
std::istringstream issline(line);
issline >> princess;
issline >> prince;
return (princess.cards[0] != 0);
}
template<unsigned int N>int Jollo<N>::GetNextAvailableCard(JolloPlayer ePlayer, int lastPlayedCard)
{
if(ePlayer == JolloPlayer::PRINCE)
{
for(int i{0}; i<prince.amountOfCards; i++) {
if(deck[prince.cards[i] - 1] != JolloPlayer::PRINCE){
deck[prince.cards[i] - 1] = JolloPlayer::PRINCE;
return prince.cards[i];
}
}
} else
if(ePlayer == JolloPlayer::PRINCESS)
{
for(int i{0}; i<princess.amountOfCards; i++) {
if(deck[princess.cards[i] - 1] != JolloPlayer::PRINCESS && deck[princess.cards[i] - 1] > lastPlayedCard) {
deck[princess.cards[i] - 1] = JolloPlayer::PRINCESS;
return princess.cards[i];
}
}
//no card was higher, return lowest available card
for(int i{0}; i<princess.amountOfCards; i++) {
if(deck[princess.cards[i] - 1] != JolloPlayer::PRINCESS) {
deck[princess.cards[i] - 1] = JolloPlayer::PRINCESS;
return princess.cards[i];
}
}
}
//ePlayer == NONE
for(unsigned int i{0}; i<N; i++)
{
if(deck[i] != JolloPlayer::PRINCE && deck[i] != JolloPlayer::PRINCESS && deck[i] > lastPlayedCard ) {
return deck[i];
}
}
return -1; //if the game is tied but there is no higher card available. e.g 50 49 51 48 52
}
template<unsigned int N>int Jollo<N>::GetPrinceMinimumWinningCard()
{
std::iota(deck.begin(), deck.end(), 1); //must be re-set every time, as indexes are set to PRINCE or PRINCESS
std::sort(prince.cards.begin(), prince.cards.end(), std::greater<int>()); //decreasing
std::sort(princess.cards.begin(), princess.cards.end()); //increasing
int princeWins {0};
int princessWins {0};
for(int round {0}; round<roundsToWin; round++) //play two first rounds
{
int princeCard = GetNextAvailableCard(JolloPlayer::PRINCE);
int princessCard = GetNextAvailableCard(JolloPlayer::PRINCESS, princeCard);
if(princessCard > princeCard){
princessWins++;
} else {
princeWins++;
}
}
int lastPrincessCard = GetNextAvailableCard(JolloPlayer::PRINCESS); //important to flip the last card on the deck before continuing
if(princessWins == roundsToWin){
return -1;
}
if(princeWins == roundsToWin){
return GetNextAvailableCard(JolloPlayer::NONE);
}
return GetNextAvailableCard(JolloPlayer::NONE, lastPrincessCard);
}
int main()
{
Jollo<52> JolloInstance;
while(true)
{
if(!JolloInstance.ReadCards()) {
break;
}
std::cout << JolloInstance.GetPrinceMinimumWinningCard() << "\n";
}
return 0;
}
</code></pre>
<p>Some test cases as requested.</p>
<pre><code>3 2 1 5 4 o:6
6 1 3 4 5 o:7
6 2 3 4 7 o:5
5 3 2 6 7 o:1
5 3 2 6 4 o:7
5 3 1 2 4 o:-1
1 2 3 4 5 o:6
3 2 1 4 5 o:6
3 2 1 4 7 o:5
1 2 3 5 4 o:6
6 2 3 1 5 o:-1
52 1 2 3 50 o:4
52 1 3 4 50 o:5
4 2 52 3 50 o:-1
52 48 47 49 50 o:51
52 49 48 50 51 o:-1
48 49 52 51 50 o:-1
48 49 50 51 52 o:1
1 49 50 51 52 o:2
2 49 50 51 52 o:1
0 0 0 0 0
</code></pre>
|
[] |
[
{
"body": "<h1>Preface: A word about competitive programming</h1>\n\n<blockquote>\n <p>Now for the code review part. What could I do better? Is this code\n somewhat similar in what would be used in a professional environment?</p>\n \n <p>(I know there is some hard coding to this since it's only being used\n to a very specific problem and that instead of having 2 hardcoded\n players prince and princess a more general approach would be to have a\n vector of players etc. I'm asking about the general code\n design/organization overall).</p>\n</blockquote>\n\n<p>Actually, this is real problem. Competitive programming sites fail to teach you skills you need to do a real world project. In general, <a href=\"https://stackoverflow.com/users/560648\">learning C++ from \"competitive programming\" is like learning English from a rap contest.</a> I suggest that you start your own scalable project and go through the design process. That will be pretty fun :)</p>\n\n<p>In fact, I'd go ahead and say that the program is created to solve a very specific problem and that the generic code review method hardly applies to it.</p>\n\n<p>From comment:</p>\n\n<blockquote>\n <p>Do you think it's good to continue solving these problems, or by being\n focused on getting a good level of C++ I should focus on something\n else?</p>\n</blockquote>\n\n<p>It's fine to do some CP occasionally (for fun, maybe), but that shouldn't be your primary focus. Remember that doing CP does not help you learn real programming a whole lot. Instead, do some relatively large-scale, long-term projects to learn more about maintaining code. And you are always free to post on Code Review. <a href=\"https://stackoverflow.com/q/388242\">The Definitive C++ Book Guide and List</a> may also be helpful to you.</p>\n\n<h1>Use consistent spacing</h1>\n\n<p>This is my first impression: the spacing is inconsistent and follows an unpopular style. Here is the (in general) standard style:</p>\n\n<ul>\n<li><p>Template declarations should look like this:</p>\n\n<pre><code>template <typename T>\nclass C;\n</code></pre>\n\n<p>not</p>\n\n<pre><code>template<typename T> class C;\n</code></pre></li>\n<li><p>Member declarations should look like this:</p>\n\n<pre><code>std::array<int, N> arr;\n</code></pre>\n\n<p>not</p>\n\n<pre><code>std::array<int,N>arr;\n</code></pre></li>\n<li><p>Loops should look like this:</p>\n\n<pre><code>for (auto& x : y) {\n</code></pre>\n\n<p>not</p>\n\n<pre><code>for(auto& x : y){\n</code></pre></li>\n<li><p>Constructors should use the injected class name:</p>\n\n<pre><code>template <class T>\nstruct S {\n S() = default;\n};\n</code></pre>\n\n<p>not</p>\n\n<pre><code> S<T>() = default; \n</code></pre></li>\n<li><p>If chains should be lain out in this way:</p>\n\n<pre><code>if (...) {\n /* ... */;\n} else if (...) {\n /* ... */;\n}\n</code></pre>\n\n<p>not</p>\n\n<pre><code>if(...)\n{\n /* ... */;\n} else\nif(...)\n{\n /* ... */;\n}\n</code></pre></li>\n</ul>\n\n<h1>A walk through</h1>\n\n<p>In this section, I select some interesting snippets to comment on.</p>\n\n<blockquote>\n<pre><code>#include <iostream>\n#include <sstream>\n#include <array>\n#include <algorithm>\n#include <numeric>\n#include <utility>\n</code></pre>\n</blockquote>\n\n<p>Please sort the include directives according to alphabetical order:</p>\n\n<pre><code>#include <algorithm>\n#include <array>\n#include <iostream>\n#include <numeric>\n#include <sstream>\n#include <utility>\n</code></pre>\n\n<p>This helps navigation.</p>\n\n<blockquote>\n<pre><code>//used as flags\nenum JolloPlayer\n{\n PRINCE = 100,\n PRINCESS = 101,\n NONE = 102\n};\n</code></pre>\n</blockquote>\n\n<p>The magic numbers <code>100</code>, <code>101</code>, and <code>102</code> are confusing. Why? At least leave a comment. Also, the enum should probably be named <code>Player_ID</code>.</p>\n\n<blockquote>\n<pre><code>template<int C> struct Player\n{\n std::array<int,C>cards;\n friend std::istream& operator>>(std::istream& is, Player& p)\n {\n for(auto& i : p.cards){\n is >> i;\n }\n return is;\n }\n int amountOfCards = C;\n};\n</code></pre>\n</blockquote>\n\n<p><code>int</code> appears for two distinct purposes in this code: card count and card ID. Type aliases make this clearer:</p>\n\n<pre><code>using Card_ID = int;\nusing Card_count = std::size_t; // counting should be done with std::size_t\n</code></pre>\n\n<p>Then, I'm not sure this class is even necessary. Keep it simple:</p>\n\n<pre><code>template <Card_count N>\nusing Cards = std::array<Card_ID, N>;\n\ntemplate <Card_count N>\nvoid read_cards(std::istream& is, Cards& cards)\n{\n for (auto& card : cards)\n is >> card;\n}\n</code></pre>\n\n<blockquote>\n<pre><code>template<unsigned int N>\nclass Jollo\n{\nprivate:\n //amount of cards, not player number\n Player<2> prince;\n Player<3> princess;\n std::array<int, N> deck;\n const int roundsToWin {2};\npublic:\n Jollo<N>(){\n static_assert(N>4, \"Jollo: deck size must be higher than 4\");\n }\n\n bool ReadCards();\n int GetPrinceMinimumWinningCard();\nprivate:\n int GetNextAvailableCard(JolloPlayer ePlayer, int lastPlayedCard = 0); //gets next card and flips deck\n};\n</code></pre>\n</blockquote>\n\n<p>Now it's <code>unsigned int</code>. That's inconsistent. Use the aforementioned <code>Card_count</code> instead.</p>\n\n<p><code>roundsToWin</code> should be <code>static constexpr</code>.</p>\n\n\n\n<blockquote>\n<pre><code>template<unsigned int N>int Jollo<N>::GetNextAvailableCard(JolloPlayer ePlayer, int lastPlayedCard)\n{\n if(ePlayer == JolloPlayer::PRINCE)\n {\n for(int i{0}; i<prince.amountOfCards; i++) {\n\n if(deck[prince.cards[i] - 1] != JolloPlayer::PRINCE){\n deck[prince.cards[i] - 1] = JolloPlayer::PRINCE;\n return prince.cards[i];\n }\n }\n } else\n if(ePlayer == JolloPlayer::PRINCESS)\n {\n for(int i{0}; i<princess.amountOfCards; i++) {\n if(deck[princess.cards[i] - 1] != JolloPlayer::PRINCESS && deck[princess.cards[i] - 1] > lastPlayedCard) {\n deck[princess.cards[i] - 1] = JolloPlayer::PRINCESS;\n return princess.cards[i];\n }\n }\n //no card was higher, return lowest available card\n for(int i{0}; i<princess.amountOfCards; i++) {\n if(deck[princess.cards[i] - 1] != JolloPlayer::PRINCESS) {\n deck[princess.cards[i] - 1] = JolloPlayer::PRINCESS;\n return princess.cards[i];\n }\n }\n }\n\n //ePlayer == NONE\n for(unsigned int i{0}; i<N; i++)\n {\n if(deck[i] != JolloPlayer::PRINCE && deck[i] != JolloPlayer::PRINCESS && deck[i] > lastPlayedCard ) {\n return deck[i];\n }\n }\n return -1; //if the game is tied but there is no higher card available. e.g 50 49 51 48 52\n}\n</code></pre>\n</blockquote>\n\n<ul>\n<li><p>Use shorter lines. A horizontal scroll would not have shown up if you kept each line less than ~80 characters.</p></li>\n<li><p>Make functions smaller. In general, a vertical scroll should not be needed to view the code of a function.</p></li>\n<li><p><code>switch</code> is appropriate here.</p></li>\n<li><p>Traversing should be done with a range-based for loop, not with an index. In particular, neither <code>int</code> nor <code>unsigned int</code> is suitable for array indexing.</p></li>\n<li><p>Use <code>++i</code>, not <code>i++</code>.</p></li>\n</ul>\n\n<blockquote>\n<pre><code>int main()\n{\n Jollo<52> JolloInstance;\n while(true)\n {\n if(!JolloInstance.ReadCards()) {\n break;\n }\n std::cout << JolloInstance.GetPrinceMinimumWinningCard() << \"\\n\";\n }\n return 0;\n}\n</code></pre>\n</blockquote>\n\n<p>This can be simpler:</p>\n\n<pre><code>for (Jollo<52> game; game.ReadCards();)\n std::cout << game.GetPrinceMinimumWinningCard() << '\\n';\n</code></pre>\n\n<p>(Note that <code>'\\n'</code> is used instead of <code>\"\\n\"</code>.)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-01T15:22:42.737",
"Id": "452016",
"Score": "0",
"body": "Thank you very much. This is very very helpful. I'll apply all of it to my next programs. As for the competitive programming, when I joined the website, I thought that it was just a simple way of getting better at programming, but then after a while when some of my solutions were too slow because they were done(more or less) the c++ way, I read articles about it and realized what competitive programming is and how it is much more about speed than readability/maintainable code. There's some really weird stuff to it, so I guess I'll continue to solve problems just for the practice part really."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-01T09:52:30.050",
"Id": "231660",
"ParentId": "231525",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "231660",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-30T11:41:41.753",
"Id": "231525",
"Score": "3",
"Tags": [
"c++",
"programming-challenge"
],
"Title": "Jollo - 2 Player high card game"
}
|
231525
|
<p>I have a program that returns the following:</p>
<pre><code>PS4 Modern Warfare (2019)
Xbox One Modern Warfare (2019)
PS4 Grand Theft Auto V (5)
Xbox One Grand Theft Auto V (5)
</code></pre>
<p>I want to remove the parentheses from the end of he strings so they would look like the following:</p>
<pre><code>PS4 Modern Warfare
Xbox One Modern Warfare
PS4 Grand Theft Auto V
Xbox One Grand Theft Auto V
</code></pre>
<p>Currently, the code I have does it however I don't believe it is the best way to go about it as it seems to0 big for what it does.</p>
<pre><code>foreach(var i in methodResponse.Response.Data.Results.Where(x => x.CategoryFriendlyName == platform))
{
if (i.BoxName.EndsWith(")"))
{
var arr = i.BoxName.ToArray();
bool exit = false;
while(exit != true)
{
for (int j = arr.Length - 1; j != 0; j--)
{
if (!exit)
{
if (arr[j] != '(')
{
i.BoxName = i.BoxName.Remove(j, 1);
}
else if (arr[j] == '(')
{
i.BoxName = i.BoxName.Remove(j, 1);
exit = true;
}
}
}
}
i.BoxName = i.BoxName.TrimEnd();
}
</code></pre>
<p>I want to be able to understand an easier way to solve this issue. I know I could use substring however as you can see, the length of the item i want to remove is not always the same.</p>
<p>NOTE: If there are two sets of brackets in the name, I simply want to remove the last set, no other.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-30T12:11:08.173",
"Id": "451621",
"Score": "3",
"body": "Welcome to Code Review! Should the space between e.g `Warfare` and `(2019)` be preserved ?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-30T13:02:22.890",
"Id": "451635",
"Score": "0",
"body": "@Heslacher No, in the code above I trim the name after."
}
] |
[
{
"body": "<p>If I understood your issue correctly, regular expressions would be sufficient for your case</p>\n\n<pre><code>var bracketsRegex = new Regex(@\"\\s+\\(\\d+\\)\");\nvar result = bracketsRegex.Replace(stringToReplace, string.Empty);\n</code></pre>\n\n<p>In case you have multiple brackets like </p>\n\n<blockquote>\n <p>PS4 Modern Warfare (2019) (2018)</p>\n</blockquote>\n\n<p>You can wrap your regex into brackets end search for one ore matches of it with <code>+</code> like below</p>\n\n<pre><code>var bracketsRegex = new Regex(@\"(\\s+\\(\\d+\\))+\");\n</code></pre>\n\n<p>You can also change one or more matches to zero or matches with <code>*</code>. Consider</p>\n\n<blockquote>\n <p>PS4 Modern Warfare(2019) (2018)</p>\n</blockquote>\n\n<p>The following code matches it</p>\n\n<pre><code>var bracketsRegex = new Regex(@\"(\\s*\\(\\d+\\))+\");\n</code></pre>\n\n<p>The same technique allows you to match multiple sequential brackets. Consider</p>\n\n<blockquote>\n <p>PS4 Modern Warfare((2019)))</p>\n</blockquote>\n\n<p>The following code will do the trick</p>\n\n<pre><code>var bracketsRegex = new Regex(@\"\\s*(\\()+\\d+(\\))+\");\n</code></pre>\n\n<p>Also you can use online evaluator like <a href=\"https://regexr.com/\" rel=\"nofollow noreferrer\">this one</a> to explore it yourself.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-30T12:36:49.700",
"Id": "451629",
"Score": "0",
"body": "But what if the string has more than one set of brackets"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-30T12:49:04.077",
"Id": "451633",
"Score": "0",
"body": "I was unsure how exactly more brackets so I've edited my answer to cover more cases. Hope this helps."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-30T13:05:22.643",
"Id": "451636",
"Score": "0",
"body": "Will the above keep one of the brakcets but remove the other. Say I have the following `(Call of Duty) Modern Warfare (2019)` I want to simply remove the last set of brackets. Will the code provided in this answer do that? I should've made that more clear in the question."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-30T13:12:17.447",
"Id": "451640",
"Score": "0",
"body": "It will remove only last brackets because `d+` in the regular expression stands for one or more digits. However, in \"(2019) Modern Warfare (2019)\" both brackets will be removed."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-31T01:31:13.633",
"Id": "451726",
"Score": "0",
"body": "Also worth mentioning the \"negation class\", which means you don't have to assume digits: `\\([^)]*\\)$`: \"opening bracket, followed by anything that is *not* a closing bracket, followed by a closing bracket, followed by end-of-line\""
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-30T12:10:52.757",
"Id": "231530",
"ParentId": "231527",
"Score": "3"
}
},
{
"body": "<p>You could simply take advantage of the <code>string.LastIndexOf()</code> method together with the <code>string.Substring()</code> method like so </p>\n\n<pre><code>private static string Clean(string value)\n{\n return value.EndsWith(\")\") ? value.Substring(0, value.LastIndexOf('(')).TrimEnd() : value;\n}\n</code></pre>\n\n<p>and use it like so </p>\n\n<pre><code>foreach(var i in methodResponse.Response.Data.Results.Where(x => x.CategoryFriendlyName == platform))\n{\n i.BoxName = Clean(i.BoxName);\n} \n</code></pre>\n\n<hr>\n\n<p>Some side notes about the posted code: </p>\n\n<ul>\n<li>Don't use abbreviations when naming stuff e.g <code>var arr</code> </li>\n<li>You shouldn't check like <code>while(exit != true)</code> but rather like so <code>while(!exit)</code></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-30T12:30:17.827",
"Id": "231533",
"ParentId": "231527",
"Score": "5"
}
},
{
"body": "<p>I like @Heslacher 's solution, I would add to it a recursive method at the end of Clean so it could handle cases like <code>(((2015)))</code> it would also handle cases like <code>(2015) (5)</code>. So what I would do is</p>\n\n<pre><code>private static string Clean(string game)\n{\n string result = value;\n result = game.EndsWith(\")\") ? game.Substring(0, game.LastIndexOf('(')).TrimEnd() : game;\n if ( result.EndsWith(\")\"))\n {\n result = Clean(result);\n }\n return result;\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-30T13:14:54.227",
"Id": "231537",
"ParentId": "231527",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "231533",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-30T11:46:36.970",
"Id": "231527",
"Score": "6",
"Tags": [
"c#"
],
"Title": "Removing characters from end of string from character to character"
}
|
231527
|
<p>I am learning dynamic programming. I read articles for the rod cutting problem and I applied it in cpp, and I got a doubt, does the below code solves the problem through memoization (say, previously rod(3) was solved, then if same function was called with same parameters) has the answer, or will it use tabulation (<code>rodMax</code> array), or uses both?</p>
<p>Since I read two different articles explaining different methods(memoization and tabulation, and read as two different methods to solve a dynamic problem), kind of confused on which method the below code runs. </p>
<pre><code>#include <iostream>
using namespace std;
int max(int a, int b){
if(a > b)
return a;
return b;
}
int arr[5] = {2, 4, 1, 2, 7};
int rodMax[5] = {-1, -1, -1, -1, -1};
int rod(int n){
if(n <=0)
return 0;
if(rodMax[n - 1] != -1){
return rodMax[n];
}
int max_val = -1;
for(int i = 0; i < n; i++){
max_val = max(max_val, arr[n-i-1]+rod(n-1));
}
//cout<<"\nmax "<<max_val<<endl;
rodMax[n - 1] = max_val;
return max_val;
}
int main() {
cout<<"ans "<<rod(5)<<endl;
//cout<<"ans "<<rod(3)<<endl;
//for(int i = 0; i <5; i++)
// cout<<rodMax[i]<<" ";
}
<span class="math-container">```</span>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-30T11:52:52.337",
"Id": "451617",
"Score": "1",
"body": "Are you sure the code works? Did you test it with different use cases?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-30T11:54:59.430",
"Id": "451618",
"Score": "0",
"body": "Hi Konijn, yes it works. Didn't test with many use cases. Just for implementation purpose, I read article and implemented it directly in C++."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-30T12:14:59.603",
"Id": "451623",
"Score": "1",
"body": "Could you please [edit] to summarise the \"rod cutting problem\", for those of us who don't recognise it from your description? Thanks."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-30T12:36:11.383",
"Id": "451628",
"Score": "0",
"body": "hey Toby, actually i got confused with tabulation and optimizing the code by using array to store intermediate results."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-30T17:01:31.260",
"Id": "451688",
"Score": "0",
"body": "https://en.wikipedia.org/wiki/Cutting_stock_problem"
}
] |
[
{
"body": "<p>Don't <code>using namespace std</code> - especially if you're going to define a <code>max()</code> function in the global namespace (why not just use <code>std::max()</code> anyway? That's what it's for!).</p>\n\n<p>Where do the values in <code>arr</code> and <code>rodMax</code> come from? Do their lengths have to agree? If so, make that obvious in the code (e.g. use <code>std::array</code>, so that we can use <code>arr.size()</code> to count the members).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-30T12:40:20.267",
"Id": "451631",
"Score": "0",
"body": "Hi values for arr(price of the rod) and rodMax(maximum price obtained after cutting the rod in different size). It should have been applied by std array. But just for quick implementation i wrote this. Thanks"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-30T12:14:07.760",
"Id": "231531",
"ParentId": "231528",
"Score": "3"
}
},
{
"body": "<ul>\n<li><strong>Use a consistent code style.</strong> <a href=\"https://en.wikipedia.org/wiki/Programming_style\" rel=\"nofollow noreferrer\">Code style</a> is a very important thing. It doesn't matter which one you choose, but any code style has to be <em>consistent</em>.</li>\n<li><strong>Choose appropriate names for entities.</strong> For example, it would be better to change the name of the <code>rod</code> function to something like <code>cutRod</code>, <code>arr</code> to <code>prices</code>, and so on.</li>\n<li><p><strong>Pass the list of prices directly to the function.</strong> It is better to avoid using global variables; pass the price array directly into the <code>cutRod</code> function:</p>\n\n<pre><code>int cutRod(const int prices[], int length) {\n ...\n}\n</code></pre></li>\n<li><strong>Don't use <code>std::endl</code> just as a new line symbol.</strong> <code>std::endl</code> is <a href=\"https://stackoverflow.com/a/14395960/8086115\">not the same</a> as just <code>\\n</code>. You should avoid using it globally.</li>\n<li><strong>Use appropriate type for counters that hold length of arrays</strong>. You should not use <code>int</code> as type for variables that hold length of arrays (such as <code>i</code>) because it is not guaranteed that <code>int</code> can hold maximal size of an array. Use <code>std::size_t</code> instead.</li>\n<li><strong>Why -1?</strong> I think it would be better to fill <code>rodMax</code> with <code>INT_MIN</code> instead of just <code>-1</code>.</li>\n<li><p><strong>Matter of taste, but...</strong> You can replace</p>\n\n<pre><code>rodMax[n - 1] = max_val;\nreturn max_val;\n</code></pre>\n\n<p>by a single line</p>\n\n<pre><code>return (rodMax[n - 1] = max_val);\n</code></pre></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-30T15:32:19.150",
"Id": "451666",
"Score": "0",
"body": "Hi thanks for the review, most of them makes sense, and i'll use it. Especially for size_t, which i have used previously, and as i said it is just an quick implementation. I have a doubt @eanmos if we use `return (rodMax[n - 1] = max_val);`, doesn't it return `true` boolean value instead of the number which is `max_val`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-30T16:07:58.810",
"Id": "451679",
"Score": "0",
"body": "@susil95, no, the `=` operator returns the new value of `rodMax[n - 1]` i. e. `max_val`. You'd be correct if we use `==` instead."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-30T17:36:06.433",
"Id": "451694",
"Score": "0",
"body": "Thanks for the info man. I just tried that, initially i used to think that anything with \"=\", will assign a value and gives an Boolean value, which is like acknowledging the statement that it ran, like `if(cout<<\"hello\")`, It prints `hello` and goes inside if block."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-30T18:17:23.043",
"Id": "451697",
"Score": "0",
"body": "@susil95, you're welcome)"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-30T12:47:11.833",
"Id": "231534",
"ParentId": "231528",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "231534",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-30T11:48:40.093",
"Id": "231528",
"Score": "2",
"Tags": [
"c++",
"algorithm",
"dynamic-programming"
],
"Title": "Rod Cutting Problem Code"
}
|
231528
|
<p>Looking at back at the C++ projects I've developed, the Makefiles are a mess. To tell you the truth, I copied one a long time ago and basically have been cutting and pasting it haphazardly ever since. I've decided to change that so I've been reading more about how Make actually works and some best practices for using it going forth. As most of the programs I write are not that complicated I've come up with a generic Makefile I can cut and paste ^W^W^W deploy going forth. I'd like some feedback on it.</p>
<p>Any input (except "you should be using cmake or $(OTHER_TRENDY_NEW_TOOL) instead") is welcome but some specific questions that come to mind are:</p>
<ul>
<li><p>Have I forgotten to add something?</p></li>
<li><p>Conversely, have I added too much?</p></li>
<li><p>Is it worth making this a POSIX makefile. Currently I've only tried
it with GNU make on Linux but portability is good. What about BSD or
Windows make? Or should I just rely on gmake being available pretty
much everywhere?</p></li>
<li><p>Do I have all the recommended compiler/linker flags for C++? I would
like to be able to choose between g++ and clang atleast so options
should be portable between both though if there is something good
that only one supports I can special case it. (Can I?)</p></li>
<li><p>I'm assuming Visual Studio/Windows in general is a whole separate can
of worms so I've ignored it for now but if you know how this Makefile
could be adapted for Windows development I'd be happy to know.</p></li>
</ul>
<p>Thanks in advance.</p>
<pre><code> PROGRAM=someprogram
SRCDIR:=src
INCDIR:=include
DEPDIR:=deps
BUILDDIR:=build
DESTDIR?=
PREFIX?=/usr/local
BINDIR?=bin
SRC:=$(wildcard $(SRCDIR)/*.cc)
OBJECTS:=$(patsubst $(SRCDIR)/%.cc,$(BUILDDIR)/%.o,$(SRC))
DEPFILES:=$(patsubst $(SRCDIR)/%.cc,$(DEPDIR)/%.d,$(SRC))
CXX?=/usr/bin/g++
STRIP?=/usr/bin/strip
INSTALL?=/usr/bin/install
VALGRIND?=/usr/bin/valgrind
CPPFLAGS:=-I$(INCDIR)
CXXFLAGS:=-std=c++17 -Wall -Wextra -Wpedantic -flto ${CXXFLAGS}
LDFLAGS:=-ffunction-sections -fdata-sections -Wl,-gc-sections $(LDFLAGS)
DEPFLAGS=-MT $@ -MMD -MP -MF $(DEPDIR)/$*.Td
COMPILE.cc=$(CXX) $(DEPFLAGS) $(CXXFLAGS) $(CPPFLAGS) $(TARGET_ARCH) -c
LINK.cc=$(CXX) $(CXXFLAGS) $(CPPFLAGS) $(LDFLAGS) $(TARGET_ARCH)
POSTCOMPILE=mv -f $(DEPDIR)/$*.Td $(DEPDIR)/$*.d && touch $@
all: debug
$(BUILDDIR)/%.o: $(SRCDIR)/%.cc $(DEPDIR)/%.d | $(DEPDIR) $(BUILDDIR)
$(COMPILE.cc) $(OUTPUT_OPTION) $<
$(POSTCOMPILE)
$(BUILDDIR)/%.o: $(SRCDIR)/%.s | $(BUILDDIR)
$(COMPILE.s) $(OUTPUT_OPTION) $<
$(BUILDDIR): ; @mkdir -p $@
$(DEPDIR): ; @mkdir -p $@
$(DEPFILES):
$(PROGRAM): $(OBJECTS)
$(LINK.cc) $(OUTPUT_OPTION) $^
debug: CPPFLAGS += -DDEBUG
debug: CXXFLAGS += -g3
debug: $(PROGRAM)
release: CXXFLAGS += -O2
release: distclean $(PROGRAM)
$(STRIP) --strip-all -R .comment -R .note $(PROGRAM)
memcheck: debug
$(VALGRIND) --suppressions=valgrind.suppressions --quiet --verbose --leak-check=full --show-leak-kinds=all --track-origins=yes --log-file=valgrind.log ./$(PROGRAM)
install: release
$(INSTALL) -m755 -D -d $(DESTDIR)$(PREFIX)/$(BINDIR)
$(INSTALL) -m755 $< $(DESTDIR)$(PREFIX)/$(BINDIR/$(PROGRAM)
clean:
-rm -rf $(BUILDDIR)
-rm -rf $(DEPDIR)
-rm valgrind.log
distclean: clean
-rm $(PROGRAM)
.PHONY: all debug release memcheck install clean distclean
.DELETE_ON_ERROR:
-include $(wildcard $(DEPFILES))
<span class="math-container">```</span>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-30T14:51:08.567",
"Id": "451661",
"Score": "0",
"body": "Here's a similar question with a [possibly useful answer](https://codereview.stackexchange.com/questions/156479/makefile-for-building-asm-c-project/156505#156505)."
}
] |
[
{
"body": "<p>It's reasonable to require GNU Make - it's available on all platforms that have their own Make (as far as I know), and trying to cope with the vagaries of all vendors' Make implementations is an exercise in futility. So I think you've taken the right approach here.</p>\n<hr />\n<p>You're working against Make by putting build products into subdirectories. It's easier to build them into the working directory, and the sources can be found using <code>VPATH</code>, then there's no need to copy all the built-in rules (not so bad when all your source files are C++, but when you need to add a few assembler and C files, then the maintenance starts to grow).</p>\n<p>Creating separate debug and release binaries in the same build tree is problematic - it can mean a total rebuild when switching from one kind to another. It's more usual to have separate build directories for the two, so you can incrementally build either at any time (of course, they can share the same source files, using <code>VPATH</code>, and can share most of the Makefile the same way).</p>\n<p>That would look something like this:</p>\n<h3>debug/Makefile</h3>\n<pre><code>CXXFLAGS += -g3 -DDEBUG\nVPATH = ../src:../include\ninclude ../Makefile\n</code></pre>\n<h3>release/Makefile</h3>\n<pre><code>CXXFLAGS += -O2\nVPATH = ../src:../include\ninclude ../Makefile\n</code></pre>\n<p>Then, building the release version doesn't affect the objects used to build the debug version, and vice versa.</p>\n<hr />\n<p>This target is problematic for a parallel build:</p>\n<blockquote>\n<pre><code>release: distclean $(PROGRAM)\n</code></pre>\n</blockquote>\n<p>We'll lose some of the files as the <code>distclean</code> isn't sequenced with respect to <code>$(PROGRAM)</code>.</p>\n<p>I don't like the explicit <code>strip</code> invocation in the <code>release</code> target: since <code>install</code> depends on release, this makes it impossible to build debug-symbol Debian packages the usual way. Just let the packager do the stripping.</p>\n<hr />\n<p>I see no value in redefining <code>COMPILE.cc</code> and <code>LINK.cc</code>: <code>CXXFLAGS</code> and <code>LDFLAGS</code> are provided specifically for you to add your own flags to these lines - just use them.</p>\n<p>Speaking of which, we normally use <code>+=</code> to add to the flags:</p>\n<pre><code>CPPFLAGS += -I$(INCDIR)\nCXXFLAGS += -std=c++17 -Wall -Wextra -Wpedantic\nCXXFLAGS += -flto\n\nLDFLAGS += -ffunction-sections -fdata-sections\nLDFLAGS += -Wl,-gc-sections\n\nDEPFLAGS = -MT $@ -MMD -MP -MF $(DEPDIR)/$*.Td\nCPPFLAGS += $(DEPFLAGS)\n</code></pre>\n<hr />\n<p><code>$(RM)</code> is provided as a more portable alternative to <code>rm -f</code>; we could use that in a few places.</p>\n<p><code>.DELETE_ON_ERROR</code> is often missed - kudos for remembering that.</p>\n<p><code>DESTDIR?=</code> is a no-op - undefined Make variables already expand to nothing. Just omit this line. It's good that you're correctly allowing this to be set by packaging systems etc.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-31T03:14:51.247",
"Id": "451728",
"Score": "0",
"body": "Haha I am actually a Debian developer so I should have been aware of the strip thing. (I did atleast remember the value of DESTDIR.) But most of the projects will never make it off my laptop let alone into a major Linux distribution. For my purposes it is handy to have the strip done automatically. Perhaps a way to satisfy both uses would be to move the strip options into $(STRIP) so it can be defined as a no-op if relying on e.g. debhelper to do the stripping. What do you think?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-31T03:21:32.570",
"Id": "451729",
"Score": "0",
"body": "I'm in two minds about your point on build objects in subdirectories. I assume the toplevel is for things like the Makefile, READMEs, Licenses etc. not ephemera. On the other hand as you say it would simplify things. As for build and release in the same build tree, don't I have to do a full rebuild anyway if I switch because I'm using different compile flags in each?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-31T03:23:46.487",
"Id": "451730",
"Score": "0",
"body": "As for distclean before release. Can I do ```release: $(PROGRAM) | distclean``` to avoid issues with parallel builds?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-31T09:02:09.273",
"Id": "451749",
"Score": "0",
"body": "I've edited to show how we can build separate debug and release builds - keep each build's products separate, so we can't accidentally link a mix of debug and release objects. Then we can incrementally build either version without having to `make clean` beforehand."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-30T14:33:14.453",
"Id": "231545",
"ParentId": "231535",
"Score": "4"
}
},
{
"body": "<p>I'm writing this as an answer because of space restrictions but this is more of a reply to @TobySpeight.</p>\n\n<p>Thanks to your help I've improved my Makefile to create debug and release builds separately but I had to make additional changes beyonf what you wrote. I am recording them here for future posterity.</p>\n\n<p>I had to change the install target so instead of depending on the release target which no longer exists, it cds to the release directory and builds there first. In my top level Makefile:</p>\n\n<pre><code>install:\n @cd release && $(MAKE) install-$(PROGRAM)\n</code></pre>\n\n<p>...and in the release Makefile:</p>\n\n<pre><code>install-$(PROGRAM): $(PROGRAM)\n $(INSTALL) -m755 -D -d $(DESTDIR)$(PREFIX)/$(BINDIR)\n $(INSTALL) -m755 $< $(DESTDIR)$(PREFIX)/$(BINDIR/$(PROGRAM)\n</code></pre>\n\n<p>With the new setup, what happens if a user runs <code>make</code> in the top-level directory? They are going to get errors. Or what if they run <code>make distclean</code> in a subdirectory? First I defined a function in the top-level Makefile to tell where we are. This was unexpectedly complicated but this works:</p>\n\n<pre><code>get_builddir = '$(findstring '$(notdir $(CURDIR))', 'debug' 'release')'\n</code></pre>\n\n<p>I defined two new targets:</p>\n\n<pre><code>checkinbuilddir:\nifeq ($(call get_builddir), '')\n $(error 'Change to the debug or release directories and run make from there.')\nendif\n\ncheckintopdir:\nifneq ($(call get_builddir), '')\n $(error 'Make this target from the top-level directory.')\nendif\n</code></pre>\n\n<p>Then I had my <code>$(PROGRAM)</code> and <code>$(DISTCLEAN)</code> targets depend on them:</p>\n\n<pre><code>$(PROGRAM): $(OBJECTS) | checkinbuilddir \n $(LINK.cc) $(OUTPUT_OPTION) $^\n $(STRIP)\n\ndistclean: | checkintopdir\n cd debug && $(MAKE) clean\n cd release && $(MAKE) clean\n</code></pre>\n\n<p>So this will be my stock Makefile going forward. I still don't deal with e.g. building libraries or multi-binary programs but I'm satisfied with it for now. Thanks once again.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-31T22:59:43.240",
"Id": "231641",
"ParentId": "231535",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "231545",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-30T12:47:51.087",
"Id": "231535",
"Score": "3",
"Tags": [
"c++",
"makefile",
"make"
],
"Title": "Generic makefile for C++ projects"
}
|
231535
|
<p>This code is supposed to :</p>
<ol>
<li><p>Read messages from a message stream</p></li>
<li><p>Filter the messages to get the ones which certain terms</p></li>
<li><p>Check if the message contains media or media URL</p></li>
<li><p>checks if the media URL is an instagram url</p></li>
<li><p>Extract meta data from the image </p></li>
<li><p>Extract the image and send it out</p></li>
<li><p>there's a condition that if the message contains the user's name, then it's sent out as a reply to the user who sent the original message</p>
<pre><code>public class MessageStreamManager {
private static final Logger logger =
LogManager.getLogger(MessageStreamManager.class);
InstagramDownloader instagramDownloader = new InstagramDownloader();
private final String AcceptedImageTypesregex = ".*\\.
(?:jpg|JPG|jpeg|JPEG|gif|GIF|png|PNG|bmp|BMP|tiff|TIFF)";
};
String MY_USER_NAME = "myUserName"
private ImageUrl imageUrl = new ImageUrl();
private MessageAnalysis messageAnalysis = new MessageAnalysis();
RelaventMessageInfo relaventMessageInfo = new RelaventMessageInfo();
public void startListeningAndProcessing() {
private Message message = getMessage();
String[] keywords = {"#travelling", "#traveling", "#traveltribe", "#traveler",
"#travelpics", "#traveller", "#travelhacks", "#vacation", "#holiday",
"#traveling", "#travelers"};
String[] botFilters = {"nude","porn"}; //words to be filtered out
FilterQuery filtered = new FilterQuery();
filtered.track(keywords);
MessageListener listener = new MessageListener() {
public void onMessage(Message message) {
try {
for (int i = 0; i < botFilters.length; i++) {
if (message.getText().contains(botFilters[i])) {
return;
}
}
if (!message.isSharedBefore()) { //if the message is wrapped as a shared message
if (message.isASharedMessage()) { // if the message was shared by "me" before
message = message.getPosteddmessage();
}
if (verifyMessageContainsURLorAttachedImage(message)) {
if (verifyURLIsAnImage(message)) {
reactWithMessage(message);
}
} else {
return;
}
}
} catch (IOException e) {
logger.info(te.getStackTrace().toString());
logger.info("Failed to get messages: " + e.getMessage());
} catch (MessageException e) {
e.printStackTrace();
}
}
private boolean verifyURLIsAnImage(Message message) {
logger.info("Verify media attached - attachements array length: " + message.getMediaEntities().length);
logger.info("Verify url in message - urls array length : " + message.getURLEntities().length);
boolean isImage = false;
if (message.getMediaEntities().length > 0 && (Pattern.matches(AcceptedImageTypesregex, message.getMediaEntities()[0].getMediaURLHttps()))) {
imageUrl.setImageUrl(message.getMediaEntities()[0].getMediaURLHttps());
logger.info("Image type attached to message is supported");
logger.info("MediaURL for attached image : " + message.getMediaEntities()[0].getMediaURLHttps());
return true;
} else if (message.getURLEntities().length > 0 && (Pattern.matches(AcceptedImageTypesregex, message.getURLEntities()[0].getExpandedURL()))) {
imageUrl.setImageUrl(message.getURLEntities()[0].getExpandedURL());
logger.info("Image type in the URL is supported");
isImage = true;
} else if (message.getURLEntities().length > 0 && (isInstagramImageURL(message.getURLEntities()[0].getExpandedURL()))) {
imageUrl.setImageUrl(message.getURLEntities()[0].getExpandedURL());
logger.info("Image type instagram in the URL is supported");
isImage = true;
}
logger.info("returning is image = " + isImage);
return isImage;
}
private boolean verifyMessageContainsURLorAttachedImage(Message message) {
boolean isImage = false;
if (message.getURLEntities().length > 0 || message.getMediaEntities() != null) {
logger.info("Message contains image");
isImage = true;
}
return isImage;
}
public void onException(Exception ex) {
ex.printStackTrace();
}
};
MessageStream messageStream = new MessageStreamFactory().getInstance();
messageStream.addListener(listener);
messageStream.filter(filtered);
}
private boolean isInstagramImageURL(String linkUrl) {
boolean isInstagram = false;
if (linkUrl.contains("instagram.com/p") && (!instagramDownloader.getDownloadUrl(linkUrl).isEmpty())) {
isInstagram = true;
}
return isInstagram;
}
private void reactWithMessage(Message message) throws IOException, MessageException {
String responseMessage = "";
String userMention = "";
if (null != relevantMessageInfo) {
logger.info("||| N A M E || # # # # # # # % % % % % % % % % " + relevantMessageInfo.getName());
String sourceMessage = message.getUser().getScreenName() + "/message/" + message.getId();
if (message.getText().contains(MY_USER_NAME)) {
userMention = ".@" + wrapperMessage.getUser().getScreenName() + " ";
sourceMessage = "";
}
responseMessage = userMention + " MY MESSAGE " + "\n" + sourceMessage;
postMessageImageFromUrl(responseMessage, imageUrl.getImageUrl(), message);
}
public void updatePost(String message, Message orgMessage) throws MessageException {
message.updatePost(message);
}
public void updatePost(MessageUpdate curMessage, Message orgMessage) throws messageException {
if (!isDuplicate(curMessage.getMessage()) && !isOld(orgMessage)) {
logger.info("======> N O T duplicate");
logger.info(curMessage.getMessage().substring(curMessage.getMessage().indexOf("#"), curMessage.getMessage().indexOf(",")));
message.updatePost(curMessage);
logger.info(curMessage.getMessage());
} else {
logger.info("======> T R U E duplicate");
logger.info(curMessage.getMessage().substring(curMessage.getMessage().indexOf("#"), curMessage.getMessage().indexOf(",")));
logger.info(curMessage.getMessage());
}
}
public boolean isDuplicate(String curMessage) throws MessageException {
boolean duplicate = false;
for (Message sentMessage : message.getUserTimeline(new Paging(1, 200))) {
if (sentMessage.getText().contains(curMessage.substring(curMessage.indexOf("#"), curMessage.indexOf(",")))) {
duplicate = true;
}
}
return duplicate;
}
public boolean isOld(Message origMessage) {
Instant now = Instant.now();
logger.info("Now = " + now);
Instant date;
date = ZonedDateTime.parse(
origMessage.getCreatedAt().toString(),
DateTimeFormatter.ofPattern("EEE MMM dd HH:mm:ss z uuuu", Locale.US)
).toInstant();
boolean old = false;
if (date.plus(1, ChronoUnit.HOURS).isBefore(now)) {
old = true;
}
return old;
}
public void updateReplyMessage(MessageUpdate curMessage, Message orgMessage) throws MessageException {
if (!isDuplicate(curMessage.getMessage()) && !isOld(orgMessage)) {
logger.info("======> N O T duplicate");
logger.info(curMessage.getMessage().substring(curMessage.getMessage().indexOf("#"), curMessage.getMessage().indexOf(",")));
message.updatePost((curMessage.inReplyToMessageId(orgMessage.getId())));
logger.info(curMessage.getMessage());
} else {
logger.info("======> T R U E duplicate");
logger.info(curMessage.getMessage().substring(curMessage.getMessage().indexOf("#"), curMessage.getMessage().indexOf(",")));
logger.info(curMessage.getMessage());
}
}
public void postMessageImageFromUrl(String messageString, String messageImageUrl, Message orgMessage) throws MessageException {
// Obtain a number between [0 - 9].
int n = rand.nextInt(10);
// Add 1 to the result to get a number from the required range
// (i.e., [1 - 10]).
n += 1;
MessageUpdate messageUpdate = new MessageUpdate(messageString);
URLConnection urlConnection = null;
URL url;
try {
url = new URL(messageImageUrl);
urlConnection = url.openConnection();
} catch (IOException e) {
logger.error(e.getMessage());
}
String imageFileName = messageImageUrl;
if (orgMessage.getText().contains(MY_USER_NAME)) {
try (InputStream in = new BufferedInputStream(urlConnection.getInputStream())) {
messageUpdate.setMedia(imageFileName, in);
updateReplyMessage(messageUpdate, orgmessage);
} catch (IOException e) {
logger.error(e.getMessage());
}
} else {
URLConnection finalUrlConnection = urlConnection;
logger.info("will send message in " + n + " seconds");
new java.util.Timer().schedule(
new java.util.TimerTask() {
@Override
public void run() {
try (InputStream in = new BufferedInputStream(finalUrlConnection.getInputStream())) {
messageUpdate.setMedia(imageFileName, in);
updateMessage(messageUpdate, orgMessage);
} catch (IOException | MessageException e) {
logger.error(e.getMessage());
}
}
},
n * 1000
);
}
if (!orgMessage.isFavorited()) {
message.createFavorite(orgMessage.getId());
logger.info("\n%%%%%%%%%%%%%%%%%\n Favorited before? " + orgmessage.isFavorited() + "\n<span class="math-container">$$$$</span><span class="math-container">$$$$</span><span class="math-container">$$$$</span><span class="math-container">$$$$</span>$$");
}
logger.info(messageString + " --> attached this image " + messageImageUrl);
}
}
</code></pre></li>
</ol>
<p>Obviously this code is very hard to change (add new message types)
I would love to receive feed back and some best practices to follow.</p>
<p>What parts of the code jump out as good candidates for the modern Java APIs (Stream, Lambdas, Optional, RxJava etc )?</p>
<p>Also what changes would you make to the code knowing it will be a Spring Boot application?</p>
<p>I also understand that adding tests can break up this code and organize it better, it would be great if I get a pointer on that and how to start with tests that can help organizing this code.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-30T13:38:12.480",
"Id": "451643",
"Score": "0",
"body": "You've got a two quotation marks on line ten."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-01T01:27:46.687",
"Id": "451920",
"Score": "0",
"body": "fixed @CasparValentine , any insights?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-01T09:13:57.143",
"Id": "451960",
"Score": "1",
"body": "i don't know man i just wanna die already"
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-30T13:25:45.150",
"Id": "231539",
"Score": "1",
"Tags": [
"java",
"spring"
],
"Title": "Filter messages from a message stream, determine type of message and and its content and react accordingly"
}
|
231539
|
<p>This code basically just does a Caesar cipher on the contents of the variable "s" with a shift of 1. </p>
<p>Sorry if the comments on the code don't explain it well. I'm quite new to Python and I'm not very good at explaining.</p>
<p>Can this be code be improved?</p>
<pre><code># Imports the lowercase alphabet as a whole string.
from string import ascii_lowercase
# Returns a list of each char in the given string.
def charSplit(str):
return [char for char in str]
letters = charSplit(ascii_lowercase)
result = []
finalResult = ""
letterIndex = 0
strIndex = 0
s = "abcde test bla bla bla"
found = False
if __name__ == "__main__":
while found == False:
# Checks if the string has been converted to the cipher.
if len(result) == len(s):
found = True
# Adds a space to the result variable if the string index is a space.
elif s[strIndex] == " ":
result.append(" ")
strIndex += 1
# Checks if the string index is equal to the letter index.
elif charSplit(s)[strIndex].lower() == letters[letterIndex]:
result.append(letters[letterIndex - 1])
strIndex += 1
#
else:
if len(letters) - 1 == letterIndex:
letterIndex = 0
else:
letterIndex += 1
# Iterates through result and adds each string to the empty string, "finalResult".
for l in result:
finalResult += l
print(finalResult)
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-30T13:50:59.703",
"Id": "451646",
"Score": "1",
"body": "How much experience do you have in Python? There's a lot in there that could be replaced by built-in functions. Did you intend to write this in a roundabout way? What are your main concerns about this code? If you're simply looking for alternative implementations, [have a look](https://codereview.stackexchange.com/search?q=%5Bpython-3.x%5D+caesar+is%3Aq)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-30T13:59:48.090",
"Id": "451650",
"Score": "1",
"body": "I've had about 4 months experience with python. I'm looking to replace any bad or unnecessary code i have written."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-31T12:36:54.337",
"Id": "451776",
"Score": "0",
"body": "Why no exception handling?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-01T13:35:48.517",
"Id": "451995",
"Score": "0",
"body": "@TobySpeight Sure. I guess CodeReview has [different rules for identifying duplicates](https://codereview.meta.stackexchange.com/questions/8/how-do-we-define-duplicate-questions) than [other sites on stackexchange](https://meta.stackexchange.com/questions/166707/changes-to-close-as-duplicate-part-deux). Nevertheless, OP may still find reviewing other implementations of [Caesar Cipher in Python](https://codereview.stackexchange.com/questions/32694/caesar-cipher-in-python) useful."
}
] |
[
{
"body": "<p>You say you're new to Python. Well, that's ok. And a <a href=\"https://en.wikipedia.org/wiki/Caesar_cipher\" rel=\"nofollow noreferrer\">Caeser Cipher</a> is a good place to start since it's complex enough for an absolute beginner while easy enough to understand what goes on, why and when.</p>\n<p>One thing to keep in mind is that Python comes <a href=\"http://protocolostomy.com/2010/01/22/what-batteries-included-means/\" rel=\"nofollow noreferrer\">batteries included</a>. This means a lot of what you want to accomplish is already written, one way or another. You just have to know where to find it.</p>\n<p>For example, take the first function of your program:</p>\n<pre><code>def charSplit(str):\n return [char for char in str]\n</code></pre>\n<p>Simple enough. <code>charSplit('foo')</code> returns <code>['f', 'o', 'o']</code>.</p>\n<p>Did you know we can do the same with <a href=\"https://www.tutorialspoint.com/python3/list_list.htm\" rel=\"nofollow noreferrer\"><code>list</code></a>? <code>list('foo')</code> returns <code>['f', 'o', 'o']</code> as well.</p>\n<p>So, we're down 1 function. Let's create a new one. You're wrapping your code quite nicely here:</p>\n<pre><code>if __name__ == "__main__":\n</code></pre>\n<p>This makes sure the code is only running when the file itself is called, not when it's imported by another file. How about taking it a step further to clean things up?</p>\n<pre><code>def main():\n # all code that was previously behind the mentioned if-statement goes here\n\nif __name__ == "__main__":\n main()\n</code></pre>\n<p>Everything above the <code>if</code> are <a href=\"https://www.python-course.eu/python3_global_vs_local_variables.php\" rel=\"nofollow noreferrer\">global variables</a>. I'm not a fan of global variables, so we'll get rid of them later. But let's assume for a moment you want to keep them around.</p>\n<p>Since some of those are only read and never overwritten (pseudo-<a href=\"https://www.python.org/dev/peps/pep-0008/#constants\" rel=\"nofollow noreferrer\">constants</a>), it's usually preferred to CAPITALIZE them. Makes them easier to recognize.</p>\n<p>How about another function? It may be a bit overkill here since the <code>main</code> function I wrote earlier already covers everything and the code only has one purpose, but code usually grows. Function-creep comes in and all of a sudden you have 300 lines of code in the same function. Better to split things up already, keeps things easier. Besides, it gives me an excuse to tell something about arguments.</p>\n<pre><code>def caesar_cipher(inp, shift):\n """\n Take inp(ut) as string, shift as integer and return ciphered string.\n """\n # code here\n</code></pre>\n<p><code>s</code> wasn't a particularly descriptive variable name, so that's <code>inp</code> now (<a href=\"https://docs.python.org/3.5/library/functions.html#input\" rel=\"nofollow noreferrer\"><code>input</code></a> is already taken.) Can you see this growing? While we're at variable names, having both a <code>result</code> and <code>finalResult</code> is somewhat confusing. The entire construct is somewhat confusing.</p>\n<pre><code># Iterates through result and adds each string to the empty string, "finalResult".\nfor l in result:\n finalResult += l\n</code></pre>\n<p>You're really just copying <code>result</code> here, so <code>finalResult</code> can go. Well, almost. We still need to go to a string, so we're interested in <code>''.join(result)</code>. That takes an empty string, and joins all parts of the <code>result</code> list into it.</p>\n<p>I don't like the <code>while</code> loop. There's 3 reasons for this and I'm going to fix 2 now and 1 later. Why? To keep things simple and easy to follow.</p>\n<p>It starts out like this:</p>\n<pre><code>while found == False:\n</code></pre>\n<p>Did you know you can rewrite that to make it even more obvious what's going on?</p>\n<pre><code>while not found:\n</code></pre>\n<p>Which, if you're familiar with other languages, reads like <code>while(!found)</code>. Python has the <code>not</code> operator, which returns True if the expression behind it is False.</p>\n<p>The other end of the loop can be improved as well. You're printing the result of the cipher, while we may want to do something completely different with it. Perhaps the result should be used in a different function? That's not the cipher's problem. Let <code>main</code> figure that out. All in all, the code so far would look like this with the above taken into account:</p>\n<pre><code># Imports the lowercase alphabet as a whole string.\nfrom string import ascii_lowercase\n\n\nLETTERS = list(ascii_lowercase)\n\ndef caesar_cipher(inp, shift):\n """\n Take inp(ut) as string, shift as integer and return ciphered string.\n """\n found = False\n strIndex = 0\n letterIndex = 0\n result = []\n\n while not found:\n # Checks if the string has been converted to the cipher.\n if len(result) == len(inp):\n found = True\n # Adds a space to the result variable if the string index is a space.\n elif inp[strIndex] == " ":\n result.append(" ")\n strIndex += 1\n # Checks if the string index is equal to the letter index.\n elif list(inp)[strIndex].lower() == LETTERS[letterIndex]:\n result.append(LETTERS[letterIndex - 1])\n strIndex += 1\n # \n else:\n if len(LETTERS) - 1 == letterIndex:\n letterIndex = 0\n else:\n letterIndex += 1\n\n return(''.join(result))\n\ndef main():\n print(caesar_cipher("abcde test bla bla bla", -1))\n\nif __name__ == "__main__":\n main()\n</code></pre>\n<p>We haven't actually <em>used</em> <code>shift</code> yet, but we'll need it to fix another problem in your code: it's a very limited Caesar cipher. After all, a proper Caesar cipher takes a shift parameter. How far should the text be shifted? 1 character? 2? 13? We can make this go round and round and round. That's one of the good things about a Caesar cipher.</p>\n<p>I'm still not a fan of the <code>while</code> loop here, so let's fix 2 things at a time. If our algorithm is correct, we can simply iterate over the input and <em>know</em> the output is correct at the end without keeping track of a <code>found</code> variable. And while we're at it, let's try to remove the other variables that are just to keep track as well.</p>\n<p>You made a good start with importing <code>ascii_lowercase</code>, so let's build on that. Did you know <code>string.ascii_lowercase</code> (just like <code>string.lowercase</code>) has an <code>index</code> function? It provides us with the position of a character in a string.</p>\n<p>What if we use that index to retrieve a different value of the alphabet instead? After all, an index is just a number. We could modify that number to get a different character altogether.</p>\n<blockquote>\n<p>For every character in the input, if the character is a letter, get a different letter from the alphabet instead.</p>\n</blockquote>\n<p>Oh, we can use a <a href=\"https://wiki.python.org/moin/ForLoop\" rel=\"nofollow noreferrer\"><code>for</code></a> loop instead of a <a href=\"https://wiki.python.org/moin/WhileLoop\" rel=\"nofollow noreferrer\"><code>while</code></a> loop!</p>\n<pre><code># Imports the lowercase alphabet as a whole string.\nfrom string import ascii_lowercase\n\n\nLETTERS = list(ascii_lowercase)\n\ndef caesar_cipher(inp, shift):\n """\n Take inp(ut) as string, shift as integer and return ciphered string.\n """\n result = []\n\n for character in inp:\n if character in LETTERS:\n # If it's a letter, we cipher it\n result.append(LETTERS[ascii_lowercase.index(character) + shift])\n else:\n # If it's NOT a letter, we won't cipher it\n result.append(character)\n\n return(''.join(result))\n\ndef main():\n print(caesar_cipher("abcde test bla bla bla", -1))\n\nif __name__ == "__main__":\n main()\n</code></pre>\n<p>See how much easier that is to read? Now we just need a minor modification to account for the limited length of the alphabet. After all, what happens if someone wants a shift of 40? Or 51? Please welcome the <a href=\"https://en.wikipedia.org/wiki/Modulo_operation\" rel=\"nofollow noreferrer\"><code>%</code> modulo</a> operator. Divide by the length of the alphabet (26) and return the remainder.</p>\n<pre><code># Imports the lowercase alphabet as a whole string.\nfrom string import ascii_lowercase\n\n\nLETTERS = list(ascii_lowercase)\n\ndef caesar_cipher(inp, shift):\n """\n Take inp(ut) as string, shift as integer and return ciphered string.\n """\n result = []\n\n for character in inp:\n if character in LETTERS:\n # If it's a letter, we cipher it\n result.append(LETTERS[(\n ascii_lowercase.index(character) + shift\n ) % len(LETTERS)])\n else:\n # If it's NOT a letter, we won't cipher it\n result.append(character)\n\n return(''.join(result))\n\ndef main():\n print(caesar_cipher("abcde test bla bla bla", 51))\n\nif __name__ == "__main__":\n main()\n</code></pre>\n<p>Now, compare this to the original version. Can you see how we got here? You started out right, and now we got something even better. And this can probably be improved even further, I'm fairly sure we don't need <code>result</code> to be a list in the first place. Have fun figuring that out :-)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-30T14:04:32.357",
"Id": "451651",
"Score": "1",
"body": "Thanks! I forgot about the list function lol."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-30T15:51:47.710",
"Id": "451673",
"Score": "1",
"body": "It's a bit to long to qualify for a good practice one-liner... but the generator expression version: `return ''.join(ascii_lowercase[(ascii_lowercase.index(char) + shift) % len(ascii_lowercase)] if char in ascii_lowercase else char for char in input)`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-31T00:17:53.907",
"Id": "451724",
"Score": "1",
"body": "One thing I'd do is break the `len(LETTERS)` out to the outer level, since it's as constant as `LETTERS` itself is. Saves quite a few calls inside the loops. Also (and I haven't tried it myself) `LETTERS` itself could be a string and indexing/`len()` should work the same as they do on lists..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-31T07:18:05.380",
"Id": "451739",
"Score": "6",
"body": "`LETTERS = list(ascii_lowercase)` is unneccesary. You can index on `ascii_lowercase` just fine, and check for inclusion using `in`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-31T08:39:51.603",
"Id": "451744",
"Score": "3",
"body": "`ascii_lowercase.index(character)` is an inefficient and convoluted way of converting a letter into a numeric index. And, as JAD said, `LETTERS` is redundant. Taking this together also makes it easier to extend the cypher beyond letters."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-31T12:59:08.037",
"Id": "451781",
"Score": "1",
"body": "Lovely and educational input. Nice comparison and a paedagogic explanation of your little evolution there!"
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-30T14:02:08.393",
"Id": "231543",
"ParentId": "231540",
"Score": "30"
}
},
{
"body": "<p>I hate to provide an \"answer only\" code review, but I'd like to expand upon Mast's \"Python comes batteries included\" point:</p>\n\n<p>Python comes with a <a href=\"https://docs.python.org/3/library/stdtypes.html#str.translate\" rel=\"noreferrer\"><code>str.translate</code></a>, function which will do a letter-for-letter substitution in a string:</p>\n\n<pre><code>>>> help(str.translate)\nHelp on method_descriptor:\n\ntranslate(self, table, /)\n Replace each character in the string using the given translation table.\n\n table\n Translation table, which must be a mapping of Unicode ordinals to\n Unicode ordinals, strings, or None.\n\n The table must implement lookup/indexing via __getitem__, for instance a\n dictionary or list. If this operation raises LookupError, the character is\n left untouched. Characters mapped to None are deleted.\n</code></pre>\n\n<p>Continuing on the batteries included, it also has a <a href=\"https://docs.python.org/3/library/stdtypes.html#str.maketrans\" rel=\"noreferrer\"><code>str.maketrans</code></a> function for creation of the translation table:</p>\n\n<pre><code>>>> help(str.maketrans)\nHelp on built-in function maketrans:\n\nmaketrans(x, y=None, z=None, /)\n Return a translation table usable for str.translate().\n\n If there is only one argument, it must be a dictionary mapping Unicode\n ordinals (integers) or characters to Unicode ordinals, strings or None.\n Character keys will be then converted to ordinals.\n If there are two arguments, they must be strings of equal length, and\n in the resulting dictionary, each character in x will be mapped to the\n character at the same position in y. If there is a third argument, it\n must be a string, whose characters will be mapped to None in the result.\n</code></pre>\n\n<p>So, to continue improvements upon Mast's solution:</p>\n\n<pre><code>import string\n\ndef caesar_cipher(msg, shift, alphabet=string.ascii_lowercase):\n shift %= len(alphabet)\n xlate = str.maketrans(alphabet, alphabet[shift:] + alphabet[:shift])\n return msg.translate(xlate)\n\ndef main():\n print(caesar_cipher(\"abcde test bla bla bla\", 51))\n\nif __name__ == \"__main__\":\n main()\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-30T16:40:57.753",
"Id": "451684",
"Score": "3",
"body": "If you want to take it further still, you could talk about docstrings for functions, and then about `doctest`... ;-)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-30T16:11:42.260",
"Id": "231556",
"ParentId": "231540",
"Score": "18"
}
},
{
"body": "<p>An super efficient way to do this would be to use list comprehension</p>\n<p>You ask the user to input the cesar shift and message</p>\n<p>Then using list-comprehension you build a list of the new letters.</p>\n<p>Then you use the <code>"".join()</code> method to convert back to a string</p>\n<pre><code>def cesar_encode(message, shift):\n new_message = [chr(ord(char) + shift) if (ord(char) + shift) < 122 else chr(47+shift+122-ord(char)) for char in message]\n return "".join(new_message)\n\nif __name__ == "__main__":\n shift = input("Enter cesar shift: ")\n message = input("Enter the message to encode: ")\n print (cesar_encode(message, int(shift)))\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-16T17:24:26.420",
"Id": "252199",
"ParentId": "231540",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "231543",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-30T13:27:05.310",
"Id": "231540",
"Score": "16",
"Tags": [
"python",
"beginner",
"python-3.x",
"cryptography",
"caesar-cipher"
],
"Title": "A Caesar cipher in Python3"
}
|
231540
|
<p>Answering a question on S/O about type annotations led to me writing a little decorator that adds type checking to functions with annotated arguments. It supports the meta types <code>Any</code>, <code>Optional[]</code>, and <code>Union[]</code>, as well as combinations such as <code>Optional[Union[...]]</code>. It takes no arguments itself, for ease of use.</p>
<p>I'm fairly new to non-SQL programming in general so I'd love feedback. There's a short README in its <a href="https://github.com/osoleve/type_enforcer" rel="nofollow noreferrer">Github repo</a>.</p>
<pre class="lang-py prettyprint-override"><code>from typing import Callable, Union, Optional
from functools import wraps
from itertools import zip_longest
import re
def enforce_types(func: Callable) -> Callable:
"""Adds run-time type checking to a fully-annotated function"""
@wraps(func)
def wrapper(*args, **kwargs):
for argument, annotation, value in zip_longest(
*zip(*func.__annotations__.items()), args,
fillvalue=""
):
# If we have Optional args, we could have more annotations than supplied arguments
if value == "":
break
# Type Any can take... any type, so continue
elif annotation == "Any":
continue
value_type = type(value).__name__
# Check for meta types
is_optional: bool = "Optional" in str(annotation)
is_union: bool = "Union" in str(annotation)
# If Optional[], get the optional type
if is_optional:
annotation = re.search("Optional\[(.*)\]", str(annotation)).group(1)
# If Union[], get the list of types
if is_union:
annotation = re.search("Union\[(.*)\]", str(annotation)).group(1)
# If there's just one type allowed, check against it
if not is_union and value_type != annotation.__name__:
raise TypeError(
f"Argument {argument} supplied wrong type: expected {annotation.__name__}, got {value_type}."
)
# If it's not a Union and it passed the last check,
# or if it's a Union and a valid type was passed in, continue
elif (not is_union) or (is_union and value_type in annotation):
continue
# If there's a type Union, check against the possible types
elif is_union and value_type in annotation:
continue
# If we get here, the argument isn't any of the appropriate values
else:
raise TypeError(
f"Argument {argument} supplied wrong type: expected one of [{annotation}], got {value_type}"
)
return func(*args, **kwargs)
return wrapper
</code></pre>
<p>Example of usage:</p>
<pre class="lang-py prettyprint-override"><code>>>> from type_enforcer import enforce_types
>>> from typing import Union, Optional
>>> @enforce_types
... def foo(x: Union[int, float], y: Optional[int] = 1) -> int:
... return int(x * y)
>>> foo(5, 2)
10
>>> foo(5)
5
>>> foo(5.)
5
>>> foo(5., 2)
10
>>> foo('5')
Traceback (most recent call last):
...
TypeError: Argument x supplied wrong type: expected one of [int, float], got str
>>> foo(5, 2.)
Traceback (most recent call last):
...
TypeError: Argument y supplied wrong type: expected one of [int, NoneType], got float
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-30T16:01:10.520",
"Id": "451675",
"Score": "1",
"body": "I once did something like this - to implement overloads. Thats even more unpythonic than this. A great help for this is the [inspect](https://docs.python.org/3/library/inspect.html) module. It may do a few things for you, with it's functions, but my greatest gain was reading it's source code for gotcha's and how iteration over perhaps-positional-perhaps keyword arguments can be done."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-30T16:02:52.693",
"Id": "451676",
"Score": "1",
"body": "For anything more than a POC you should use either a dedicated library such as [pytypes](https://github.com/Stewori/pytypes). Or if you want to roll your own use [typing_inspect](https://github.com/ilevkivskyi/typing_inspect). Rolling your own `typing_inspect` is not simple if you want to support all versions of Python."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-30T16:07:01.847",
"Id": "451678",
"Score": "0",
"body": "@Peilonrayz I'm of course not going to use this in production, it's an experiment/learning exercise :) But I'd like to not have learned the wrong things while doing it, so here I am."
}
] |
[
{
"body": "<p>This is a very very poor implementation.</p>\n\n<ul>\n<li><p>Firstly the code has little care for nested datatypes, and makes them a pain to add in a future version. </p>\n\n<p>To add support for this all that needs to be done is change the, per type, control flow to use recursion. The option to use standard loops rather than recursion is available too, however that will likely make the code harder to read.</p></li>\n<li><p>The code just looks very error prone. Whilst RegEx has it's place in some limited scenarios, this is not then. The following snippet is almost never a good idea.</p>\n\n<pre><code>is_optional: bool = \"Optional\" in str(annotation)\nif is_optional:\n annotation = re.search(\"Optional\\[(.*)\\]\", str(annotation)).group(1)\n</code></pre>\n\n<p>This is the kind of nonsense I would expect of a junior that just learnt what RegEx is.</p></li>\n<li><p>Whilst 'proper' low level typing inspection isn't that readable, mangling it with strings makes the code harder to read for people used to interacting with <code>typing</code>.</p>\n\n<p>Also, when performing low level changes on core Python libraries read the PEPs that accompany them. They're their for a reason. For instance, PEP 484 states how to remove the need for using strings.</p>\n\n<blockquote>\n <p>The string literal should contain a valid Python expression (i.e., compile(lit, '', 'eval') should be a valid code object) and it should evaluate without errors once the module has been fully loaded. The local and global namespace in which it is evaluated should be the same namespaces in which default arguments to the same function would be evaluated.</p>\n</blockquote>\n\n<p>Furthermore, reading the PEP is not required, as the <code>typing</code> documentation shows a function that does this out of the box.</p>\n\n<blockquote>\n <p><a href=\"https://docs.python.org/3/library/typing.html#typing.get_type_hints\" rel=\"nofollow noreferrer\">typing.get_type_hints</a>(obj[, globals[, locals]])<br>\n Return a dictionary containing type hints for a function, method, module or class object.</p>\n</blockquote></li>\n</ul>\n\n<p>Whilst I can understand that hacking a solution may be the most fun way to implement something. It's how I learnt the <code>typing</code> library. You should at least read the documentation of the module. Python's documentation is very high-quality, and ignoring it leads to poor code.</p>\n\n<p>Here's a naive implementation:</p>\n\n<pre><code>import typing\nimport inspect\n\n\ndef is_type(instance, type_info):\n if type_info == typing.Any:\n return True\n if hasattr(type_info, '__origin__'):\n if type_info.__origin__ in {typing.Union, typing.Optional}:\n return any(is_type(instance, arg) for arg in type_info.__args__)\n return isinstance(instance, type_info)\n\n\ndef enforce_types(func):\n types_info = typing.get_type_hints(func)\n signature = inspect.signature(func)\n\n def inner(*args, **kwargs):\n sig = signature.bind(*args, **kwargs)\n sig.apply_defaults()\n for name, value in sig.arguments.items():\n if not is_type(value, types_info.get(name, typing.Any)):\n raise TypeError(\n '{name} is not of the correct type'\n .format(name=name)\n )\n return func(*args, **kwargs)\n\n return inner\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-30T17:31:27.557",
"Id": "451693",
"Score": "0",
"body": "Thank you for the detailed feedback!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-30T17:25:13.613",
"Id": "231562",
"ParentId": "231547",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "231562",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-30T14:49:01.593",
"Id": "231547",
"Score": "2",
"Tags": [
"python",
"python-3.x"
],
"Title": "A Decorator that turns Function Annotations into Type Checks"
}
|
231547
|
<p>I am working on an angular stack that has <code>n</code> amount of services that hold data in stores of this type:</p>
<pre><code>fooStore$ = BehaviorSubject<FooStoreType>({})
</code></pre>
<p>accessing properties in these have generally been done like this:</p>
<pre><code>export wantedPropSelector$ = fooStore$.pipe(
map(store => store.wantedProp)
);
</code></pre>
<p>Now I'm working on improving this by adding memoization and selector singletons for each service. I've ended up with a pattern that allows this syntax in the service-side:</p>
<pre><code>export wantedPropSelector$ = select(fooStore$, store => store.wantedProp);
</code></pre>
<p>and the <code>select</code> function looks like this:</p>
<pre><code>type MappingFunction<T, R> = (mappable: T) => R;
type MemoizationFunction<R> = (previousResult: R, currentResult: R) => boolean;
export function select<T, R>(
inStream: Observable<T>,
mappingFunction: MappingFunction<T, R>,
memoizationFunction?: MemoizationFunction<R>
): Observable<R> {
return inStream.pipe(
map(mappingFunction),
distinctUntilChanged(memoizationFunction),
shareReplay(1)
);
}
</code></pre>
<p>My assumption is that <code>distinctUntilChanged</code> will give me memoization, and it's possible to send in custom memoization logic for Objects, and <code>shareReplay(1)</code> will allow me to turn the selectors into singletons that also return the last value.</p>
<p>I'd greatly appreciate CR on this from anyone sufficiently experienced with RxJs to point out any possible flaws in this code.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-30T15:33:21.417",
"Id": "451668",
"Score": "1",
"body": "Welcome to Code Review! While I don't have any experience with RxJs myself, this looks like a good question to me. If you are interested in more about Code Review, read the [tour] or [ask]."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-30T15:14:41.827",
"Id": "231550",
"Score": "4",
"Tags": [
"javascript",
"angular-2+",
"rxjs"
],
"Title": "RxJs memoized singleton selectors"
}
|
231550
|
<p>I am a beginner who just picked up Java (2 months ago) and I am solving some questions. For this question, the overall problem wants me to choose the cheapest price plan, so I listed out the possibilities of every plan and 'hardcoded' the logic by inputting the number of services, as the services is more important than the plan. However, I would like to improve the algorithm of this method and as a beginner my foundation is very weak.</p>
<p>Is there any other ways where I can further improve this method or is there any other solutions? This is because if I need to implement a new service, my entire solution will be flawed. Hence, I am looking at constructors/interfaces and arrays. However, it gets very confusing when there is a plan and services being involved and then to get the cheapest price as well.</p>
<p>Therefore, I would appreciate any help or advise to improve on this method of solving. Please pardon me for my weak explanation and lack of concept in Java as this is my first post.</p>
<h3>Problem statement</h3>
<blockquote>
<p>Create a java program</p>
<p>The seller from corporation Test provides the following plans and its
price:</p>
<ul>
<li>PLAN1: (voice, email), $100 per year</li>
<li>PLAN2: (email, database, admin), $150 per year</li>
<li>PLAN3: (voice, admin), $125 per year</li>
<li>PLAN4: (database, admin), $135 per year</li>
</ul>
<p>The customer wants (email, voice, admin) service. He has the following
choices to cover his need:</p>
<ul>
<li>(PLAN1, PLAN2): 100 + 150 = $250 (PLAN1, PLAN3): 100 + 125 = $225</li>
<li>(PLAN2, PLAN3): 150 + 125 = $270 (PLAN1, PLAN4): 100 + 135 = $235</li>
<li>(PLAN2, PLAN3, PLAN4) = 150 + 125 + 135 = $410</li>
<li>…// other possible plan choices omitted</li>
</ul>
<p>And the minimum price is $225, PLAN1 + PLAN3.</p>
</blockquote>
<h2>My solution</h2>
<pre><code>package practice;
import java.util.Scanner;
public class Test {
private static Scanner input;
public static void main(String[] args) {
input = new Scanner(System.in);
System.out.println("We have the following services:");
System.out.println("Voice, Database, Admin, Email");
System.out.println("How many services would you like?");
// input number of services
int choice = input.nextInt();
// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
// Logic starts here
// when number of services required is 1
switch (choice) {
case 1:
Scanner input1 = new Scanner(System.in);
System.out.println("What type of services would you like?");
System.out.println("1. Voice");
System.out.println("2. Database");
System.out.println("3. Admin");
System.out.println("4. Email");
// input 1 option
int choice1 = input1.nextInt();
switch (choice1) {
case 1:
System.out.println("$100");
break;
case 2:
System.out.println("$135");
break;
case 3:
System.out.println("$125");
break;
case 4:
System.out.println("$100");
break;
default:
System.out.println("Invalid option. Please try again");
}
break;
// when number of services required is 2
case 2:
Scanner input2 = new Scanner(System.in);
System.out.println("What type of services would you like?");
System.out.println("1. Voice");
System.out.println("2. Database");
System.out.println("3. Admin");
System.out.println("4. Email");
// input 2 options
int choice2 = input2.nextInt();
int choice3 = input2.nextInt();
// plan(1,4) -> $100
if (choice2 == 1 && choice3 == 4) {
System.out.println("$100");
// plan(1,3) -> $125
} else if (choice2 == 1 && choice3 == 3) {
System.out.println("$125");
// plan(2,3) & (3,4) -> $125
} else if ((choice2 == 2 && choice3 == 3) || (choice2 == 3 && choice3 == 4)) {
System.out.println("$150");
} else
System.out.println("Invalid option. Please try again");
break;
// when number of services required is 3
case 3:
Scanner input3 = new Scanner(System.in);
System.out.println("What type of services would you like?");
System.out.println("1. Voice");
System.out.println("2. Database");
System.out.println("3. Admin");
System.out.println("4. Email");
// input 3 options
int choice4 = input3.nextInt();
int choice5 = input3.nextInt();
int choice6 = input3.nextInt();
// plan(1,3,4) -> $225
if (choice4 == 1 && choice5 == 3 && choice6 == 4) {
System.out.println("$225");
// plan(1,2,3) -> $235
} else if (choice4 == 1 && choice5 == 2 && choice6 == 3) {
System.out.println("$325");
// plan(2,3,4) -> $150
} else if (choice4 == 2 && choice5 == 3 && choice6 == 4) {
System.out.println("$150");
} else
System.out.println("Invalid option. Please try again");
break;
// when number of services required is all 4
case 4:
System.out.println("All 4 services will cost $250");
break;
default:
System.out.println("Invalid input.");
}
}
}
</code></pre>
<h2>Output</h2>
<pre class="lang-none prettyprint-override"><code>We have the following services:
Voice, Database, Admin, Email
How many services would you like?
3
What type of services would you like?
1. Voice
2. Database
3. Admin
4. Email
1
3
4
$225
</code></pre>
|
[] |
[
{
"body": "<p>Thanks for sharing your code.</p>\n\n<p>your solution is straight <em>procedural</em>. \nThere is nothing wrong with <em>procedural</em> solutions as such but Java is an <em>object oriented</em> programming language and therefore you should learn to find OO-ish solutions to problems.<br>\nHowever: this is just an advice, no judgement.</p>\n\n<p>Here is what I consider problematic in your code:</p>\n\n<h1>General approach</h1>\n\n<h2>no calculation</h2>\n\n<p>Your code <em>hides</em> the concept of the <em>Service Plan</em> from the problem statement by cascading decisions.\nThis leads to the \"spaghetti code\" we see and what you consider problematic yourself.</p>\n\n<p>On top of that your code fails if the user enters the service IDs in an unexpected order, eg.: <code>4 3 1</code>.</p>\n\n<p>A proper solution would try to calculate the best plan combination, so that adding new plans and/or services would just be a configuration.</p>\n\n<h2>no reuse of variables</h2>\n\n<p>At every assignment you create a new variable. </p>\n\n<p>You declare multiple variables <code>input</code> with numbers. There should be only one variable <code>input</code> since <code>System.in</code> is a <em>singelton</em> and cannot be accessed concurrently anyway.\nOn top of that you declared <code>input</code> (without number) as a <em>class variable</em>. \nSince you only use this variable at only one method in our code which is the same where you assign it its value this is not needed.</p>\n\n<p>The variables <code>choice1</code>, <code>choice2</code> and <code>choice4</code> hold the same value regarding the business case: the first selected service ID.\nThere should be only one variable <code>firstSelectedServiceID</code> to be used in all cases of the outer switch.\nSimilar is true for the other numbered <code>choice</code> variables.</p>\n\n<h1>Naming</h1>\n\n<p>Finding good names is the hardest part in programming. So always take your time to think carefully of your identifier names.</p>\n\n<h2>Choose your names from the problem domain</h2>\n\n<p>You have some identifiers which are named after their technical implementation: the same name with numbers. \nThis makes your code hard to read and hard to understand.\nYour variables should better be named like this:</p>\n\n<ul>\n<li><code>choice</code>: should be <code>numberOfServices</code><br>\ninstead of writing a comment you can name the variable accordingly</li>\n<li><code>choice1</code>, <code>choice2</code> and <code>choice4</code> as mentioned before</li>\n<li><code>choice3</code> and <code>choice5</code> should be <code>secondSelectedServiceID</code></li>\n<li><code>choice6</code> should be <code>thirdSelectedServiceID</code></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-20T18:56:30.497",
"Id": "454548",
"Score": "0",
"body": "Hi Timothy, thanks for taking the time out to comment on my codes. I am deeply humble by the advice and will looked to revise on my foundations level. It is my first time learning programming on my own and java is my first language. I really appreciate your advice and will looked to implement them in the near future. Cheers! :)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-30T20:28:26.690",
"Id": "231568",
"ParentId": "231555",
"Score": "3"
}
},
{
"body": "<p>I'm going to code review from the top down. Don't be discouraged, but I have a lot of suggestions:</p>\n\n<h2>Change name of class 'Test'</h2>\n\n<p>Lots of projects put classes outside of the production build based on the ClassName starting or ending with <code>Test</code>. Of course it doesn't matter when you're just messing around, but it's good practice to avoid such a name for a class that is not an Automated test. </p>\n\n<p>Another problem arises when you create a test for Test, if you follow the common naming pattern you're left with <code>TestTest</code>, which is an awkward name.</p>\n\n<h2>Change name of 'input'. Set it as Final.</h2>\n\n<p><code>input</code> is a poor name. Normally input would refer to input from somewhere, such as the user. Not the object used to get the input. I suggest renaming it <code>scanner</code>. You can also declare it as <code>final</code> since it never needs to change.</p>\n\n<h2>Use methods & don't repeat yourself.</h2>\n\n<p>Whenever you copy & paste some code in more than 1 place, you should ask yourself if it could be a method. This holds true even when you make a slight change to the pasted code.</p>\n\n<p>I work with a fairly large code base and I've only seen a maximum of 1-2 lines of code repeated. Even that could be reduced to 0. In other words, you should never repeat yourself.</p>\n\n<p>Even if you forget about re-usability, You should get into the habit of creating methods wherever they make sense to help readability of your code.</p>\n\n<p>This could be a method:</p>\n\n<pre><code>Scanner input1 = new Scanner(System.in);\nSystem.out.println(\"What type of services would you like?\");\nSystem.out.println(\"1. Voice\");\nSystem.out.println(\"2. Database\");\nSystem.out.println(\"3. Admin\");\nSystem.out.println(\"4. Email\");\n\nint choice1 = input1.nextInt();\n</code></pre>\n\n<p>But we already have an <code>input</code>, so we don't need to instantiate another Scanner object.\nYou can either take it as an parameter, or just reference it directly if it's kept as a class variable.</p>\n\n<p>So a better method would look like:</p>\n\n<pre><code>private static int promptUserForBeginningServices(Scanner scanner)\n{\n System.out.println(\"We have the following services:\");\n System.out.println(\"Voice, Database, Admin, Email\");\n System.out.println(\"How many services would you like?\");\n\n return scanner.nextInt();\n}\n</code></pre>\n\n<p>..However you may notice this method is doing 2 things: Prompting the user, & getting a result for number of services. Methods should really only be doing 1 thing. But this is our first iteration of refactoring. So we will leave it for now.</p>\n\n<h2>Change the names of 'choice'</h2>\n\n<p>A better name would be <code>choiceEnteredByUser</code>, or <code>typeOfServiceSelected</code>. </p>\n\n<p>\"choice\" is ambiguous. Actually, it's meaningless. You could have named it <code>x</code> & it would be as descriptive.</p>\n\n<h2>Commenting</h2>\n\n<p>Commenting where the logic start is not helpful. Use comments to describe what code does, when it's not clear. Actually, your first approach is to use descriptive methods & descriptive method names. If it's still not 100% clear, use a comment.</p>\n\n<h2>ENUMS</h2>\n\n<p>Whenever You have a switch statement, you should ask yourself if you should be using an ENUM. That's not to say every switch statement should be an enum, but a lot of them should be. This is one of those times.</p>\n\n<p>\"1\" is meaningless. You should never have meaningless code.</p>\n\n<p>...That being said, you don't need a switch statement at all, you should be using a Map or parallel arrays.</p>\n\n<h2>Magic Numbers</h2>\n\n<p>Magic numbers / magic strings are those literal values you have hanging around. The numbers in your switch statement, the strings you output to the user (\"What type of services would you like?\") these should be declare as final static variables at the top of your class. This will help maintenance & readability.</p>\n\n<h2>End notes</h2>\n\n<p>I normally post the finished product when doing code reviews, but I think in this case it would do more damage than good. Don't try to move from 0 - 10 in one round of refactoring. You'll learn a LOT from simply adding methods. Your code will become 10x easier to read, you'll be able to see all the useless duplication & be able to make changes a lot easier.</p>\n\n<p>After you've added methods, adding an ENUM will be another 'aha moment' or epiphany (for lack of better term).</p>\n\n<p>Once you have an ENUM & methods, see if you can remove all of your magic strings.</p>\n\n<p>Once you have all your String messages at the top, you'll probably notice you can group them... See if you can put them into Arrays. Afterwards, your code has literally been cut in half (by line number, assuming you can print those array messages in a loop).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-20T18:54:31.627",
"Id": "454547",
"Score": "1",
"body": "Hi sir, I have not tried using ENUMS but I will look to implement it in the near future. Thanks for the advice, really appreciate you taking the time out to help me out. :)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-31T02:36:34.670",
"Id": "231577",
"ParentId": "231555",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-30T16:08:54.757",
"Id": "231555",
"Score": "3",
"Tags": [
"java",
"algorithm"
],
"Title": "Create a java program to find the cheapest plan that have the services required"
}
|
231555
|
<p>I have got 2 working codes, where one is a bit longer and another a bit shorter. Is it some way to bind all these layers as a one group?</p>
<p>The first one is:</p>
<pre><code> map.on('zoomend', function() {
if (map.getZoom() <6){
map.removeLayer(job);
}else{
map.addLayer(job);
}
if (map.getZoom() <7){
map.removeLayer(job2);
}else{
map.addLayer(job2);
}
if (map.getZoom() <8){
map.removeLayer(job3);
}else{
map.addLayer(job3);
}
});
</code></pre>
<p>and another one</p>
<pre><code> map.on('zoomend', function() {
if (map.getZoom() <8){
map.removeLayer(job);
}
if (map.getZoom() <8){
map.removeLayer(job2);
}
if (map.getZoom() <8){
map.removeLayer(job3);
}
else {
map.addLayer(job);
map.addLayer(job2);
map.addLayer(job3);
}
});
</code></pre>
<p>I would like to avoid this kind of repeats, as I am going to have multitude of layers in the future.</p>
|
[] |
[
{
"body": "<p>In your case a better way is using a predefined mapping (as <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map\" rel=\"nofollow noreferrer\"><code>Map</code></a>) holding the relations between <em>zoom</em> limits and respective <em>jobs</em>.<br>Then, just iterate through the mapping and perform add/remove operation:</p>\n\n<pre><code>const zoomJobsMap = new Map([\n [6, job],\n [7, job2],\n [8, job3],\n ...\n]);\n\nmap.on('zoomend', function() {\n let zoom = map.getZoom(); # get zoom value at once\n for (var [zoomLimit, jobObj] of zoomJobsMap) {\n (zoom < zoomLimit)? map.removeLayer(jobObj) : map.addLayer(jobObj);\n\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-30T17:56:24.750",
"Id": "231564",
"ParentId": "231557",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "231564",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-30T17:00:25.137",
"Id": "231557",
"Score": "2",
"Tags": [
"javascript",
"leaflet"
],
"Title": "Setting zoom for layer disappearance in Leaflet"
}
|
231557
|
<p>I want to find the longest palindromic substring using dynamic programming in Python3. The strings can be as large as this string.</p>
<p>I have seen other questions on this problem that successfully solve it but I am unable to improve my own code following their strategy.</p>
<p>This, approach 3 is the strategy that I want to implement. Even then, my code is not time-efficient.</p>
<p>My code is:</p>
<pre><code>class Solution:
def __init__(self):
self.not_pal = {}
self.pals = {}
def check_pal(self, s, i, j):
if len(s) == 0:
return False
if i == j:
return True
if i == j-1:
if s[i] == s[j]:
return True
return False
if s[i] == s[j]:
return self.check_pal(s, i+1, j-1)
return False
def longestPalindrome(self, s):
max_pal_str = ''
length = len(s)
for i in range(len(s)):
if length-i <= len(max_pal_str):
continue
for j in range(len(s)-1, -1, -1):
if self.not_pal.get(s[i: j+1]):
continue
if self.pals.get(s[i: j+1]):
continue
if len(s[i: j+1]) <= len(max_pal_str):
continue
if self.check_pal(s, i, j):
self.pals[s[i:j+1]] = 1
if len(s[i: j+1]) > len(max_pal_str):
max_pal_str = s[i: j+1]
else:
self.not_pal[s[i:j+1]] = 1
return max_pal_str
</code></pre>
<p>I am unable to improve this code further. I expect it to be faster than brute force codes which check all the permutations and combinations without any memoization. It is failing with TLE on Leetcode.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-30T17:21:14.447",
"Id": "451690",
"Score": "4",
"body": "Well, you succeeded in writing pretty unreadable code =) What's with all the the single-letter variable names and magic numbers?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-30T17:26:11.020",
"Id": "451692",
"Score": "0",
"body": "@Mast\n\nI am sorry for writing bad code.\ni,j -> loop iterators\ns -> given string\n1 is just any value in the dictionary(I should have used `sets`, right?)\n\nIs there any other friction for you to read the code? Apologies for presenting it in such a state."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-30T19:06:10.740",
"Id": "451700",
"Score": "1",
"body": "To counter-balance the unclear variable names, maybe you could add more context to your question :) This way, we could help you write clearer code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-31T15:25:21.497",
"Id": "451806",
"Score": "2",
"body": "You say \"The strings can be as large as this string\", but which string do you mean? You also talk about \"This, approach 3 is the strategy that I want to implement\", but I have no idea what you mean by that. Please add a bit more detail, like the problem description and what your strategy to solve it actually is."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-04T02:08:35.777",
"Id": "452272",
"Score": "0",
"body": "Does the problem on Leetcode require that your code be in a class like this?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-04T02:11:34.857",
"Id": "452273",
"Score": "0",
"body": "Yes. It has to be in a class or a func in this class will call another class. Global vars and methods won't work."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-30T17:13:04.930",
"Id": "231558",
"Score": "1",
"Tags": [
"python",
"python-3.x",
"strings",
"dynamic-programming",
"palindrome"
],
"Title": "How do I optimize memoization in order to find longest palindromic substring?"
}
|
231558
|
<p>I wrote <code>cat</code> program in x86 NASM and I would like to know if there is anything that can be improved.</p>
<p>This implementation of <code>cat</code> supports:</p>
<ul>
<li>Reading from stdin.</li>
<li>Multiple arguments.</li>
</ul>
<p>I checked few cases and program behaves exactly like original <code>cat</code> command.</p>
<p>I was thinking if I should add labels like <code>write</code> even if I wouldn't <code>jmp</code> to them, so code would be cleaner.</p>
<p>Code:</p>
<pre><code>section .text
global _start
_start:
;esi=1
mov esi, 1
;if(argc==1)
;goto open
cmp dword [esp], 1
jnz open
;else
;fd=STDIN_FILENO
mov dword [fd], 0
jmp read
open:
;fd=open(path,oflag)
mov eax, 5
mov ebx, [esp+esi*4+4]
mov ecx, 0
int 0x80
mov [fd], eax
read:
;bytes_read=read(fd,buf,BUFSIZE)
mov eax, 3
mov ebx, [fd]
mov ecx, buf
mov edx, BUFSIZE
int 0x80
;write(STDOUT_FILENO,buf,bytes_read)
mov edx, eax
mov eax, 4
mov ebx, 1
mov ecx, buf
int 0x80
;if(bytes_read!=0)
;goto read
cmp edx, 0
jnz read
;close(fd)
mov eax, 6
mov ebx, [fd]
int 0x80
;esi++
inc esi
;if(esi<argc)
cmp dword esi, [esp]
jl open
exit:
mov eax, 1
mov ebx, 0
int 0x80
section .data
BUFSIZE equ 1024
section .bss
buf resb BUFSIZE
fd resd 1
</code></pre>
|
[] |
[
{
"body": "<blockquote>\n <p>I was thinking if I should add labels like write even if I wouldn't jmp to them, so code would be cleaner.</p>\n</blockquote>\n\n<p>Writing labels that aren't jumped to is fine. Provided they have meaningful names, it can help to understand the program.</p>\n\n<h2>My comments (not in a particular order)</h2>\n\n<blockquote>\n<pre><code>;esi=1\nmov esi, 1\n</code></pre>\n</blockquote>\n\n<p>This is a redundant comment! I already can see what the instruction does. What I can't know is what the <code>ESI</code> register will be used for.</p>\n\n<blockquote>\n<pre><code>;if(argc==1)\n;goto open\ncmp dword [esp], 1\njnz open\n</code></pre>\n</blockquote>\n\n<p>Here the comment does not correspond to the code. The code actually does <code>if(argc!=1)</code>.</p>\n\n<blockquote>\n<pre><code>cmp edx, 0\njnz read\n</code></pre>\n</blockquote>\n\n<p>The more usual way to test for zero would be <code>test edx, edx</code>. It has a smaller encoding and is generally a bit faster.</p>\n\n<blockquote>\n<pre><code>mov ebx, 0\n</code></pre>\n</blockquote>\n\n<p>Similarly, zeroing a register is best done using the <code>xor</code> instruction (<code>xor ebx, ebx</code>). This is both faster and shorter.</p>\n\n<blockquote>\n<pre><code>mov dword [fd], 0\n</code></pre>\n</blockquote>\n\n<p>Your program would not need this instruction at all, if you would move the <em>fd</em> variable from the <code>.bss</code> section to the <code>.data</code> section using <code>fd dd 0</code>.</p>\n\n<p>This in turn opens up an opportunity to shorter the code from:</p>\n\n<pre><code> cmp dword [esp], 1\n jnz open\n mov dword [fd], 0\n jmp read\nopen:\n</code></pre>\n\n<p>to:</p>\n\n<pre><code> cmp dword [esp], 1\n je read\nopen:\n</code></pre>\n\n<p>Also note that in conjunction with the <code>cmp</code> instruction, it's better to use <code>je</code> and <code>jne</code>.<br>\nIn conjunction with the <code>test</code> instruction, it's preferable to use <code>jz</code> and <code>jnz</code>. </p>\n\n<p><code>je</code> and <code>jz</code> have an identical encoding but choosing the right instruction mnemonic better expresses what the intention of the code is.</p>\n\n<blockquote>\n<pre><code>;if(esi<argc)\ncmp dword esi, [esp]\njl open\n</code></pre>\n</blockquote>\n\n<p>The <em>argc</em> is by its very nature an <strong>unsigned</strong> number. After all it's just a count. You should use the conditional jumps that are provided to deal with the unsigned conditions. So better use <code>jb open</code> (JumpIfBelow).<br>\nAlso there's no point in writing the <code>dword</code> size-tag. The mention of the dword register <code>ESI</code> already dictates the size.</p>\n\n<blockquote>\n<pre><code>mov edx, eax\nmov eax, 4\nmov ebx, 1\nmov ecx, buf\nint 0x80\n</code></pre>\n</blockquote>\n\n<p>I always prefer to write the function number directly above the <code>int 0x80</code> instruction. That way it's immediately clear what function is getting invoked. And for perfection I even assign the registers in a sorted manner:</p>\n\n<pre><code>mov edx, eax\nmov ecx, buf\nmov ebx, 1\nmov eax, 4\nint 0x80\n</code></pre>\n\n<hr>\n\n<h2>Putting it all together</h2>\n\n<ul>\n<li>not being afraid to write redundant labels</li>\n<li>putting the comments in a separate column for readability</li>\n<li>shaving off one more byte by using the fact that <code>ESI==1</code> when <code>cmp dword [esp], 1</code> is executed.</li>\n</ul>\n\n<pre class=\"lang-none prettyprint-override\"><code>section .text\n global _start\n\n_start:\n mov esi, 1\n cmp [esp], esi ;if(argc==1) goto read\n je read\nopen:\n xor ecx, ecx ;fd=open(path,oflag)\n mov ebx, [esp+esi*4+4]\n mov eax, 5\n int 0x80\n mov [fd], eax\nread:\n mov edx, BUFSIZE ;bytes_read=read(fd,buf,BUFSIZE)\n mov ecx, buf\n mov ebx, [fd]\n mov eax, 3\n int 0x80\nwrite:\n mov edx, eax ;write(STDOUT_FILENO,buf,bytes_read)\n mov ecx, buf\n mov ebx, 1\n mov eax, 4\n int 0x80\nmore:\n test edx, edx ;if(bytes_read!=0) goto read\n jnz read\nclose:\n mov ebx, [fd] ;close(fd)\n mov eax, 6\n int 0x80\nnext:\n inc esi\n cmp esi, [esp] ;if(esi<argc)\n jb open\nexit:\n xor ebx, ebx\n mov eax, 1\n int 0x80\n\nsection .data\n fd dd 0 ;fd=STDIN_FILENO\n\nsection .bss\n BUFSIZE equ 1024\n buf resb BUFSIZE\n</code></pre>\n\n<h2>Concern</h2>\n\n<p>Nowhere in your code do you check for any errors from api calls like <code>open</code> or <code>read</code>. Imagine what might happen in these cases?</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-31T17:05:56.813",
"Id": "451845",
"Score": "0",
"body": "Thanks for pointing out these comments. Can you tell me how do you know that `test` is faster (same with `xor`)? Or how can I check myself is something is faster in NASM? I forgot I can define this variable, so it will be `0` at start and assign other value later. I was always assigning registers \"for perfection\" starting with `eax`, so it looks like in most programming languages i.e. <function name>(<args>). I'm not checking for errors, cause writing this code took me bit of time and I wanted to know if I'm on right track. I will add error handling later. Thanks for that answer."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-31T17:07:30.360",
"Id": "451846",
"Score": "0",
"body": "By the way, is there any difference if constant is defined in `.bss` section, not in `.data`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-31T17:10:09.723",
"Id": "451847",
"Score": "0",
"body": "Can you also tell me why are you comparing `[esp]` with `esi`, not just `1`? Is it faster when you are using register for that?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-31T17:13:42.963",
"Id": "451849",
"Score": "0",
"body": "@DeBos99 Ordinarily I would define that constant near the top of the program, even before starting the `.code` section. That way it's sooner clear for the reader what the constant equates to. As for the speed of `test` and `xor`, that's what the architecture tells us. My personal tests back this up."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-31T17:16:17.487",
"Id": "451850",
"Score": "0",
"body": "@DeBos99 I compared with the register (that happened to contain the value of 1), because that made the instruction exactly 1 byte shorter. Shorter instructions are often (not always) a bit faster."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-31T17:17:23.410",
"Id": "451851",
"Score": "0",
"body": "Ok, so I should move whole `.bss` section to the top and/or `.data`? In relation to `test` and `xor` could you tell me how could I make such a tests myself or its more complicated process?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-31T17:18:18.583",
"Id": "451852",
"Score": "0",
"body": "Can you tell me how do you know that this instruction is shorter? I thought that if you are giving constant number instead of whole register, its shorter."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-31T17:21:45.007",
"Id": "451855",
"Score": "0",
"body": "@DeBos99 No, you can leave the sections in place. Write your `equ` outside of any section. Checking the speed of an instruction is done through repeating the instruction(s) millions of times in a loop and measuring the time it takes."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-31T17:26:19.097",
"Id": "451856",
"Score": "0",
"body": "@DeBos99 I have the advantage of being an assembler designer myself and so I know the length of almost all the instructions by heart. But anyway, if an instruction contains an immediate number (the 1 in this case), that will nearly always require additional storage."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-31T17:30:05.317",
"Id": "451858",
"Score": "1",
"body": "I did everything you described in answer and comments and code looks much cleaner, but for some reason executable file that is created is 2 times bigger. Is it cause I used some instruction I didn't use before or I did something wrong?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-31T17:42:42.330",
"Id": "451863",
"Score": "0",
"body": "@DeBos99 That's probably because now for the first time your program has an actual `.data` section. It's not much but aligment makes it bigger. The original version only truly used a `.bss` section and that is never included in the file itself (because of what it stands for which is **uninitialized data**)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-31T17:46:32.370",
"Id": "451866",
"Score": "0",
"body": "Oh now I see. There was only constant here that can be anywhere else, so the section was technically empty. Can you tell me if there is any good NASM tutorial? For now I was using [this one](https://www.tutorialspoint.com/assembly_programming/), but I see they skipped few bits I needed."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-31T17:58:39.360",
"Id": "451868",
"Score": "1",
"body": "@DeBos99 I could not suggest to you a tutorial mainly because I've never used one. When writing code for the x86 architecture, you should download the relevant Intel manuals from their website. You could also peek at the Intel Optimization Manual. And where NASM is concerned, I think the accompanying manual should suffice. Good hunting!"
}
],
"meta_data": {
"CommentCount": "13",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-31T15:57:06.163",
"Id": "231618",
"ParentId": "231560",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "231618",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-30T17:22:10.890",
"Id": "231560",
"Score": "6",
"Tags": [
"linux",
"assembly",
"x86"
],
"Title": "Cat program in x86 NASM"
}
|
231560
|
<p>I have a code that will delete the row if the entire row is exactly the same. So if in row 1 I have 100,200,300,400,500,600 in column A,B,C,D,E,F respectively, and in row 3 I have the same thing, it will remove row 3.</p>
<pre><code>Sub remove()
Dim a As Long
For a = Cells(Rows.Count, 1).End(xlUp).row To 1 Step -1
If WorksheetFunction.CountIf(Range("A1:A" & a), Cells(a, 1)) > 1 Then
If WorksheetFunction.CountIf(Range("B1:B" & a), Cells(a, 2)) > 1 Then
If WorksheetFunction.CountIf(Range("C1:C" & a), Cells(a, 3)) > 1 Then
If WorksheetFunction.CountIf(Range("D1:D" & a), Cells(a, 4)) > 1 Then
If WorksheetFunction.CountIf(Range("E1:E" & a), Cells(a, 5)) > 1 Then
If WorksheetFunction.CountIf(Range("F1:F" & a), Cells(a, 6)) > 1 Then Rows(a).Delete
End If
End If
End If
End If
End If
Next
End Sub
</code></pre>
<p>However this code looks a little long and I was wondering if I could use a for loop but I have no idea on how to start. I am new to VBA coding which is why my methods could be a little hard coded. Any help is appreciated, Thank you!</p>
<p>(Edit) <a href="http://www.mediafire.com/file/fmomovtaq4i2kr6/Book1.xlsm" rel="nofollow noreferrer">Here</a> is a sample workbook that I have created.
In this workbook I have a few names on the first column and the next few columns are the points they obtain on different days. However, there are entries that have the exact same entry row, meaning, the points and the name is exactly the same and this is what I want to remove. in the sample workbook, the name james have the 2 exact same entries and therefore, it will remove 1 of it. However Lan and Denise does not have the same entries hence it remains after running the code. </p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-31T03:54:11.203",
"Id": "451731",
"Score": "0",
"body": "It isn't clear what you are trying to do. Please provide a valid dataset. A downloadable workbook would be even better."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-31T06:00:32.570",
"Id": "451733",
"Score": "0",
"body": "Hi TinMan, I have edited in a workbook and a more detailed explanation. Thank you for your help"
}
] |
[
{
"body": "<p>The proper way to do this is use the <code>Range.RemoveDuplicates</code> method. </p>\n\n<p>Here is the refactored macro created by clicking the Remove Duplicates button on the Data tab of the Ribbon. <code>Array(1, 2, 3, 4, 5, 6)</code> contains all the column numbers that need matching data for a row to be deleted.</p>\n\n<pre><code>Application.ScreenUpdating = False\nRange(\"A1\").CurrentRegion.RemoveDuplicates Columns:=Array(1, 2, 3, 4, 5, 6), Header:=xlYes\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-31T06:44:52.720",
"Id": "451738",
"Score": "0",
"body": "Thank You for the help!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-31T06:31:48.843",
"Id": "231585",
"ParentId": "231575",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "231585",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-31T01:10:55.903",
"Id": "231575",
"Score": "1",
"Tags": [
"vba",
"excel"
],
"Title": "Remove row when everything in the row is same"
}
|
231575
|
<p>Please take a look at this little snippet of code and explicate on whether there are an efficiency enhancements that you'd make for it. It standards a row of a pandas.DataFrame by adding zeros to it so that the total length of the datum is the same as the longest datum in the column</p>
<p>Sample "solubility.csv" file for testing</p>
<pre><code>SMILES,Solubility
[Br-].CCCCCCCCCCCCCCCCCC[N+](C)(C)C,-3.6161271205000003
O=C1Nc2cccc3cccc1c23,-3.2547670983
[Zn++].CC(c1ccccc1)c2cc(C(C)c3ccccc3)c(O)c(c2)C([O-])=O.CC(c4ccccc4)c5cc(C(C)c6ccccc6)c(O)c(c5)C([O-])=O,-3.9244090954
C1OC1CN(CC2CO2)c3ccc(Cc4ccc(cc4)N(CC5CO5)CC6CO6)cc3,-4.6620645831
</code></pre>
<pre><code>def generate_standard():
dataframe = pd.read_csv('solubility.csv', usecols = ['SMILES','Solubility'])
dataframe['standard'],longest = '',''
for _ in dataframe['SMILES']:
if len(str(_)) > len(longest):
longest = str(_)
continue
# index,row in dataframe
for index,row in dataframe.iterrows():
# datum from column called 'SMILES'
smi = row['SMILES']
# zeros = to difference between longest datum and current datum
zeros = (0 for x in range(len(longest) - len(str(smi))))
# makes the zeros into type str
zeros_as_str = ''.join(str(x) for x in zeros)
# concatenate the two str
std = str(smi) + zeros_as_str
# and place it in a new column called standard at the current index
dataframe.at[index,'standard'] = std
return dataframe,longest
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-31T05:47:14.227",
"Id": "451732",
"Score": "1",
"body": "Where did `longest` come from in your snippet? Add more context with a minimal and testable dataframe fragment"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-31T12:59:16.307",
"Id": "451782",
"Score": "0",
"body": "@RomanPerekhrest Edits have been made. Hope this helps you. Thanks for taking some time to look at my code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-31T14:43:58.417",
"Id": "451799",
"Score": "0",
"body": "I will upvote both of these when I have 15 rep. But regardless, thank you everyone."
}
] |
[
{
"body": "<p>Ways to improve and optimize:</p>\n\n<ul>\n<li><p>function <code>generate_standard</code> is named too general whereas it loads concrete csv file <code>'solubility.csv'</code> and processes a particular column <code>'SMILES'</code>.<br>A more maintainable and flexible way is to make the function more decoupled and unified such that it accepts an input <em>csv</em> file name and the crucial column name. <br>The main purpose can be described as <strong><em>\"aligning a specific column's values length by the longest value\"</em></strong>.<br>Let's give a function the appropriate name with the following signature:</p>\n\n<pre><code>def align_col_length(fname, col_name):\n \"\"\"Align a specified column's values length by the longest value\"\"\"\n df = pd.read_csv(fname)\n ...\n</code></pre></li>\n<li><p>finding the longest string value in <code>SMILES</code> column.<br>Instead of <code>for</code> loop, since you are dealing with <code>pandas</code> which is powerful enough and allows <code>str</code> accessor on <code>pd.Series</code> objects (points to column values in our case):</p></li>\n</ul>\n\n<blockquote>\n <p><code>Series</code> and <code>Index</code> are equipped with a set of string processing\n methods that make it easy to operate on each element of the array.\n Perhaps most importantly, these methods exclude missing/NA values\n automatically. These are accessed via the <code>str</code> attribute and\n generally have names matching the equivalent (scalar) built-in string\n methods</p>\n</blockquote>\n\n<p>Thus, applying a flexible chain <code>df[col_name].str.len()</code> + <a href=\"https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.idxmax.html\" rel=\"nofollow noreferrer\"><code>pd.Series.idxmax</code></a> we would be able to get the row label/position of the maximum value.<br>Then, just easily get the column's longest value by the row position using:</p>\n\n<pre><code>longest = df.loc[df[col_name].str.len().idxmax(), col_name]\n</code></pre>\n\n<ul>\n<li><em>New</em> <code>dataframe['standard']</code> column with padded values. <br>It only remains to apply a flexible one-liner using <a href=\"https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.str.pad.html\" rel=\"nofollow noreferrer\"><code>pd.Series.str.pad</code></a> routine (to pad the <code>col_name</code> values up to width of <code>len(longest)</code>)</li>\n</ul>\n\n<hr>\n\n<p>The final optimized function now becomes a more concise and <code>pandas</code>-flavored:</p>\n\n<pre><code>import pandas as pd\n\ndef align_col_length(fname, col_name):\n \"\"\"Align a specified column's values length by the longest value\"\"\"\n df = pd.read_csv(fname)\n longest = df.loc[df[col_name].str.len().idxmax(), col_name]\n df['standard'] = df[col_name].str.pad(len(longest), side='right', fillchar='0')\n\n return df, longest\n</code></pre>\n\n<hr>\n\n<p>Testing:</p>\n\n<pre><code>df, longest = align_col_length('solubility.csv', col_name='SMILES')\n\nprint('longest SMILE value:', longest)\nprint('*' * 30) # just visual separator\nprint(df)\n</code></pre>\n\n<p>The output:</p>\n\n<pre><code>longest SMILE value: [Zn++].CC(c1ccccc1)c2cc(C(C)c3ccccc3)c(O)c(c2)C([O-])=O.CC(c4ccccc4)c5cc(C(C)c6ccccc6)c(O)c(c5)C([O-])=O\n******************************\n SMILES ... standard\n0 [Br-].CCCCCCCCCCCCCCCCCC[N+](C)(C)C ... [Br-].CCCCCCCCCCCCCCCCCC[N+](C)(C)C000000000000000000000000000000000000000000000000000000000000000000000\n1 O=C1Nc2cccc3cccc1c23 ... O=C1Nc2cccc3cccc1c23000000000000000000000000000000000000000000000000000000000000000000000000000000000000\n2 [Zn++].CC(c1ccccc1)c2cc(C(C)c3ccccc3)c(O)c(c2)C([O-])=O.CC(c4ccccc4)c5cc(C(C)c6ccccc6)c(O)c(c5)C([O-])=O ... [Zn++].CC(c1ccccc1)c2cc(C(C)c3ccccc3)c(O)c(c2)C([O-])=O.CC(c4ccccc4)c5cc(C(C)c6ccccc6)c(O)c(c5)C([O-])=O\n3 C1OC1CN(CC2CO2)c3ccc(Cc4ccc(cc4)N(CC5CO5)CC6CO6)cc3 ... C1OC1CN(CC2CO2)c3ccc(Cc4ccc(cc4)N(CC5CO5)CC6CO6)cc300000000000000000000000000000000000000000000000000000\n\n[4 rows x 3 columns]\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-31T14:11:20.373",
"Id": "231601",
"ParentId": "231576",
"Score": "2"
}
},
{
"body": "<p>Here are a few comments:</p>\n\n<ul>\n<li>In <code>pandas</code> it is customary to use <code>df</code> as a generic name for a dataframe. It is well understood and a lot shorter than <code>dataframe</code>, which is why I will use it in the rest of this answer.</li>\n<li>Use <code>_</code> only as an unused placeholder. If you want to do something with the object, give it a name. Even a single character name like <code>s</code> for a string is more meaningful than <code>_</code>.</li>\n<li>You don't need to initialize variables before using them. <code>longest = ''</code> is unneeded. </li>\n<li><p>The first for loop could be implemented using the built-in <a href=\"https://docs.python.org/3/library/functions.html#max\" rel=\"nofollow noreferrer\"><code>max</code></a> function using the <code>key</code> parameter:</p>\n\n<pre><code>longest = max(dataframe['SMILES'], key=len)`.\n</code></pre></li>\n<li><p>But <code>pandas</code> has <a href=\"https://pandas.pydata.org/pandas-docs/stable/user_guide/text.html\" rel=\"nofollow noreferrer\">vectorized string methods</a>. Instead of <code>max</code>, you can use</p>\n\n<pre><code>longest = df.SMILES[df.SMILES.str.len().idxmax()]\n</code></pre></li>\n<li><p>Instead of <code>str.join</code>ing a generator of zeros, use string multiplication:</p>\n\n<pre><code>zeros_as_str = \"0\" * (len(longest) - len(smi))\n</code></pre></li>\n<li><p>But what you really want to do is to use <a href=\"https://docs.python.org/3/library/stdtypes.html#str.ljust\" rel=\"nofollow noreferrer\"><code>str.ljust</code></a>, which is also vectorized by <code>pandas</code>. This makes the whole function a lot shorter (and probably faster, too, because the iteration does not necessarily happen in Python anymore). You also don't actually need the longest string, you just need its length:</p>\n\n<pre><code>def generate_standard():\n df = pd.read_csv('solubility.csv', usecols=['SMILES','Solubility'])\n longest = df.SMILES.str.len().max()\n df[\"standard\"] = df.SMILES.str.ljust(longest, \"0\")\n return df, longest\n</code></pre></li>\n<li><p>Python has an official style-guide, <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">PEP8</a>. It recommends using a space after a comma in a tuple, but no spaces around the <code>=</code> when using it for keyword arguments.</p></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-31T14:19:13.487",
"Id": "231604",
"ParentId": "231576",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "231601",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-31T01:51:42.580",
"Id": "231576",
"Score": "2",
"Tags": [
"python",
"strings",
"pandas"
],
"Title": "Standardizes Rows of a Pandas.DataFrame Object"
}
|
231576
|
<p>I am comparing the index of the current component displayed in the viewport against an array of all the components on the screen to determine to direction the user in scrolling.</p>
<p>Does this function have too many concerns? and can the if statements be reduced to something cleaner?</p>
<pre><code>function getDirection(component) {
let direction;
if (!this.lastComponentInViewport) {
direction = "none";
} else {
let oldIndex = this.components.indexOf(this.lastComponentInViewport);
let newIndex = this.components.indexOf(component);
if (newIndex === oldIndex) direction = "none";
if (newIndex > oldIndex) direction = "next";
if (newIndex < oldIndex) direction = "previous";
}
return direction;
}),
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-31T02:44:32.970",
"Id": "451727",
"Score": "0",
"body": "I could start with removing the outer if/else statement and combine here: `if (newIndex === oldIndex || !this.lastComponentInViewport)\n direction = \"none\";`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-31T06:07:57.297",
"Id": "451734",
"Score": "1",
"body": "Welcome to Code Review. You are welcome to answer your own question. Addressing main concerns in comments to questions is frowned upon. (Here, I suggest editing afterthoughts to the question proper.)"
}
] |
[
{
"body": "<p><strong><code>\"none\"</code></strong> can be treated as a default returned value, thus eliminating multiple occurrences of <code>direction = \"none\"</code> assignment.<br> In that way it'd be enough to just consider non-<code>none</code> cases:</p>\n\n<pre><code>function getDirection(component) {\n let oldIndex, newIndex,\n lastComp = this.lastComponentInViewport;\n\n if (lastComp) {\n oldIndex = this.components.indexOf(lastComp);\n newIndex = this.components.indexOf(component);\n if (newIndex > oldIndex) return \"next\";\n if (newIndex < oldIndex) return \"previous\";\n }\n return \"none\";\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-31T06:22:37.953",
"Id": "231583",
"ParentId": "231578",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "231583",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-31T02:42:58.593",
"Id": "231578",
"Score": "3",
"Tags": [
"javascript",
"algorithm",
"design-patterns"
],
"Title": "Calculating direction based on index of array"
}
|
231578
|
<p>This is my first C++ program (not counting "hello world") and I'd like to know if there are some semantic mistakes or if I could rewrite the code in a more simple way.</p>
<p>It performs brute-force factorisation of the number provided on standard input.</p>
<p>Here is the code:</p>
<pre><code>#include <iostream>
#include <cstdio>
using namespace std;
int main() {
int f1 = 0;
int f2 = 0;
int p;
int increment = 1;
cin >> p;
if ((f1 && f2) == p) {
cout << f1 << "x" << f2 << "=" << p;
}
else if (p < 00) {
cout << "Insert a positive number";
}
while (
( (f1 && f2) != p) && (f1 < p) && (f2 <= p) ) {
f1++;
if (f1 * f2 == p) {
cout << f1 << "x" << f2 << "=" << p << "\n";
}
f2 = increment;
if (f1 == p) {
increment++;
f1 = 0;
}
}
system("pause");
return 0;
}
</code></pre>
<p>Thanks for your feedback!</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-31T06:13:00.897",
"Id": "451735",
"Score": "1",
"body": "Welcome to Code Review. When you copy the code above into a development environment: does it compile *as is*?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-31T08:11:48.220",
"Id": "451740",
"Score": "2",
"body": "What is ``f1 && f2`` supposed to be? Please research what the ``&&`` operator does, and rethink your code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-31T13:58:19.133",
"Id": "451790",
"Score": "0",
"body": "Have you tested this code and does it work?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-31T14:03:16.773",
"Id": "451791",
"Score": "0",
"body": "@greybeard it compiles and seems to give the proper answer."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-31T15:30:42.067",
"Id": "451807",
"Score": "0",
"body": "@dumetrulo is my use of && wrong? It was supposed to be something like \"while the value stored in f1 AND f2 is not equal the value of p [...] Is this logic wrong?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-01T15:27:22.957",
"Id": "452018",
"Score": "0",
"body": "@Toriality Yes, it's incorrect. If you want to test whether both ``f1`` and ``f2`` are not equal to ``p``, you have to test it separately: ``(f1 != p) && (f2 != p)``. Together with the other conditions in that line, it can be simplified to just ``(f1 < p) && (f2 < p)``, given that when both ``f1`` and ``f2`` are less than ``p``, neither can be equal to it."
}
] |
[
{
"body": "<p>Only include the headers needed, <code>cstdio</code> is not needed for this code.</p>\n<p>The first if,</p>\n<pre><code> if ((f1 && f2) == p) {\n cout << f1 << "x" << f2 << "=" << p;\n }\n</code></pre>\n<p>is not needed.</p>\n<p>It might be better if the second if was</p>\n<pre><code> if (p <= 0) {\n cout << "Insert a positive number";\n }\n</code></pre>\n<p>It might also be better if the above code either exited the program or was within a loop that would allow the user to enter a positive number.</p>\n<h2>Avoid Using Namespace <code>std</code></h2>\n<p>If you are coding professionally you probably should get out of the habit of using the <code>using namespace std;</code> statement. The code will more clearly define where <code>cout</code> and other identifiers are coming from (<code>std::cin</code>, <code>std::cout</code>). As you start using namespaces in your code it is better to identify where each function comes from because there may be function name collisions from different namespaces. The identifier<code>cout</code> you may override within your own classes, and you may override the operator <code><<</code> in your own classes as well. This <a href=\"https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice\">stack overflow question</a> discusses this in more detail.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-31T14:25:14.430",
"Id": "231605",
"ParentId": "231579",
"Score": "2"
}
},
{
"body": "<p>Don't <code>using namespace std;</code> - this namespace isn't designed for wholesale import like that.</p>\n\n<p>Import <code><cstdlib></code> to declare <code>std::system()</code> - though note that almost any use of this function makes your code highly platform-specific (that just gives a <code>sh: pause: not found</code> error here, for example).</p>\n\n<p>Never ignore the return value from <code>std::system</code> or from streaming with <code>>></code>.</p>\n\n<p>Error messages should go to <code>std::cerr</code> and end with a newline (and we should return early in the error case, rather than continuing to the <code>while</code> loop).</p>\n\n<p><code>if ((f1 && f2) == p)</code> is a highly unconventional way of writing <code>if (p == 0)</code>. Don't make it unnecessarily hard to read.</p>\n\n<p>In the <code>while</code> condition, <code>(f1 && f2) != p)</code> can only be false when <code>p</code> is <code>1</code>, so just treat that case separately, before the loop.</p>\n\n<p>Prefer pre-increment (<code>++x</code>) to post-increment (<code>x++</code>) in C++ code when not using the result. Here, with integers, the compiler can optimize to the same code, but with more complex types, that's not always possible.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-31T18:03:50.500",
"Id": "231627",
"ParentId": "231579",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-31T02:54:11.413",
"Id": "231579",
"Score": "3",
"Tags": [
"c++",
"beginner"
],
"Title": "Identify possible pair of factors from a product"
}
|
231579
|
<p>I need to extract the dimensions (width and height) of a jpeg file for inserting in an html document. According to the <a href="http://www.faqs.org/faqs/jpeg-faq/part1/" rel="nofollow noreferrer">JPEG image compression FAQ</a>, cautions against what's commonly out there,</p>
<blockquote>
<p>Some people have recommended just searching for the byte pair
representing SOFn, without paying attention to the marker block structure.
This is unsafe because a prior marker might contain the SOFn pattern, either
by chance or because it contains a JPEG-compressed thumbnail image.</p>
</blockquote>
<p>It said to look up <a href="https://github.com/ImageMagick/jpeg-turbo/blob/master/rdjpgcom.c" rel="nofollow noreferrer">rdjpgcom.c</a>, which is part of the open-source <a href="https://imagemagick.org/" rel="nofollow noreferrer">ImageMagick</a>. It seems to agree with the <a href="https://stackoverflow.com/a/18264693">advice on this answer</a>. However, this file prints out jpeg comments, so I wrote one to specifically get the dimensions.</p>
<pre><code>#include <stdlib.h> /* EXIT */
#include <stdio.h> /* [f]printf fopen fclose fread */
#include <assert.h> /* assert */
#include <errno.h> /* errno */
/** Attempt to read the size of a jpeg.
@param[file] File that has been opened in binary mode and rewound; required.
@param[width, height] Pointers that get overwritten on success; required.
@return Success, otherwise `errno` will (probably) be set.
@license <http://www.faqs.org/faqs/jpeg-faq/part1/> said to look up
[rdjpgcom.c](https://github.com/ImageMagick/jpeg-turbo/blob/master/rdjpgcom.c),
which has
[IJG License](https://github.com/ImageMagick/jpeg-turbo/blob/master/README.ijg)
and possibly related [ImageMagick](https://imagemagick.org/script/license.php).
I used as a reference to write this function. */
static int jpeg_dim(FILE *const fp, unsigned *const width,
unsigned *const height) {
unsigned char f[8];
unsigned skip;
assert(fp && width && height);
/* The start of the file has to be an `SOI`. */
if(fread(f, 2, 1, fp) != 1) return 0;
if(f[0] != 0xFF || f[1] != 0xD8) return errno = EDOM, 0;
for( ; ; ) {
/* Discard up until the last `0xFF`, then that is the marker type. */
do { if(fread(f, 1, 1, fp) != 1) return 0; } while(f[0] != 0xFF);
do { if(fread(f, 1, 1, fp) != 1) return 0; } while(f[0] == 0xFF);
switch(f[0]) {
case 0xC0: case 0xC1: case 0xC2: case 0xC3: case 0xC5: /* _sic_ */
case 0xC6: case 0xC7: case 0xC9: /* _sic_ */ case 0xCA: case 0xCB:
case 0xCD: /* _sic_ */ case 0xCE: case 0xCF:
/* `SOF` markers. */
if(fread(f, 8, 1, fp) != 1) return 0;
if((skip = (f[0] << 8) | f[1]) != 8u + 3 * f[7])
return errno = EDOM, 0;
*width = (f[5] << 8) | f[6];
*height = (f[3] << 8) | f[4];
return 1;
case 0xD8: case 0xD9:
/* Image data `SOS, EOI` without image size. */
return errno = EDOM, 0;
default:
/* Skip the rest by reading it's size. */
if(fread(f, 2, 1, fp) != 1) return 0;
if((skip = (f[0] << 8) | f[1]) < 2) return errno = EDOM, 0;
if(fseek(fp, skip - 2, SEEK_CUR) != 0) return 0;
}
}
}
int main(int argc, char **argv) {
FILE *fp = 0;
unsigned width, height;
int success = EXIT_FAILURE;
if(argc != 2 || !(fp = fopen(argv[1], "rb"))
|| !jpeg_dim(fp, &width, &height)) goto catch;
printf("Jpeg width: %u, height: %u.\n", width, height);
success = EXIT_SUCCESS;
goto finally;
catch:
if(errno) {
perror("jpeg size");
} else {
fprintf(stderr, "Use with jpeg filename to see the size.\n");
}
finally:
if(fp) fclose(fp);
return success;
}
</code></pre>
<p>It seems to work, but I'd like to review it to make sure that it's correct.</p>
|
[] |
[
{
"body": "<p>(kind of nitpicking here, it looks quite solid to me)</p>\n\n<p><strong>Code</strong>:</p>\n\n<pre><code> /* Discard up until the last `0xFF`, then that is the marker type. */\n do { if(fread(f, 1, 1, fp) != 1) return 0; } while(f[0] != 0xFF);\n do { if(fread(f, 1, 1, fp) != 1) return 0; } while(f[0] == 0xFF);\n</code></pre>\n\n<p>While we might have extra <code>0xff</code> fill to read, I'm not sure we should be reading and discarding non-<code>0xff</code> bytes. If the data in the file doesn't follow the expected format our assumptions about the marker / chunk structure might be wrong too, which could lead to invalid results.</p>\n\n<p>Outputting the wrong size could cause more problems than returning an error, so I'd be inclined to pick the latter instead.</p>\n\n<hr>\n\n<pre><code> if((skip = (f[0] << 8) | f[1]) != 8u + 3 * f[7])\n return errno = EDOM, 0;\n</code></pre>\n\n<p>No need to set <code>skip</code> here, since we return in both branches.</p>\n\n<p>We're checking the SOF chunk length matches with the number of image components? It might be nice to have a comment or something to mention this.</p>\n\n<hr>\n\n<p>Using <code>errno</code> seems unnecessary if we return success / failure in the return value (and the only error code used <code>EDOM</code>).</p>\n\n<hr>\n\n<p><strong>Style:</strong></p>\n\n<p>Some of the compound statements seem a bit forced. e.g.</p>\n\n<p>e.g.:</p>\n\n<pre><code>if(argc != 2 || !(fp = fopen(argv[1], \"rb\"))\n || !jpeg_dim(fp, &width, &height)) goto catch;\n</code></pre>\n\n<p>If we split this up, the flow becomes much simpler, we can introduce local variables later, and we don't need multiple branches in the error handling:</p>\n\n<pre><code>int main(int argc, char **argv) {\n\n if (argc != 2) {\n fprintf(stderr, \"Use with jpeg filename to see the size.\\n\");\n return EXIT_FAILURE;\n }\n\n FILE* fp = fopen(argv[1], \"rb\"); // note: we only need this if argc was correct\n if (!fp) {\n perror(\"jpeg size\"); // note: fopen() may not set errno on non-POSIX platforms\n return EXIT_FAILURE;\n }\n\n unsigned width, height; // note: we only need these if fopen worked\n if (!jpeg_dim(fp, &width, &height))\n {\n perror(\"jpeg size\"); // note: errno isn't very helpful here... we could return an error code instead\n return EXIT_FAILURE;\n }\n\n printf(\"Jpeg width: %u, height: %u.\\n\", width, height);\n\n fclose(fp);\n\n return EXIT_SUCCESS;\n}\n</code></pre>\n\n<p>There are quite a few repeated statements in <code>jpeg_dim</code> (<code>fread</code> and stuff like <code>((f[5] << 8) | f[6]</code>). These are quite concise, but should probably still be factored into separate functions.</p>\n\n<p>I'd suggest something like a <code>jpeg_read_u8</code>, <code>jpeg_read_u16</code> and <code>jpeg_skip</code>:</p>\n\n<pre><code>static int jpeg_read_u8(FILE *const fp, unsigned char *const u8) {\n assert(u8);\n\n unsigned char b;\n if (fread(&b, 1, 1, fp) != 1)\n return 0;\n\n *u8 = b;\n return 1;\n}\n\nstatic int jpeg_read_u16(FILE *const fp, unsigned short *const u16) {\n assert(u16);\n\n unsigned char b[2];\n if (fread(&b, 1, 2, fp) != 2)\n return 0;\n\n *u16 = (b[0] << 8) | b[1];\n return 1;\n}\n\nstatic int jpeg_skip(FILE *const fp, unsigned bytes) {\n return fseek(fp, bytes, SEEK_CUR) == 0;\n}\n\nstatic int jpeg_dim(FILE *const fp, unsigned *const width, unsigned *const height) {\n assert(fp);\n assert(width && height);\n\n /* The start of the file has to be an `SOI`. */\n unsigned char soi0; if (!jpeg_read_u8(fp, &soi0) || soi0 != 0xff) return 0;\n unsigned char soi1; if (!jpeg_read_u8(fp, &soi1) || soi1 != 0xd8) return 0;\n\n for (; ; ) {\n /* Read first byte of next marker */\n unsigned char m0; if (!jpeg_read_u8(fp, &m0) || m0 != 0xff) return 0;\n /* Discard fill characters */\n unsigned char m1; do { if (!jpeg_read_u8(fp, &m1)) return 0; } while (m1 == 0xff);\n\n switch (m1) {\n case 0xC0: case 0xC1: case 0xC2: case 0xC3: case 0xC5: /* _sic_ */\n case 0xC6: case 0xC7: case 0xC9: /* _sic_ */ case 0xCA: case 0xCB:\n case 0xCD: /* _sic_ */ case 0xCE: case 0xCF: {\n /* `SOF` markers. */\n unsigned short Lf; if (!jpeg_read_u16(fp, &Lf)) return 0;\n if (!jpeg_skip(fp, 1)) return 0; /* skip Precision */\n unsigned short Y; if (!jpeg_read_u16(fp, &Y)) return 0;\n unsigned short X; if (!jpeg_read_u16(fp, &X)) return 0;\n unsigned char Nf; if (!jpeg_read_u8(fp, &Nf)) return 0;\n /* Check that the chunk length (Lf) matches the number of image components (Nf) */\n if (Lf != 8u + 3 * Nf) return 0;\n *width = X; *height = Y;\n return 1;\n }\n case 0xD8: case 0xD9:\n /* Image data `SOS, EOI` without image size. */\n return 0;\n default: {\n /* Skip the rest by reading it's size. */\n unsigned short Lf;\n if (!jpeg_read_u16(fp, &Lf) || Lf < 2) return 0;\n if (!jpeg_skip(fp, Lf - 2)) return 0;\n }\n }\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-31T21:02:17.070",
"Id": "451907",
"Score": "1",
"body": "Wrt 'discarding non-`0xff` bytes', the code in `rdjpgcom.c` issues a warning (in `next_marker`) and just keeps going until the next marker, but apparently any extra `0xFF` are legal padding. For this application, I don't care about issuing a warning, but that's worth another comment."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-01T21:38:08.773",
"Id": "452075",
"Score": "0",
"body": "The exact line in `rdjpjcom.c` is, \"There could also be non-FF garbage between markers. The treatment of such garbage is unspecified; we choose to skip over it but emit a warning msg.\""
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-31T14:45:07.173",
"Id": "231608",
"ParentId": "231580",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "231608",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-31T04:26:01.283",
"Id": "231580",
"Score": "4",
"Tags": [
"c",
"file",
"image",
"file-structure"
],
"Title": "Read JPEG dimensions properly"
}
|
231580
|
<p>I have a WPF application that uses Interop Excel and Interop MS Access instances to manage and read data and as well as to create reports. I use a class to manage these instances which is created as a singleton. </p>
<p>There are two things that concern me about this class. After a day of testing a published version of my app I find a straggler or two of MS Access or Excel left in my processes. Secondly a trivial bug causes the Access Application to flash onto the screen when it closes (this will eventually be handled by moving the Access window off screen). I'm not worried about this bug but it did reveal something about my application. After I closed my application and had moved on to some other task (a minute or 5 passes by) and this bug shows itself. This tells me that Access had waited till then to close itself up / get collected by the garbage collector. Any suggestions as to how to reduce the delay between my application closing and Access closing.</p>
<p>Also if possible I would like peoples opinion on the structure of the class and if the method <code>BreakAllConnections</code> would benefit from splitting the action of closing Excel and Access into separate threads?</p>
<p>Would the method also benefit from adding a timer which would force kill the interop instances and threads trying to close the interop instances after 1.5 seconds (I think the app has either 2 or 3 seconds to clean itself up). This would be for the cases where an instance is "frozen"/hanging/in the middle of a long execution? </p>
<p>Also if you see something else out of place pleas let me know. Managing interop instances has been a fun challenge and this is what I've come up with. </p>
<p>Lastly would you register to other events to maximize the chance that the method <code>BreakAllConnections</code> gets called when the application ceases to exist for one reason or another. </p>
<pre><code>using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Windows;
using Excel = Microsoft.Office.Interop.Excel;
using Access = Microsoft.Office.Interop.Access;
namespace Tenant_Tool_Analytics_Module.Utillity
{
public class ConnectionManager
{
[DllImport("user32.dll")]
static extern int GetWindowThreadProcessId(int hWnd, out int lpdwProcessId);
//Old Code for tying to resolve flashing access window.
//[DllImport("user32.dll", EntryPoint = "SetWindowPos")]
//public static extern IntPtr SetWindowPos(IntPtr hWnd, int hWndInsertAfter, int x, int Y, int cx, int cy, int wFlags);
public static readonly ConnectionManager instance = new ConnectionManager();
private ConnectionManager()
{
Console.WriteLine("Connection Manager Started");
AppDomain.CurrentDomain.ProcessExit += new EventHandler(OnProcessExit);
AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(OnProcessExit);
}
void OnProcessExit(object sender, EventArgs e)
{
BreakAllConnections();
}
private Excel.Application _excelApp;
public Excel.Application excelApp
{
get
{
if (_excelApp == null)
{
try
{
_excelApp = new Excel.Application();
}
catch
{
//TODO Move message box to parents
MessageBox.Show("Abort Error: Could not open Excel Application");
}
}
return _excelApp;
}
}
private Access.Application _accessApp;
public Access.Application accessApp
{
get
{
if (_accessApp == null)
{
try
{
//MessageBox.Show($"OS: {EnvironmentFunctions.is64BitOperatingSystem} Process: {EnvironmentFunctions.is64BitProcess}");
if (EnvironmentFunctions.is64BitOperatingSystem && !EnvironmentFunctions.is64BitProcess)
{
string PathValue = "";
string sAdd = "";
string strCommonFiles =
System.Environment.GetEnvironmentVariable("CommonProgramFiles(x86)");
sAdd = ";" + strCommonFiles + "\\microsoft shared\\DAO";
PathValue = System.Environment.GetEnvironmentVariable("Path");
PathValue += sAdd;
Environment.SetEnvironmentVariable("path", PathValue);
}
_accessApp = new Access.Application();
}
catch
{
MessageBox.Show("Termination Error: Could not open Access Application");
Environment.Exit(110);
}
}
return _accessApp;
}
}
public void BreakAllConnections()
{
try
{
if (_excelApp != null) {
foreach (Excel.Workbook wb in _excelApp.Workbooks)
{
wb.Close(0);
Marshal.ReleaseComObject(wb);
}
_excelApp.Quit(); Marshal.ReleaseComObject(_excelApp); _excelApp = null; }
}
catch
{
GetWindowThreadProcessId(_excelApp.Hwnd, out int id);
Process.GetProcessById(id).Kill();
}
try
{
if (_accessApp != null)
{
_accessApp.CloseCurrentDatabase();
_accessApp.Quit();
Marshal.ReleaseComObject(_accessApp);
_accessApp = null;
}
}
catch
{
GetWindowThreadProcessId(_accessApp.hWndAccessApp(), out int id);
Process.GetProcessById(id).Kill();
}
}
}
}
</code></pre>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-31T04:31:56.333",
"Id": "231581",
"Score": "1",
"Tags": [
"c#",
"child-process"
],
"Title": "Class Managing Interop Instances"
}
|
231581
|
<p>I have a <strong>team lead</strong> that used to write references in a single script then access it in every script. Like for accessing a variable he has to write code in this way <code>staticRef.scpRefGui.CLDropDown_Ref.Dropdown_ref.value</code></p>
<p>And sometime I see this kind of function calling <code>staticRef.scpRefGui.CQAScrollViewPOI_Ref.ShowExcelObjsInScrollView(username,WS_EnumClass.POIYaInfo.POI, list);</code> </p>
<p>Here is another example, this code is getting a key from references file:</p>
<pre><code> public void testDict() {
if (scpRef.AutoQADict_Ref.DictQA.ContainsKey(SheetNameDict))
{
if (scpRef.AutoQADict_Ref.DictQA[SheetNameDict].ContainsKey(UsernameDict))
{
if (scpRef.AutoQADict_Ref.DictQA[SheetNameDict][UsernameDict].ContainsKey(ObjName)) {
Debug.Log("dict: " + scpRef.AutoQADict_Ref.DictQA[SheetNameDict][UsernameDict][ObjName]);
}
else {
Debug.Log("ObjName: " + ObjName + " Not Found");
}
}
else {
Debug.Log("UsernameDict: " + UsernameDict + " Not Found");
}
}
else {
Debug.Log("SheetNameDict Key: " + SheetNameDict + " Not Found");
}
}
</code></pre>
<p>I have <strong>strong disagreement</strong> of this way of coding. As it is unclear, contains several references, against SOLID, hard to debug etc (maybe I am wrong thats why i posted here). Please help me that this is a valid approach? You(this site) have reviewed so many codes! Seriously bad code design kills you, and i am killing myself after seeing/updating this kind of code.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-31T12:48:51.143",
"Id": "451778",
"Score": "3",
"body": "Everything about that code is bad. It doesn't follow the usual naming standards for one, it uses words like \"ref\" and \"static\" and \"dict\" in their names, and it doesn't use [`TryGetValue()`](https://docs.microsoft.com/en-us/dotnet/api/system.collections.generic.dictionary-2.trygetvalue). And using nested dictionaries -- why not write proper classes with properties etc.? Where did this team lead even pick up these spectacularly bad habits?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-31T12:49:58.507",
"Id": "451779",
"Score": "0",
"body": "I guess self coined!"
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-31T05:43:39.573",
"Id": "231582",
"Score": "2",
"Tags": [
"c#",
"design-patterns",
"unity3d",
"reference"
],
"Title": "Access a variable after several references"
}
|
231582
|
<p>I made a program to attempt to find all palindromes in the danish language. Words.txt contains about 50.000 lines of danish words. Palindromes.txt is empty initially.</p>
<p>Im running the program on a Intel® Core™ m3-7Y30 Processor - which has a base frequency of 1.00 GHz. Seeing as the program - as it currently stands - has to check 50.000 * 50.000 = 2.500.000.000 words, it is really slow. Ive been running it for about 25 minutes now without a result (unsuprisingly). I am fairly new to C++, and so I have no idea how to optimize this.</p>
<p>Thats why im posting here - any tips on how to optimize the speed of the program would be greatly appreciated!</p>
<pre><code>#include <string>
#include <fstream>
#include <iostream>
#include <vector>
#include <sstream>
#include <algorithm>
#include <chrono>
std::string read_file(const std::string& path)
{
std::ifstream file(path);
if (!file.is_open())
{
std::cerr << "Couldent open file!" << std::endl;
}
std::string content = std::string(std::istreambuf_iterator<char>(file), std::istreambuf_iterator<char>());
if (content.empty())
{
std::cerr << "Couldent read file content" << std::endl;
}
return content;
}
std::vector<std::string> split_words(const std::string& words_string)
{
std::vector<std::string> words;
words.reserve(50000);
std::stringstream ss_word(words_string);
std::string word;
while (!ss_word.eof())
{
ss_word >> word;
words.push_back(word);
}
return words;
}
std::vector<std::string> find_palinedromes(const std::vector<std::string>& words)
{
std::vector<std::string> palindromes;
std::string first_word = std::string();
std::string second_word = std::string();
for (int i = 0; i < words.size(); ++i)
{
for (int j = 0; j < words.size(); ++j)
{
first_word = words[i];
second_word = words[j];
std::reverse(first_word.begin(), first_word.end());
if (first_word == second_word)
{
if (std::find(palindromes.begin(), palindromes.end(), first_word) == palindromes.end())
{
palindromes.push_back(first_word);
}
}
}
}
return palindromes;
}
void write_to_file(const std::string& path, const std::vector<std::string>& words)
{
std::ofstream file(path);
if (!file.is_open())
{
std::cerr << "Couldent open file!" << std::endl;
}
for (const std::string& word : words)
{
file << word + "\n";
}
}
int main()
{
auto start = std::chrono::high_resolution_clock::now();
std::string words_string = read_file("C:/Users/A/source/repos/Bresenhams/Bresenhams/src/Words.txt");
std::vector<std::string> words = split_words(words_string);
std::vector<std::string> palindromes = find_palinedromes(words);
write_to_file("C:/Users/A/source/repos/Bresenhams/Bresenhams/src/Palindromes.txt", palindromes);
auto stop = std::chrono::high_resolution_clock::now();
auto duration = std::chrono::duration_cast<std::chrono::seconds>(stop - start);
std::cout << "Found all palindromes in: " << duration.count() << std::endl;
return 0;
}
</code></pre>
|
[] |
[
{
"body": "<p>You are doing a double loop checking against all other words to determine if something is a palindrome. This is unnecessary. You can look at a single word and determine if it is a palindrome, by reversing it. This should reduce the number of checks by a factor of n.</p>\n\n<p>You should also prefer using a range for to a raw for-loop. </p>\n\n<p>find_palindromes can then become something like this:</p>\n\n<pre><code>std::vector<std::string> find_palindromes(const std::vector<std::string>& words)\n{\n for (const std::string& word : words )\n {\n std::string reverseWord(word);\n std::reverse(reverseWord.begin(), reverseWord.end());\n\n if (word == reverseWord)\n {\n if (std::find(palindromes.begin(), palindromes.end(), first_word) == palindromes.end())\n {\n palindromes.push_back(first_word);\n }\n }\n }\n\n return palindromes;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-31T15:15:43.753",
"Id": "451803",
"Score": "0",
"body": "Waw, no idea why I thought I needed two words.. This is optimal, thank you!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-31T14:12:05.657",
"Id": "231602",
"ParentId": "231586",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "231602",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-31T06:58:50.080",
"Id": "231586",
"Score": "2",
"Tags": [
"c++",
"performance",
"vectors"
],
"Title": "Find all palindromes in the danish language"
}
|
231586
|
<p>Below are two ways to calculate an element of the Fibonacci series. Can someone please help me understand why <code>fib1</code> is so much faster (over 60x) than <code>fib2</code> ?</p>
<p><code>fib2</code> is just an assignment and a decrement whereas <code>fib1</code> involves a dictionary and recursive calls.</p>
<p>Thanks.</p>
<pre><code>import timeit
def fib1(n, lookup=dict()):
if n == 0 or n == 1:
lookup[n] = n
elif n not in lookup:
lookup[n] = fib1(n - 1, lookup) + fib1(n - 2, lookup)
return lookup[n]
def fib2(n):
n1, n2 = 0, 1
while n > 1:
n -= 1
n1, n2 = n2, n1 + n2
return n2
n = 1000
recursive = timeit.timeit(lambda: fib1(984), number=n)
iterative = timeit.timeit(lambda: fib2(984), number=n)
print("recursive:", recursive)
print("iterative:", iterative)
"""
output:
recursive: 0.0012962640030309558
iterative: 0.08570116000191774
"""
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-31T08:33:53.110",
"Id": "451742",
"Score": "7",
"body": "`fib1` shares its cache between the 1000 calls from `timeit`; `fib2` doesn't get to reuse anything between its 1000 calls. But \"Help me understand my own code\" isn't really \"code review\"."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-31T08:49:09.207",
"Id": "451746",
"Score": "1",
"body": "To complement Peter's answer, see [this article](https://docs.python-guide.org/writing/gotchas/). Your `lookup` dictionary is acting as a mutable default argument."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-31T08:51:43.467",
"Id": "451747",
"Score": "0",
"body": "If I were being truly pedantic the correct thing to do would have been to just post the last sentence of my earlier comment, so as not to encourage off-topic questions."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-31T09:38:54.323",
"Id": "451752",
"Score": "0",
"body": "I made a similar sort of mistake at work recently. We're always taught to profile a bunch of times to take an average, but that can mask if one run (say, the first run) is massively slower than the rest because a bunch of work from the first run is being cached. Peter and JAD explain why, that's happening. If you change n to 1, you'll see the actual runtime performance is what you'd expect: the loop is much faster. As to which measurement you care about, it depends on your use case. If your code needs to calculate fib once, use fib2. If it needes to call it repeatedly, perhaps use fib1."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-31T09:40:17.053",
"Id": "451753",
"Score": "0",
"body": "It may be informative to put a `print(n)` statement at the start of fib1."
}
] |
[
{
"body": "<p>The key difference is in a technic called \"memoization\". According to <a href=\"https://en.wikipedia.org/wiki/Memoization\" rel=\"nofollow noreferrer\">Wikipedia</a>:\n<em>In computing, memoization or memoisation is an optimization technique used primarily to speed up computer programs by storing the results of expensive function calls and returning the cached result when the same inputs occur again.</em>\nSo basically, in the first function, you save all the previous results while on the second function you need to calculate everything again from the beginning for every new call.\nA quick search on the internet gives this <a href=\"https://www.python-course.eu/python3_memoization.php\" rel=\"nofollow noreferrer\">tutorial</a> if you wish to learn more.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-31T08:52:07.180",
"Id": "231590",
"ParentId": "231588",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "231590",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-31T08:23:38.803",
"Id": "231588",
"Score": "0",
"Tags": [
"python",
"performance",
"python-3.x",
"recursion",
"fibonacci-sequence"
],
"Title": "Fibonnaci sequence calculation"
}
|
231588
|
<p>The original question is as follows:</p>
<blockquote>
<p>Consider the leftmost and righmost appearances of some value in an array. We'll say that the "span" is the number of elements between the two inclusive. A single value has a span of 1. Returns the largest span found in the given array. (Efficiency is not a priority.)</p>
<p>maxSpan([1, 2, 1, 1, 3]) → 4 <br>
maxSpan([1, 4, 2, 1, 4, 1, 4]) → 6 <br>
maxSpan([1, 4, 2, 1, 4, 4, 4]) → 6 <br></p>
</blockquote>
<p>Here is my implementation of the maxSpan function.</p>
<pre><code>public int maxSpan(int[] nums) {
Map<Integer, List<Integer>> spans = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
if (!spans.containsKey(nums[i])) {
List<Integer> position = new ArrayList<>();
position.add(i);
spans.put(nums[i], position);
} else {
List<Integer> position = spans.get(nums[i]);
position.add(i);
}
}
int globalMaxSpan = 0; // empty set has maxSpan = 0
for (List<Integer> value : spans.values()) { //iterating over values only
int localMaxSpan = 0;
if (value.size() > 1) {
localMaxSpan = value.get(value.size() - 1) - value.get(0) + 1;
} else localMaxSpan = 1;
if (localMaxSpan > globalMaxSpan)
globalMaxSpan = localMaxSpan;
}
return globalMaxSpan;
}
</code></pre>
<p>Here is another implementation of the same algorithm I found on GitHub implemented by others.</p>
<pre><code>public int maxSpan(int[] nums) {
int max = 0;
for(int i = 0; i < nums.length; i++) {
int j = nums.length - 1;
while(nums[i] != nums[j])
j--;
int span = j - i + 1;
if(span > max)
max = span;
}
return max;
}
</code></pre>
<p>Although my implementation is O(n) runtime but it is more complicated than the below implementation. Please give comments to my code in different aspects. Thanks.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-31T11:25:33.620",
"Id": "451765",
"Score": "0",
"body": "Please include the specification that you are implementing. I.e. what does maxSpan mean?"
}
] |
[
{
"body": "<p>Some minor modifications can be applied to your code to improve readibility, your first part of code is this:</p>\n\n<blockquote>\n<pre><code>Map<Integer, List<Integer>> spans = new HashMap<>();\nfor (int i = 0; i < nums.length; i++) {\n if (!spans.containsKey(nums[i])) {\n List<Integer> position = new ArrayList<>();\n position.add(i);\n spans.put(nums[i], position);\n } else {\n List<Integer> position = spans.get(nums[i]);\n position.add(i);\n }\n}\n</code></pre>\n</blockquote>\n\n<p>You can use a ternary operator and aggregate operations executed in both branchs of <code>if else</code> like below:</p>\n\n<pre><code>Map<Integer, List<Integer>> spans = new HashMap<>();\nfinal int n = nums.length;\nfor (int i = 0; i < n; ++i) {\n boolean condition = spans.containsKey(nums[i]);\n List<Integer> position = condition ? spans.get(nums[i]) : new ArrayList<>();\n position.add(i);\n spans.put(nums[i], position);\n}\n</code></pre>\n\n<p>Same suggestions for the second part of your code:</p>\n\n<blockquote>\n<pre><code>int globalMaxSpan = 0; // empty set has maxSpan = 0\nfor (List<Integer> value : spans.values()) { //iterating over values only\n int localMaxSpan = 0;\n if (value.size() > 1) {\n localMaxSpan = value.get(value.size() - 1) - value.get(0) + 1;\n } else localMaxSpan = 1;\n if (localMaxSpan > globalMaxSpan)\n globalMaxSpan = localMaxSpan;\n}\nreturn globalMaxSpan;\n</code></pre>\n</blockquote>\n\n<p>You can write a more concise code like this below using again a ternary operator because you already know every list has at least one element:</p>\n\n<pre><code>int globalMaxSpan = 0;\n\nfor (List<Integer> value : spans.values()) {\n final int size = value.size();\n int localMaxSpan = size > 1 ? value.get(size - 1) - value.get(0) + 1 : 1;\n globalMaxSpan = Math.max(globalMaxSpan,localMaxSpan);\n}\n\nreturn globalMaxSpan;\n</code></pre>\n\n<p>It is possible to write a more complex version of this part of code to avoid calls <code>max</code> operations (I made it) when lists contains exactly one value, but the version is not concise like this and so I won't post it.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-31T18:29:20.030",
"Id": "231629",
"ParentId": "231589",
"Score": "1"
}
},
{
"body": "<p>Your choice of data structures is unnecessarily heavy. You're interested only in the first and last index of a number, so store only those in a lightweight data structure of two integers (an array):</p>\n\n<pre><code>for (int i = 0; i < nums.length; i++) {\n final int num = nums[i];\n int[] span = spans.get(num);\n if (span == null) {\n span = new int[] { i, i };\n spans.put(num, span);\n } else {\n span[1] = i;\n }\n}\n</code></pre>\n\n<p>Java comes with built in functions for selecting larger or smaller number from two, so use them instead of if-statements or ternary operations. It makes code easier to read.</p>\n\n<pre><code>// Empty set has maxSpan = 0\nint maxSpan = 0;\nfor (int[] span: spans.values()) {\n maxSpan = Math.max(maxSpan, span[1] - span[0] + 1);\n}\nreturn maxSpan;\n</code></pre>\n\n<p>Avoid end-of-line comments. They make the code messy and are a pain in the ass to maintain. Avoid unnecessary comments that describe <em>what</em> code does. The reader can already see that the code iterates over values. Instead document <em>why</em> the code does what it does.</p>\n\n<p>Use variable names that describe what the variable is used for. <code>Value</code> does not give any new information to the reader about what it contains.</p>\n\n<p><code>Position</code> as a name for a list is deceptive. It's singular form suggests that it contains one value when it instead contains all positions of a certain number.</p>\n\n<p>Edit: You don't actually even need to store the last occurrence of a number. Just store the first one and calculate the maxSpan as you traverse the array the first time.</p>\n\n<pre><code>int maxSpan = 0;\nfor (int i = 0; i < nums.length; i++) {\n final int num = nums[i];\n Integer firstIndex = firstIndexes.get(num);\n if (firstIndex == null) {\n firstIndex = i;\n firstIndexes.put(num, firstIndex);\n }\n maxSpan = Math.max(maxSpan, i - firstIndex + 1);\n}\nreturn maxSpan;\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-02T09:52:07.000",
"Id": "452102",
"Score": "0",
"body": "Thanks for your comment. Yes, you are right we don't need an extra loop for calculating maxSpan."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-01T08:05:51.373",
"Id": "231656",
"ParentId": "231589",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-31T08:51:35.263",
"Id": "231589",
"Score": "3",
"Tags": [
"java"
],
"Title": "maxSpan function implementation"
}
|
231589
|
<p>I want to create a very simple banking application where (i) predefined accounts with a positive balance can send money (ii) requesting balance and a list of transactions can be found. </p>
<p>I have created API for those operations. All the operations are persisted into the database. I also wrote test cases to verify. </p>
<p>I always try to learn from different sources and use the best practices related to project structure and clean code. It would be great if somebody gives me suggestions and ideas about what improvement I can make on the codes. </p>
<p>Here is my project structure: </p>
<pre><code>
├── pom.xml
├── src
│ ├── main
│ │ ├── java
│ │ │ └── com
│ │ │ └── forhadmethun
│ │ │ └── banking
│ │ │ ├── BankingApplication.java
│ │ │ ├── config
│ │ │ │ └── documentation
│ │ │ │ └── DocumentationConfig.java
│ │ │ ├── controller
│ │ │ │ ├── api
│ │ │ │ │ └── AccountController.java
│ │ │ │ └── request
│ │ │ │ ├── AccountStatementRequest.java
│ │ │ │ └── TransferBalanceRequest.java
│ │ │ ├── dto
│ │ │ │ ├── model
│ │ │ │ │ └── AccountStatement.java
│ │ │ │ └── response
│ │ │ │ ├── ResponseError.java
│ │ │ │ └── Response.java
│ │ │ ├── entity
│ │ │ │ ├── Account.java
│ │ │ │ └── Transaction.java
│ │ │ ├── repository
│ │ │ │ ├── AccountRepository.java
│ │ │ │ └── TransactionRepository.java
│ │ │ └── service
│ │ │ ├── AccountService.java
│ │ │ └── impl
│ │ │ └── AccountServiceImpl.java
│ │ └── resources
│ │ ├── application.properties
│ │ ├── static
│ │ └── templates
│ └── test
│ └── java
│ └── com
│ └── forhadmethun
│ └── banking
│ └── service
│ └── impl
│ └── AccountServiceImplTest.java
</code></pre>
<p>AccountController.java</p>
<pre><code>@RestController
@RequestMapping("/api/account")
public class AccountController {
@Autowired private AccountService accountService;
@RequestMapping("/create")
public List<Account> create(@RequestBody Account account) {
accountService.save(account);
return accountService.findAll();
}
@RequestMapping("/all")
public List<Account> all() {
return accountService.findAll();
}
@RequestMapping("/sendmoney")
public Response sendMoney(
@RequestBody TransferBalanceRequest transferBalanceRequest
) {
return Response.ok().setPayload(
accountService.sendMoney(
transferBalanceRequest
)
);
}
@RequestMapping("/statement")
public Response getStatement(
@RequestBody AccountStatementRequest accountStatementRequest
){
return Response.ok().setPayload(
accountService.getStatement(accountStatementRequest.getAccountNumber())
);
}
}
</code></pre>
<p>AccountStatementRequest.java</p>
<pre><code>@Getter
@Setter
@NoArgsConstructor
public class AccountStatementRequest {
private String accountNumber;
}
</code></pre>
<p>TransferBalanceRequest.java</p>
<pre><code>@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
public class TransferBalanceRequest {
private String fromAccountNumber;
private String toAccountNumber;
private BigDecimal amount;
}
</code></pre>
<p>AccountStatement.java</p>
<pre><code>@AllArgsConstructor
@NoArgsConstructor
@Data
public class AccountStatement {
BigDecimal currentBalance;
List<Transaction> transactionHistory;
}
</code></pre>
<p>Response.java</p>
<pre><code>package com.forhadmethun.banking.dto.response;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonInclude;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.experimental.Accessors;
import java.util.Date;
@Getter
@Setter
@Accessors(chain = true)
@NoArgsConstructor
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonIgnoreProperties(ignoreUnknown = true)
public class Response<T> {
private Status status;
private T payload;
private Object errors;
private Object metadata;
public static <T> Response<T> badRequest() {
Response<T> response = new Response<>();
response.setStatus(Status.BAD_REQUEST);
return response;
}
public static <T> Response<T> ok() {
Response<T> response = new Response<>();
response.setStatus(Status.OK);
return response;
}
public static <T> Response<T> unauthorized() {
Response<T> response = new Response<>();
response.setStatus(Status.UNAUTHORIZED);
return response;
}
public static <T> Response<T> validationException() {
Response<T> response = new Response<>();
response.setStatus(Status.VALIDATION_EXCEPTION);
return response;
}
public static <T> Response<T> wrongCredentials() {
Response<T> response = new Response<>();
response.setStatus(Status.WRONG_CREDENTIALS);
return response;
}
public static <T> Response<T> accessDenied() {
Response<T> response = new Response<>();
response.setStatus(Status.ACCESS_DENIED);
return response;
}
public static <T> Response<T> exception() {
Response<T> response = new Response<>();
response.setStatus(Status.EXCEPTION);
return response;
}
public static <T> Response<T> notFound() {
Response<T> response = new Response<>();
response.setStatus(Status.NOT_FOUND);
return response;
}
public static <T> Response<T> duplicateEntity() {
Response<T> response = new Response<>();
response.setStatus(Status.DUPLICATE_ENTITY);
return response;
}
public void addErrorMsgToResponse(String errorMsg, Exception ex) {
ResponseError error = new ResponseError()
.setDetails(errorMsg)
.setMessage(ex.getMessage())
.setTimestamp(new Date());
setErrors(error);
}
public enum Status {
OK, BAD_REQUEST, UNAUTHORIZED, VALIDATION_EXCEPTION, EXCEPTION, WRONG_CREDENTIALS, ACCESS_DENIED, NOT_FOUND, DUPLICATE_ENTITY
}
@Getter
@Accessors(chain = true)
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonIgnoreProperties(ignoreUnknown = true)
public static class PageMetadata {
private int size;
private long totalElements;
private int totalPages;
private int number;
public PageMetadata(int size, long totalElements, int totalPages, int number) {
this.size = size;
this.totalElements = totalElements;
this.totalPages = totalPages;
this.number = number;
}
}
}
</code></pre>
<p>ResponseError.java</p>
<pre><code>@Getter
@Setter
@Accessors(chain = true)
@NoArgsConstructor
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonIgnoreProperties(ignoreUnknown = true)
public class ResponseError {
private Date timestamp;
private String message;
private String details;
}
</code></pre>
<p>Account.java</p>
<pre><code>@Builder
@AllArgsConstructor
@NoArgsConstructor
@Data
@Entity
@Table(name = "account")
public class Account {
@Id
@GeneratedValue
private Long accountId;
String accountNumber;
BigDecimal currentBalance;
}
</code></pre>
<p>Transaction.java</p>
<pre><code>@NoArgsConstructor
@AllArgsConstructor
@Data
@Entity
@Table(name = "transaction")
public class Transaction {
@Id
@GeneratedValue
private Long transactionId;
private String accountNumber;
private BigDecimal transactionAmount;
private Timestamp transactionDateTime;
}
</code></pre>
<p>AccountRepository.java</p>
<pre><code>@Repository
public interface AccountRepository extends JpaRepository<Account, Long> {
Account findByAccountNumberEquals(String accountNumber);
}
</code></pre>
<p>TransactionRepository.java</p>
<pre><code>@Repository
public interface TransactionRepository extends JpaRepository<Transaction, Long> {
List<Transaction> findByAccountNumberEquals(String accountNumber);
}
</code></pre>
<p>AccountService.java</p>
<pre><code>public interface AccountService {
List<Account> findAll();
Account save(Account account);
Transaction sendMoney(
TransferBalanceRequest transferBalanceRequest
);
AccountStatement getStatement(String accountNumber);
}
</code></pre>
<p>AccountServiceImpl.java</p>
<pre><code>@Service
public class AccountServiceImpl implements AccountService {
@Autowired
private AccountRepository accountRepository;
@Autowired
TransactionRepository transactionRepository;
public Account save(Account account){
accountRepository.save(account);
return accountRepository.findByAccountNumberEquals(account.getAccountNumber());
}
public List<Account> findAll(){
return accountRepository.findAll();
}
public Account findByAccountNumber(String accountNumber){
Account account = accountRepository.findByAccountNumberEquals(accountNumber);
return account;
}
@Override
public Transaction sendMoney(
TransferBalanceRequest transferBalanceRequest
) {
String fromAccountNumber = transferBalanceRequest.getFromAccountNumber();
String toAccountNumber = transferBalanceRequest.getToAccountNumber();
BigDecimal amount = transferBalanceRequest.getAmount();
Account fromAccount = accountRepository.findByAccountNumberEquals(
fromAccountNumber
);
Account toAccount = accountRepository.findByAccountNumberEquals(toAccountNumber);
if(fromAccount.getCurrentBalance().compareTo(BigDecimal.ONE) == 1
&& fromAccount.getCurrentBalance().compareTo(amount) == 1
){
fromAccount.setCurrentBalance(fromAccount.getCurrentBalance().subtract(amount));
accountRepository.save(fromAccount);
toAccount.setCurrentBalance(toAccount.getCurrentBalance().add(amount));
accountRepository.save(toAccount);
Transaction transaction = transactionRepository.save(new Transaction(0L,fromAccountNumber,amount,new Timestamp(System.currentTimeMillis())));
return transaction;
}
return null;
}
@Override
public AccountStatement getStatement(String accountNumber) {
Account account = accountRepository.findByAccountNumberEquals(accountNumber);
return new AccountStatement(account.getCurrentBalance(),transactionRepository.findByAccountNumberEquals(accountNumber));
}
</code></pre>
<p>AccountServiceImplTest.java</p>
<pre><code>@RunWith(SpringRunner.class)
@DataJpaTest
public class AccountServiceImplTest {
@TestConfiguration
static class AccountServiceTestContextConfiguration {
@Bean
public AccountServiceImpl accountServiceImplTest() {
return new AccountServiceImpl();
}
}
@Autowired
private AccountServiceImpl accountService;
@Test
public void sendMoneyTest() {
Account account1 = new Account(0L, "1001", new BigDecimal(50000));
Account account2 = new Account(0L, "2002", new BigDecimal(2000));
accountService.save(account1);
accountService.save(account2);
TransferBalanceRequest transferBalanceRequest =
new TransferBalanceRequest(
account1.getAccountNumber(),
account2.getAccountNumber(),
new BigDecimal(3000)
);
accountService.sendMoney(transferBalanceRequest);
assertThat(accountService.findByAccountNumber(account1.getAccountNumber())
.getCurrentBalance())
.isEqualTo(new BigDecimal(47000));
assertThat(accountService.findByAccountNumber(account2.getAccountNumber())
.getCurrentBalance())
.isEqualTo(new BigDecimal(5000));
}
@Test
public void getStatement() {
Account account1 = new Account(0L, "1001", new BigDecimal(50000));
Account account2 = new Account(0L, "2002", new BigDecimal(2000));
accountService.save(account1);
accountService.save(account2);
TransferBalanceRequest transferBalanceRequest =
new TransferBalanceRequest(
account1.getAccountNumber(),
account2.getAccountNumber(),
new BigDecimal(3000)
);
accountService.sendMoney(transferBalanceRequest);
assertThat(accountService.getStatement(account1.getAccountNumber())
.getCurrentBalance())
.isEqualTo(new BigDecimal(47000));
accountService.sendMoney(transferBalanceRequest);
assertThat(accountService.getStatement(account1.getAccountNumber())
.getCurrentBalance()).isEqualTo(new BigDecimal(44000));
assertThat(accountService.getStatement(account1.getAccountNumber())
.getTransactionHistory().size()).isEqualTo(2);
}
}
<span class="math-container">```</span>
</code></pre>
|
[] |
[
{
"body": "<p>Your implementation is good. I would suggest following points to improve:</p>\n\n<ul>\n<li><p>Use <code>@GetMapping</code>, <code>@PostMapping</code> and the others instead of <code>@RequestMapping</code>. It gives the other developers clear description of what method is used.</p></li>\n<li><p>It would be nice to add media types (<code>consumes=\"...\"</code>, <code>produces=\"...\"</code>)</p></li>\n<li><p>I would make <code>AccountController.accountService</code> field <code>final</code> and add as constructor param. It shows that <code>AccountController</code> can't exists without <code>AccountService</code>. In other words you don't have a way create a inconsistent instance of AccountService (in application context or tests). </p></li>\n<li><p>Do not return all accounts on account creation (<code>AccountController</code>). Usually we return new account with filled ID.</p></li>\n<li><p>Use generics in Response<...></p></li>\n<li><p>I think you could use <code>org.springframework.http.ResponseEntity</code> instead of your <code>Response</code></p></li>\n<li><p>If <code>AccountStatementRequest</code> can't exists without <code>accountNumber</code> make the field final. (the same for <code>TransferBalanceRequest</code> and <code>AccountStatement</code>)</p></li>\n<li><p>It would be nice to annotate <code>AccountServiceImpl</code> (or it<code>s methods at leaset</code>sendMoney<code>)</code>@Transactional`. It should be done in single transaction I guess.</p></li>\n<li><p>I would move <code>dto.response</code> classes to <code>controller.response</code> and <code>dto.model</code> to <code>dto</code></p></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-20T22:37:08.477",
"Id": "454565",
"Score": "0",
"body": "many many thanks for the suggestions ^_^ :)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-06T13:37:45.680",
"Id": "231954",
"ParentId": "231594",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-31T12:38:41.373",
"Id": "231594",
"Score": "4",
"Tags": [
"java",
"rest",
"spring",
"spring-mvc",
"jpa"
],
"Title": "Simple Banking application in Spring boot, JPA, REST where balance can be transferred among predefined accounts and transaction history retrievable"
}
|
231594
|
<p>I'm trying to create a way to clock in and clock out at work using python and tkinter. There are several features to be implemented. </p>
<ul>
<li>Change the Employee Name</li>
<li>Clock In button</li>
<li>Clock Out button </li>
<li>Export file with the information </li>
</ul>
<p>I have all the components and they work when I run the different features individually. When I try to combine to one script, the program fails. </p>
<pre><code>import tkinter as tk
import time
class StopWatch(Frame):
""" Implements a stop watch frame widget. """
def __init__(self, parent=None, **kw):
Frame.__init__(self, parent, kw)
self._start = 0.0
self._elapsedtime = 0.0
self._running = 0
self.timestr = StringVar()
self.makeWidgets()
def makeWidgets(self):
""" Make the time label. """
l = Label(self, textvariable=self.timestr)
self._setTime(self._elapsedtime)
l.pack(fill=X, expand=NO, pady=2, padx=2)
def _update(self):
""" Update the label with elapsed time. """
self._elapsedtime = time.time() - self._start
self._setTime(self._elapsedtime)
self._timer = self.after(50, self._update)
def _setTime(self, elap):
""" Set the time string to Minutes:Seconds:Hundreths """
minutes = int(elap/60)
seconds = int(elap - minutes*60.0)
hseconds = int((elap - minutes*60.0 - seconds)*100)
self.timestr.set('%02d:%02d:%02d' % (minutes, seconds, hseconds))
def Start(self):
""" Start the stopwatch, ignore if running. """
if not self._running:
self._start = time.time() - self._elapsedtime
self._update()
self._running = 1
def Stop(self):
""" Stop the stopwatch, ignore if stopped. """
if self._running:
self.after_cancel(self._timer)
self._elapsedtime = time.time() - self._start
self._setTime(self._elapsedtime)
self._running = 0
def Reset(self):
""" Reset the stopwatch. """
self._start = time.time()
self._elapsedtime = 0.0
self._setTime(self._elapsedtime)
def clock_in(self):
global e1
data = e1.get()
ClockIn_time = datetime.datetime.now()
ClockIn_date = datetime.datetime.now().strftime('%Y-%m-%d')
totalinput = [ data, ClockIn_time, ClockIn_date]
with open(r"C:\Users\Desktop\ClockIn.csv", "a") as savedb:
w = csv.writer(savedb)
w.writerow(totalinput)
def clock_out(self):
global e1
data = e1.get()
ClockOut_time = datetime.datetime.now()
ClockOut_date = datetime.datetime.now().strftime('%Y-%m-%d')
totalinput = [ data, ClockOut_time , ClockOut_date ]
with open(r"C:\Users\Desktop\ClockIn.csv", "a") as savedb:
w = csv.writer(savedb)
w.writerow(totalinput)
def main():
root = Tk()
sw = StopWatch(root)
sw.pack(side=TOP)
root.geometry("400x400")
####
label = tk.Label(root, text="Employee Name: ")
label.pack(side="top")
new = StringVar()
e1 = Entry(root, textvariable=new)
e1.pack()
#######
Button(root, text='Clock In', command=lambda :[sw.Start(), sw.clock_in()]).pack(side=LEFT)
Button(root, text='Clock Out', command=lambda :[sw.Start(), sw.clock_out()]).pack(side=LEFT)
Button(root, text='Reset', command=sw.Reset).pack(side=LEFT)
Button(root, text='Quit', command=root.quit).pack(side=LEFT)
root.mainloop()
if __name__ == '__main__':
main()
</code></pre>
<p>I'm having trouble <code>get()</code> the employees name and saving to a file. I've created a stand alone tkinter app, I'm able to do this, when I implement multiple features I cannot get them all to marinate. </p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-31T14:37:35.583",
"Id": "451798",
"Score": "3",
"body": "*When I try to combine to one script, the program fails.* - it's a question about different program **state**, but not about the quality of a working program"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-31T15:35:07.507",
"Id": "451809",
"Score": "0",
"body": "Depends on the definition of fails. The program runs. It fails the requirements. So it's a poor quality working code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-31T18:04:08.537",
"Id": "451871",
"Score": "3",
"body": "@JohnFriel Code that doesn't meet the requirements is broken/not working code here (and probably everywhere) :) When your code will work, don't hesitate to post it here and we will help you make it better. Until then, I'm afraid your question is off-topic. Also, I edited your indentation, I think it looked this way because of when you pasted it here."
}
] |
[
{
"body": "<h2>Incorrect indention</h2>\n\n<p>All of the methods in a class need to be indented such that they are inside the class definition. (this is based on the original version of the code you posted.</p>\n\n<p>Instead of this:</p>\n\n<pre><code> class StopWatch(Frame): \n \"\"\" Implements a stop watch frame widget. \"\"\" \n def __init__(self, parent=None, **kw): ...\n\ndef makeWidgets(self): ... \ndef _update(self): ...\ndef _setTime(self, elap): ...\ndef Start(self): ... \ndef Stop(self): ... \ndef Reset(self): ... \ndef clock_in(self): ...\ndef clock_out(self): ...\n</code></pre>\n\n<p>You need to do this:</p>\n\n<pre><code>class StopWatch(Frame): \n \"\"\" Implements a stop watch frame widget. \"\"\" \n def __init__(self, parent=None, **kw): ...\n\n def makeWidgets(self): ... \n def _update(self): ...\n def _setTime(self, elap): ...\n def Start(self): ... \n def Stop(self): ... \n def Reset(self): ... \n def clock_in(self): ...\n def clock_out(self): ...\n</code></pre>\n\n<h2>Follow PEP8 Guidelines</h2>\n\n<p><a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">PEP8</a> gives guidelines that every python program should follow. Specifically in your case, function names need to begin with a lowercase character.</p>\n\n<h2>StringVar is unnecessary overhead</h2>\n\n<p>In most cases, using <code>StringVar</code> adds overhead with no real value. While this is more of a personal preference, I see no reason to use it. <code>StringVar</code> objects are good if you want the exact same value displayed in two or more widgets, or if you're wanting to trace changes. Otherwise they are superfluous. </p>\n\n<p>Instead of <code>self.timestr</code>, you can directly alter the widget value. So, instead of saving a reference to the <code>StringVar</code>, save a reference to the widget:</p>\n\n<pre><code>def makeWidgets(self): \n ... \n self.time_label = Label(self, textvariable=self.timestr)\n ... \n\ndef _setTime(self, elap):\n ... \n self.time_label.configure(text='%02d:%02d:%02d' % (minutes, seconds, hseconds))\n ...\n</code></pre>\n\n<h2>Be consistent with private methods</h2>\n\n<p>By convention, private methods (methods that are only used internally) are named with a leading underscore. You do this with <code>_update</code> and <code>_setTime</code>, but you didn't do it with <code>makeWidgets</code>. You should try to be consistent: if a function is only used internally, name it with a leading underscore. </p>\n\n<h2>Don't hard-code the filename</h2>\n\n<p>Your program would be a bit more portable if you didn't hard-code the filename. Right now you have the filename hard-coded in the <code>clock_in</code> and <code>clock_out</code> functions. </p>\n\n<p>Instead, make it a parameter when you instantiate the class, or make it global.</p>\n\n<p>For example:</p>\n\n<pre><code>def clock_in(self):\n ...\n with open(self.filename, \"a\") as savedb:\n ...\n\ndef clock_out(self):\n ...\n with open(self.filename, \"a\") as savedb:\n ...\nsw = StopWatch(root, filename=r\"C:\\Users\\Desktop\\ClockIn.csv\")\n</code></pre>\n\n<h2>Separate widget creation from widget layout</h2>\n\n<p>In my experience, separating widget creation makes the code easier to visualize and easier to maintain. </p>\n\n<p>Instead of this:</p>\n\n<pre><code>Button(root, text='Clock In', command=lambda :[sw.Start(), sw.clock_in()]).pack(side=LEFT)\nButton(root, text='Clock Out', command=lambda :[sw.Start(), sw.clock_out()]).pack(side=LEFT)\nButton(root, text='Reset', command=sw.Reset).pack(side=LEFT)\nButton(root, text='Quit', command=root.quit).pack(side=LEFT)\n</code></pre>\n\n<p>... do this:</p>\n\n<pre><code>clock_in_button = Button(...)\nclock_out_button = Button(...)\nreset_button = Button(...)\nquit_button = Button(...)\n\nclock_in_button.pack(side=LEFT)\nclock_out_button.pack(side=LEFT)\nreset_button.pack(side=LEFT)\nquit_button.pack(side=LEFT)\n</code></pre>\n\n<p>This makes it much more clear to see at a glance that all for buttons are aligned to the left. When it's all blocked together it's much harder to see.</p>\n\n<h2>Incorrect use of tkinter</h2>\n\n<p>You're importing tkinter with <code>import tkinter as tk</code> but then trying to use tk classes without the <code>tk.</code> prefix.</p>\n\n<p>The import is good, but you need to fix all of the code that is creating widgets. For example, <code>tk.Button(...)</code> instead of just <span class=\"math-container\">`</span>Button(...).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-31T18:27:08.770",
"Id": "451887",
"Score": "0",
"body": "Great places to start. Thank you for the bullet points."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-31T18:09:27.267",
"Id": "231628",
"ParentId": "231597",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "231628",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-31T13:33:28.383",
"Id": "231597",
"Score": "1",
"Tags": [
"python",
"python-3.x",
"tkinter"
],
"Title": "Creating an Employee Punch Clock"
}
|
231597
|
<p><a href="https://i.stack.imgur.com/OqLNg.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/OqLNg.png" alt="enter image description here"></a></p>
<p><a href="https://i.stack.imgur.com/Yp9Aq.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Yp9Aq.png" alt="enter image description here"></a></p>
<p>I just finished a full minesweeper clone which is based on <a href="http://www.minesweeper.info/downloads/Winmine95.html" rel="nofollow noreferrer">Minesweeper for Windows 95</a>.</p>
<p>I used C++ and Qt to realize it. The full source code can be find in <a href="https://github.com/sandro4912/Minefield" rel="nofollow noreferrer">my git hub</a>.</p>
<p>Since this is too much code too review, I want to focus on the logic of the cells. For that I created the following classes:</p>
<ul>
<li><code>Cell</code>: Represents a single cell in the <code>Minefield</code></li>
<li><code>CellInputHandler</code>: This <code>QEventfilter</code> gets installed on each <code>Cell</code> to manage movements and right and left clicks with the cells. </li>
<li><code>Minefield</code>: Manages all the cells' events and tells the game when important events happen (bomb hit, uncovered all safe cells, uncovered first cell).</li>
</ul>
<p>You wonder why <code>CellInputHandler</code> handles the events and not each individual <code>Cell</code> directly. Minesweeper supports the following movement which could not be directly implemented in a single cell:</p>
<ul>
<li>press left mouse button on <code>Cell</code> A and hold it.</li>
<li>Move out of <code>Cell</code> A ⟶ <code>Cell</code> A gets "unpressed" on move out</li>
<li>Move into <code>Cell</code> B ⟶ <code>Cell</code> B gets "pressed"</li>
</ul>
<p>In the Cells directly implemented, I could not detect moving into the Cell with a pressed Mouse Button. So an event filter was the solution. Still, I feel this is a strange solution because I have to make it a friend of <code>Cell</code> and friends are often a bad design choice.</p>
<p>So please let me know what you think about the code. Also tell me any other bad practices or improvements I could have made.</p>
<p>Feel free to also check the other classes in the repo. If there's anything strange, let me know.</p>
<h3>cell.h</h3>
<pre><code>#ifndef CELL_H
#define CELL_H
#include <QWidget>
#include <QElapsedTimer>
#include <QTimer>
class CellInputHandler;
class Cell : public QWidget
{
Q_OBJECT
public:
enum class State{
empty,
mine
};
Cell(State state, QWidget *parent = nullptr);
void setCountOfNeighbourMines(int count);
[[nodiscard]] int countOfNeighbourMines() const;
[[nodiscard]] bool hasMine() const;
[[nodiscard]] bool hasQuestionmark() const;
[[nodiscard]] bool isCovered() const;
[[nodiscard]] bool isFLagged() const;
[[nodiscard]] bool isPressed() const;
[[nodiscard]] bool neighbourHasMine() const;
[[nodiscard]] bool neighbourIsFlagged() const;
public slots:
void toggleColor(bool value);
void toggleNewQuestionMarks(bool value);
void increaseCountOfFlaggedNeighbours();
void decreaseCountOfFlaggedNeighbours();
void uncoverIfCoveredAndNoMine();
void uncoverIfNotFlagged();
void pressIfCoveredOrQuestionmark();
void releaseIfCoveredOrQuestionmarkPressed();
void showMine();
void setToFlaggedWrong();
signals:
void hitMine();
void flagged();
void unflagged();
void uncovered();
void uncoveredEmptyCell();
void uncoverAreaWithNoMines();
void uncoverNotFlaggedNeighbours();
void pressed();
void released();
void pressNeighbours();
void releaseNeighbours();
protected:
void paintEvent(QPaintEvent *event) override;
private slots:
void mark();
private:
enum class DisplayType{
covered,
coveredPressed,
neigboursHave0Mines,
neigboursHave1Mine,
neigboursHave2Mines,
neigboursHave3Mines,
neigboursHave4Mines,
neigboursHave5Mines,
neigboursHave6Mines,
neigboursHave7Mines,
neigboursHave8Mines,
questionmark,
questionmarkPressed,
flagged,
mine,
mineExploded,
flaggedWrong,
};
QImage displayImage(DisplayType type);
void uncover();
void uncoverMine();
void setToUncoveredDisplayType();
friend class CellInputHandler;
void handleMousePressEvent(QMouseEvent *event);
void handleMouseReleaseEvent(QMouseEvent *event);
void handleMouseMoveEventInsideLeftButton(QMouseEvent *event);
void handleMouseMoveEventOutsideLeftButton(QMouseEvent *event);
void handleMouseMoveEventInsideBothButtons(QMouseEvent *event);
void handleMouseMoveEventOutsideBothButtons(QMouseEvent *event);
const bool mHasMine;
bool mNeighboursPressed;
bool mQuestionMarksOn;
bool mColorOn;
int mCountOfNeighbourMines;
int mCountOfNeigboursFlagged;
QElapsedTimer mElapsedTimer;
QTimer mSingleMouseTimerLeft;
QTimer mSingleMouseTimerRight;
DisplayType mDisplayType;
};
#endif // CELL_H
</code></pre>
<h3>cell.cpp</h3>
<pre><code>#include "cell.h"
#include "converttograyscale.h"
#include "cellinputhandler.h"
#include <QApplication>
#include <QIcon>
#include <QPainter>
#include <QStylePainter>
#include <QStyleOptionButton>
#include <QMouseEvent>
#include <QImage>
#include <QDebug>
Cell::Cell(Cell::State state, QWidget *parent)
:QWidget{ parent },
mHasMine{ static_cast<bool>(state) },
mNeighboursPressed{ false },
mQuestionMarksOn{ true },
mColorOn{ true },
mCountOfNeighbourMines{ 0 },
mCountOfNeigboursFlagged{ 0 },
mDisplayType{ DisplayType::covered }
{
setFixedSize(displayImage(mDisplayType).size());
mElapsedTimer.start();
constexpr auto intervall = 50;
for(QTimer* timer : {&mSingleMouseTimerRight, &mSingleMouseTimerLeft}){
timer->setInterval(intervall);
timer->setSingleShot(true);
}
connect(&mSingleMouseTimerLeft, &QTimer::timeout,
this, &Cell::pressIfCoveredOrQuestionmark);
connect(&mSingleMouseTimerRight, &QTimer::timeout,
this, &Cell::mark);
setMouseTracking(true);
}
void Cell::setCountOfNeighbourMines(int count)
{
constexpr auto minNeighbourMines = 0;
constexpr auto maxNeighbourMines = 8;
Q_ASSERT(count >= minNeighbourMines && count <= maxNeighbourMines);
mCountOfNeighbourMines = count;
}
int Cell::countOfNeighbourMines() const
{
return mCountOfNeighbourMines;
}
bool Cell::hasMine() const
{
return mHasMine;
}
bool Cell::hasQuestionmark() const
{
return mDisplayType == DisplayType::questionmark;
}
bool Cell::isCovered() const
{
return mDisplayType == DisplayType::covered;
}
bool Cell::isFLagged() const
{
return mDisplayType == DisplayType::flagged;
}
bool Cell::isPressed() const
{
return mDisplayType == DisplayType::coveredPressed ||
mDisplayType == DisplayType::questionmarkPressed;
}
bool Cell::neighbourHasMine() const
{
return mCountOfNeighbourMines != 0;
}
bool Cell::neighbourIsFlagged() const
{
return mCountOfNeigboursFlagged != 0;
}
void Cell::toggleColor(bool value)
{
mColorOn = value;
update();
}
void Cell::toggleNewQuestionMarks(bool value)
{
mQuestionMarksOn = value;
}
void Cell::increaseCountOfFlaggedNeighbours()
{
++mCountOfNeigboursFlagged;
Q_ASSERT(mCountOfNeigboursFlagged <= 8);
}
void Cell::decreaseCountOfFlaggedNeighbours()
{
--mCountOfNeigboursFlagged;
Q_ASSERT(mCountOfNeigboursFlagged >= 0);
}
void Cell::uncoverIfCoveredAndNoMine()
{
if (hasMine() || !isCovered()) {
return;
}
setToUncoveredDisplayType();
update();
if(!neighbourHasMine()) {
emit uncoverAreaWithNoMines();
}
}
void Cell::uncoverIfNotFlagged()
{
if (isFLagged() || mDisplayType == DisplayType::flaggedWrong) {
return;
}
uncover();
update();
if(!neighbourHasMine()) {
emit uncoverAreaWithNoMines();
}
}
void Cell::pressIfCoveredOrQuestionmark()
{
if(mSingleMouseTimerLeft.isActive()) {
mSingleMouseTimerLeft.stop();
}
if(mDisplayType == DisplayType::covered) {
mDisplayType = DisplayType::coveredPressed;
emit pressed();
update();
}
else if(mDisplayType == DisplayType::questionmark) {
mDisplayType = DisplayType::questionmarkPressed;
emit pressed();
update();
}
}
void Cell::releaseIfCoveredOrQuestionmarkPressed()
{
if(mSingleMouseTimerLeft.isActive()) {
mSingleMouseTimerLeft.stop();
}
if(mDisplayType == DisplayType::coveredPressed) {
mDisplayType = DisplayType::covered;
emit released();
update();
}
else if(mDisplayType == DisplayType::questionmarkPressed) {
mDisplayType = DisplayType::questionmark;
emit released();
update();
}
}
void Cell::showMine()
{
if(hasMine()) {
mDisplayType = DisplayType::mine;
update();
}
}
void Cell::setToFlaggedWrong()
{
mDisplayType = DisplayType::flaggedWrong;
update();
}
void Cell::paintEvent(QPaintEvent *event)
{
Q_UNUSED(event)
QPainter painter{ this };
auto image = displayImage(mDisplayType);
if(!mColorOn) {
image = convertToGrayscale(image);
}
painter.drawImage(rect(), image);
}
void Cell::mark()
{
switch (mDisplayType) {
case DisplayType::covered:
mDisplayType = DisplayType::flagged;
emit flagged();
update();
break;
case DisplayType::flagged:
if(mQuestionMarksOn) {
mDisplayType = DisplayType::questionmark;
}
else {
mDisplayType = DisplayType::covered;
}
emit unflagged();
update();
break;
case DisplayType::questionmark:
mDisplayType = DisplayType::covered;
update();
break;
default:
break;
}
}
QImage Cell::displayImage(Cell::DisplayType type)
{
switch(type){
case DisplayType::covered:
return QImage{":/ressources/cell_covered.png"};
case DisplayType::coveredPressed:
return QImage{":/ressources/cell_covered_pressed.png"};
case DisplayType::neigboursHave0Mines:
return QImage{":/ressources/cell_0.png"};
case DisplayType::neigboursHave1Mine:
return QImage{":/ressources/cell_1.png"};
case DisplayType::neigboursHave2Mines:
return QImage{":/ressources/cell_2.png"};
case DisplayType::neigboursHave3Mines:
return QImage{":/ressources/cell_3.png"};
case DisplayType::neigboursHave4Mines:
return QImage{":/ressources/cell_4.png"};
case DisplayType::neigboursHave5Mines:
return QImage{":/ressources/cell_5.png"};
case DisplayType::neigboursHave6Mines:
return QImage{":/ressources/cell_6.png"};
case DisplayType::neigboursHave7Mines:
return QImage{":/ressources/cell_7.png"};
case DisplayType::neigboursHave8Mines:
return QImage{":/ressources/cell_8.png"};
case DisplayType::questionmark:
return QImage{":/ressources/cell_questionmark.png"};
case DisplayType::questionmarkPressed:
return QImage{":/ressources/cell_questionmark_pressed.png"};
case DisplayType::flagged:
return QImage{":/ressources/cell_flagged.png"};
case DisplayType::mine:
return QImage{":/ressources/cell_mine.png"};
case DisplayType::mineExploded:
return QImage{":/ressources/cell_mine_explode.png"};
case DisplayType::flaggedWrong:
return QImage{":/ressources/cell_nomine.png"};
}
return QImage{};
}
void Cell::uncover()
{
if(hasMine()) {
uncoverMine();
}
else {
setToUncoveredDisplayType();
}
emit uncovered();
update();
}
void Cell::uncoverMine()
{
mDisplayType = DisplayType::mineExploded;
emit hitMine();
}
void Cell::setToUncoveredDisplayType()
{
mDisplayType = static_cast<DisplayType>(
static_cast<int>(
DisplayType::neigboursHave0Mines) + mCountOfNeighbourMines);
emit uncoveredEmptyCell();
}
void Cell::handleMousePressEvent(QMouseEvent *event)
{
if(!(event->buttons().testFlag(Qt::LeftButton) ||
event->buttons().testFlag(Qt::RightButton))) {
return;
}
if(event->buttons().testFlag(Qt::LeftButton)) {
mSingleMouseTimerLeft.start();
}
else if (event->buttons().testFlag(Qt::RightButton)){
mSingleMouseTimerRight.start();
}
const auto elapsedTime = mElapsedTimer.restart();
if(elapsedTime >= QApplication::doubleClickInterval()) {
return;
}
if((mSingleMouseTimerLeft.isActive() &&
event->buttons().testFlag(Qt::RightButton)) ||
(mSingleMouseTimerRight.isActive() &&
event->buttons().testFlag(Qt::LeftButton))){
if(!isPressed()) {
pressIfCoveredOrQuestionmark();
mNeighboursPressed = true;
emit pressNeighbours();
}
for(QTimer* timer : { &mSingleMouseTimerRight,
&mSingleMouseTimerLeft }) {
timer->stop();
}
}
}
void Cell::handleMouseReleaseEvent(QMouseEvent *event)
{
if(mNeighboursPressed) {
if(event->button() == Qt::LeftButton ||
event->button() == Qt::RightButton)
{
mNeighboursPressed = false;
if(mCountOfNeigboursFlagged == mCountOfNeighbourMines) {
if(isPressed()) {
uncover();
}
emit uncoverNotFlaggedNeighbours();
emit uncoverAreaWithNoMines();
}
else {
if(isPressed()) {
releaseIfCoveredOrQuestionmarkPressed();
}
emit releaseNeighbours();
}
}
}
else if(event->button() == Qt::LeftButton) {
uncover();
if(mDisplayType == DisplayType::neigboursHave0Mines) {
emit uncoverAreaWithNoMines();
}
}
}
void Cell::handleMouseMoveEventInsideLeftButton(QMouseEvent *event)
{
Q_UNUSED(event)
if(!isPressed()) {
pressIfCoveredOrQuestionmark();
}
}
void Cell::handleMouseMoveEventOutsideLeftButton(QMouseEvent *event)
{
Q_UNUSED(event)
if(mSingleMouseTimerLeft.isActive()) {
mSingleMouseTimerLeft.stop();
}
if(isPressed()) {
releaseIfCoveredOrQuestionmarkPressed();
}
}
void Cell::handleMouseMoveEventInsideBothButtons(QMouseEvent *event)
{
handleMouseMoveEventInsideLeftButton(event);
mNeighboursPressed = true;
emit pressNeighbours();
}
void Cell::handleMouseMoveEventOutsideBothButtons(QMouseEvent *event)
{
handleMouseMoveEventOutsideLeftButton(event);
if(mNeighboursPressed) {
mNeighboursPressed = false;
emit releaseNeighbours();
}
}
</code></pre>
<h3>cellinputhandler.h</h3>
<pre><code>#ifndef CELLINPUTHANDLER_H
#define CELLINPUTHANDLER_H
#include <QObject>
#include <QElapsedTimer>
#include <QTimer>
class Cell;
class QMouseEvent;
class CellInputHandler : public QObject
{
Q_OBJECT
public:
explicit CellInputHandler(QObject *parent = nullptr);
protected:
bool eventFilter(QObject *watched, QEvent *event) override;
private:
void handleMouseButtonPressEvents(QObject *watched, QEvent *event);
void handleMouseButtonReleaseEvents(QObject *watched, QEvent *event);
void handleMouseMoveEvents(QEvent *event);
void cellMoveInsideHandle(Cell *cell, QMouseEvent *mouseEvent);
void cellMoveOutsideHandle(Cell *cell, QMouseEvent *mouseEvent);
Cell *mLastCell;
};
#endif // CELLINPUTHANDLER_H
</code></pre>
<h3>cellinputhandler.cpp</h3>
<pre><code>#include "cellinputhandler.h"
#include "cell.h"
#include <QApplication>
#include <QEvent>
#include <QMouseEvent>
#include <QDebug>
CellInputHandler::CellInputHandler(QObject *parent)
: QObject{ parent },
mLastCell{ nullptr }
{
}
bool CellInputHandler::eventFilter(QObject *watched, QEvent *event)
{
if(event->type() == QEvent::MouseButtonPress){
handleMouseButtonPressEvents(watched, event);
return true;
}
if(event->type() == QEvent::MouseButtonRelease){
handleMouseButtonReleaseEvents(watched, event);
return true;
}
if(event->type() == QEvent::MouseMove) {
handleMouseMoveEvents(event);
return true;
}
return false;
}
void CellInputHandler::handleMouseButtonPressEvents(
QObject *watched, QEvent *event)
{
auto mouseEvent = static_cast<QMouseEvent*>(event);
auto cell = qobject_cast<Cell *>(watched);
cell->handleMousePressEvent(mouseEvent);
mLastCell = cell;
}
void CellInputHandler::handleMouseButtonReleaseEvents(
QObject *watched, QEvent *event)
{
Q_UNUSED(watched)
auto mouseEvent = static_cast<QMouseEvent*>(event);
auto widget = QApplication::widgetAt(QCursor::pos());
auto cell = qobject_cast<Cell *>(widget);
if(cell) {
cell->handleMouseReleaseEvent(mouseEvent);
mLastCell = cell;
}
else if(mLastCell) {
mLastCell->handleMouseReleaseEvent(mouseEvent);
}
}
void CellInputHandler::handleMouseMoveEvents(QEvent *event)
{
auto mouseEvent = static_cast<QMouseEvent*>(event);
if(mouseEvent->buttons().testFlag(Qt::LeftButton)) {
auto widget = QApplication::widgetAt(mouseEvent->globalPos());
if(widget) {
auto cell = qobject_cast<Cell *>(widget);
if(mLastCell && (!cell || cell != mLastCell)) {
cellMoveOutsideHandle(mLastCell, mouseEvent);
}
if(!cell) {
mLastCell = nullptr;
}
else if(cell != mLastCell) {
cellMoveInsideHandle(cell, mouseEvent);
mLastCell = cell;
}
}
}
}
void CellInputHandler::cellMoveInsideHandle(
Cell *cell, QMouseEvent *mouseEvent)
{
if(mouseEvent->buttons().testFlag(Qt::RightButton)) {
cell->handleMouseMoveEventInsideBothButtons(mouseEvent);
}
else {
cell->handleMouseMoveEventInsideLeftButton(mouseEvent);
}
}
void CellInputHandler::cellMoveOutsideHandle(
Cell *cell, QMouseEvent *mouseEvent)
{
if(mouseEvent->buttons().testFlag(Qt::RightButton)) {
cell->handleMouseMoveEventOutsideBothButtons(mouseEvent);
}
else {
cell->handleMouseMoveEventOutsideLeftButton(mouseEvent);
}
}
</code></pre>
<h3>minefield.h</h3>
<pre><code>#ifndef MINEFIELD_H
#define MINEFIELD_H
#include <QVector>
#include <QWidget>
#include "cell.h"
#include <vector>
class CellInputHandler;
class Minefield : public QWidget
{
Q_OBJECT
public:
Minefield(const QVector<Cell *> &cells, int width, int height,
QWidget *parent = nullptr);
[[nodiscard]] int fieldWidth() const;
[[nodiscard]] int fieldHeight() const;
[[nodiscard]] int countOfMines() const;
[[nodiscard]] int minesLeft() const;
signals:
void toggleColorInCells(int value);
void toggleNewQuesionMarksInCells(int value);
void uncoveredFirstCell();
void uncoveredEmptyCell();
void uncoveredAllSafeCells();
void pressedCell();
void releasedCell();
void mineExploded();
void minesLeftChanged(int minesLeft);
private slots:
void flaggedCell();
void unflaggedCell();
void checkIfFirstCellIsUncovered();
void checkIfSafeCellsUncovered();
private:
void connectWithCells();
void addCellsToLayout();
void showAllMines();
void showWrongFlaggedCells();
void disableInput();
bool mFirstCellUncovered{ false };
bool mSafeCellsUncovered{ false };
QVector<Cell *> mCells;
int mFieldWidth;
int mFieldHeight;
int mMinesLeft;
CellInputHandler *mCellInputHandler;
};
#endif // MINEFIELD_H
</code></pre>
<h3>minefield.cpp</h3>
<pre><code>#include "minefield.h"
#include "cell.h"
#include "cellinputhandler.h"
#include "cellutility.h"
#include <QDebug>
#include <QGridLayout>
Minefield::Minefield(const QVector<Cell *> &cells, int width, int height,
QWidget *parent)
:QWidget{ parent },
mCells{ cells },
mFieldWidth{ width },
mFieldHeight{ height },
mMinesLeft{ countOfMines()},
mCellInputHandler{ new CellInputHandler{ this } }
{
Q_ASSERT(mCells.size() == (mFieldWidth * mFieldHeight));
connectCellsWithNeighbourCells(mCells, mFieldWidth, mFieldHeight);
for(auto &cell : mCells) {
cell->installEventFilter(mCellInputHandler);
}
connectWithCells();
addCellsToLayout();
}
int Minefield::fieldWidth() const
{
return mFieldWidth;
}
int Minefield::fieldHeight() const
{
return mFieldHeight;
}
int Minefield::countOfMines() const
{
auto count = 0;
for(const auto& cell : mCells) {
if(cell->hasMine()) {
++count;
}
}
return count;
}
int Minefield::minesLeft() const
{
return mMinesLeft;
}
void Minefield::flaggedCell()
{
--mMinesLeft;
emit minesLeftChanged(mMinesLeft);
}
void Minefield::unflaggedCell()
{
++mMinesLeft;
emit minesLeftChanged(mMinesLeft);
}
void Minefield::checkIfFirstCellIsUncovered()
{
if(!mFirstCellUncovered) {
mFirstCellUncovered = true;
for(const auto &cell : mCells) {
disconnect(cell, &Cell::uncovered,
this, &Minefield::checkIfFirstCellIsUncovered);
}
emit uncoveredFirstCell();
}
}
void Minefield::checkIfSafeCellsUncovered()
{
if(!mSafeCellsUncovered && allSafeCellsUncovered(mCells)) {
mSafeCellsUncovered = true;
for(const auto &cell : mCells) {
disconnect(cell, &Cell::uncovered,
this, &Minefield::checkIfSafeCellsUncovered);
}
disableInput();
emit uncoveredAllSafeCells();
}
}
void Minefield::connectWithCells()
{
for(const auto &cell : mCells) {
connect(cell, &Cell::pressed,
this, &Minefield::pressedCell);
connect(cell, &Cell::released,
this, &Minefield::releasedCell);
connect(cell, &Cell::uncoveredEmptyCell,
this, &Minefield::uncoveredEmptyCell);
connect(cell, &Cell::flagged,
this, &Minefield::flaggedCell);
connect(cell, &Cell::unflagged,
this, &Minefield::unflaggedCell);
connect(cell, &Cell::uncovered,
this, &Minefield::checkIfFirstCellIsUncovered);
connect(cell, &Cell::uncovered,
this, &Minefield::checkIfSafeCellsUncovered);
connect(this, &Minefield::toggleNewQuesionMarksInCells,
cell, &Cell::toggleNewQuestionMarks);
connect(this, &Minefield::toggleColorInCells,
cell, &Cell::toggleColor);
if(cell->hasMine()) {
connect(cell, &Cell::hitMine,
[=](){
showWrongFlaggedCells();
showAllMines();
disableInput();
emit mineExploded();
});
}
}
}
void Minefield::addCellsToLayout()
{
auto layout = new QGridLayout;
layout->setSpacing(0);
layout->setContentsMargins(0,0,0,0);
for(int i = 0; i < mCells.size(); ++i) {
auto column = static_cast<int>(i % mFieldWidth);
auto row = static_cast<int>(i / mFieldWidth);
layout->addWidget(mCells[i], row, column);
}
setLayout(layout);
}
void Minefield::showAllMines()
{
for(const auto cell : mCells) {
if(cell->hasMine() && cell->isCovered()) {
cell->showMine();
}
}
}
void Minefield::showWrongFlaggedCells()
{
for(const auto &cell : mCells) {
if(!cell->hasMine() && cell->isFLagged()) {
cell->setToFlaggedWrong();
}
}
}
void Minefield::disableInput()
{
setAttribute(Qt::WA_TransparentForMouseEvents);
}
</code></pre>
|
[] |
[
{
"body": "<p>Nice, well-presented code, apart from some spacing inconsistency following <code>for</code>, <code>if</code> etc.</p>\n\n<hr>\n\n<p>I think the <code>Cell</code> constructor should be <code>explicit</code>. It's odd that it's missing initializers for the timers (I use <code>gcc -Weffc++</code>, so tend to include them even for types that won't end up uninitialized).</p>\n\n<blockquote>\n<pre><code> constexpr auto intervall = 50;\n</code></pre>\n</blockquote>\n\n<p>would be better named <code>interval</code>.</p>\n\n<hr>\n\n<blockquote>\n<pre><code>void Cell::paintEvent(QPaintEvent *event)\n{\n Q_UNUSED(event)\n</code></pre>\n</blockquote>\n\n<p>We could simply leave the argument unnamed instead:</p>\n\n<pre><code>void Cell::paintEvent(QPaintEvent*)\n{\n</code></pre>\n\n<hr>\n\n<p>Neither <code>cell.cpp</code> nor <code>cellinputhandler.cpp</code> needs <code><QDebug></code>.</p>\n\n<hr>\n\n<p>This looks suspect:</p>\n\n<pre><code>auto mouseEvent = static_cast<QMouseEvent*>(event);\nauto widget = QApplication::widgetAt(QCursor::pos());\n</code></pre>\n\n<p>Why are we not using the event's position here, as we do in <code>handleMouseMoveEvents()</code>? I don't think we can rely on <code>QCursor::pos()</code> being race-free relative to event delivery.</p>\n\n<hr>\n\n<p>A bit of duplication here:</p>\n\n<blockquote>\n<pre><code>if(!(event->buttons().testFlag(Qt::LeftButton) ||\n event->buttons().testFlag(Qt::RightButton))) {\n return;\n}\n\nif(event->buttons().testFlag(Qt::LeftButton)) {\n mSingleMouseTimerLeft.start();\n}\nelse if (event->buttons().testFlag(Qt::RightButton)){\n mSingleMouseTimerRight.start();\n}\n</code></pre>\n</blockquote>\n\n<p>We could combine those into a single conditional:</p>\n\n<pre><code>if (event->buttons().testFlag(Qt::LeftButton)) {\n mSingleMouseTimerLeft.start();\n}\nelse if (event->buttons().testFlag(Qt::RightButton)) {\n mSingleMouseTimerRight.start();\n}\nelse {\n return;\n}\n</code></pre>\n\n<hr>\n\n<p><code>minefield.h</code> has no need to include <code><vector></code> (perhaps left over from an earlier version?).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-02T16:22:51.153",
"Id": "452127",
"Score": "0",
"body": "what does `-Weffc++` do? With `intervall` I guess the german in me slipped through. I thought `Q_UNUSED` is the more Qt way to hide unused parameters. Normally I tend to do `void Cell::paintEvent(QPaintEvent * /*event*/)` so its still possible to read the meaning."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-04T09:16:57.643",
"Id": "452305",
"Score": "1",
"body": "[`-Weffc++`](https://gcc.gnu.org/onlinedocs/gcc/C_002b_002b-Dialect-Options.html#index-Wno-effc_002b_002b) enables warnings about violations of several style guidelines from Scott Meyers’ _Effective C++_ series of books."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-04T17:03:29.623",
"Id": "452391",
"Score": "0",
"body": "ah these books are here on my shelf. do you know how to enable this flag with qt creator?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-04T17:12:23.830",
"Id": "452392",
"Score": "0",
"body": "No idea, but if it uses qmake you should be able to append to `QMAKE_CXXFLAGS` in the project file. Beware that you'll want to use `-isystem` rather than `-I` for the Qt includes if you add `-Weffc++`, or you'll get a mountain of warnings from Qt's own headers! I also found that `moc`-built sources fail my normal choice of warning flags, so had to suppress them there, too."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-04T17:36:04.757",
"Id": "452394",
"Score": "0",
"body": "i added this in the pro file `QMAKE_CXXFLAGS = -Weffc++ -isystem` like you said i get a million warnings from qt headers. but why? i thought i enabled `isystem`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-04T17:41:37.513",
"Id": "452396",
"Score": "0",
"body": "same when i write `QMAKE_CXXFLAGS += -Weffc++\nQMAKE_CXXFLAGS += -isystem` So how to add `isystem` ?"
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-31T14:25:17.577",
"Id": "231606",
"ParentId": "231598",
"Score": "2"
}
},
{
"body": "<p>I see some things that may help you improve your code.</p>\n\n<h2>Don't leak memory</h2>\n\n<p>I see that there are a number of places in which <code>new</code> is invoked but there is no corresponding <code>delete</code>. For example, one leak can be addressed by adding this destructor:</p>\n\n<pre><code>Minefield::~Minefield() {\n delete mCellInputHandler;\n}\n</code></pre>\n\n<h2>Put <code>friend</code> declarations in <code>public</code> section</h2>\n\n<p>It's misleading to put a <code>friend</code> declaration (as in <code>friend class CellInputHandler</code> in <code>cell.h</code>) in a <code>private</code> section. Because access specifiers have no effect on <code>friend</code> declarations, any <code>friend</code> designation is essentially public. For this reason, I advocate always putting <code>friend</code> declarations in <code>public</code> sections.</p>\n\n<h2>Write code for human comprehension</h2>\n\n<p>The <code>Cell</code> constructor has this peculiar line:</p>\n\n<pre><code>mHasMine{ static_cast<bool>(state) },\n</code></pre>\n\n<p>I had to look up the definition of <code>state</code> and found this:</p>\n\n<pre><code>enum class State{\n empty,\n mine\n};\n</code></pre>\n\n<p>Rather than relying on an unintuitive <code>static_cast</code>, I would suggest instead writing this:</p>\n\n<pre><code> mHasMine{ state == State::mine },\n</code></pre>\n\n<h2>Put static initializers into declaration</h2>\n\n<p>When you have a class that has a member data items that are initialized to constants (as with <code>Cell</code>), I recommend using in-class initializers instead of explicitly listing them as part of the constructor. See <a href=\"https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#Rc-in-class-initializer\" rel=\"nofollow noreferrer\">C.48</a> for details.</p>\n\n<h2>Prefer a <code>switch</code> to long <code>if</code> chain</h2>\n\n<p>In the <code>CellInputHandler::eventFilter()</code> we have this code:</p>\n\n<pre><code>if(event->type() == QEvent::MouseButtonPress){\n handleMouseButtonPressEvents(watched, event);\n return true;\n}\nif(event->type() == QEvent::MouseButtonRelease){\n handleMouseButtonReleaseEvents(watched, event);\n return true;\n}\nif(event->type() == QEvent::MouseMove) {\n handleMouseMoveEvents(event);\n return true;\n}\nreturn false;\n</code></pre>\n\n<p>I would suggest instead writing it like this:</p>\n\n<pre><code>bool result{true};\nswitch (event->type()) {\n case QEvent::MouseButtonPress:\n handleMouseButtonPressEvents(watched, event);\n break;\n case QEvent::MouseButtonRelease:\n handleMouseButtonReleaseEvents(watched, event);\n break;\n case QEvent::MouseMove:\n handleMouseMoveEvents(event);\n break;\n default:\n result = false;\n}\nreturn result;\n</code></pre>\n\n<p>The resulting object code is likely to be very similar, but it has an advantage for human comprehension. First, it's easy to see that only a single value is being interrogated. Second, there is a single <code>return</code> which, to me, makes it simpler for readers of the code to understand the flow.</p>\n\n<h2>Rethink your event handler</h2>\n\n<p>The typical approach in Qt is to have each object handle its own events. Since <code>Minefield</code> is derived from <code>QWidget</code>, I would have expected that it would have an <code>event</code> handler. Instead we have the separate <code>CellInputHandler</code> implemented as an <code>EventFilter</code>. I would suggest that the events handled within <code>CellInputHandler</code> would be better expressed as part of the <code>event()</code> override function in <code>Minefield</code>. </p>\n\n<p>Even better, however, would be to eliminate that completely and simply let the <code>Cell</code> objects handle their own events. Let's consider the scenario you mentioned:</p>\n\n<ol>\n<li>press left mouse button on Cell A and hold it.</li>\n<li>Move out of Cell A -> Cell A gets \"unpressed\" on move out</li>\n<li>Move into Cell B -> Cell B gets \"pressed\"</li>\n</ol>\n\n<p>All that's needed is to provide handlers for <code>QEvent::Enter</code> and <code>QEvent::Leave</code>. Pseudocode:</p>\n\n<pre><code>Enter: \n if LeftMouseButtonDown, call LeftMouseButtonDown handler\n\nLeave:\n if LeftMouseButtonDown, restore to normal state\n</code></pre>\n\n<p><strong>Note</strong>: Unfortunately, as pointed out in the comment, this doesn't actually work out of the box because a <code>QWidget</code> does a <code>grabMouse()</code> on mouse button press events. However, I suspect that one could issue an explicit <code>releaseMouse()</code> call from within the handler and still keep this approach. I may experiment with that if I get some time.</p>\n\n<h2>Encapsulate more</h2>\n\n<p>I don't think there's much reason for any class other than <code>Minefield</code> to know about individual <code>Cell</code>s. Therefore, I'd suggest changing the interface so that <code>Minefield</code>'s constructor is only give a width and height and all <code>Cell</code> creation and further handling would be inside the class.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-18T05:20:39.910",
"Id": "454168",
"Score": "0",
"body": "my plan was to implement enter and leave in cell (it seems much cleaner) but it does not work the sliding between cells. See this discussion: https://forum.qt.io/topic/107430/detect-if-mouse-buttons-are-pressed-when-sliding-into-widget/2. The Cells are available in the constructor so I can pass not random Cells for test to the Minefield. And about the memory leak. mCellInputHandler gets the `Minefield` as its parent in the `Minefield` Constructor.so it should be deleted when `Minefield` is destroyed"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-18T14:01:45.560",
"Id": "454236",
"Score": "0",
"body": "I had forgotten that a widget does a MouseCapture on mouse press events, so I understand the dilemma now. As for the memory leak, you might try running [`valgrind`](http://valgrind.org/) to check your assumption. I did and found the application was leaking memory."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-18T14:18:53.263",
"Id": "454239",
"Score": "0",
"body": "yes I will try valgrind. I think I forgot to run it. The cell think is quite a big dilemma. They way its solved now it really looks strange. I was thinking maybe the change between the cells can be implemented by using drag and drop."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-18T17:32:17.513",
"Id": "454262",
"Score": "0",
"body": "I found the memory leak in the class `Game`. I make `QTime *mElapsedTime` on the heap but it never gets freed. So I freed it in the destructor. After that no more errors from valgrind"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-18T20:30:50.433",
"Id": "454279",
"Score": "0",
"body": "That's great! Also, I've tried quite a few things with Qt to address the event issue and I am now persuaded that your approach with the `EventFilter` is probably the best currently available approach. If there were an elegant way to convince Qt widgets not to `grabMouse` that would likely be better, but I haven't found a good way to do that other than the `EventFilter` approach you've already implemented. I don't know if you've learned anything from my answer, but I have learned something from your question, so *thank you* for asking it!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-18T20:37:10.907",
"Id": "454280",
"Score": "0",
"body": "dont worry i still learned some things from it. like finding the leak. theres always space to improve. getti g the game work right took me far more longer than expected especially the part with the events in zhe cells. It was a good exercise to learn more from qt"
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-17T17:53:47.170",
"Id": "232553",
"ParentId": "231598",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "232553",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-31T13:48:12.610",
"Id": "231598",
"Score": "6",
"Tags": [
"c++",
"game",
"c++17",
"qt"
],
"Title": "Minefield - A Cross Platform Minesweeper clone"
}
|
231598
|
<p>I wrote a simple lighter version of <code>std::shared_ptr<T></code> called <code>res_ptr<T></code>.</p>
<p><code>std::shared_ptr<T></code> is somewhat heavy due to all the nuances of its control block: support for safe deleting without virtual destructor, support for <code>std::weak_ptr<T></code> (I am not certain on all details of the implementation... but I believe that it either requires an extra allocation for the control block, or has complicated logic on when to delete...).</p>
<p>The <code>res_ptr<T></code> requires <code>T</code> to inherit from class <code>resource</code> that manages the reference counter and deletes the instance upon destruction once the counter reaches zero requires. Yes, it doesn't support array version <code>res_ptr<T[]></code> and I don't think that it should but I might wrong.</p>
<p><code>res_version<T></code> is a helper class that attaches <code>resource</code> class to classes that do not inherit from <code>resource</code> that shouldn't change anything besides that.</p>
<p>Besides that, it is supposed to have fairly same interface as <code>std::shared_ptr<T></code> and <code>std::unique_ptr<T></code>. I know it currently lacks option for custom deleter but I don't think that I'll ever need it so I don't intend to implement it.</p>
<p>The implementation I have is written on Visual Studio and isn't fully portable. Though, honestly, this class is going to be the least of my worries once I need portability for the codebase. Though, if it is something else besides modifying <code>#pragma once</code> or issues with initialization of <code>std::atomic</code> I'd like to know.</p>
<p>I'd like to know if there are any issues or downsides that I failed to consider as well as general code review.</p>
<pre><code>#pragma once
#include <atomic>
class resource
{
public:
virtual ~resource() = default;
resource() = default;
// moving / copying does not alter the reference counter
resource(resource&&) noexcept : resource() {};
resource(const resource&) noexcept : resource() {};
resource& operator = (resource&&) noexcept {};
resource& operator = (const resource&) noexcept {};
void add_ref() const noexcept
{
m_refcount.fetch_add(1, std::memory_order_relaxed);
}
int reduce_ref() const noexcept
{
return m_refcount.fetch_sub(1, std::memory_order_relaxed)-1;
}
int count() const noexcept
{
return m_refcount.load(std::memory_order_relaxed);
}
private:
mutable std::atomic<int> m_refcount = 0;
};
template<typename T>
class res_version :
public T, public resource
{
public:
template<typename... Args>
res_version(Args... args):
T(std::forward<Args>(args)...)
{};
};
template<typename PResource, typename Enable = void>
class res_ptr;
template<typename PResource>
class res_ptr<PResource, typename std::enable_if_t<std::is_base_of_v<resource, PResource>>>
{
public:
template<typename PResourceDerived, typename E>
friend class res_ptr;
constexpr res_ptr() noexcept = default;
constexpr res_ptr(nullptr_t) noexcept {};
template<typename PResourceDerived, std::enable_if_t<std::is_base_of_v<PResource, PResourceDerived>, int> = 0>
explicit res_ptr(PResourceDerived* ptr) : m_ptr(static_cast<PResource*>(ptr))
{
if(m_ptr) m_ptr->add_ref();
};
~res_ptr()
{
release();
}
// copy ctor
res_ptr(const res_ptr& ptr) noexcept :
m_ptr(ptr.get())
{
if (m_ptr) m_ptr->add_ref();
};
// copy ctor cast
template<typename PResourceDerived, std::enable_if_t<std::is_base_of_v<PResource, PResourceDerived> && !std::is_same_v<PResource, PResourceDerived>,int> = 0>
res_ptr( const res_ptr<PResourceDerived> & ptr) noexcept :
m_ptr(static_cast<PResource*>(ptr.get()))
{
if (m_ptr) m_ptr->add_ref();
};
// move ctor
res_ptr( res_ptr&& ptr) noexcept :
m_ptr(std::exchange(ptr.m_ptr, nullptr))
{};
// move ctor cast
template<typename PResourceDerived, std::enable_if_t<std::is_base_of_v<PResource, PResourceDerived> && !std::is_same_v<PResource, PResourceDerived>,int> = 0>
res_ptr( res_ptr<PResourceDerived> && ptr) noexcept :
m_ptr(static_cast<PResource*>(std::exchange(ptr.m_ptr, nullptr)))
{};
// copy
res_ptr& operator = (const res_ptr& other) noexcept
{
if (this != &other)
{
release();
m_ptr = other.m_ptr;
if (m_ptr) m_ptr->add_ref();
}
return *this;
}
// move
res_ptr& operator = ( res_ptr&& other) noexcept
{
if (this != &other)
{
release();
m_ptr = std::exchange(other.m_ptr,nullptr);
}
return *this;
}
// copy cast
template<typename PResourceDerived, std::enable_if_t<std::is_base_of_v<PResource, PResourceDerived> && !std::is_same_v<PResource, PResourceDerived>, int> = 0>
res_ptr& operator = (const res_ptr<PResourceDerived>& other) noexcept
{
release();
m_ptr = static_cast<PResource*>(other.m_ptr);
if (m_ptr) m_ptr->add_ref();
return *this;
}
// move cast
template<typename PResourceDerived, std::enable_if_t<std::is_base_of_v<PResource, PResourceDerived> && !std::is_same_v<PResource, PResourceDerived>, int> = 0>
res_ptr& operator = ( res_ptr<PResourceDerived>&& other) noexcept
{
release();
m_ptr = static_cast<PResource*>(std::exchange(other.m_ptr,nullptr));
return *this;
}
PResource* operator -> () const noexcept
{
return m_ptr;
}
PResource& operator * () const noexcept
{
return *m_ptr;
}
PResource* get() const noexcept
{
return m_ptr;
}
operator bool () const noexcept
{
return m_ptr != nullptr;
}
void release()
{
if (m_ptr && (m_ptr->reduce_ref() == 0))
{
delete m_ptr;
}
}
template<typename PResource>
bool operator == (const res_ptr<PResource>& other) noexcept
{
return m_ptr == other.m_ptr;
}
template<typename PResource>
bool operator != (const res_ptr<PResource>& other) noexcept
{
return m_ptr != other.m_ptr;
}
private:
PResource* m_ptr = nullptr;
};
template<typename PResource, typename... Args>
res_ptr<PResource> make_resource(Args&& ... args)
{
return res_ptr<PResource>(new PResource(std::forward<Args>(args)...));
}
template<typename PResourceDerived, typename PResourceBase>
res_ptr<PResourceDerived> resource_dynamic_cast(const res_ptr<PResourceBase>& uPtr) noexcept
{
PResourceDerived* ptr = dynamic_cast<PResourceDerived*>(uPtr.get());
return res_ptr<PResourceDerived>(ptr);
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-31T15:34:47.227",
"Id": "451808",
"Score": "4",
"body": "Do you have any tests? It's worth including them in the review (for two reasons: it helps reviewers run and exercise the code themselves, and it may identify corner cases that need testing)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-31T16:28:04.167",
"Id": "451824",
"Score": "1",
"body": "There is a reason that `std::shared_ptr` is not light wait. Its difficult to write correctly and needs all that code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-31T16:31:25.150",
"Id": "451830",
"Score": "1",
"body": "@MartinYork `res_ptr<T>` is not designed to replace `std::shared_ptr<T>` but to provide a more efficient version for certain classes."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-31T16:42:23.803",
"Id": "451834",
"Score": "0",
"body": "@TobySpeight I don't have any tests dedicated to `res_ptr<T>`... only tests that utilize `res_ptr<T>` within larger projects. If you can supplement some good ideas on those edge cases that are worth testing you can post it as an answer."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-31T17:05:05.613",
"Id": "451842",
"Score": "2",
"body": "@ALX23z not sure I am convinced this is any more efficient than `std::shared_ptr` (having read the code) you would need to show me evidence of that. Also since `std::shared_ptr` has much more testing on it I am inclined to think there is something non obvious here that will cause problems (without lots of though going into testing and validating). They found bugs in shared_ptr for well over a decade after it was first written before it got to its current state. It is a good try (probably one of the best I have seen) but this should not be used in production code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-31T17:21:04.480",
"Id": "451854",
"Score": "0",
"body": "@MartinYork currently it is for development code. I do believe there might be issues when this class is used in odd cases. I didn't bother dealing with `const / volatile` and I am not entirely sure how to address them with smart pointers since my skills with SFINAE are limited - I heard that even for `std::unique_ptr` and `std::shared_ptr` this doesn't work perfectly due to language limitations. For general use, the biggest problem is the design itself as it requires the underlying class to inherit from `resource`. How does one properly inherits from `resource`? Each version has issues."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-03T19:26:02.963",
"Id": "452236",
"Score": "0",
"body": "@MartinYork The **number one issue (to me)** with shared_ptr (and most std template types) is the cost of the template instantiation: it does not scale as the number of templates in the application grows. It tries to do 'many things', when in most cases the 'many things' don't apply; if they do, use it. However, shared_ptr is *against* \"pay only for what you use\". (That said, there are already several such lightweight implementations in-the-wild too.)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-03T22:29:32.027",
"Id": "452244",
"Score": "0",
"body": "@user2864740 What you said does not make any sense. Templates only instantiate what they need (never more), the cost is never more than the cost of creating the class. So the statement **it does not scale** is just ludicrously wrong. The statement **'many things'** is also misguided and totally untrue. The use of SFINE is the classic example of how that is not true (each type is specifically instantiated with only what needs to be done and specialized). Also **pay only for what you use** I see as totally misleading as you only pay for waht you use (as with all templates). Prove your statement"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-03T22:30:52.280",
"Id": "452245",
"Score": "0",
"body": "@user2864740 **That said, there are already several such lightweight implementations in-the-wild too**. Sure there are always people that want to try their hand for lots of reasons. This does not mean it is a good idea. Please provide data that any of these \"light-weight\" ones are better than `std::shared_ptr`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-03T23:45:52.397",
"Id": "452262",
"Score": "0",
"body": "Perhaps you missed the part about “compilation”. It does not scale with the number of distinct instantiations due to having a very high C cost per-instantiation type. This is easy to verify using Clang and “-ftime-trace”, or measuring compilation times with an increasing number of T-types. Hint: the cost in Clang on our code is over 100ms PER type instantiation. Maybe some compilers are much better *shrug*. Hence, it does not scale (or scales linearly at an impractical rate). Compare to unique_ptr which is barely 1ms, or a custom lightweight implementation that is equally as fast per T-inst."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-03T23:53:54.550",
"Id": "452263",
"Score": "0",
"body": "Coupled with template issues in general (ie. needing instantiations in each TU for open types) this can easily lead to per-TU costs which further exasperates the scaling issue into slow program compilation times."
}
] |
[
{
"body": "<p>The only thing I see that is a mistake is the bool operator. Instead of:</p>\n\n<pre><code>operator bool () const noexcept\n</code></pre>\n\n<p>You probably want:</p>\n\n<pre><code>explicit operator bool () const noexcept\n</code></pre>\n\n<p>The <code>explicit</code> prevents the compiler from being able to automatically convert your object to <code>bool</code> as part of a comparison.</p>\n\n<pre><code>res_ptr<X> data = getResPtr();\n\nif (true == data) {\n // Not sue you want that auto conversion.\n // The standard shared_ptr does not want this implicit conversion\n // I am sure there are other cases where it can be out-converted where\n // you don't want that to happen.\n\n doSomeWorkWithBool(data); // If that function takes a bool\n // it auto converts before the call.\n // auto conversions are not usually what\n // you want.\n}\n\n// Note:\nif (data) {\n // This still works as expected with the explicit\n // It is designed so that in a bool context like if()/while()/for() etc\n // the explicit conversion to bool is applied but in other contexts it\n // does not work any you need an explicit cast\n\n doSomeWorkWithBool(static_cast<bool>(data)); // Need an explict cast here\n // if you use the `explicit`\n // in the bool operator.\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-31T17:02:52.840",
"Id": "451841",
"Score": "0",
"body": "Thanks! I added `explicit` in the code (I don't update the question's version as per rules). Though, what you posted raised a question for me... `res_ptr<int>` does not compile because `int` doesn't inherit from resource. `res_ptr<res_version<int>>` needs to be used for this class to work with `int`. I didn't design `res_ptr` class to work with `int` so it might not be an issue but this design might be an issue in itself..."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-31T16:51:12.983",
"Id": "231620",
"ParentId": "231599",
"Score": "4"
}
},
{
"body": "<h1>Missing headers</h1>\n\n<ul>\n<li><code><cstddef></code> for <code>std::nullptr_t</code></li>\n<li><code><type_traits></code> for <code>std::is_base_of_v</code>, <code>std::is_same_v</code>, <code>std::enable_if_t</code></li>\n<li><code><utility></code> for <code>std::exchange</code>, <code>std::forward</code></li>\n</ul>\n\n<h1>Layout</h1>\n\n<p>The code is hard to read, with long lines and huge blocks of spaces (perhaps a misguided attempt to align keywords?). Stick to a conventional layout and it will be much easier to read.</p>\n\n<h1>Fix the errors and warnings</h1>\n\n<p>These should need no further explanation (except perhaps the one caused by misspelling <code>std::nullptr_t</code>):</p>\n\n<pre class=\"lang-none prettyprint-override\"><code>231599.cpp: In member function ‘resource& resource::operator=(resource&&)’:\n231599.cpp:13:55: warning: no return statement in function returning non-void [-Wreturn-type]\n 13 | resource& operator = (resource&&) noexcept {};\n | ^\n | return *this;\n231599.cpp: In member function ‘resource& resource::operator=(const resource&)’:\n231599.cpp:14:55: warning: no return statement in function returning non-void [-Wreturn-type]\n 14 | resource& operator = (const resource&) noexcept {};\n | ^\n | return *this;\n231599.cpp: At global scope:\n231599.cpp:43:7: warning: extra ‘;’ [-Wpedantic]\n 43 | {};\n | ^\n | -\n231599.cpp:57:5: error: non-static data member ‘nullptr_t’ declared ‘constexpr’\n 57 | constexpr res_ptr(nullptr_t) noexcept {};\n | ^~~~~~~~~\n231599.cpp:57:34: error: expected ‘;’ at end of member declaration\n 57 | constexpr res_ptr(nullptr_t) noexcept {};\n | ^\n | ;\n231599.cpp:57:37: error: expected unqualified-id before ‘noexcept’\n 57 | constexpr res_ptr(nullptr_t) noexcept {};\n | ^~~~~~~~\n231599.cpp:63:6: warning: extra ‘;’ [-Wpedantic]\n 63 | };\n | ^\n | -\n231599.cpp:83:6: warning: extra ‘;’ [-Wpedantic]\n 83 | };\n | ^\n | -\n231599.cpp:94:7: warning: extra ‘;’ [-Wpedantic]\n 94 | {};\n | ^\n | -\n231599.cpp:169:14: error: declaration of template parameter ‘PResource’ shadows template parameter\n 169 | template<typename PResource>\n | ^~~~~~~~\n231599.cpp:49:10: note: template parameter ‘PResource’ declared here\n 49 | template<typename PResource>\n | ^~~~~~~~\n231599.cpp:175:14: error: declaration of template parameter ‘PResource’ shadows template parameter\n 175 | template<typename PResource>\n | ^~~~~~~~\n231599.cpp:49:10: note: template parameter ‘PResource’ declared here\n 49 | template<typename PResource>\n | ^~~~~~~~\n231599.cpp: In constructor ‘res_ptr<PResource, typename std::enable_if<is_base_of_v<resource, PResource>, void>::type>::res_ptr(res_ptr<PResource, typename std::enable_if<is_base_of_v<resource, PResource>, void>::type>&&)’:\n231599.cpp:87:20: error: ‘exchange’ is not a member of ‘std’\n 87 | m_ptr(std::exchange(ptr.m_ptr, nullptr))\n | ^~~~~~~~\n231599.cpp: In constructor ‘res_ptr<PResource, typename std::enable_if<is_base_of_v<resource, PResource>, void>::type>::res_ptr(res_ptr<PResourceDerived>&&)’:\n231599.cpp:93:44: error: ‘exchange’ is not a member of ‘std’\n 93 | m_ptr(static_cast<PResource*>(std::exchange(ptr.m_ptr, nullptr)))\n | ^~~~~~~~\n231599.cpp: In member function ‘res_ptr<PResource, typename std::enable_if<is_base_of_v<resource, PResource>, void>::type>& res_ptr<PResource, typename std::enable_if<is_base_of_v<resource, PResource>, void>::type>::operator=(res_ptr<PResource, typename std::enable_if<is_base_of_v<resource, PResource>, void>::type>&&)’:\n231599.cpp:116:26: error: ‘exchange’ is not a member of ‘std’\n 116 | m_ptr = std::exchange(other.m_ptr,nullptr);\n | ^~~~~~~~\n231599.cpp: In member function ‘res_ptr<PResource, typename std::enable_if<is_base_of_v<resource, PResource>, void>::type>& res_ptr<PResource, typename std::enable_if<is_base_of_v<resource, PResource>, void>::type>::operator=(res_ptr<PResourceDerived>&&)’:\n231599.cpp:139:46: error: ‘exchange’ is not a member of ‘std’\n 139 | m_ptr = static_cast<PResource*>(std::exchange(other.m_ptr,nullptr));\n | ^~~~~~~~\n231599.cpp: In function ‘int main()’:\n231599.cpp:207:34: error: invalid use of incomplete type ‘class res_ptr<int, void>’\n 207 | auto a = make_resource<int>(5);\n | ^\n231599.cpp:47:7: note: declaration of ‘class res_ptr<int, void>’\n 47 | class res_ptr;\n | ^~~~~~~\n231599.cpp: In instantiation of ‘res_ptr<PResource> make_resource(Args&& ...) [with PResource = int; Args = {int}]’:\n231599.cpp:207:34: required from here\n231599.cpp:186:29: error: return type ‘class res_ptr<int, void>’ is incomplete\n 186 | res_ptr<PResource> make_resource(Args&& ... args)\n | ^~~~~~~~~~~~~\n231599.cpp:188:12: error: invalid use of incomplete type ‘class res_ptr<int, void>’\n 188 | return res_ptr<PResource>(new PResource(std::forward<Args>(args)...));\n | ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n231599.cpp:47:7: note: declaration of ‘class res_ptr<int, void>’\n 47 | class res_ptr;\n | ^~~~~~~\n</code></pre>\n\n<h1>Usage guidance</h1>\n\n<p>My first simple test, expecting a similar interface to <code>std::make_shared()</code>, failed:</p>\n\n<pre><code>auto a = make_resource<int>(5);\n</code></pre>\n\n<p>So I tried the next most obvious course:</p>\n\n<pre><code>auto a = make_resource<res_version<int>>(5);\n</code></pre>\n\n<p>This also fails, due to attempting to inherit from a non-struct type.</p>\n\n<p>It seems I need to create a struct (with a constructor) even for something this simple! Much less friendly than the standard shared pointer.</p>\n\n<h1>Questionable choices</h1>\n\n<p>Why use <code>int</code> to count references? An unsigned type would be more appropriate.</p>\n\n<p>We should check for overflow before incrementing the counter, and throw an exception if that would happen, otherwise we could delete objects still in use. I don't think that's possible without changing away from <code>std::memory_order_relaxed</code>.</p>\n\n<p>The <code>res_version</code> adapter should virtually inherit <code>resource</code>, to avoid the diamond problem when subclasses inherit from more than one of these.</p>\n\n<p>I'd prefer the <code>res_version</code> constructor to include an initializer for the <code>resource</code> base, rather than omitting it. The <code>T()</code> constructor is likely to be tricky here, as it makes it hard for users to select the <code>T{}</code> constructor - important for classes such as <code>std::vector</code>.</p>\n\n<p>The statement <code>if (m_ptr) m_ptr->add_ref();</code> is used many times - worth encapsulating in a member function (any decent compiler will inline it).</p>\n\n<p><code>std::is_base_of_v<PResource, PResourceDerived> && !std::is_same_v<PResource, PResourceDerived></code> is used many times - encapsulate that too (<code>is_derived_from<></code>, perhaps?).</p>\n\n<p><del>We haven't implemented <code>swap()</code>, so <code>std::swap()</code> will fall back to copying via a temporary, which implies needless updates to the count.</del></p>\n\n<p><code>res_ptr::operator=(res_ptr&&)</code> can be implemented in terms of <code>swap()</code> (if we write that), instead of releasing first.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-31T18:10:37.603",
"Id": "451873",
"Score": "0",
"body": "I find standard layout unreadable. Fixed errors with copy and move assignment for `resource` (strange that MSVS doesn't care...). I never tried to work with base types... nor it was designed to do so. It is annoying that C++ works this way. About why `int` to count references... I doubt it will ever make int overflow `int` for ref counter so it is not a practical error. `is_derived_from<>` perhaps the encapsulation is preferred indeed, but I am not too certain how to properly address cases when keywords `const/volatile` are included."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-31T18:13:04.213",
"Id": "451875",
"Score": "0",
"body": "\"The res_version adapter should virtually inherit resource, to avoid the diamond problem when subclasses inherit from more than one of these.\" I don't think so. If a subclass inherits `resource` version then you shouldn't make `res_version` to begin with; or better make a compatibility version that doesn't add anything anything if `resource` is a subclass."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-31T18:14:31.197",
"Id": "451877",
"Score": "0",
"body": "Wait... doesn't `swap` use `std::move` when possible? If it doesn't then it is a `std` error or the compiler's implementation of `std` fault."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-31T18:15:49.697",
"Id": "451878",
"Score": "0",
"body": "Ah yes, `std::swap()` requires `MoveAssignable`, so that's okay after all."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-31T18:19:28.237",
"Id": "451882",
"Score": "0",
"body": "`int` may overflow with as little as 32768 references, depending on the platform. You might consider that \"unlikely\", but I'd probably go for a `std::size_t` if not checking for overflow."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-31T18:23:03.067",
"Id": "451886",
"Score": "0",
"body": "I see `int` overflow is a portability issue. I am too used with `int` being 4 bytes long. Will switch to `std::size_t` or `unsigned long`... BTW are there any promises that `std::size_t` or `unsigned long` can be atomic without utilization of mutexes?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-31T18:27:20.477",
"Id": "451888",
"Score": "1",
"body": "No, just as there isn't such a guarantee for `std::atomic<int>` - it's entirely dependent on the capabilities of the target you're compiling for, so the C++ standard can't mandate such choices. It's what you'd call a quality of implementation issue. I'd expect most platforms to use spinlocks rather than process mutexes if they don't have hardware atomic integer operations, though."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-01T06:40:58.433",
"Id": "451950",
"Score": "0",
"body": "Checking for overflow and throwing is a trade-off more so than a preferable choice. Particularly so when the emphasis is lightweight."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-01T08:39:15.333",
"Id": "451958",
"Score": "0",
"body": "@PasserBy, true - but let's make sure it's a *conscious* trade-off!"
}
],
"meta_data": {
"CommentCount": "9",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-31T17:39:56.477",
"Id": "231626",
"ParentId": "231599",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "231626",
"CommentCount": "11",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-31T13:52:50.180",
"Id": "231599",
"Score": "7",
"Tags": [
"c++",
"memory-management",
"c++14",
"pointers"
],
"Title": "A lightweight version of std::shared_ptr<T>"
}
|
231599
|
<p>This was the first game I made not too long ago (2018), and while I'm working on another, more complex version, I want to know how good or bad I did this one and what can be improved.</p>
<p>Note: the change of players and detection of free spaces are the things I did with help of a friend, everything else I did it myself.</p>
<pre><code>#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
int printBoard();
int clear(int h, int w);
int freeSpace();
int player();
int checkLine(int x, int y, int z);
int winner();
int player_input;
char board[9] = {' ', ' ', ' ',
' ', ' ', ' ',
' ', ' ', ' '};
int player_num = 1;
char symbol = 'X';
int main(void)
{
char start;
clear(24, 80);
printf("\nTotito game on a 3x3 board:\n");
printf("Enter number from 1 to 9 to mark the respective spaces in the board.\n");
printf("Press a number to start the game: ");
scanf("%c", &start);
clear(24, 80);
printBoard();
while (true)
{
player();
clear(24, 80);
printBoard();
winner();
player_num = (player_num == 1)? 2: 1;
symbol = (player_num == 1)? 'X': 'O';
}
}
int printBoard() // 3x3 board
{
int lines = 7;
int columns = 7;
int n = 0;
for (int i = 1; i <= lines; i++)
{
printf(" ");
for (int j = 0; j < columns; j++)
{
if (i % 2 != 0)
{
if (j % 2 == 0)
{
printf("+");
}
else
{
printf("---");
}
}
else
{
if (j % 2 == 0)
{
printf("|");
}
else
{
printf(" %c ", board[n]);
n++;
}
}
}
printf("\n");
}
}
int clear(int h, int w)
{
printf("\033[0;0H");
for (int i = 0; i < w; i++)
{
for (int j = 0; j < h; j++)
{
printf(" ");
}
}
printf("\033[0;0H");
}
int freeSpace()
{
for (int i = 0; i < sizeof(board); i++)
{
if (board[i] == ' ')
{
return true;
}
}
}
int player()
{
printf("Player %d: ", player_num);
if (freeSpace())
{
scanf("%d", &player_input);
}
while (board[player_input - 1] != ' ')
{
printf("\033[1APlayer %d: Not empty, try again: ", player_num);
scanf("%d", &player_input);
}
board[player_input - 1] = symbol;
}
int checkLine(int x, int y, int z)
{
if ((board[x] == symbol) && (board[x] == board[y]) && (board[y] == board[z]))
{
printf("Player %d wins!\n", player_num);
exit(0);
}
}
int winner()
{
checkLine(0, 1, 2); //first horizontal
checkLine(3, 4, 5); //second horizontal
checkLine(6, 7, 8); //third horizontal
checkLine(0, 3, 6); //first vertical
checkLine(1, 4, 7); //second vertical
checkLine(2, 5, 8); //third vertical
checkLine(0, 4, 8); //first diagonal
checkLine(2, 4, 6); //second diagonal
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-31T14:33:15.723",
"Id": "451796",
"Score": "0",
"body": "Please include the header files, this program currently doesn't compile because the headers are missing."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-31T14:36:29.973",
"Id": "451797",
"Score": "1",
"body": "Okay, it's edited now,"
}
] |
[
{
"body": "<h2>Compiler Options and Warning Checking</h2>\n<p>It might be a good idea to use the -wall compiler switch. It will provide warning messages that may indicate possible logic errors in some cases. When compiled with -wall this program yields the following warning messages:</p>\n<blockquote>\n<p>D:\\ProjectsNfwsi\\CodeReview\\tictactoev1\\main.c(89) : warning C4716: 'printBoard': must return a value<br />\nD:\\ProjectsNfwsi\\CodeReview\\tictactoev1\\main.c(104) : warning C4716: 'clear': must return a value<br />\nD:\\ProjectsNfwsi\\CodeReview\\tictactoev1\\main.c(115) : warning C4715: 'freeSpace': not all control paths return a value<br />\nD:\\ProjectsNfwsi\\CodeReview\\tictactoev1\\main.c(133) : warning C4716: 'player': must return a value<br />\nD:\\ProjectsNfwsi\\CodeReview\\tictactoev1\\main.c(142) : warning C4715: 'checkLine': not all control paths return a value<br />\nD:\\ProjectsNfwsi\\CodeReview\\tictactoev1\\main.c(161) : warning C4716: 'winner': must return a value</p>\n</blockquote>\n<p>In some cases the functions should be declared <code>void</code> rather than int, in other cases there might be a bug when not all control paths return a value, this is certainly true in <code>freeSpace</code>.</p>\n<h2>Global Variables</h2>\n<p>Global variables make programs very, very difficult to write, read, debug and maintain. In the C programming language they can cause modules (other .c files) not link if the global variable is declared in multiple modules. Due to the nature of global variables, it is sometimes very difficult to find where they are changed in order to remove a bug.</p>\n<p>There is a discussion about global variables in this <a href=\"https://stackoverflow.com/questions/484635/are-global-variables-bad\">stackoverflow question</a></p>\n<p>It is much better to pass a variables into functions where they are needed.</p>\n<h2>Avoid Using <code>exit()</code></h2>\n<p>For a number of reasons the use of the <code>exit()</code> function should be avoided. The <code>exit()</code> function should be used when there is a non-recoverable error in a program. Since it is not being used for this purpose in this program it should definitely be avoided. It would be much better if the functions <code>checkLine()</code> and <code>winner()</code> returned values that indicated status.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-31T15:45:52.113",
"Id": "451812",
"Score": "0",
"body": "Okay, I'll correct all what you said, but what are other ways to close the program when the game is finished? Also, how good is my code in terms of clarity, readibility, and looking clean and understandable in general?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-31T15:49:37.063",
"Id": "451815",
"Score": "1",
"body": "@AlexaN The code is readable, the variable names are pretty good or I would have mentioned it in the review. About closing the program, it should always be done from main, that is what return 0 is about. Test the return value from `winner()` in main and exit if true."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-31T15:58:24.973",
"Id": "451820",
"Score": "0",
"body": "Ok, thank you! XD"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-01T17:52:24.647",
"Id": "452042",
"Score": "0",
"body": "You should stick to one naming convention; some of your variables use snake_case (```player_input```) while your methods use camelCase (```checkLine```). You can take a look at this answer (https://stackoverflow.com/a/1722518) for a more detailed explanation of C's naming conventions."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-02T13:36:05.673",
"Id": "452116",
"Score": "0",
"body": "@cliesens Okay, I'll fix it right away."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-31T15:41:37.540",
"Id": "231616",
"ParentId": "231603",
"Score": "2"
}
},
{
"body": "<h3>1. Determination the length of an array</h3>\n\n<p>Look at the marked line:</p>\n\n<pre><code>int freeSpace()\n{\n for (int i = 0; i < sizeof(board); i++) // <----\n {\n if (board[i] == ' ')\n {\n return true;\n }\n }\n}\n</code></pre>\n\n<p>This code works because <code>board</code> has type <code>char [9]</code>. For this reason <code>sizeof(board)</code> equals to the number of elements in <code>board</code><sup>1</sup>. But this code may fails, in case if you change the type of <code>board</code>.</p>\n\n<p>The correct way to determine the size of an array is</p>\n\n<pre><code>sizeof(board) / sizeof(board[0])\n</code></pre>\n\n<p>It would be better to define a macro:</p>\n\n<pre><code>#define ARRAY_LENGTH(a) (sizeof(a) / sizeof((a)[0]))\n</code></pre>\n\n<h3>2. Declaration of a function that takes no parameters</h3>\n\n<p>The correct way to declare a function without any parameters is</p>\n\n<pre><code>int printBoard(void);\n</code></pre>\n\n<p>instead of</p>\n\n<pre><code>int printBoard();\n</code></pre>\n\n<p>Please, for more details, take a look at <a href=\"https://stackoverflow.com/questions/5929711/c-function-with-no-parameters-behavior\">this</a> question on SO.</p>\n\n<hr>\n\n<p><sup>1</sup> Since <code>sizeof(char)</code> always equals to 1.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-01T17:20:58.560",
"Id": "452039",
"Score": "0",
"body": "Thanks for the explanation, I'll correct it."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-01T08:13:56.250",
"Id": "231657",
"ParentId": "231603",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-31T14:16:11.190",
"Id": "231603",
"Score": "2",
"Tags": [
"beginner",
"c",
"game",
"tic-tac-toe"
],
"Title": "Tic Tac Toe in C - Version 1"
}
|
231603
|
<p>Suppose my goal is to add elements to list in python if they pass a conditional. There are many ways to do this and I show some. Would it be possible if you could review each block and describe its performance in context of the other blocks? Additionally, if possible, can you provide some performance heuristics for the task of appending these elements to my lists?</p>
<p>For each of these lists, the output is the same</p>
<pre><code>[0,1,2,3]
</code></pre>
<p><strong>Block 01</strong></p>
<pre><code>my_list = []
for num in range(10):
if num < 4:
my_list.append(num)
</code></pre>
<p><strong>Block 02</strong></p>
<pre><code>my_list = [num for num in range(10) if num < 4]
</code></pre>
<p><strong>Block 03</strong> </p>
<pre><code>cond = lambda num: num < 4
my_list = [num for num in range(10) if cond]
</code></pre>
<p><strong>Block 04</strong></p>
<pre><code>my_list = list(filter(lambda num: num < 4, list(range(10))))
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-31T15:44:12.300",
"Id": "451811",
"Score": "1",
"body": "Have you met our Lord and Saviour, the [`timeit`](https://docs.python.org/3.8/library/timeit.html) module ?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-31T15:47:53.560",
"Id": "451814",
"Score": "0",
"body": "No, I have not met it unfortunately. I am not new to Python but would like to focus more on testing, performance, and optimization. Are there any unix commands you know where, at the command line, I can get performance metrics? Also, can you provide an example of using timeit in one of the blocks?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-31T15:50:08.690",
"Id": "451817",
"Score": "0",
"body": "Timeit is a standard library module of Python that does exactly that. And no, I don't have any experience using it myself."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-31T15:54:59.737",
"Id": "451818",
"Score": "1",
"body": "Here: timeit.timeit('list(filter(lambda num: num < 4, list(range(10))))',number=5000) produces: 0.014093596000009256 AND timeit.timeit('[num for num in range(10) if num < 4]',number=5000) produces: 0.006313477999981387 SO Block 2 is more than 2x faster than Block 4 So you can use it in your code: import timeit, then timeit.timeit('expression',number = number of iterations)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-01T09:47:30.920",
"Id": "451963",
"Score": "1",
"body": "Feel free to use that to answer your own question. That's perfectly valid."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-01T13:13:25.093",
"Id": "451989",
"Score": "1",
"body": "Block 3 has a bug. Since functions are always truthy, and you don't actually call the function, you get all numbers in the list. It should be `[num for num in range(10) if cond(num)]`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-01T13:16:59.510",
"Id": "451991",
"Score": "1",
"body": "Anyways, I'm not sure if this is on-topic here. Comparative reviews are OK, but you need to want to get feedback on any and all aspects of the code(s). Instead you seem to be asking us to give you advice on general best practices (which would be off-topic) and this does not seem to be real code, but rather a generic example (hypothetical code is also off-topic). Asking us to write code for you (in this case the timing code), would also be off-topic."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-01T14:04:05.667",
"Id": "451998",
"Score": "1",
"body": "@Graipher Thanks for pointing this out. I am mainly concerned with each of these _specific_ blocks of code and improving each of their performances but the outcome of which works the fastest will determine which I use most often. I suppose I have written my own timing code."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-31T15:31:42.733",
"Id": "231614",
"Score": "1",
"Tags": [
"python",
"performance"
],
"Title": "Efficiency Heuristics for Adding Elements to Lists in Python"
}
|
231614
|
<p>Best rational approximations is a technical term and not subjective. The best rational approximations are the convergents of a value plus it's semi convergents that are closer to the original value than the previous convergents.</p>
<p>Hi everyone,</p>
<p>I've written some quick code in Python that is my tool for exploring various aspects of music theory, number theory, and my obsession with OEIS. It's currently written to spit out a list of the ratio's themselves. It would be quite easy to tweak to your needs. This may also help anyone exploring the logic of infinite continued fractions and convergents. I use the decimal module here for precision. It's written so you can paste any value you want into the input field - that can easily be tweaked to accept any real number from code. Phasers to stun. I call it my approximilator.</p>
<p>(Python 3)</p>
<pre><code>import decimal
import math
D = decimal.Decimal
def contFrac(x, k):
"""Cont Frac from Real value"""
cf = []
q = math.floor(x)
cf.append(q)
x = x - q
i = 0
while x != 0 and i < k:
q = math.floor(1 / x)
if q > k:
break
cf.append(q)
x = 1/x - q
i += 1
return cf
def bestra(clist, app):
"""Best Rational Approximation from Cont. Frac"""
hn0, kn0 = 0, 1
hn1, kn1 = 1, 0
"""Best Rational Approx Init"""
ran, rad = 0, 0
conlist, ralist, finallist = [], [], []
for n in clist:
for i in range(1, n+1):
ran = (hn0 + (i*hn1))
rad = (kn0 + (i*kn1))
try:
if D.copy_abs(app-D(ran/rad)) < D.copy_abs(app-D(hn1/kn1)):
ralist.append({'ratio': f'{ran}/{rad}', 'denom' : rad})
except:
pass
hn2 = (n*hn1)+hn0
kn2 = (n*kn1)+kn0
conlist.append({'ratio': f'{hn2}/{kn2}', 'denom': kn2})
hn0, kn0 = hn1, kn1
hn1, kn1 = hn2, kn2
for x in sorted(conlist+ralist, key = lambda i: i['denom']):
finallist.append(x['ratio'])
return list(dict.fromkeys(finallist))
if __name__ == "__main__":
value = D(input('Input value to approximate: '))
prec = len(str(value))*2
decimal.getcontext().prec = prec
vc = contFrac(value, prec)
print(bestra(vc, value))
</code></pre>
<p>Some output for Pi to entice:</p>
<pre><code>'3/1', '13/4', '16/5', '19/6', '22/7', '179/57', '201/64', '223/71', '245/78', '267/85', '289/92', '311/99', '333/106', '355/113', '52163/16604', '52518/16717', '52873/16830', '53228/16943', '53583/17056', '53938/17169', '54293/17282', '54648/17395', '55003/17508', '55358/17621', '55713/17734', '56068/17847', '56423/17960'
</code></pre>
|
[] |
[
{
"body": "<h2>PEP-8 Guidelines</h2>\n\n<p>Follow the <a href=\"https://lmgtfy.com/?q=pep8+style+guide&s=d&t=w\" rel=\"nofollow noreferrer\">PEP-8 Style Guidelines</a>, such as:</p>\n\n<ul>\n<li>1 space around operators (<code>1 / x</code> instead of <code>1/x</code>)</li>\n<li><code>snake_case</code> for identifiers & functions (<code>cont_frac</code> instead of <code>contFrac</code>)</li>\n</ul>\n\n<h2>Import As</h2>\n\n<p>The preferred method of creating an alias for an import is:</p>\n\n<pre><code>from decimal import Decimal as D\n</code></pre>\n\n<p>Since you are only using the <code>floor</code> function from <code>math</code>, you could also:</p>\n\n<pre><code>from math import floor\n</code></pre>\n\n<h2>Docstrings</h2>\n\n<p><code>\"\"\"Docstrings\"\"\"</code> exist to help a user with the usage of a function. There are usually in triple quotes, because they should be multi-line strings, with enough information to be useful to the caller, without needing the caller to read the source code.</p>\n\n<pre><code>def continue_fraction(x, k):\n \"\"\"\n Construct a continued fraction from a real value\n\n Parameters:\n x (float): Real value to determine continued fraction of\n k (int): A loop limit representing accuracy somehow\n\n Returns:\n List[Int]: List of continued fraction values\n \"\"\"\n</code></pre>\n\n<p>A <code>\"\"\"docstring\"\"\"</code> is the <strong>first</strong> statement of a module, class, function or method, if it is a string. In particular,</p>\n\n<pre><code> \"\"\"Best Rational Approx Init\"\"\"\n</code></pre>\n\n<p>is not a <code>\"\"\"docstring\"\"\"</code>, because it is not the first statement. It should be a comment.</p>\n\n<pre><code> # Best Rational Approx Init\n</code></pre>\n\n<p>Comments are used to document the source code, for someone <em>reading the source code</em>. In contrast, <code>\"\"\"Docstrings\"\"\"</code> are used to provide help to the user of the item, so they <em>do not have to read the source code</em>. It is displayed using the <code>help()</code> command:</p>\n\n<pre><code>>>> help(continue_fraction)\n</code></pre>\n\n<p>Don't use docstrings as comments, or vise-versa.</p>\n\n<h2>Superfluous Parenthesis</h2>\n\n<pre><code> ran = (hn0 + (i*hn1))\n rad = (kn0 + (i*kn1))\n</code></pre>\n\n<p>should be written as</p>\n\n<pre><code> ran = hn0 + i * hn1\n rad = kn0 + i * kn1\n</code></pre>\n\n<h2>Named Tuple</h2>\n\n<p>Consider using a named tuple, instead of using dictionaries for fixed content items.</p>\n\n<pre><code>from collections import namedtuple\n\nfraction = namedtuple(\"fraction\", \"ratio, denom\")\n\n...\n\n ...\n ralist.append(fraction(f'{ran}/{rad}', rad))\n ...\n\n for x in sorted(conlist + ralist, key=lambda i: i.denom):\n finallist.append(x.ratio)\n</code></pre>\n\n<h2>Collection</h2>\n\n<p>Why are you maintaining <code>ralist</code> separate from <code>conlist</code>, when you later add the two lists together and sort them?? Why not just maintain a single list?</p>\n\n<h2>List Comprehension</h2>\n\n<p>List appending is inefficient:</p>\n\n<pre><code> finallist = []\n for x in sorted(conlist + ralist, key=lambda i: i.denom):\n finallist.append(x.ratio)\n</code></pre>\n\n<p>due to repeated reallocations of the list as the list size grows. It is better to construct and initialize the list in one operation:</p>\n\n<pre><code> finallist = [ x.ration for x in sorted(conlist + ralist, key=lambda i: i.denom) ]\n</code></pre>\n\n<p><s></p>\n\n<h2>Useless</h2>\n\n<p>This operation:</p>\n\n<pre><code>return list(dict.fromkeys(finallist))\n</code></pre>\n\n<p>takes a list, turns it into a dictionary with each list item as a key (all the dictionary values are <code>None</code>), and then constructs a list from just the dictionary's keys. Uhm. As long as the dictionary is kept in insertion order, which it is because you are using <code>f''</code> strings so must be using Python 3.6 or later, this is indistinguishable from:</p>\n\n<pre><code>return finallist\n</code></pre>\n\n<p></s></p>\n\n<p>Apparently the goal here was to remove duplicates. A comment would have helped; it is not obvious.</p>\n\n<h2>Meaningful Function and Variable Names</h2>\n\n<p>What is <code>contFrac</code> and <code>bestra</code>? It would be way clearer to use <code>continued_fraction</code> and <code>best_rational_approximation</code>, especially if you are writing this for \"<em>anyone exploring the logic of infinite continued fractions</em>\".</p>\n\n<p><code>conlist</code>, <code>ralist</code>, <code>clist</code>, <code>app</code>, <code>ran</code> and <code>rad</code> are equally obscure.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-01T14:04:28.917",
"Id": "451999",
"Score": "0",
"body": "`list(dict.fromkeys(finallist))` is different from `finallist` if it has duplicates. But that is not the best way to get rid of duplicates."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-01T15:49:12.690",
"Id": "452023",
"Score": "0",
"body": "Solid, any suggestions to remove duplicates?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-01T16:02:32.753",
"Id": "452026",
"Score": "0",
"body": "I see. [w3schools](https://www.w3schools.com/python/python_howto_remove_duplicates.asp) recommends that as the way to remove duplicates. Using [`itertools.groupby()`](https://docs.python.org/3.8/library/itertools.html#itertools.groupby) to removed duplicates should be faster for large already sorted datasets. See especially the `unique_justseen()` recipe."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-01T18:27:06.910",
"Id": "452047",
"Score": "0",
"body": "unique_justseen(), excellent. Thanks for your time , I appreciate it."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-01T04:55:24.177",
"Id": "231653",
"ParentId": "231617",
"Score": "2"
}
},
{
"body": "<p>Revised version per answer:</p>\n\n<pre><code>import decimal\nfrom math import floor\nfrom decimal import Decimal as D\nfrom collections import namedtuple\n\ndef continued_fraction(x, k):\n cf = []\n q = floor(x)\n cf.append(q)\n x = x - q\n i = 0\n\n while x != 0 and i < k:\n q = floor(1 / x)\n if q > k:\n break\n cf.append(q)\n x = 1 / x - q\n i += 1\n\n return cf\n\ndef best_rational_approximation(clist, app):\n hn0, kn0 = 0, 1\n hn1, kn1 = 1, 0\n ran, rad = 0, 0\n conlist, finallist = [], []\n fraction = namedtuple(\"fraction\", \"ratio, numer, denom\")\n for n in clist:\n for i in range(1, n + 1):\n ran = hn0 + (i * hn1)\n rad = kn0 + (i * kn1)\n try:\n if D.copy_abs(app-D(ran/rad)) < D.copy_abs(app-D(hn1/kn1)):\n conlist.append(fraction(f'{ran}/{rad}', ran, rad))\n except:\n pass\n hn2 = (n * hn1) + hn0\n kn2 = (n * kn1) + kn0\n conlist.append(fraction(f'{hn2}/{kn2}', hn2, kn2))\n hn0, kn0 = hn1, kn1\n hn1, kn1 = hn2, kn2\n #Change x.ratio to x.denom or x.numer for numerators or denominators \n finallist = [ x.ratio for x in sorted(conlist, key=lambda i: i.denom) ]\n return list(dict.fromkeys(finallist))\n\n\nif __name__ == \"__main__\":\n value = D(input('Input value to approximate: '))\n prec = len(str(value))*2\n decimal.getcontext().prec = prec\n vc = continued_fraction(value, prec)\n print(best_rational_approximation(vc, value))\n~ \n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-01T15:54:13.737",
"Id": "231685",
"ParentId": "231617",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "231653",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-31T15:52:01.393",
"Id": "231617",
"Score": "1",
"Tags": [
"python",
"python-3.x",
"mathematics",
"numerical-methods",
"rational-numbers"
],
"Title": "Get the best rational approximations for any real number in builtin Python"
}
|
231617
|
<p>I am designing this nice form handling in React/Redux/Saga and I am quite afraid it might not be optimised. So I decided to ask you what you think :)</p>
<p>First of all, I won't get into details how I normalise the json-s to get to this structure, because this post will get huge, so this is how my redux state is being initialised on FORM/INIT:</p>
<pre><code>form: {
formName: {
fields: { //this is were I save my form definition, for rendering purposes
section1: {
children: {
textInput: {
id: 'textInput',
name: 'Name',
type: 'text',
validations: [
{
type: 'required',
message: 'This field is required!'
}
]
}
}
}
},
model: {
path: 'section1.children.textInput',
value: 'Some value',
isTouched: false,
activeErrorState: {
hasError: false,
message: ''
}
}
}
}
</code></pre>
<p>Basically, for "speed" (which might not be the case...) I am separating my values/active-error-state/flags from my definitions. Plus, I flatten the model and strip representational types like "section", "group", "formGroup" that are used by the component, that generates the form from the "fields" definition. Plus, I have this "path" key, which in my head helps me browse the "fields" tree faster :) In this example, it is just 3 levels nested, but in my real world, I have sometimes up to 10 levels depth.</p>
<p>So here is what worries me in my code.</p>
<p>This is the saga, that is triggered on every change in my form fields:</p>
<pre><code>function* changeFormField(action) {
// selects the redux store
const store = yield select();
// the payload have the name of the form, the name of the field and the value that need to get changed in the redux store (the model part of my form)
const { formName, fieldName, value } = action.payload;
// finding the form's fields definition and model is quite easy:
const { fields, model } = store.form[formName];
// I need to search the whole fields three to find the deeply nested field name, so that I can get it's validations definitions:
const fieldDefinition = findInObjectByString(fields, model[fieldName].path);
// I have a function that creates validation functions based on the validation definitions
const validations = getValidations(fieldDefinition.validations);
// I check if the new value is correct or not
const runValidationsResult = runValidations(fieldName, value, validations);
// this line triggers an action that updates the model.
yield put(
Actions.updateFormField(
formName,
fieldName,
value,
runValidationsResult
)
);
}
</code></pre>
<p>As you can see, I need to go through this findInObjectByString function which browses the "fields" three for the validations definition on every "onChange".</p>
<pre><code>export const findInObjectByString = (nestedObject, string) => {
// I clone the nested object, because I am afraid of mutations :)
let clonedNestedObject = deepclone(nestedObject);
// strip the string just in case
string = string.replace(/\[(\w+)\]/g, '.$1');
// remove a possible first '.' just in case
string = string.replace(/^\./, '');
// split the string into array of keys to iterate and search the three
const pathArray = string.split('.');
// eslint-disable-next-line no-plusplus
for (let i = 0, n = pathArray.length; i < n; ++i) {
const k = pathArray[i];
if (k in clonedNestedObject) {
clonedNestedObject = clonedNestedObject[k];
} else {
return;
}
}
// eslint-disable-next-line consistent-return
return clonedNestedObject;
};
</code></pre>
<p>And I also need to use it one more time (get the field's type), when I flatten the object, so I can send it to backend:</p>
<pre><code>export const flattenFormModel = (formObject) => {
const { fields, model } = formObject;
// this is a reduce function that takes a flat model and flattens it even more :D because BE has specific needs as it comes to how it takes the values, so I need to make some small modifications to my model and send it away:
return Object.keys(model).reduce((acc, cur) => {
let currentValue = model[cur].value;
const fieldDefinition = findInObjectByString(fields, model[cur].path);
// BE specific things, is why this is needed :)
if (fieldDefinition.type === FIELD_TYPES.DROPDOWN && currentValue) {
currentValue = currentValue.value;
}
// BE specific things, is why this is needed :)
if (fieldDefinition.type === FIELD_TYPES.DYNAMIC && currentValue) {
currentValue = currentValue.map((item) => {
if (item.newField) {
delete item.newField;
return {
...item,
id: 0
};
}
return item;
});
}
return {
...acc,
[cur]: currentValue
};
}, {});
};
</code></pre>
<p>Now in my gut, I have the feeling that this is not a great approach. I find it too much three search (even though it is a hash three, I access it by key). I was thinking of putting validations and type in the model as well, but doesn't that means that there is no need for the fields/model separation?</p>
<p>One thing that needs to be considered however is that the BE is completely unaware of my form's structure. It sends me initial model like flat structure: [{name: value}, {name: value}].</p>
<p>Please help a fellow developer become a better code writer :)</p>
<p>10x a lot!</p>
|
[] |
[
{
"body": "<p>The reason why you have to search in the way you currently are is because your redux store is so deeply nested. Flatten it and it will make things a lot easier. Have all text inputs, regardless of which form or section it belongs to, in a data structure with its own unique <code>id</code>.</p>\n\n<p>The <code>textfield</code> doesn't need to \"know\" which form or section it belongs to. You make that the job of another aspect of your store. I prefer JavaScript <code>Map</code>s, but you are more than welcome to use objects.</p>\n\n<p>Create keys dedicated to keeping track of which sections contain which form, and what textfields belong to which section.</p>\n\n<p>When you need to access inputs, all you need is to grab the <code>id</code> of the textfield directly</p>\n\n<p>Something along the lines of this. Model only needs to know the id. Not the object nesting structure.</p>\n\n<pre><code>{\n\nforms: new Map(\n [\n 'form1',\n ['section1', 'section2' //...]\n ]\n)\n\nfields: new Map(\n [\n 'section1',\n ['textInput', 'otherTextInput']\n ]\n)\n\ntextInputs: new Map(\n [\n 'textInput',\n {\n id: 'textInput',\n name: 'Name',\n type: 'text',\n validations: [\n {\n type: 'required',\n message: 'This field is required!'\n }\n ]\n }\n ],\n [\n 'otherTextInput',\n {\n id: 'otherTextInput',\n name: 'Name',\n type: 'text',\n validations: [\n {\n type: 'required',\n message: 'This field is required!'\n }\n ]\n }\n ]\n)\n\nmodel: {\n path: 'textInput',\n value: 'Some value',\n isTouched: false,\n activeErrorState: {\n hasError: false,\n message: ''\n }\n }\n}\n<span class=\"math-container\">```</span>\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-07T10:18:24.817",
"Id": "452781",
"Score": "0",
"body": "Hi Andrew! Your answer is great, however I try to keep my state this nested and not flat, because this is the payload that the Backend needs. So it is quite easy for me to just take the redux state and POST it to the API"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-07T22:15:40.243",
"Id": "452866",
"Score": "0",
"body": "@ChrisPanayotova Your backend code should not affect the structure of your frontend. They are completely separate entities and you tangle up one in order to perfectly accommodate for the other. Your redux store should be written in terms of ease of use for your frontend. Write an algorithm to structure your redux data to match what the backend needs before the api call is made."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-01T21:15:29.387",
"Id": "231708",
"ParentId": "231621",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-31T16:52:18.283",
"Id": "231621",
"Score": "2",
"Tags": [
"javascript",
"react.js",
"redux"
],
"Title": "Redux/Redux-saga forms architecture optimisations"
}
|
231621
|
<p>This is program that computes the minimum of the function <span class="math-container">\$y=(ax+b)^2\$</span>. The program will find the value of <span class="math-container">\$x\$</span> that gives the minimum <span class="math-container">\$y\$</span>. It will start with an initial value <span class="math-container">\$x\$</span> that you assign. </p>
<pre><code>#include <stdio.h>
#include <stdlib.h>
int main()
{
int a, b, i;
float threshold, xt1, xt0, l_r, x, min_y;
threshold=0.001;
l_r=0.01;
xt0=500;
scanf("%d",&a);
scanf("%d",&b);
xt1=xt0-l_r*2*a*(a*xt0+b);
for (i=0;i<20;++i){
while ((xt1-xt0)>threshold){
xt1=xt1-l_r;
return xt1;
}
while ((xt1-xt0)<threshold && (xt1-xt0)!=0){
xt1=x;
min_y=2*a*(a*x+b);
printf("min y is %f",min_y);
break;
}
}
return 0;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-31T19:50:40.993",
"Id": "451900",
"Score": "2",
"body": "Unfortunately, this appears to be off-topic here because this doesn't appear to be working as intended. Please note that Code Review is about improving existing, working code. Code Review is not the site to ask for help in fixing or changing *what* your code does. Once the code does what you want, we would love to help you do the same thing in a cleaner way! Please see our [help center](/help/on-topic) for more information."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-01T00:42:08.440",
"Id": "451914",
"Score": "0",
"body": "@Edward How is it not working? I don't see any specifics. It's closeable due to lack of context, for sure, but I don't see a not-working-as-intended."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-01T00:45:56.263",
"Id": "451915",
"Score": "2",
"body": "The line `return xt1;` is very suspect, don’t you think?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-01T13:44:00.883",
"Id": "451997",
"Score": "0",
"body": "@Edward Help me out, which combination of `a` and `b` will fail?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-01T14:27:10.937",
"Id": "452003",
"Score": "0",
"body": "@konijn: try `a=1, b=-600`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-08T11:35:17.290",
"Id": "452921",
"Score": "0",
"body": "`(ax+b)^2=(ax)^2+2abx+b^2`. Derivation of that is `2*x*(a^2)+2ab`. Extreme is where derivation is equal zero. `2*x*(a^2)+2ab=0` => `x=-2ab/(2*(a^2))=-b/a`. Second derivation is `4ax`. If second derivation at the extreme is positive the extreme is a minimum, otherwise minimum is negative infinity."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-08T11:58:46.440",
"Id": "452922",
"Score": "0",
"body": "Sry, mistake, second derivative is `2*(a^2)`, which is always positive and so `-b/a` is always the minimum. `a!=0`"
}
] |
[
{
"body": "<p>Firstly, the iterative approach is unnecessary, as we know the minimum must be at x = -b/a. I'll assume that the use of a quadratic function here is supposed to be illustrative of a more general function.</p>\n\n<p>There's an unnecessary include of <code><stdlib.h></code>, so we can drop that. <code>return 0;</code> is not needed at the end of <code>main()</code>, so we can omit that too.</p>\n\n<p>It's clearer to declare <code>main()</code> as taking no arguments: <code>int main(void)</code>.</p>\n\n<p>It's 20 years since local variables needed to be declared at the beginning of their enclosing scope; it's better to declare where first initialised if possible, to reduce the likelihood of accidentally using an uninitialised variable. This is a bug we have in this program, where we use <code>x</code> before it's ever initialised.</p>\n\n<p>Always, <strong>always</strong> check the result of <code>scanf()</code> and family before assuming that assignments were made. If either of these fail, then we can't assume that <code>a</code> and <code>b</code> contain valid values:</p>\n\n<pre><code>if (scanf(\"%d%d\", &a, &b) != 2) {\n fputs(\"Invalid inputs\\n\", stderr);\n return EXIT_FAILURE; /* from <stdlib.h> */\n}\n</code></pre>\n\n<p>As an aside, why do we only want integer values for <code>a</code> and <code>b</code>? I think they should be <code>double</code> (as should all the <code>float</code> variables).</p>\n\n<p>A <code>while</code> loop that ends in an unconditional <code>break</code> or <code>return</code> can only ever run 0 or 1 times, so it's equivalent to an <code>if</code> statement, and should be written as such. In fact, why are we returning a <code>float</code> from <code>main()</code>?</p>\n\n<p>The code disagrees with the description in printing the result:</p>\n\n<blockquote>\n<pre><code> printf(\"min y is %lf\",min_y);\n</code></pre>\n</blockquote>\n\n<p>Weren't we supposed to print the minimum <em>x</em> ordinate? (<code>min_y</code> is trivially always zero for y = (<em>a</em>x + <em>b</em>)², isn't it?)</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-01T08:55:09.057",
"Id": "231659",
"ParentId": "231622",
"Score": "2"
}
},
{
"body": "<p>With numeric tasks that could yield a wide range of answers, more informative to use <code>\"%e\"</code> than <code>\"%f\"</code> - else small non-zero values appear as <code>\"0.000000\"</code>.</p>\n\n<pre><code>// printf(\"min y is %f\",min_y);\nprintf(\"min y is %e\\n\",min_y);\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-01T19:23:14.357",
"Id": "231697",
"ParentId": "231622",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-31T17:03:34.637",
"Id": "231622",
"Score": "-1",
"Tags": [
"c",
"mathematics"
],
"Title": "Find minimum value of a quadratic function"
}
|
231622
|
<p>How can I speed up this code?</p>
<pre class="lang-py prettyprint-override"><code>coin=[50000, 20000, 10000, 5000, 2000, 1000, 500, 200, 100, 50, 20, 10, 5, 2, 1]
def matrix(coins, kerdes): # it create a metrix
tabla = [[0 for m in range(kerdes + 1)] for m in range(len(coins) + 1)]
for i in range(kerdes + 1):
tabla[0][i] = i
return tabla
def change_making(coin, change):
table = matrix(coin, change)
for c in range(1, len(coin) + 1):
for r in range(1, change + 1):
if coin[c - 1] == r:
table[c][r] = 1
elif coin[c - 1]> r:
table[c][r] = table[c-1][r]
else:
table[c][r] = min(table[c - 1][r], 1 + table[c][r - coin[c - 1]])
return table[-1][-1] #return the minimum coin what we need to make the change
newcoin=int(input()) # ask the new coin
coin.append(newcoin) #add to the coin list
coin.sort(reverse=True) #sort the list to get the biggest coin to first
changemakings=[int(x) for x in input().split()] # order the 'orders' to list for easier work with it
for changes in changemakings:
print(change_making(coin, changes))
</code></pre>
<p>This is my code it calculate the minimum coin, with possible to give new coin which will result a non canonical change system.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-31T17:12:33.780",
"Id": "451848",
"Score": "0",
"body": "post a testable `changemakings` list values"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-31T17:34:11.513",
"Id": "451861",
"Score": "0",
"body": "from 1 to 10^7 like [1,18,35,4587425,9400]"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-31T19:06:18.410",
"Id": "451892",
"Score": "0",
"body": "Can you clarify what does \"minimum change\" (as resulting digit) conceptually mean? Please provide a more extended description"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-31T21:11:36.517",
"Id": "451908",
"Score": "0",
"body": "Yes i miss wrote it. I meant coin."
}
] |
[
{
"body": "<p>I ran a few examples through the code and I have made the following assumptions:</p>\n\n<ul>\n<li><p>the code calculates the minimum amount of coins needed to produce the user's input</p></li>\n<li><p>the user can enter in a custom coin and it will use that as part of its calculations</p></li>\n</ul>\n\n<p>Instead of using a matrix, I just found the highest coin which can be used to make change, then subtracted it from the total user inputted amount, and repeated it until there was no change left.</p>\n\n<pre><code>coins = [50000, 20000, 10000, 5000, 2000, 1000, 500, 200, 100, 50, 20, 10, 5, 2, 1]\n\ncoinToAdd = int(input(\"Enter in coin to add to coins:\"))\nuserMoney = int(input(\"Enter in coin to calculate change:\"))\ncoins.append(coinToAdd)\ncoins.sort(reverse=True)\ntotalCoins = 0\nwhile [j for j in coins if userMoney >= j]:\n userMoney = userMoney - [j for j in coins if userMoney >= j][0]\n totalCoins = totalCoins + 1\n\nprint(totalCoins)\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-01T23:14:01.630",
"Id": "233242",
"ParentId": "231623",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-31T17:04:12.700",
"Id": "231623",
"Score": "4",
"Tags": [
"python",
"performance",
"python-3.x"
],
"Title": "Money change/minimum coin algorithm"
}
|
231623
|
<p>Rate limiter has to comply with the spec:</p>
<blockquote>
<p>Every request comes in with a unique clientID, deny a request if that
client has made more than 100 requests in the past second.</p>
</blockquote>
<p>Would be happy if you review:</p>
<pre><code>import java.util.HashMap;
import java.util.TreeSet;
import java.util.Map;
public class RateLimiter {
private static final int REQ_LIMIT = 100;
private static final int TIME_CUTOFF = 1000;
private Map<String, TreeSet<Long>>_client_requests = new HashMap<String, TreeSet<Long>>();
public RateLimiter() {
}
public boolean isAllowed(String clientId) {
TreeSet<Long> reqs = this._client_requests.get(clientId);
if (reqs != null) {
Long current_ts = System.currentTimeMillis();
if (current_ts - reqs.first() < TIME_CUTOFF) {
if (reqs.size() < REQ_LIMIT) {
reqs.add(current_ts);
}
else return false;
}
else {
reqs.retainAll(reqs.tailSet(current_ts - TIME_CUTOFF));
reqs.add(current_ts);
}
}
else {
TreeSet<Long> new_client_reqs = new TreeSet<>();
new_client_reqs.add(System.currentTimeMillis());
this._client_requests.put(clientId, new_client_reqs);
}
return true;
}
}
</code></pre>
<p>Tests:</p>
<pre><code>import junit.framework.Assert;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
/**
* Unit test for simple App.
*/
public class AppTest
extends TestCase
{
/**
* Create the test case
*
* @param testName name of the test case
*/
public AppTest( String testName )
{
super(testName);
}
/**
* @return the suite of tests being tested
*/
public static Test suite()
{
return new TestSuite( AppTest.class );
}
/**
* Rigourous Test :-)
*/
public void testRateLimiter()
{
RateLimiter rl = new RateLimiter();
Assert.assertTrue(rl.isAllowed("1"));
}
public void testRateLimiterManyReqs() throws InterruptedException
{
RateLimiter rl = new RateLimiter();
for (int i = 0; i < 100; i++) {
Assert.assertTrue(rl.isAllowed("1"));
Thread.sleep(5);
}
Assert.assertFalse(rl.isAllowed("1"));
}
}
</code></pre>
|
[] |
[
{
"body": "<p>I believe a <code>LinkedList</code> would fit this problem better. Add to the end of it, delete from the beginning. All such operations would be O(1).</p>\n\n<p>Using <code>System.nanoTime</code> is better for comparing time than <code>System.currentTimeMillis</code> - which goes by the computer system time and can thus change in case of time synchronization.</p>\n\n<p>You're using <code>junit.framework.TestCase</code>, but I'd recommend using <code>@Test</code> annotation instead.</p>\n\n<p>You need more exhaustive tests.</p>\n\n<p>Your <code>RateLimiter</code> constructor is the default constructor which does not need to be specified.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-01T11:08:12.043",
"Id": "451969",
"Score": "0",
"body": "thanks a lot. How would you implement `reqs.retainAll(reqs.tailSet(current_ts - TIME_CUTOFF));` using LinkedList?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-01T12:15:46.370",
"Id": "451980",
"Score": "0",
"body": "@rok Using LinkedList, that would be something like `while (list.peekFirst() < value) { list.removeFirst(); }`"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-31T22:53:52.640",
"Id": "231639",
"ParentId": "231624",
"Score": "3"
}
},
{
"body": "<p>It would make sense to assume that a rate limiter is used in a multithreaded environment. Your code has no synchronization and will break on concurrent access.</p>\n\n<p>Testing time dependant operstions by relying on the wall clock is hard (imposible) to get 100% reliable. You need to use a time provider that can be configured to return the exact values your test case requires. I think JodaTime (and other major libraries) have ready made tools for this </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-02T07:28:20.730",
"Id": "231722",
"ParentId": "231624",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-31T17:11:53.447",
"Id": "231624",
"Score": "6",
"Tags": [
"java"
],
"Title": "RateLimiter Java"
}
|
231624
|
<p>I am trying to perform optimization using a surrogate model instead of the real function and for that, I need the gradient of my LSTM model with respect to the input. In this case, I have 3 features that vary over time. The LSTM calculates from the initial value of these 3 features the following 100 time steps hence the Jacobian matrix has the shape 100x3x3. It turns out that my code for evaluating the gradient is slower (235 seconds per iteration) than the code that calculates the gradient function (18 seconds per iteration). Would you mind helping me to speed up the gradient evaluation so I can perform optimization using the evaluation function?</p>
<p>The LSTM model and the data can be download from <a href="https://gofile.io/?c=azKljF" rel="nofollow noreferrer">https://gofile.io/?c=azKljF</a></p>
<p>Code:</p>
<pre><code># multivariate multi-step encoder-decoder lstm for the power usage dataset
from numpy import split, sqrt, linspace, load, savetxt
from numpy import array, zeros, mean,sum, min, max
from pandas import read_csv, DataFrame
from matplotlib import pyplot
from keras.models import Sequential
from keras.layers import Dense
from keras.layers import LSTM
from keras.layers import RepeatVector
from keras.layers import TimeDistributed
from keras.models import model_from_json
from keras import backend as k
import matplotlib.pyplot as plt
import tensorflow as tf
import datetime
sess=tf.Session()
sess.run(tf.global_variables_initializer())
# split a univariate dataset into train/test sets
def split_dataset(data,n_train,n_test,steps_per_simulation):
train, test = data[:n_train*steps_per_simulation,:], data[-n_test*steps_per_simulation:,:]
train = array(split(train, len(train)/steps_per_simulation))
test = array(split(test, len(test)/steps_per_simulation))
return train, test
# evaluate forecasts against expected values
def evaluate_forecasts(actual, predicted):
# calculate an RMSE score for each day
actual=actual.reshape(actual.shape[0]*actual.shape[1],actual.shape[2])
predicted=predicted.reshape(predicted.shape[0]*predicted.shape[1],predicted.shape[2])
rmse=zeros(actual.shape[1])
mse=zeros(actual.shape[1])
for j in range(actual.shape[1]):
# calculate mse
mse[j] = sum(((actual[:,j]-predicted[:,j])/predicted[:,j])**2)
# calculate rmse
rmse = sqrt(mse/len(actual[:,j]))
mean_rmse=mean(rmse)
return mean_rmse, rmse
# summarize scores
def summarize_scores(name, score, scores):
s_scores = ', '.join(['%.5f' % s for s in scores])
print('%s: [%.5f] %s' % (name, score, s_scores))
# convert history into inputs and outputs
def to_supervised(train, n_input, n_output):
# flatten data
data = train.reshape((train.shape[0]*train.shape[1], train.shape[2]))
X, y = list(), list()
in_start = 0
# step over the entire history one time step at a time
for _ in range(len(data)):
# define the end of the input sequence
in_end = in_start + n_input
out_end = in_end + n_output
# ensure we have enough data for this instance
if out_end <= len(data):
X.append(data[in_start:in_end, :])
y.append(data[in_end:out_end, :])
# move along one time step
in_start += 1
return array(X), array(y)
# train the model
def build_model(train, n_input, n_feat, n_output):
# prepare data
train_x, train_y = to_supervised(train, n_input,n_output)
# define parameters
verbose, epochs, batch_size = True, 4, 7*n_output
n_timesteps, n_features, n_outputs = train_x.shape[1], train_x.shape[2], train_y.shape[1]
# reshape output into [samples, timesteps, features]
train_y = train_y.reshape((train_y.shape[0], train_y.shape[1], train_y.shape[2]))
# define model
model = Sequential()
model.add(LSTM(10, activation='relu', input_shape=(n_timesteps, n_features)))
model.add(RepeatVector(n_outputs))
model.add(LSTM(10, activation='relu', return_sequences=True))
model.add(TimeDistributed(Dense(100, activation='relu')))
model.add(TimeDistributed(Dense(n_feat)))
model.compile(loss='mse', optimizer='adam')
# fit network
model.fit(train_x, train_y, epochs=epochs, batch_size=batch_size, verbose=verbose,shuffle='true')
return model
# evaluate a single model
def build(train, n_input,n_output,n_feat):
# fit model
model = build_model(train, n_input,n_feat,n_output)
history = [x for x in train]
return model, history
def predict(model,test,n_input,n_feat):
# walk-forward validation over each week
data = array(test)
data = data.reshape((data.shape[0]*data.shape[1], data.shape[2]))
predictions = list()
for i in range(test.shape[0]):
for j in range(0,test.shape[1]):
input_x=test[i,j:j+n_input,:].reshape(1,n_input,n_feat)
yhat = model.predict(input_x, verbose=0)
yhat = yhat[0]
predictions.append(yhat[0,:])
predictions = array(predictions).reshape(test.shape)
return predictions
def predict100(model,test2,n_input,n_output,n_feat):
predictions2 = zeros((test2.shape[0],n_input+n_output,n_feat))
predictions2[:,:n_input,:]=test2[:,:n_input,:]
for i in range(test2.shape[0]):
input_x=test2[i,:n_input,:].reshape(1,n_input,n_feat)
yhat = model.predict(input_x, verbose=0)
yhat = yhat[0:n_output,:].reshape(yhat.shape[1],yhat.shape[2])
predictions2[i,n_input:,:]=yhat
return predictions2
def evaluate_model(test, predictions):
score, scores = evaluate_forecasts(test, predictions)
return score, scores
def normalize(x0,data):
Norm_dataset=zeros(x0.shape)
n_feat=x0.shape[-1]
for i in range(0,n_feat):
Norm_dataset[:,i]=(x0[:,i]-min(data[:,i]))/(max(data[:,i])-min(data[:,i]))
return Norm_dataset
def unnormalize(x0,data):
Unnorm_dataset=zeros(x0.shape)
n_feat=x0.shape[-1]
for i in range(0,n_feat):
Unnorm_dataset[:,i]=x0[:,i]*(max(data[:,i])-min(data[:,i]))+min(data[:,i])
return Unnorm_dataset
#
def jacobian_tensorflow(model,x0,n_feat,n_output,sess):
jacobian_matrix = []
for i in range(n_output):
print('Calculating dx'+str(i+1)+'/dx0')
start_time = datetime.datetime.now()
for m in range(n_feat):
# We iterate over the M elements of the output vector
start_time1 = datetime.datetime.now()
grad_func = tf.gradients(model.output[:,i,m], model.input)
end_time1 = datetime.datetime.now()
diff1 = (end_time1 - start_time1).total_seconds()
print('Calculating Jacobian function time=',diff1)
start_time2 = datetime.datetime.now()
gradients = sess.run(grad_func, feed_dict={model.input: x0})
end_time2 = datetime.datetime.now()
diff2 = (end_time2 - start_time2).total_seconds()
print('Evaluating Jacobian time=',diff2)
jacobian_matrix.append(gradients[0][0,:])
end_time = datetime.datetime.now()
diff = (end_time - start_time).total_seconds()
print('Total time=',diff)
return array(jacobian_matrix)
def get_grad_func(model,n_feat,n_output):
grad_func1=[]
grad_func2=[]
grad_func3=[]
grad_func=[]
for i in range(n_output):
print('Calculating dx'+str(i+1)+'/dx0')
grad_func1.append(tf.gradients(model.output[:,i,0], model.input))
grad_func2.append(tf.gradients(model.output[:,i,1], model.input))
grad_func3.append(tf.gradients(model.output[:,i,2], model.input))
grad_func1= tf.reshape(grad_func1,[n_output,1,n_feat])
output1=tf.stack(grad_func1)
grad_func2= tf.reshape(grad_func2,[n_output,1,n_feat])
output2=tf.stack(grad_func2)
grad_func3= tf.reshape(grad_func3,[n_output,1,n_feat])
output3=tf.stack(grad_func3)
grad_func.append(output1)
grad_func.append(output2)
grad_func.append(output3)
return grad_func
def eval_grad(model,x0,n_feat,n_output,sess,grad_func):
jacobian_matrix = []
for i in range(n_output):
print('Evaluating dx'+str(i+1)+'/dx0')
for n in range(n_feat):
for m in range(n_feat):
gradients = sess.run(grad_func[n][i,:,m], feed_dict={model.input: x0})
jacobian_matrix.append(gradients)
J_matrix=zeros((n_output,n_feat,n_feat))
count=0
for i in range(n_output):
for j in range(n_feat):
J_matrix[i,j,:]=jacobian_matrix[count:count+n_feat]
count=count+n_feat
return J_matrix
# load the new file
L3D=load('lorenz-3d.npy')
original_dataset=L3D[:,:,:].reshape(L3D.shape[0]*L3D.shape[1],L3D.shape[2])
n_input=1
n_output=100
steps_per_simulation=501
n_train=9970
n_test=30
dataset = normalize(original_dataset,original_dataset)
n_feat=dataset.shape[1]
# split into train and test
train, test = split_dataset(dataset,n_train,n_test,steps_per_simulation)
# load json and create model
json_file = open('1_input_100_output_9970training.json', 'r')
loaded_model_json = json_file.read()
json_file.close()
model = model_from_json(loaded_model_json)
# load weights into new model
model.load_weights("1_input_100_output_9970training.h5")
print("Loaded model from disk")
x0=dataset[0,:].reshape(1,n_input,n_feat)
sess.run(tf.global_variables_initializer())
#I replaced n_output =100 by n_output=5 so the code runs faster
grad_func=get_grad_func(model,n_feat,5)
J=eval_grad(model,x0,n_feat,5,sess,grad_func)
savetxt('Jacobian',J.reshape(J.shape[0],J.shape[2]))
sess.close()
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-01T00:28:12.950",
"Id": "451913",
"Score": "1",
"body": "Use numpy. n-dimensional numerics are simply not feasible in bare Python."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-01T13:40:49.920",
"Id": "451996",
"Score": "1",
"body": "Per your question, please do provide `data and full code`, this question will quickly get closed otherwise."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-31T17:16:14.737",
"Id": "231625",
"Score": "4",
"Tags": [
"python",
"performance",
"session",
"tensorflow"
],
"Title": "Evaluating a previously calculated gradient function"
}
|
231625
|
<p>I'm writing a code generation library, I've exposed a couple of methods and of course in order to define a member you need to specify it's type, the easiest way is to use <code>typeof(Type)</code>, which I later format so that it it's compilable and I can insert it as a code chunk e.g. <code>System.Int32</code>, which for non-generic types is basically concatenating the namespace and the type's name. </p>
<p>That works fine but generic types have the backtick followed by the number of arguments, so I needed a method to format all the types, so that they are always compilable e.g. <code>System.Collection.Generics.List<System.Int32></code>. </p>
<pre><code>public static class TypeExtensions
{
public static string FormatTypeName(this Type type)
{
if(type == null) { throw new ArgumentNullException(nameof(type)); }
if (type.IsGenericType)
{
var definedArguments = type.GetGenericArguments();
var genericIdentifier = $"`{definedArguments.Length}";
if (definedArguments.First().FullName == null)
{
var genericBraces = "<".PadRight(definedArguments.Length, ',') + ">";
return $"{type.Namespace}.{type.Name.Replace(genericIdentifier, genericBraces)}";
}
var formattedTypes = definedArguments.Select(definedArgument => definedArgument.FormatTypeName());
var newGenericArguments = $"<{string.Join(", ", formattedTypes)}>";
return $"{type.Namespace}.{type.Name.Replace(genericIdentifier, newGenericArguments, StringComparison.InvariantCultureIgnoreCase)}";
}
return $"{type.Namespace}.{type.Name}";
}
}
</code></pre>
<p>It supports indefinite amount of nested and linear generic arguments due to the recursion that is in-place. </p>
<hr>
<p>The way it works is pretty straight forward, there are 2 possible incomes, we have no arguments defined e.g. <code>typeof(Dictionary<,>)</code> or all of the arguments are defined e.g <code>typeof(Dictionary<int, int>)</code>.</p>
<p>Since the C# compiler doesn't allow partially defined arguments we can simply check if the first of the arguments has a FullName (note that <code>Name</code> is the name pf the generic argument not the type behind it), if it does we simply concatenate all of the arguments and surround them by <code><></code>. if the first argument doesn't have value then it's empty and we just leave the braces with commas separating the arguments.</p>
<hr>
<p>Since this will be used in a code generation tool, performance is not crucial, but always welcome as long as it doesn't damage the readability and maintainability of the code, which I consider more important in this case. </p>
<p>However since it will be used in a code generation tool, I'm more worried about whether I've missed some edge cases.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-31T19:42:30.457",
"Id": "451895",
"Score": "0",
"body": "Since FormatTypeName is an extension method I don't think that the parameter type can ever be null. Also, if you want more performance you can take a look at this answer for how to create strings of repeated characters. https://stackoverflow.com/a/720915/7412948"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-31T19:43:52.867",
"Id": "451896",
"Score": "3",
"body": "@JeffreyParks It can be null! :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-31T19:45:17.613",
"Id": "451897",
"Score": "1",
"body": "Good to know! Also, if this proves to be too slow and you have a lot of repeated type usage, you could consider caching the results into a static Dictionary<type,string> so you avoid a lot of repeated work."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-31T19:49:21.427",
"Id": "451899",
"Score": "2",
"body": "@JeffreyParks an extension method is just syntax sugar for `ExtClass.ExtMethod(obj)`, it's not a member call on `obj` ;-)"
}
] |
[
{
"body": "<p>You can let <code>CSharpCodeProvider</code> format Type names:</p>\n\n<pre><code>public static string FormatTypeName(this Type type)\n{\n using (var c = new CSharpCodeProvider()) {\n var r = new CodeTypeReference(type);\n return c.GetTypeOutput(r);\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-31T19:47:46.190",
"Id": "231633",
"ParentId": "231630",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-31T19:14:16.980",
"Id": "231630",
"Score": "3",
"Tags": [
"c#",
".net",
"formatting",
".net-core"
],
"Title": "Formatting a type's name"
}
|
231630
|
<p>You can set any size of the field, you can set how much you need to put in a row to win. I think I got a pretty flexible program.
What do you think about the code? I would like to know if I made mistakes in program design. </p>
<p>skeleton:</p>
<pre><code>public class Main {
private static String[] turn;
private static int hmInARowToWin;
private static Scanner sc = new Scanner(System.in);
private static pole[][] area;
public static void main(String[] args) {
System.out.println("Hi, lets play tik tak toe!");
while(true) {
System.out.println("Pick x.length and y.length of area(print"+'"'+"x y"+'"'+"): ");
turn = sc.nextLine().split(" ");
if(turn.length!=2) {
System.out.println("print: "+'"'+"x y"+'"'+"!");
}
else if(!isNumeric(turn[0])||!isNumeric(turn[1])) {
System.out.println("x and y should be numbers!");
}
else if(Integer.parseInt(turn[0])<=0||Integer.parseInt(turn[1])<=0) {
System.out.println("x and y should be >0!");
}
else {
area = new pole[Integer.parseInt(turn[0])][Integer.parseInt(turn[1])];
break;
}
}
fillAreaNOTHING();
String hmInARowToWinString;
while(true) {
System.out.println("hm in a row?");
hmInARowToWinString = sc.nextLine();
if(!isNumeric(hmInARowToWinString)) {
System.out.println("it should be a number!");
}
else if(Integer.parseInt(hmInARowToWinString)<3) {
System.out.println("it should be >2");
}
else if(Integer.parseInt(hmInARowToWinString)>Math.max(area.length,area[0].length)) {
System.out.println("u can not win");
}
else {
hmInARowToWin=Integer.parseInt(hmInARowToWinString);
break;
}
}
player winner;
while(true) {
printArea();
thisPlayerTurn(player.FIRST);
if(checkforWin(player.FIRST)) {
winner = player.FIRST;
break;
}
printArea();
thisPlayerTurn(player.SECOND);
if(checkforWin(player.SECOND)) {
winner = player.SECOND;
break;
}
}
printArea();
System.out.println("u won, "+winner.name);
}
private static void thisPlayerTurn(player p) {
System.out.println(p.name+" player, yours turn!(print: "+'"'+"x y"+'"'+")");
while(true) {
turn = sc.nextLine().split(" ");
if(turn.length!=2) {
System.out.println("print: "+'"'+"x y"+'"'+"!");
}
else if(!isNumeric(turn[0])||!isNumeric(turn[1])) {
System.out.println("x and y should be numbers!");
}
else if(!isXandYIn()) {
System.out.println("x and y should be in area! P.S.: area.lengthY="+area.length+", area.lengthX="+area[0].length);
}
else if(area[Integer.parseInt(turn[1])][Integer.parseInt(turn[0])]!=pole.NOTHING){
System.out.println("this place is already taken! Take another.");
}
else {
if(p==player.FIRST) {
area[Integer.parseInt(turn[1])][Integer.parseInt(turn[0])] = pole.X;
}
else { //second
area[Integer.parseInt(turn[1])][Integer.parseInt(turn[0])] = pole.O;
}
break;
}
}
}
private static boolean checkforWin(player p) {
pole toCheck;
if(p==player.FIRST) {
toCheck = pole.X;
}
else { //second
toCheck = pole.O;
}
for(int y=0;y<area.length;y++) {
for(int x=0;x<area[0].length;x++) {
if(area[y][x]!=toCheck) {continue;}
if(checkHorizontal(x,y,toCheck)||checkVertical(x,y,toCheck)||checkRightUpDiagonal(x,y,toCheck)||checkLeftUpDiagonal(x,y,toCheck)) {
return true;
}
}
}
return false;
}
private static boolean checkLeftUpDiagonal(int x, int y,pole toPick);
private static boolean checkRightUpDiagonal(int x, int y,pole toPick);
private static boolean checkVertical(int x, int y,pole toPick);
private static boolean checkHorizontal(int x, int y,pole toPick);
private static boolean isXandYIn() {}
public static boolean isNumeric(String strNum);
public static void printArea();
static void fillAreaNOTHING();
private static String repeat(int times,String string);
enum pole{
X,O,NOTHING
}
enum player{
FIRST("first"),SECOND("second");
String name;
player(String name){
this.name = name;
}
}
}
</code></pre>
<p>full code:</p>
<pre><code>public class Main {
private static String[] turn;
private static int hmInARowToWin;
private static Scanner sc = new Scanner(System.in);
private static pole[][] area;
public static void main(String[] args) {
System.out.println("Hi, lets play tik tak toe!");
while(true) {
System.out.println("Pick x.length and y.length of area(print"+'"'+"x y"+'"'+"): ");
turn = sc.nextLine().split(" ");
if(turn.length!=2) {
System.out.println("print: "+'"'+"x y"+'"'+"!");
}
else if(!isNumeric(turn[0])||!isNumeric(turn[1])) {
System.out.println("x and y should be numbers!");
}
else if(Integer.parseInt(turn[0])<=0||Integer.parseInt(turn[1])<=0) {
System.out.println("x and y should be >0!");
}
else {
area = new pole[Integer.parseInt(turn[0])][Integer.parseInt(turn[1])];
break;
}
}
fillAreaNOTHING();
String hmInARowToWinString;
while(true) {
System.out.println("hm in a row?");
hmInARowToWinString = sc.nextLine();
if(!isNumeric(hmInARowToWinString)) {
System.out.println("it should be a number!");
}
else if(Integer.parseInt(hmInARowToWinString)<3) {
System.out.println("it should be >2");
}
else if(Integer.parseInt(hmInARowToWinString)>Math.max(area.length,area[0].length)) {
System.out.println("u can not win");
}
else {
hmInARowToWin=Integer.parseInt(hmInARowToWinString);
break;
}
}
player winner;
while(true) {
printArea();
thisPlayerTurn(player.FIRST);
if(checkforWin(player.FIRST)) {
winner = player.FIRST;
break;
}
printArea();
thisPlayerTurn(player.SECOND);
if(checkforWin(player.SECOND)) {
winner = player.SECOND;
break;
}
}
printArea();
System.out.println("u won, "+winner.name);
}
private static void thisPlayerTurn(player p) {
System.out.println(p.name+" player, yours turn!(print: "+'"'+"x y"+'"'+")");
while(true) {
turn = sc.nextLine().split(" ");
if(turn.length!=2) {
System.out.println("print: "+'"'+"x y"+'"'+"!");
}
else if(!isNumeric(turn[0])||!isNumeric(turn[1])) {
System.out.println("x and y should be numbers!");
}
else if(!isXandYIn()) {
System.out.println("x and y should be in area! P.S.: area.lengthY="+area.length+", area.lengthX="+area[0].length);
}
else if(area[Integer.parseInt(turn[1])][Integer.parseInt(turn[0])]!=pole.NOTHING){
System.out.println("this place is already taken! Take another.");
}
else {
if(p==player.FIRST) {
area[Integer.parseInt(turn[1])][Integer.parseInt(turn[0])] = pole.X;
}
else { //second
area[Integer.parseInt(turn[1])][Integer.parseInt(turn[0])] = pole.O;
}
break;
}
}
}
private static boolean checkforWin(player p) {
pole toCheck;
if(p==player.FIRST) {
toCheck = pole.X;
}
else { //second
toCheck = pole.O;
}
for(int y=0;y<area.length;y++) {
for(int x=0;x<area[0].length;x++) {
if(area[y][x]!=toCheck) {continue;}
if(checkHorizontal(x,y,toCheck)||checkVertical(x,y,toCheck)||checkRightUpDiagonal(x,y,toCheck)||checkLeftUpDiagonal(x,y,toCheck)) {
return true;
}
}
}
return false;
}
private static boolean checkLeftUpDiagonal(int x, int y,pole toPick) {
/*
i mean:
X
X
X
*/
;
int leftUpDirection=0,rightDownDirection=0;
boolean areWeLookingOnTempX;
if(x>y) {
areWeLookingOnTempX=false;
}
else {
areWeLookingOnTempX=true;
}
for(int tempX = x-1,tempY = y-1;areWeLookingOnTempX ? tempX>=0 : tempY>=0;tempX--,tempY--) {
if(area[tempY][tempX]==toPick) {
leftUpDirection++;
}
else {
break;
}
}
if(area[0].length-x>area.length-y) {
areWeLookingOnTempX=false;
}
else {
areWeLookingOnTempX=true;
}
for(int tempX = x+1,tempY = y+1;areWeLookingOnTempX ? tempX<area[0].length : tempY<area.length;tempX++,tempY++) {
if(area[tempY][tempX]==toPick) {
rightDownDirection++;
}
else {
break;
}
}
return 1+leftUpDirection+rightDownDirection==hmInARowToWin;
}
private static boolean checkRightUpDiagonal(int x, int y,pole toPick) {
/*
i mean:
X
X
X
*/
int rightUpDirection=0,leftDownDirection=0;
boolean areWeLookingOnTempX;
if(area[0].length-x>y+1) {
areWeLookingOnTempX=false;
}
else {
areWeLookingOnTempX=true;
}
for(int tempX = x+1,tempY = y-1;areWeLookingOnTempX ? tempX<area[0].length:tempY>=0;tempX++,tempY--) {
if(area[tempY][tempX]==toPick) {
rightUpDirection++;
}
else {
break;
}
}
if(x+1>area.length-y) {
areWeLookingOnTempX=false;
}
else {
areWeLookingOnTempX=true;
}
for(int tempX = x-1,tempY = y+1;areWeLookingOnTempX ? tempX>=0:tempY<area.length;tempX--,tempY++) {
if(area[tempY][tempX]==toPick) {
leftDownDirection++;
}
else {
break;
}
}
return 1+rightUpDirection+leftDownDirection==hmInARowToWin;
}
private static boolean checkVertical(int x, int y,pole toPick) {
/*
i mean:
X
X
X
*/
int upDirection=0,downDirection=0;
for(int i=y-1;i>=0;i--) {
if(area[i][x]==toPick) {
upDirection++;
}
else {
break;
}
}
for(int i=y+1;i<area.length;i++) {
if(area[i][x]==toPick) {
downDirection++;
}
else {
break;
}
}
return 1+upDirection+downDirection==hmInARowToWin;
}
private static boolean checkHorizontal(int x, int y,pole toPick) {
/*
i mean:
X X X
*/
int rightDirection=0,leftDirection=0;
for(int i=x-1;i>=0;i--) {
if(area[y][i]==toPick) {
leftDirection++;
}
else {
break;
}
}
for(int i=x+1;i<area[0].length;i++) {
if(area[y][i]==toPick) {
rightDirection++;
}
else {
break;
}
}
return 1+rightDirection+leftDirection==hmInARowToWin;
}
private static boolean isXandYIn() {
int turnX = Integer.parseInt(turn[0]);
int turnY = Integer.parseInt(turn[1]);
if(turnX<0||area[0].length<=turnX) {
return false;
}
if(turnY<0||area.length<=turnY) {
return false;
}
return true;
}
public static boolean isNumeric(String strNum) {
try {
Integer.parseInt(strNum);
} catch (NumberFormatException | NullPointerException nfe) {
return false;
}
return true;
}
public static void printArea() {
if(area != null) {
for(int i=0;i<area.length;i++) {
if(i!=0) {
System.out.println(repeat(area[0].length-1,"----")+"---");
}
for(int b=0;b<area[0].length;b++) {
if(b!=0) {
System.out.print("|");
}
System.out.print(" ");
if(area[i][b]==pole.X) {
System.out.print("X");
}
else if(area[i][b]==pole.O) {
System.out.print("0");
}
else {
System.out.print(" ");
}
System.out.print(" ");
}
System.out.println();
}
}
}
static void fillAreaNOTHING() {
for(int i=0;i<area.length;i++) {
for(int b=0;b<area[0].length;b++) {
area[i][b] = pole.NOTHING;
}
}
}
private static String repeat(int times,String string) {
String newStr="";
for(int i=0;i<times;i++) {
newStr+=string;
}
return newStr;
}
enum pole{
X,O,NOTHING
}
enum player{
FIRST("first"),SECOND("second");
String name;
player(String name){
this.name = name;
}
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-01T06:11:23.837",
"Id": "451947",
"Score": "0",
"body": "Welcome to Code review! I have rolled back your last two edits. 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>Nice job using ENUMS </p>\n\n<p>I'm going to try to do the Code Review top-down.</p>\n\n<p><strong>Don't shorten variable names</strong></p>\n\n<p>The compiler doesn't care how long names are. I'm guessing the 'hm' in <code>hmInARowToWin</code> stands for 'howMany'. So it should be changed to <code>howManyInARowToIn</code> or <code>amountInARowToWin</code>.</p>\n\n<p><strong>Use 'final' keyword when possible</strong></p>\n\n<p>Your scanner object is never going to change. So you could delcare it as final. You should then change the name to <code>SC</code> or <code>SCANNER</code>.</p>\n\n<p><strong>Enums should begin with an upper-case letter and be UpperCamelCase</strong></p>\n\n<p>This is just a naming standard. Java has common naming practices you should be following.</p>\n\n<p>So <code>player</code> should be <code>Player</code>, <code>pole</code> should be <code>Pole</code>.</p>\n\n<p><strong>Avoid magic Strings / magic numbers</strong></p>\n\n<p>Lots to be said on this topic, tbh you can google 'magic strings' or 'avoid magic numbers' for more information but it boils down to maintainability. It's easier to make changes if the static String are declared as a class variable:</p>\n\n<pre><code>private static final String WELCOME_MESSAGE = \"Hi, lets play tik tak toe!\";\n</code></pre>\n\n<p>It's also easier to spot typos if you only have one place to look (Developers are known for typos and generally magic Strings are things the users will see, which are very important to be correct).</p>\n\n<p><strong>Use backslash as an escape character</strong></p>\n\n<p>Change from: <code>\"Pick x.length and y.length of area(print\"+'\"'+\"x y\"+'\"'+\"): \"</code></p>\n\n<p>to: <code>\"Pick x.length and y.length of area(print\\\"x y\\\"): \"</code></p>\n\n<p><strong>Use plenty of methods to breakup your code into pieces</strong></p>\n\n<p>This is a skill that takes some practice. Again a lot could be said here, but basically you want each of your methods to be doing only 1 thing.</p>\n\n<p>Getting input from the user & doing something with it should be put into a method.</p>\n\n<p>Validating the input should be a method</p>\n\n<p><strong>Use white space between conditions to increase readability</strong></p>\n\n<p>Change:\n<code>(Integer.parseInt(turn[0])<=0||Integer.parseInt(turn[1])<=0)</code></p>\n\n<p>To:\n<code>(Integer.parseInt(turn[0]) <= 0 || Integer.parseInt(turn[1]) <= 0)</code></p>\n\n<p>Same goes for additions, make sure a whitespace comes before & after the <code>+</code>.</p>\n\n<p><strong>Use camel case for method names & ensure method names make sense</strong></p>\n\n<p><code>fillAreaNOTHING</code> should be renamed to <code>fillAreaNothing</code>. Then it should be renamed to <code>fillAreaWithNothing</code>, the javadoc would explain <code>nothing</code> is the class variable and/or use `{@link Pole#NOTHING} in the java doc.</p>\n\n<p><strong>Use class variables strategically. Variables should be within the smallest scope possible</strong></p>\n\n<p>Putting all variables at class level because it's slightly easier creates spaghetti code and makes it really hard to follow. It also makes it harder / impossible to write methods that only do 1 thing.</p>\n\n<p>Your <code>fillAreaWithNothing</code> method should take <code>area</code> as a parameter.</p>\n\n<p><strong>Create Classes. Java is an Object Oriented language after all</strong></p>\n\n<p>Your main method should be calling some kind of TicTacToe class. You'll also want to keep the non-related stuff out of that class, such as checking if a String is a number or not.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-01T05:18:29.397",
"Id": "451943",
"Score": "0",
"body": "Thanks!\nI fixed my mistakes. Look at it, please."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-31T22:59:19.010",
"Id": "231640",
"ParentId": "231632",
"Score": "7"
}
}
] |
{
"AcceptedAnswerId": "231640",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-31T19:43:57.910",
"Id": "231632",
"Score": "5",
"Tags": [
"java",
"game",
"console",
"tic-tac-toe"
],
"Title": "Tic tac toe game for the console"
}
|
231632
|
<p>This code checks user permissions for uploading file, and if user can upload, then the file undergoes a check to see if it exists in SharePoint. If so then the file is pulled and uploaded to S3 bucket. This all works fine, but I have been told all these catches create callback hell. I've been trying to implement promises but I am very confused on how to change these callbacks to promises. Appreciate any help. </p>
<pre><code>//////////////////
// Dependencies //
//////////////////
const path = require('path');
const fs = require('fs');
const ping = require('tcp-ping');
const Semaphore = require('mysql-semaphore');
const dateFormat = require('dateformat');
const randomstring = require("randomstring");
const rimraf = require("rimraf");
const docx4js = require('docx4js');
var sppull = require("sppull").sppull;
const storage = require('azure-storage');
///////////////////////////////
// Sequelize database models //
///////////////////////////////
const Sequelize = require('sequelize');
const sequelize = require('../util/database');
const Op = Sequelize.Op;
const ProjectContacts = sequelize.import('../models/db/project_contact');
////////////////////////
// Local dependencies //
////////////////////////
const { parseJsonFile, encrypt, makeDirs, waitForLock, pullFromSharePoint, decrypt, doesFileExistSp } = require('../util/common');
const { getNormalizedFilepath, updateTAndCCleanup, convertDocxToHtml, insertNewTCVersion, waitForFileUpload } = require('../util/update-t-and-c-helper');
const { listContainers, createContainer, uploadString, uploadLocalFile, listBlobs, downloadBlob } = require('../util/blob-helper');
const createError = require('../util/error-management').createErrorFlow;
const { getProjectPath, saveMetadata, copyFileSpToS3Cleanup } = require('../util/copy-to-s3-helper');
const { getTimeTaken, formatLockKey, saveFileToSp, createFolderIfNotExists, createFolderPathRecursively, processExcelFileRequest } = require('../util/common');
const logger = require('../util/logger')(module);
</code></pre>
<pre><code>const fileName = req.body.fileName.trim();
const spSite = req.body.spSite;
const spFolder = req.body.spFolder;
const email = req.body.email_address;
const downloadPath = req.body.S3Path;
const spFile = `${spFolder}/${fileName}`;
const before = Date.now();
const uploadFolderName = 'upload';
const siteUrl = `${process.env.SP_URL}/sites/${spSite}/`;
const creds = {
username: process.env.SP_USER,
password: decrypt(process.env.SP_PASSWORD)
};
</code></pre>
<pre><code>ProjectContacts.findAll({ where: { can_upload_files: 1, email_address: email }, attributes: ['email_address', 'project_id', 'can_upload_files'] })
.then(projectContacts => {
if (projectContacts.length > 0) { //If email can upload, proceed
doesFileExistSp(creds, spSite, siteUrl, spFile) //Check if file exists in SharePoint
.then(exists => {
if (exists) {
logger.info(`DOWNLOAD PATH: ${downloadPath}`);
logger.info(`FILENAME: ${fileName}`);
const sppullContext = {
siteUrl: siteUrl, //SharePoint URL
creds: {
username: process.env.SP_USER,
password: decrypt(process.env.SP_PASSWORD)
}
};
const sppullOptions = {
spRootFolder: spFolder, // The folder path for the file in SharePoint
dlRootFolder: downloadPath, // Where the file is saved locally
strictObjects: [fileName], // Only download the fileName specified as a query parameter
muteConsole: true
};
pullFromSharePoint(sppullContext, sppullOptions)
.then(filepath => { //Pull file with fileName from SharePoint
logger.info(`FILE NOW IN PATH: ${filepath}`);
// Create the upload directory within the project directory.
const s3UploadFolder = path.join(downloadPath, uploadFolderName);
makeDirs(s3UploadFolder)
.then(() => { //creates upload folder in s3
function saveMetadataCallback(errorObj) { //callback for saveMetadata which checks for errors, semaphore/locks not being used
if (errorObj) {
const filepath = path.join(downloadPath, fileName);
copyFileSpToS3Cleanup(filepath, semaphore, lockKey).then(() => {
const error = createError(errorObj.errorMsg, errorObj.statusCode, errorObj.origErr);
return next(errorObj);
}).catch(errorObj => {
const error = createError(errorObj.errorMsg, errorObj.statusCode, errorObj.origErr);
return next(error);
});
}
}
saveMetadata(saveMetadataCallback); // Save the metadata info.json files.
}).catch(err => {
const filepath = path.join(downloadPath, fileName);
copyFileSpToS3Cleanup(filepath, semaphore, lockKey)
.then(() => {
const error = createError('Unable to create upload directory', 500, err);
return next(error);
}).catch(errorObj => {
const error = createError(errorObj.errorMsg, errorObj.statusCode, errorObj.origErr);
return next(error);
});
});
return res.status(200).json({
message: `${fileName} has been uploaded to ${filepath}`
})
}).catch(errorObj => {
const filepath = path.join(downloadPath, fileName);
copyFileSpToS3Cleanup(filepath, semaphore, lockKey)
.then(() => {
const error = createError(errorObj.errorMsg, errorObj.statusCode, errorObj.origErr);
return next(error);
}).catch(errorObj => {
const error = createError(errorObj.errorMsg, errorObj.statusCode, errorObj.origErr);
return next(error);
});
});
} else {
const error = createError('File does not exist!');
return next(error);
}
}).catch(err => {
const error = createError('File does not exist!');
return next(error);
})
} else {
logger.error(`${email} does not have permission to upload`);
return res.status(401).json({
message: `${email} does not have permission to upload`
});
}
});
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-31T22:59:18.550",
"Id": "451911",
"Score": "0",
"body": "Can you add your requires in there? Otherwise it will be hard to know what functions you wrote, and what functions you call from 3rd party libraries."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-01T02:14:14.387",
"Id": "451928",
"Score": "0",
"body": "Show the whole module file. The code context is important here."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-01T13:16:35.073",
"Id": "451990",
"Score": "1",
"body": "Added. Let me know if I should add some of the local dependencies code, to clarify it even more."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-01T13:24:08.677",
"Id": "451992",
"Score": "0",
"body": "Almost spit out my coffee when I saw `creds.password`, then I saw it was fine"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-01T13:25:45.993",
"Id": "451993",
"Score": "0",
"body": "lol! I'm being extra careful to not post the credentials."
}
] |
[
{
"body": "<p>Got it using promises:</p>\n\n<pre><code>//Finds if project_contact email has permission to upload\n function findProjectContacts() {\n return new Promise((resolve, reject) => {\n ProjectContacts.findAll({ where: { can_upload_files: 1, email_address: email }, attributes: ['email_address', 'project_id', 'can_upload_files'] })\n .then(projectContacts => {\n if (projectContacts.length > 0) {\n return resolve(true);\n }\n else {\n const error = createError(`${email} does not have permission to upload!`, 401);\n return reject(error);\n }\n })\n .catch(err => {\n const error = createError(`${email} does not have permission to upload!`, 401, err);\n return reject(error)\n })\n })\n }\n\n //Checks if file exists in SharePoint\n function findFile() {\n return new Promise((resolve, reject) => {\n doesFileExistSp(creds, spSite, siteUrl, spFile).then(exists => {\n if (!exists) {\n const error = createError(`${filename} does not exist in ${spFolder}`, 404);\n return reject(error);\n } else {\n return resolve(true);\n }\n }).catch(err => {\n const error = createError(`${filename} does not exist in ${spFolder} `, 404, err);\n return reject(error);\n });\n });\n }\n\n //Pulls file from SharePoint to download into specified filepath\n function pullFile() {\n return new Promise((resolve, reject) => {\n const sppullContext = {\n siteUrl: siteUrl, //SharePoint URL\n creds: creds\n };\n const sppullOptions = {\n spRootFolder: spFolder, // The folder path for the file in SharePoint\n dlRootFolder: downloadPath, // Where the file is saved locally\n strictObjects: [filename], // Only download the filename specified as a query parameter\n muteConsole: true\n };\n pullFromSharePoint(sppullContext, sppullOptions) //Pull file with filename from SharePoint\n .then(filepath => {\n if (!fs.existsSync(filepath)) {\n const error = createError(`${filepath} does not exist`, 404);\n return reject(error);\n }\n else {\n logger.info(`FILE NOW IN PATH: ${filepath}`);\n const s3UploadFolder = path.join(downloadPath, uploadFolderName);\n makeDirs(s3UploadFolder);\n\n }\n return resolve(true);\n });\n });\n }\n\n findProjectContacts()\n .then(permission => {\n if (permission === true)\n return findFile();\n })\n .then(fileFound => {\n if (fileFound === true)\n return pullFile();\n }).then(fileCopied => {\n if (fileCopied === true)\n logger.info(`${filename} has been uploaded`);\n return res.status(200).json({\n message: `${filename} has been uploaded`\n });\n }).catch(errorObj => {\n return next(errorObj);\n })\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-27T16:25:14.953",
"Id": "233076",
"ParentId": "231634",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "233076",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-31T19:50:16.080",
"Id": "231634",
"Score": "4",
"Tags": [
"javascript",
"node.js"
],
"Title": "Uploading a file from web-based platform to S3 bucket using NodeJS - Callback Hell"
}
|
231634
|
<p>I am trying to solve <a href="https://www.hackerrank.com/challenges/max-transform/problem" rel="nofollow noreferrer">this question</a> on HackerRank (problem details below).</p>
<p><strong>Naive solution</strong></p>
<p>This solution implements the problem as described and produces the correct solution. It is not very efficient, however, and produces time-out errors on the predefined tests for larger sized arrays of <code>A</code>, e.g. <code>big_A</code> (see below).</p>
<pre><code>big_A = [371, 7372, 5149, 3766, 587, 3575, 799, 7431, 8071, 6041, 6332, 9656, 3128, 6271, 6708, 7741, 8412, 9687, 6014, 4012, 6124, 415, 5356, 3053, 2810, 9803, 9978, 7697, 70, 966242, 4976, 8644, 3429, 8476, 4383, 5373, 251, 9021, 1645, 8793, 7913, 5763, 3178, 9554, 6988, 1701, 6574, 7263, 1487, 9215, 3403, 2624, 8997, 123929, 4557, 3036, 9485, 546, 4085, 627, 22122, 365, 6823, 8838, 8475, 693102, 4140, 204801, 6701, 4831, 4312, 6549, 8092, 9138, 8040, 8121, 3325, 27206, 343, 5881, 44268, 7494, 283, 5452, 7417, 3473, 1788, 183, 4904, 8625, 3536, 3142, 4263, 99129, 9012, 1136, 3980, 3626, 9915, 7515, 77976, 2309, 694, 62514, 6651, 6503, 7004, 7591, 7775, 9187, 73133, 5078, 3353, 674195, 246, 693102, 6918, 29866, 5033, 4831, 4365, 5106, 7457, 4719, 7242, 8838, 1593, 7303, 4295, 5333, 2027, 4717, 8930, 6011, 1528, 959, 14383, 7291, 2910, 8407, 3492, 9187, 28684, 8153, 7990, 1580, 8818, 378, 2010, 3425, 4415, 4786, 3550, 716, 2866, 157, 8526, 3913, 7869, 3171, 5241, 5733, 7276, 1115, 85705, 6616, 992977, 7060, 6922, 7492, 6988, 1216, 2082, 3429, 1082, 8818, 430, 6509, 7837, 81, 8493, 106, 1538, 5173, 6420, 307421, 1843, 5413, 5356, 9176, 8109, 2973, 9445, 7080, 5884, 65602, 3259, 1565, 1472, 9060, 6545, 4969, 2516, 6288, 273932, 8096, 6901, 7482, 5380, 29866, 754, 3586, 8765, 1465, 152208, 572, 83558, 2506, 935206, 9450, 543753, 4228, 4910, 8167, 51337, 8048, 7967, 6042, 8110, 8148, 4184, 5023, 4184, 5575, 1854, 4307, 14503, 6535, 4257, 5047, 3806, 2871, 2880, 5829, 3159, 53682, 9186, 3628, 3578, 6497, 90013, 364, 9922, 2923, 9534, 8672, 2116, 2742, 2685, 2887, 5941, 1496, 1984, 5661, 5401, 2733, 2840, 8659, 1340, 3844, 2576, 9534, 7778, 4, 15811, 4295, 8765, 6107, 7008, 1729, 6591, 8342, 8460, 14431, 8297, 8526, 7449, 4029, 4897, 3017, 5505, 235, 3712, 4199, 6104, 4456, 8741, 3642, 8004, 6613, 9917, 96502, 2024, 7696, 6954, 962, 3961, 8771, 397537, 8524, 8030, 933, 3117, 3879, 3256, 5661, 8544, 9275, 74765, 9281, 4916, 5682, 3456, 5066, 6436, 4379, 85739, 280, 4624, 4161, 5809, 380, 32154, 7855, 5088, 2834, 9437, 3523, 5472, 8778, 2405, 22859, 5779, 6324, 7080, 22387, 6089, 7472, 3862, 5314, 36091, 1532, 3829, 19743, 2986, 4334, 4626, 9283, 4322, 1322, 2775, 5763, 8457, 85705, 6838, 8101, 8793, 7763, 3562, 8709, 6643, 8631, 4459, 5005, 8357, 33690, 9400, 8779, 2736, 3839, 8200, 5947, 3155, 20111, 6432, 1286, 4937, 1424, 2910, 2625, 7367, 6116, 7373, 234, 6773, 8242, 8647, 6378, 7488, 78555, 1603, 4759, 6448, 8798, 44, 4042, 6586, 9400, 266, 2454, 90742, 3712, 5683, 7705, 7821, 4134, 2066, 978, 6121, 7841, 5809, 6463, 4048, 6761, 9850, 29866, 4591, 5848, 6343, 61, 6346, 6110, 2980, 2581, 3524, 3113, 5710, 5130, 39480, 425, 8502, 1943, 7602, 3523, 1136, 69974, 2090, 4922, 616, 2124, 42110, 6195, 1141, 9817, 3616, 813, 4743, 9048, 6681, 415, 8757, 9136, 8178, 9160, 63943, 9963, 6413, 170, 30849, 3115, 7750, 4154, 1626, 9524, 5700, 3150, 2280, 6816, 6561, 55836, 82526, 2161, 5503, 7026, 6685, 592471, 4675, 4558, 2138, 3348, 9428, 916, 5556, 1508, 3876, 4694, 8905, 4718, 1866, 5777, 6474, 7957, 9540, 6006, 6452, 4491, 2371, 4461, 2168, 2813, 3528, 9721, 9687, 66271, 1043, 8079, 4709, 6858, 6781, 2416, 1113, 433780, 8520, 686044, 8358, 7485, 6573, 3504, 45587, 1843, 7779, 2421, 5909, 3817, 73133, 22213, 8108, 5475, 77, 7088, 1752, 9496, 7332, 48517, 101, 7555, 4129, 4166, 1267, 7053, 2521, 8520, 1461, 3159, 3591, 9013, 1598, 10954, 8932, 3248, 6110, 7588, 3269, 8968, 894344, 84763, 174, 4166, 630, 9163, 4512, 99378, 81001, 364, 2433, 2690, 1531, 7737, 3112, 44, 9687, 5472, 7329, 5273, 9973, 29810, 189, 7088, 3552, 992977, 5988, 4046, 1464, 5333, 6118, 8243, 5604, 5434, 4743, 8089, 2491, 2083, 8410, 8976, 7449, 977, 47720, 5020, 6838, 190, 5763, 5041, 33460, 3355, 587, 6867, 6824, 9522, 6485, 4899, 6444, 3258, 9454, 1401, 3861, 1668, 6593, 2699, 33, 4485, 2186, 314, 5579, 4747, 1881, 9140, 7695, 3281, 5967, 5982, 5467, 8189, 8345, 1928, 8449, 6375, 20111, 3317, 5036, 2299, 3376, 9646, 3097, 977, 258395, 5739, 5345, 2728, 9356, 5436, 397537, 7810, 4447, 4334, 1999, 1045, 71835, 4403, 1752, 90742, 3842, 5378, 7453, 2456, 628, 5432, 6701, 6807, 7977, 7645, 8818, 1714, 8342, 44654, 8177, 744, 9483, 8568, 6806, 260, 4725, 3735, 5102, 2922, 7837, 686044, 2667, 6937, 15811, 4292, 4446, 9626, 6914, 779, 1324, 8517, 2426, 7251, 93108, 9435, 4235, 16143, 7208, 7303, 1598, 4419, 14503, 6191, 2979, 4216, 757, 5921, 961071, 1955, 6758, 8999, 9024, 9985, 65810, 572, 4620, 4489, 4627, 8378, 8567, 5726, 5525, 6998, 4365, 39649, 4297, 21762, 5855, 27206, 7364, 3159, 6747, 2041, 7400, 5081, 9024, 177415, 9413, 6409, 97508, 621, 85545, 9907, 8192, 6280, 9934, 1574, 3626, 227, 84763, 21762, 837, 9022, 3552, 1053, 89162, 4840, 6089, 1121, 7878, 1255, 5229, 2721, 9510, 5103, 4854, 6968, 9496, 866, 5856, 3107, 7000, 5106, 390, 3737, 3469, 8721, 1866, 6081, 4604, 33442, 861368, 7848, 9893, 1627, 6104, 3891, 8359, 7716, 1000, 5090, 5828, 7173, 9317, 2611, 6605, 6311, 7553, 6271, 8051, 751, 5191, 6110, 9746, 921183, 4680, 183391, 1078, 5575, 73660, 9702, 5025, 4242, 1929, 3069, 4426, 1098, 1716, 6340, 2258, 7683, 3097, 9708, 6536, 5387, 40277, 8480, 1479, 8897, 22213, 4860, 1755, 5321, 2622, 8995, 2454, 7418, 7001, 6020, 58942, 809, 7681, 244, 1814, 6564, 9875, 7450, 9982, 5260, 2148, 8203, 7357, 6685, 7618, 531, 8872, 85765, 7766, 9115, 6852, 644315, 1388, 3645, 4438, 6409, 912, 5892, 20289, 7058, 6559, 5760, 6953, 328, 5108, 2310, 2589, 2321, 8768, 5853, 43602, 3353, 68378, 19, 66, 1439, 3765, 40, 20289, 5575, 1974, 5687, 5517, 88489, 7917, 5226, 171, 2685, 7219, 9711, 6936, 6523, 9945, 5510, 9654, 5894, 8344, 6131, 243, 1982, 9723, 4244, 11284, 4409, 1597, 2506, 160, 2060, 1779, 467, 2532, 2733, 4065, 5235, 8049, 9795, 9704, 8030, 4973, 5452, 6021, 2402, 8313, 919, 5366, 4044, 5654, 9460, 1892, 8935, 99378, 4592, 4101, 4066, 121, 2887, 63310, 2313, 5349, 6287, 7674, 1196, 7091, 53301, 6308, 4461, 1536, 2481, 6022, 9721, 6123, 7001, 4071, 4444, 6574, 6867, 5188, 8931, 5666, 4910, 6819, 8556, 6781, 3484, 2243, 8344, 8778, 6664, 5829, 7332, 51760, 9074, 7489, 9812, 8917, 2936, 2409, 6360, 7104, 9758, 6026, 2061, 6424, 4064, 9528, 4951, 43278, 5695, 3918, 51337, 7291, 8779, 3645, 67977, 7620, 218520, 10985, 65636, 9149, 2138, 439533, 199, 8778, 2917, 15850, 1668, 3444, 5205, 9746, 9286, 8432, 4282, 2728, 745, 7373, 2251, 2573, 2085, 581, 9530, 1772, 9563, 3346, 12708, 9411, 53301, 6796, 2535, 2527, 4542, 3399, 3766, 317, 5107, 4761, 5666, 3206, 4016, 9309, 4835, 7209, 5985, 2871, 10985, 695, 1879, 8729, 7329, 1668, 451, 4352, 1074, 9997, 1987, 1021, 2402, 5010, 9775, 15850, 3525, 485, 5821, 67551, 90227, 5850, 6480, 8344, 4446, 2695, 419, 4725, 2978, 7860, 7364, 3483, 2612, 7840, 9830, 6847, 965, 5534, 2540, 7896, 7278, 9832, 5650, 4182, 2894, 9437, 6108, 7143, 8957, 3732, 9714, 4476, 4890, 9907, 1822, 4890, 8920, 572, 5091, 7260, 9759, 8412, 7995, 433535, 3525, 1622, 9969, 8917, 3574, 5132, 2387, 9212, 7018, 6186, 1744, 4835, 9013, 9311, 6820, 5298, 4281, 6123, 6291, 433780, 63310, 69974, 919, 5238, 6051, 5204, 9982, 7446, 3932, 31807, 3190, 77976, 9809, 7332, 1391, 609007, 1900, 9935, 7943, 1798, 11553, 8747, 6288, 29866, 2744, 3792, 2260, 5747, 4510, 5041, 4929, 3162, 69881, 5988, 6222, 1880, 2794, 6537, 8980, 5848, 1517, 1251, 2581, 14289, 9726, 2143, 294, 9367, 3015, 7058, 2835, 3646, 99129, 69974, 2114, 15811, 2480, 2576, 6015, 944, 7391, 9203, 883, 5338, 88907, 2402, 6793, 7213, 9512, 5033, 7491, 7496, 4665, 6409, 1580, 261, 6332, 6553, 9133, 3159, 3972, 1984, 474, 9283, 8503, 5033, 67, 8173, 1126, 2066, 665, 7914, 1679, 7513, 73135, 9787, 8167, 8087, 6536, 3984, 7828, 8535, 34570, 5903, 7002, 9964, 8782, 1649, 38296, 4134, 9599, 5023, 14289, 20111, 71290, 4679, 9979, 8525, 6474, 2355, 3479, 30849, 29834, 9222, 3656, 9039, 6503, 5828, 2018, 6960, 3399, 6019, 45587, 3233, 1279, 7060, 6480, 3603, 35014, 4076, 8999, 4937, 6212, 9868, 1690, 4733, 396, 1541, 4533, 2514, 219, 520, 9524, 2419, 8249, 99773, 7658, 89162, 1916, 1814, 2128, 1209, 86138, 9133, 4779, 2996, 7893, 88272, 6463, 1916, 9985, 112, 6343, 7088, 7914, 9832, 5556, 6707, 3663, 6852, 5700, 2621, 1100, 8960, 14767, 6525, 18, 6116, 5819, 8432, 5338, 2855, 4989, 8967, 3502, 25468, 6143, 7360, 2485, 7214, 7641, 1345, 8547, 5021, 9176, 3726, 6420, 7456, 479, 7208, 6000, 4047, 6271, 74765, 2183, 6497, 1240, 5987, 3139, 3174, 4510, 2217, 4888, 5579, 4275, 9646, 857, 870, 7536, 4679, 7183, 1645, 2887, 6968, 704, 2082, 5040, 319, 6509, 1439, 8207, 38377, 9901, 9646, 274372, 2275, 1227, 4297, 7018, 6984, 29866, 8838, 260, 6018, 952, 9944, 1076, 550, 5238, 2695, 4344, 309848, 7030, 9028, 6573, 6929, 72995, 5979, 7255, 276, 68378, 6502, 1745, 1764, 14383, 3359, 4602, 918, 2736, 5259, 6613, 119, 5370, 8331, 6889, 1198, 869, 4589, 3630, 959, 7012, 7332, 2026, 8980, 1216, 5088, 3656, 157, 577, 9237, 5370, 1986, 14289, 266, 6820, 2224, 5893, 2153, 813, 9559, 665, 6807, 7917, 3867, 8937, 8, 2411, 9909, 841, 74765, 481, 667, 7072, 66271, 9978, 8366, 1325, 7271, 6686, 1752, 1376, 2114, 35014, 389276, 5212, 9356, 3792, 1532, 4148, 4663, 7411, 121, 6573, 5518, 3736, 3521, 6124, 48517, 7203, 9021, 22387, 7237, 4823, 2292, 1065, 600457, 526, 694, 5036, 5819, 2309, 19247, 2889, 3847, 1205, 5513, 4242, 7607, 4777, 9823, 5158, 9664, 5516, 4249, 3059, 4692, 4050, 477, 6014, 7080, 2506, 7567, 8548, 6112, 961, 402531, 9277, 670, 3326, 2791, 6998, 6053, 1113, 5120, 5378, 6680, 6232, 471, 7211, 6337, 6378, 16541, 3738, 7482, 1511, 9361, 7366, 3206, 3685, 1666, 51118, 21762, 2581, 7417, 6553, 5322, 4072, 4680, 1230, 3750, 9597, 9540, 43602, 1394, 9880, 5161, 3485, 5944, 1804, 7417, 2205, 4199, 2554, 9656, 95, 5203, 3310, 1124, 9921, 8708, 5235, 7628, 7499, 1612, 8333, 819, 6902, 180, 7435, 8847, 6424, 3316, 7810, 6676, 1111, 7237, 3473, 8159, 5872, 5708, 1987, 25, 4288, 2610, 39557, 6220, 8089, 4556, 3806, 6613, 9843, 99129, 1999, 543753, 7896, 575937, 9298, 9437, 636, 5387, 8751, 8207, 2460, 7620, 87527, 8480, 3393, 28550, 3169, 1788, 3060, 25200, 8793, 8200, 3816, 2944, 8808, 88, 5749, 5158, 1279, 1995, 962294, 2909, 8869, 84899, 6653, 624, 4148, 6332, 5199, 3814, 213, 6130, 7958, 21299, 9410, 430, 4951, 624, 5083, 189, 7863, 5149, 45632, 4973, 8379, 121, 2519, 8460, 7435, 3713, 4887, 7277, 6707, 7219, 2254, 1362, 5629, 3923, 5833, 3233, 1649, 4036, 2211, 1236, 1097, 7515, 1634, 5687, 3052, 9742, 897, 8926, 1159, 3469, 9935, 88272, 4386, 2233, 821, 550, 8869, 2889, 6879, 17305, 2404, 4330]
def solve(A):
m = 1_000_000_007 # Modulus 10**9 + 7.
def transform(A):
B = []
for k in range(len(A)):
for i in range(len(A) - k):
j = i + k + 1
B.append(max(A[i:j]))
return B
return sum(transform(transform(A))) % m
A = [3, 2, 1]
>>> solve(A)
58
# S(A) => [3, 2, 1, 3, 2, 3]
# S(S(A)) => [3, 2, 1, 3, 2, 3, 3, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3]
# sum(S(S(A)) => 58
</code></pre>
<p><strong>Improved solution, but still not good enough</strong></p>
<p>Noting that only the sum of second transform needs to be returned rather than the array itself, the second call sums the values rather than appends them to <code>B</code>.</p>
<p>Furthermore, in the square matrix below the first row is simply <code>A</code> itself. Each subsequent row is the max of the item directly above and the item directly above and one left. For example, the lower right value of 3 (<code>k=2, j=3</code>) is calculated as <code>max((k=1, j=2), (k=1, j=3)) = max(3, 2) = 3</code>.</p>
<pre><code>A = [3, 2, 1]
k i j slice(i:j) max(A[i:j])
- - - ---------- -----------
0 0 1 0:1 3
0 1 2 1:2 2
0 2 3 2:3 1
1 0 2 0:2 3
1 1 3 1:3 2
2 0 3 0:3 3
max(A[k:j])
j
k 1 2 3
- -----------
0 | 3 2 1 |
1 | 3 2 |
2 | 3 |
------------
</code></pre>
<p>Although this code is significantly faster than the naive code for <code>A</code> with more numbers, it still times out on all of the tests. There must be an improved algorithm. How can I do better?</p>
<pre><code>def solve(A):
m = 1_000_000_007 # Modulus 10 ** 9 + 7.
B = max_vals = A
while len(max_vals) > 1:
max_vals = list(map(max, zip(max_vals, max_vals[1:])))
B.extend(max_vals)
max_vals = B
total = sum(max_vals) % m
while len(max_vals) > 1:
max_vals = list(map(max, zip(max_vals, max_vals[1:])))
total += sum(max_vals) % m
return total % m
A = [3, 2, 1]
>>> solve(A)
58
</code></pre>
<p><strong>Problem Details</strong></p>
<p>Let <code>A</code> be a zero-indexed array of integers. For <code>0 <= i <= j < length(A)</code>, let <code>Ai...j</code> denote the subarray of <code>A</code> from index <code>i</code> to index <code>j</code>, inclusive.</p>
<p>Let's define the max transform of <code>A</code> as the array obtained by the following procedure:</p>
<ul>
<li>Let <code>B</code> be a list, initially empty.</li>
<li>For <code>k</code> from <code>0</code> to <code>length(A) - 1)</code>:
<ul>
<li>For <code>i</code> from <code>0</code> to <code>length(A) - k - 1</code>
<ul>
<li>Let <code>j = i + k</code></li>
<li>Append <code>max(Ai...j)</code> to the end of <code>B</code></li>
</ul></li>
</ul></li>
<li>Return <code>B</code></li>
</ul>
<p>The returned array is defined as the max transform of <code>A</code>. We denote it by <code>S(A)</code>.</p>
<p>Complete the function <code>solve</code> that takes an integer array <code>A</code> as input.</p>
<p>Given an array <code>A</code>, find the sum of the elements of <code>S(S(A))</code>, i.e., the max transform of the max transform of <code>A</code>. Since the answer may be very large, only find it modulo <code>10^9 + 7</code>. </p>
<p><strong>Problem constraints</strong></p>
<ul>
<li><code>1 <= n <= 2 * 10^5</code></li>
<li><code>1 <= Ai <= 10^6</code> <em>(note that duplicate values may occur)</em></li>
</ul>
|
[] |
[
{
"body": "<p>With 1719 numbers in <code>big_A</code>, <code>S(big_A)</code> will have 1478340 numbers, and <code>S(S(big_A))</code> will have over 1 trillion (1092745316970) numbers. Adding up that many numbers will take a significant amount of time.</p>\n\n<p>Most of the numbers are the same. <code>S(S([3,2,1]))</code> has 21 numbers, and with a sum of 58, a lot of those numbers will be <code>3</code>. If you can figure out how many numbers are <code>3</code>’s, you could multiply instead of add, saving significant time.</p>\n\n<p>Consider just the maximum value in the input to the transform. It immediately dominates the two values in the next row, and three in the next row, and so on until it reaches either edge of the output rows:</p>\n\n<pre><code>*** *** *** max *** *** *** *** *** ***\n *** *** max max *** *** *** *** ***\n *** max max max *** *** *** ***\n max max max max *** *** ***\n max max max max *** ***\n max max max max ***\n max max max max\n max max max\n max max\n max\n</code></pre>\n\n<p>The sum of all of the values is <code>(4*7) * max + sum(left_side) + sum(right_side)</code>. So, if you can find the maximum in the input, and the location of the maximum, you can divide the problem into a directly calculated chunk, and 2 sub-problems. Recursive divide & conquer, FTW.</p>\n\n<p>Code left to student. </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-01T05:44:03.873",
"Id": "451944",
"Score": "0",
"body": "The diagram and the paragraph below it are very useful. I will try to implement that in the coming days."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-01T01:03:14.837",
"Id": "231644",
"ParentId": "231636",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-31T21:43:12.133",
"Id": "231636",
"Score": "3",
"Tags": [
"python",
"algorithm"
],
"Title": "HackerRank Max Transform Python Solution"
}
|
231636
|
<p>I have a server and client application. In the client application, there are HttpRequestException class exceptions on requests. As it seems to me - these exceptions happen in isolated cases and not always speak about a connection problem. So I decided to do a repeat of the queries with a small amount of time:</p>
<pre><code>private static async Task<T> RetryRequest<T>(Func<Task<T>> func, int retryCount = 3, int retryTimeout = 1000)
{
var tryCount = 0;
Exception lastException = null;
while (tryCount < retryCount)
{
tryCount++;
try
{
return await func.Invoke();
}
catch (HttpRequestException exception)
{
lastException = exception;
await Task.Delay(retryTimeout);
}
}
if (lastException != null)
throw lastException;
throw new HttpRequestException("Can't get request after retrying");
}
</code></pre>
<p>Usage example:</p>
<pre><code>public async Task<List<NewsItemDto>> GetNewsAsync(DateTime date)
{
return await RetryRequest(async () =>
{
var sd = date.ToString("dd.MM.yyyy", null);
var query = new { date = sd };
var queryString = query.ToQueryString();
var response = await _client.GetAsync($"/{ModPlusPlatformRoute}/news{queryString}").ConfigureAwait(false);
await response.HandleErrorAsync().ConfigureAwait(false);
return await response.GetDataAsync<List<NewsItemDto>>().ConfigureAwait(false);
});
}
</code></pre>
<p>HandleErrors:</p>
<pre><code>public static async Task HandleErrorAsync(this HttpResponseMessage response)
{
if ((int)response.StatusCode >= 400)
{
MediaTypeHeaderValue ct = response.Content.Headers.ContentType;
if (ct != null && ct.MediaType == "text/html")
throw new ClientException(await response.Content.ReadAsStringAsync().ConfigureAwait(false), response.StatusCode.ToString());
ErrorModel errorModel = await response.GetDataAsync<ErrorModel>().ConfigureAwait(false);
if (errorModel != null)
throw new ClientException(errorModel.Error, errorModel.StatusCode.ToString());
var webException = new WebException($"Error with code: {response.StatusCode}");
AppMetrica.SendHttpException(webException, response.RequestMessage.ToString());
throw webException;
}
}
</code></pre>
<p>Work method I checked as best I could - everything seems fine. But I am confused by too much use of asynchrony</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-01T12:39:25.030",
"Id": "451983",
"Score": "3",
"body": "Any reason for not using an existing solution like [Polly](https://github.com/App-vNext/Polly)?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-01T16:30:37.057",
"Id": "452028",
"Score": "0",
"body": "Feel you are reinventing the wheel. You can do this with the httpclient see https://stackoverflow.com/a/19650002 for example of having the client retry. If you don't have to have the httpclient then I would also recommend looking into Polly"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-02T13:20:57.640",
"Id": "452111",
"Score": "0",
"body": "@BohdanStupak Yes, there is a reason why I cannot use third-party libraries in my project"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-02T13:24:48.007",
"Id": "452113",
"Score": "0",
"body": "@CharlesNRice \nI saw that topic. Judging by the discussions in that version, there are a lot of problems. Some of them have already been discussed there and there is probably a part that is not yet known. My option seemed simpler to me and required less alterations in the code"
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-31T22:03:22.123",
"Id": "231637",
"Score": "2",
"Tags": [
"c#",
"http",
"task-parallel-library",
"asp.net-web-api"
],
"Title": "Retry HttpClient request without handlers"
}
|
231637
|
<p>I have a bare-bones example of how I plan to load excel sheets into pandas data frames. However, the code runs unexpectedly slow. I'm open to suggestions on ways I can speed this up, even converting the source files to a different file format. Anything to make it snappier because I will need a loop to do this several times over multiple sheets and workbooks. Thank you. </p>
<pre><code>import os
import pandas as pd
path_to_data_files = 'C:/DataArchive/'
files = sorted(os.listdir(path_to_data_files), reverse=True)
file = pd.ExcelFile(path_to_data_files + files[0])
sheet_names = file.sheet_names
df = file.parse(sheets[0])
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-31T23:17:47.647",
"Id": "451912",
"Score": "2",
"body": "Can you give a directory listing showing typical file sizes and counts?"
}
] |
[
{
"body": "<p>There are several ways you can go about doing this.</p>\n\n<ol>\n<li><p>Use pandas.read_excel</p></li>\n<li><p>Manually convert excel workbook to csv file then use pandas.read_csv</p></li>\n<li><p>Use Python code to convert excel workbook to csv file then use pandas.read_csv</p></li>\n</ol>\n\n<p>The third method is your best approach. It's the fastest.</p>\n\n<p>Here is my excel workbook</p>\n\n<p><a href=\"https://i.stack.imgur.com/kleSE.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/kleSE.png\" alt=\"enter image description here\"></a></p>\n\n<p><strong>1</strong></p>\n\n<pre><code>df1 = pandas.read_excel('workbook.xlsx')\nprint(df1)\n</code></pre>\n\n<p>Out</p>\n\n<pre><code> col1 col2 col3 col4\n0 I should be completing\n1 my linear algebra homework\n</code></pre>\n\n<p><strong>2</strong></p>\n\n<p>I named the .csv file 'workbook.csv'</p>\n\n<pre><code>df2 = pandas.read_csv('workbook.csv')\nprint(df2)\n</code></pre>\n\n<p>Out</p>\n\n<pre><code> col1 col2 col3 col4\n0 I should be completing\n1 my linear algebra homework\n</code></pre>\n\n<p><strong>3</strong></p>\n\n<pre><code>import csv\nimport xlrd\nwith xlrd.open_workbook('workbook.xlsx') as wb:\n sh = wb.sheet_by_index(0)\n with open('workbook.csv', 'w', newline=\"\") as csv_file:\n col = csv.writer(csv_file)\n for row in range(sh.nrows):\n col.writerow(sh.row_values(row))\ndf3 = pandas.read_csv('workbook.csv')\nprint(df3)\n</code></pre>\n\n<p>Here is the .csv produced, calle</p>\n\n<pre><code>col1,col2,col3,col4\nI,should,be,completing\nmy,linear,algebra,homework\n</code></pre>\n\n<p>And then the subsequent dataframe</p>\n\n<pre><code> col1 col2 col3 col4\n0 I should be completing\n1 my linear algebra homework\n</code></pre>\n\n<p><strong>VERDICT</strong></p>\n\n<p>All the outputs for each method is the same but <strong>method 3 is the fastest</strong>. This means you should import csv and xlrd to convert each of your xlsx files to csv files and then use read_csv. You can use os to get into your specific directories. Add for loops for each file for solution 3.</p>\n\n<p><strong>NOTE</strong> </p>\n\n<p>Test method <strong>1</strong> versus <strong>2</strong> for yourself because I am getting somewhat inconsistent results using the timeit module and writing</p>\n\n<pre><code>start = timeit.timeit()\n# code\nend = timeit.timeit()\nprint(f\"Time {end - start} {df}\")\n</code></pre>\n\n<p>but I am not sure if I am using it correctly. So, at the very least, try the first and last methods for yourself and see which ones go faster.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-01T01:27:21.920",
"Id": "451919",
"Score": "1",
"body": "Thank you Trevor. I will try these. If I could upvote, I would. Very thorough answer."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-01T01:38:32.723",
"Id": "451926",
"Score": "1",
"body": "No problem, @Heather Gray, if you want, I think you can check the answer instead of upvoting. Also, I am usually on this site, so just comment if you run into anything."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-01T12:51:42.417",
"Id": "451986",
"Score": "1",
"body": "Interesting that reading the excel file, writing a csv file (which includes a loop in pure Python) and then reading and parsing that csv file is faster for you than just letting pandas directly read and parse the excel file. It would be interesting to see the timings, including for larger files."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-01T12:59:11.373",
"Id": "451987",
"Score": "2",
"body": "Also, if #2 is not faster than #3, you are doing your timings wrong. #2 is fully included in #3, as the last step. Unless you count the time it takes you to manually save the worksheet as a CSV, of course."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-01T13:05:32.200",
"Id": "451988",
"Score": "3",
"body": "Case in point, for two files with four columns and 1501 (3001) rows, one being the header, all data numerical, I get 0.057s (0.112s), 0.002s (0.003s), 0.056s (0.115s), respectively, making #1 the preferred choice if you don't want to do the conversion manually, because it is a lot easier to use and not really slower."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-01T01:05:36.147",
"Id": "231645",
"ParentId": "231638",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "231645",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-31T22:45:00.733",
"Id": "231638",
"Score": "4",
"Tags": [
"python",
"performance",
"pandas"
],
"Title": "Load excel sheet to data frame"
}
|
231638
|
<p>I need to build something that is not very complicated, but efficient. I don't have much time to debug.</p>
<p>I don't know if this method is strong enough to encrypt a data to be displayed in a Qr code.</p>
<p>It will be compiled in Qt.</p>
<pre><code> #include <botan/botan.h>
#include <botan/aes.h>
#include <botan/kdf.h>
#include <botan/pbkdf2.h>
#include <botan/hmac.h>
#include <botan/sha160.h>
using namespace std;
using namespace Botan;
// .....
bool BotanWrapper::EncryptFile(QString Source, QString Destination)
{
try
{
//Setup the key derive functions
PKCS5_PBKDF2 pbkdf2(new HMAC(new SHA_160));
const u32bit PBKDF2_ITERATIONS = 8192;
//Create the KEY and IV
KDF* kdf = get_kdf("KDF2(SHA-1)");
//Create the master key
SecureVector<byte> mMaster = pbkdf2.derive_key(48, mPassword.toStdString(), &mSalt[0], mSalt.size(),PBKDF2_ITERATIONS).bits_of();
SymmetricKey mKey = kdf->derive_key(32, mMaster, "salt1");
InitializationVector mIV = kdf->derive_key(16, mMaster, "salt2");
string inFilename = Source.toStdString();
string outFilename = Destination.toStdString();
std::ifstream in(inFilename.c_str(),std::ios::binary);
std::ofstream out(outFilename.c_str(),std::ios::binary);
Pipe pipe(get_cipher("AES-256/CBC/PKCS7", mKey, mIV,ENCRYPTION),new DataSink_Stream(out));
pipe.start_msg();
in >> pipe;
pipe.end_msg();
out.flush();
out.close();
in.close();
return true;
}
catch(...)
{
return false;
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-01T06:08:43.580",
"Id": "451945",
"Score": "0",
"body": "You should indent the code. It is easy to read then."
}
] |
[
{
"body": "<p>I don't know the Botan library, so I'll stick to some general recommendations.</p>\n\n<hr>\n\n<p>Don't include whole namespaces at global scope, especially the <code>std</code> namespace.</p>\n\n<hr>\n\n<p>The only use of Qt in this function is to accept <code>QString</code> arguments, with which we do nothing but convert to standard strings. So why not remove the dependency, and allow the function to be used in non-Qt projects, by accepting the filenames as <code>const std::string&</code>? We can keep the interface by providing a (header-only, trivially inlinable) wrapper separately as a convenience for use with Qt:</p>\n\n<pre><code>//encrypt.h\nbool EncryptFile(const std::string& source, const std::string& destination);\n</code></pre>\n\n\n\n<pre><code>//encrypt-qt.h\nbool EncryptFile(QString source, QString destination)\n{ return EncryptFile(source.toStdString(), destination.toStdString(); }\n</code></pre>\n\n<p>There's certainly no need to use <code>c_str()</code> when passing to the streams' constructors - a <code>std::string</code> is fine (and expected) there.</p>\n\n<hr>\n\n<p>I'd probably go one further with the overloads, and provide a version that accepts a pair of streams, so that we could use this for network streaming or in-memory encryption:</p>\n\n<pre><code>//encrypt.h\nbool EncryptFile(std::istream& source, std::ostream& destination);\n\nbool EncryptFile(const std::string& source, const std::string& destination);\n{\n try {\n std::ifstream in(source, std::ios::binary);\n std::ofstream out(destination, std::ios::binary);\n return EncryptFile(in, out);\n } catch (...) {\n return false;\n }\n}\n</code></pre>\n\n<hr>\n\n<p>Why do we return true, even if writing the output failed? For example, try passing <code>/dev/full</code> as the destination. We could fix that:</p>\n\n<pre><code>return in && out;\n</code></pre>\n\n<p>Alternatively, we could arrange for the streams to throw exceptions:</p>\n\n<pre><code> in.exceptions(std::ifstream::failbit | std::ifstream::bad);\n out.exceptions(std::ifstream::failbit | std::ifstream::bad);\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-01T11:08:40.623",
"Id": "231664",
"ParentId": "231642",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-31T23:46:47.333",
"Id": "231642",
"Score": "0",
"Tags": [
"c++",
"cryptography"
],
"Title": "Encrypt a file using Botan library"
}
|
231642
|
<p>I have solved the <a href="https://www.hackerrank.com/challenges/designer-pdf-viewer/problem" rel="nofollow noreferrer">designer pdf</a> question with haskell. The code works. I am posting the code here to know how I could have done it better.</p>
<blockquote>
<ul>
<li>First line contains the weight of each alphabet</li>
<li>Second line contains the word.</li>
</ul>
<p>Sample input</p>
<pre><code>1 3 1 3 1 4 1 3 2 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 7
zaba
</code></pre>
<p>Output</p>
<pre><code>28
</code></pre>
<p>Explanation<br>
each character would take 1 space and multiply it with the max weight<br>
4 characters * 1 space * 7 weight = 28<br>
'z' has the max weight of 7.</p>
</blockquote>
<p>Code</p>
<pre><code>import Data.List
import Data.Maybe
getintval::(Maybe Int) -> Int
getintval Nothing = 1
getintval (Just x) = x
solve'::[Char]->[(Char, Int)] -> Int
solve' ch lst = k $ map getintval $ map (\x -> finder' x) ch
where
k::[Int] -> Int
k fb = (*) (length ch) $ foldl (\acc x -> max acc x) 1 fb
finder'::Char -> Maybe Int
finder' g = case i of
Just(x1,x2) -> Just x2
Nothing -> Just 1
where i = find(\(val1, val2) -> val1 == g) lst
solve::[Char] -> [Char] -> Int
solve wght val = solve' val rec
where
rec::[(Char, Int)]
rec = zipWith (\x y -> (x, y)) ['a'..'z'] word1
word1::[Int]
word1 = map(read::String->Int) $ words wght
main::IO()
main = do
weight <- getLine
pdfstr <- getLine
putStr . show $ solve weight pdfstr
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-01T06:08:47.747",
"Id": "451946",
"Score": "0",
"body": "Welcome to Code Review. I have been hesitating to use a *block quote* for the problem description as it is not even close to a verbatim quote. At least for titling, revisit [How do I ask a Good Questio?](https://codereview.stackexchange.com/help/how-to-ask)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-03T20:57:34.913",
"Id": "452241",
"Score": "0",
"body": "A concern not really addressed by the nice answer from \nGurkenglas: the initial [hackerRank problem](https://www.hackerrank.com/challenges/designer-pdf-viewer/problem) is quite explicitly about character __heights__ (as in the on-screen vertical dimension). However, your source code is about __weight__ which is confusing. For example, the first argument of `solve` could be called `heightsLine` or maybe `hLine` for brevity, not `weight` or`wght` . In a similar fashion, it is unusual to use `ch` (first argument of solve') for an input word. Normally ch would stand for a single CHaracter."
}
] |
[
{
"body": "<p><code>getintval</code> is just <code>fromMaybe 1</code>. <code>finder</code> always produces <code>Just</code> - you probably meant to map <code>Nothing</code> to <code>Nothing</code>. <code>finder'</code> is just <code>lookup</code>. <code>foldl (\\acc x -> max acc x) 1</code> is just <code>maximum</code> (so long as <code>ch</code> is never empty). <code>k</code> can be inlined.</p>\n\n<pre><code>solve' :: [Char] -> [(Char, Int)] -> Int\nsolve' ch lst = (*length ch) $ maximum $ map (fromMaybe 1 . (`lookup` lst)) ch\n</code></pre>\n\n<p><code>zipWith (\\x y -> (x, y))</code> is just <code>zip</code>. <code>read</code>'s type can be deduced. <code>rec</code> and <code>word1</code> can be inlined.</p>\n\n<pre><code>solve :: [Char] -> [Char] -> Int\nsolve wght val = solve' val $ zip ['a'..'z'] $ map read $ words wght\n</code></pre>\n\n<p><code>mapMaybe</code> throws away invalid characters. We can flatten the call tree by letting <code>main</code> assemble the pieces.</p>\n\n<pre><code>solve :: [Char] -> [(Char, Int)] -> Int\nsolve ch lst = (*length ch) $ maximum $ mapMaybe (`lookup` lst) ch\n\nparse :: [Char] -> [(Char, Int)]\nparse = zip ['a'..'z'] . map read . words\n\nmain :: IO ()\nmain = do\n weight <- getLine\n pdfstr <- getLine\n print $ solve pdfstr $ parse weight \n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-04T18:39:39.510",
"Id": "452415",
"Score": "0",
"body": "Thank you so much. This was really helpful"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-02T19:49:20.677",
"Id": "231749",
"ParentId": "231648",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "231749",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-01T01:21:03.037",
"Id": "231648",
"Score": "2",
"Tags": [
"programming-challenge",
"haskell"
],
"Title": "Compute text area given letter heights and a text"
}
|
231648
|
<p><strong>Problem</strong></p>
<p>I have a DI scenario where I have multiple classes that implement a common interface (<code>IModelService</code>).</p>
<p>I'm using a generic framework class (<code>PredictionEnginePool<,></code>) that has options injected (<code>PredictionEnginePoolOptions<></code>). This has a property (<code>ModelLoader</code>) that must be set using <code>AddOptions</code> in <code>Startup.ConfigureServices</code> where I set it to an instance of <code>CustomModelLoader</code> obtained from the service provider (from the <code>AddSingleton</code> implementation factory) during options configuration. <code>CustomModelLoader</code> depends on a single <code>IModelService</code> for its lifetime, so it needn't be injected with <code>IEnumerable<IModelService></code>.</p>
<p><strong>Research</strong></p>
<p>I have researched various patterns to achieve my aim which is to have <code>CustomModelLoader</code> have access to a single registered <code>IModelService</code> object while being assigned to the <code>ModelLoader</code> property of the options class <code>PredictionEnginePoolOptions<,></code> (which is then injected into <code>PredictionEnginePool<,></code>). But most of the solutions I've found use a service locator anti-pattern or break SRP and/or OCP; for example, most of the solutions offered on <a href="https://stackoverflow.com/q/39174989/197591">this SO question</a>. And many people suggest that the built-in DI framework of .NET Core is too simple to cater for complex scenarios and to use something like Autofac or StructureMap.</p>
<p>However, I refuse to believe that Microsoft would make such a scenario difficult or impossible (as it's not <em>that</em> complicated) in a new modern framework as .NET Core which builds on almost two decades of experience from .NET Framework. I've been pretty impressed with .NET Core so far in terms of complying with and enabling SOLID and other good coding principles.</p>
<p><strong>Own Attempt So Far</strong></p>
<p>The code below shows my attempt to resolve this based on various related questions on SO. Basically, to provide <code>CustomModelLoader</code> with a single <code>IModelService</code> object, I inject options into it (<code>CustomModelLoaderOptions</code>). This has a <code>IModelService</code> property on it. To set this, I have another call to <code>AddOptions</code> which sets the property (<code>ModelService</code>) by getting the single <code>IModelService</code> object that returns <code>true</code> from <code>CanTrain</code> (a strategy design pattern). I use <code>GetServices<IModelService></code> to resolve the <code>IModelService</code> objects. <code>CanTrain</code> is implemented in each concrete type (<code>RegressionModelService</code> and <code>TimeSeriesModelService</code>) to state whether it can work with the type specified at startup for each generic version of <code>PredictionEnginePool</code> (<code>RegressionPrediction</code> and <code>TimeSeriesPrediction</code> which are just simple POCOs).</p>
<p>These are the interfaces and classes:</p>
<pre><code>interface IModelService
{
bool CanTrain(Type type);
}
class RegressionModelService : IModelService
{
public bool CanTrain(Type type) => type == typeof(RegressionPrediction);
}
class TimeSeriesModelService : IModelService
{
public bool CanTrain(Type type) => type == typeof(TimeSeriesPrediction);
}
class CustomModelLoaderOptions
{
public IModelService ModelService { get; set; }
}
class CustomModelLoader : ModelLoader
{
public CustomModelLoader(IOptionsFactory<CustomModelLoaderOptions> options) {}
}
</code></pre>
<p>My only real restriction is <code>PredictionEnginePool<,></code> and <code>PredictionEnginePoolOptions<,></code>. These are framework classes that cannot change and must be registered as per below. The following code is in <code>Startup.ConfigureServices</code>:</p>
<pre><code>services.AddScoped<IModelService, RegressionModelService>();
services.AddScoped<IModelService, TimeSeriesModelService>();
services.AddScoped<CustomModelLoader>();
AddPredictionEnginePool<RegressionPrediction>();
AddPredictionEnginePool<TimeSeriesPrediction>();
void AddPredictionEnginePool<T>()
{
services.AddSingleton<PredictionEnginePool<Input, T>>(sp =>
{
services.AddOptions<PredictionEnginePoolOptions<Input, T>>().Configure(options1 =>
{
services.AddOptions<CustomModelLoaderOptions>().Configure(options2 =>
{
options2.ModelService = sp.GetServices<IModelService>().Single(s => s.CanTrain(typeof(T)));
});
options1.ModeLoader = sp.GetService<CustomModelLoader>();
});
});
}
</code></pre>
<p><strong>Question</strong></p>
<p>I have spent many hours on this and I believe the above solution solves it without breaking SOLID principles (particularly SRP and OCP) and without using any anti-patterns. It's also using the built-in DI framework and avoids named instances.</p>
<p>However, I am not entirely happy with my solution because it still requires me to call <code>GetService</code> on the service provider to get <code>IModelService</code> and then assign it to a property on <code>CustomModelLoaderOptions</code> which is then injected into <code>CustomModelLoader</code>. I don't mind doing this for <code>CustomModelLoader</code> itself and assigning it to a property on <code>PredictionEnginePoolOptions<,></code> which is then injected into <code>PredictionEnginePool<,></code> as this is the <a href="https://github.com/dotnet/machinelearning-samples/blob/master/samples/csharp/end-to-end-apps/DeepLearning_ImageClassification_TensorFlow/TensorFlowImageClassification/Startup.cs" rel="nofollow noreferrer">documented way</a> (per the sample applications) to do it for this class, but I feel I'm just copying this methodology to work around another design problem that could be solved <em>without</em> having to call <code>GetService</code>, and somehow let the DI framework take care of it. Is this possible, perhaps with a different code design pattern?</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-01T01:54:10.307",
"Id": "231649",
"Score": "3",
"Tags": [
"c#",
"dependency-injection",
"asp.net-core",
".net-core",
"asp.net-core-webapi"
],
"Title": "ASP .NET Core DI: Dependency on single implementation of multiple registrations of service type"
}
|
231649
|
<p>We need to tunnel certain applications over a VPN at work. Ideally we would use a dedicated firewall/network appliance for this but the only permanent infrastructure we have are Mac Pro's running Squid.</p>
<p>This means that if our VPN connection drops or anything happens to the link, we have to manually click "Connect VPN" and then update squid.conf to point to the new VPN IP. I decided to write an AppleScript task that runs as a cronjob, then depending on whether a disconnect had occurred, squid would then be reconfigured.</p>
<p><strong>AutoReconnectVPN.scpt</strong> (AppleScript)</p>
<pre><code>global gAttempts
tell application "System Events"
tell current location of network preferences
repeat 10 times
set myConnection to the service "VPN"
if myConnection is not null then
if current configuration of myConnection is not connected then
connect myConnection
set gAttempts to gAttempts + 1
else
-- Return 0 if theres no need to reconfigure squid
return gAttempts
end if
end if
delay 5
end
end tell
end tell
</code></pre>
<p><strong>SetProxyIP.sh</strong> (bash script)</p>
<pre><code>#!/bin/bash
# Sets tcp_outgoing_address in squid.conf to point to IP of ppp0
# Ensure tcp_outgoing_address already exists in squid.conf!
export VPNIP=''
CONFDIR=~/Library/Preferences/squid.conf
for i in 1 2 3 4 5; do
export VPNIP="$(ifconfig ppp0 | sed -En 's/127.0.0.1//;s/.*inet (addr:)?(([0-9]*\.){3}[0-9]*).*/\2/p')"
echo "GETTING VPN IP" $VPNIP
if [[ $VPNIP =~ ^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$ ]];
then
sed -i .bak 's/.*tcp_outgoing_address.*.*/tcp_outgoing_address '$VPNIP'/' $CONFDIR
# Would have used squid -k reconfigure, fails with error in our environment?
kill -9 `cat /tmp/squid.pid` || :
/usr/local/squid/sbin/squid -f $CONFDIR
break
fi
sleep 1
done
</code></pre>
<p>Then a cronjob to run every minute</p>
<pre><code>*/1 * * * * osascript ~/vpnscripts/AutoReconnectVPN.scpt; if [ "$?" -eq "0" ] ; then ~/vpnscripts/SetProxyIP.sh; fi
</code></pre>
<p>Perhaps a continual daemon process would be more elegant and remove the possible 1 minute downtime between checks, but this is acceptable for our purposes.</p>
<p>This is my first experience with <em>sed</em> so I'm expecting there could be room for improvement there. My main hope is that someone could stumble upon this and find it useful.</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-01T01:59:21.687",
"Id": "231650",
"Score": "2",
"Tags": [
"bash",
"networking",
"macos",
"applescript"
],
"Title": "Auto re-connecting to a VPN on OS X and pointing Squid accordingly"
}
|
231650
|
<p>i'm trying to build an API wrapper class, that sends requests in a JSON format. the sample request format is something like this:</p>
<pre><code>{
"items": [
{
"brand": "brand",
"idCategory": "idCategory",
"idItem": "idItem",
"attributes": [
{
"idUda": "idUda",
"price": "price"
},
{
"idUda": "idUda",
"price": "price"
}
],
"description": "description",
"skus": [
{
"price": {
"offer": "offer",
"default": "default"
},
"stock": {
"available": "available",
"amount": "amount"
},
"gtin": "gtin",
"images": [
"image",
"image"
],
"idSku": "idSku",
}
]
}
]
}
</code></pre>
<p>my first thought was to create an object for each element of the JSON request that is an array, something like this:</p>
<pre><code> $attr1 = new Attribute;
$attr1->setIdUda('xxx')
->setPrice('99999');
$price = new Price;
$price->setOffer('teste')
->setDefault('99.99');
$stock = new Stock;
$stock->setAvailable(true)
->setAmount('9999');
$product = new Product;
$product->setBrand('Apple')
->setIdCategory('500')
->setIdItem('9999')
->setAttributes($attr1)
->setDescription('nice product')
->setSkus($price);
->setSkus($stock);
</code></pre>
<p>and each one these objects have a <code>toArray()</code> method, that returns an associative array, eg:</p>
<pre><code>class Price {
//getters and setters....
function toArray() {
return array(
'offer' => $this->offer,
'default' => $this->default
)
}
}
</code></pre>
<p>inside of the <code>Product</code> class all these attributes setters are grouped to form an array so i can convert it to the JSON format later.</p>
<pre><code>class Product {
//.....
public function setAttributes(Attribute $attributes) {
$this->attributes['attributes'][] = $attributes->toArray();
return $this;
}
}
</code></pre>
<p>but it still feels like it's highly coupled, because i have to set the key of each one of these arrays, in order to form the JSON data.</p>
<p>What would be the "best" approach to make this code easier to maintain? should i use classes only for some attributes? how should i consider it?</p>
|
[] |
[
{
"body": "<p>There is no problem modelling the request with classes representing each part of the request and a class that aggregates them.</p>\n\n<p>One thing to note here, those classes adhere to builder pattern - builder of JSON.\nMaybe you dont know that there is an interface <code>\\JsonSerializable</code> which would comminucate the intent of the classes much better then a <code>toArray()</code> method. Although many arrays can be deemd json serializable, its not always true. Where as json serializable object is always serializable to json and it makes it clear that the json serializability is its purpose...</p>\n\n<p>Then i quite dont understand this piece:</p>\n\n<pre><code> $product\n ->setSkus($price);\n ->setSkus($stock);\n</code></pre>\n\n<p>You set skus to a Price object, then overwrite with Stock object?\nGiven this piece of data:</p>\n\n<pre><code>\"skus\": [\n {\n \"price\": {\n \"offer\": \"offer\",\n \"default\": \"default\"\n },\n \"stock\": {\n \"available\": \"available\",\n \"amount\": \"amount\"\n },\n \"gtin\": \"gtin\",\n \"images\": [\n \"image\",\n \"image\"\n ],\n \"idSku\": \"idSku\",\n }\n ]\n</code></pre>\n\n<p>I would expect that there is one more object between <code>Product</code> and <code>Stock</code>/<code>Price</code> object. Maybe a <code>Sku</code> object:</p>\n\n<pre><code>$product->addSku((new Sku())->setPrice($price)->setStock($stock));\n</code></pre>\n\n<p>And I wouldnt also see problem adding methods for more convenient work (that would instantiate the parts classes):</p>\n\n<pre><code>$sku = new Sku();\n$sku->setPrice('offer', 'default');\n$sku->setStock('available', 'amount')\n</code></pre>\n\n<p>instead of:</p>\n\n<pre><code>$sku = new Sku();\n$sku->setPrice(new Price('offer', 'default'));\n$sku->setStock(new Stock('available', 'amount'));\n</code></pre>\n\n<p>After all, those classes are not meant to represent the request, they represent a builder of a json request. And builder should make it as easy to build the target as possible....</p>\n\n<p>EDIT: you were worried about coupling. I dont think this brings in any more coupling then necesary. The API uses specific keys in the request and these will never change, unless the API introduces BC break. But then maybe it was not a very good API structure... Anyway it wouldnt hurt to have those keys defined as constants of the bulder classes, so you dont have to repeat string literals all over the place... if nothing it makes it easier to find all occurences of a key.</p>\n\n<p>Chances are that there are multiple ways the api could have been designed, yet retaining the same capabilities. And this means that there are also multiple ways to model the request with php objects. But you should prefer to have this 1:1. The api designer was probably aware of the multiple ways and chosen the one he chosen for a reason. And you should follow that reasoning...</p>\n\n<p>Well this statement might have seem quite abstract, so let me complete it with an example. Lets say we have api structure:</p>\n\n<pre><code>{\n \"scopeA\": {\n \"configA1\": \"valueA1\"\n },\n \"scopeB\": {\n \"configB1\": \"valueB1\"\n }\n}\n</code></pre>\n\n<p>but we can also model it as this structure:</p>\n\n<pre><code>{\n \"scopeAconfigA1\": \"valueA1\",\n \"scopeBconfigB1\": \"valueB1\"\n}\n</code></pre>\n\n<p>but the first structure is the API structure, and so the PHP model should also have the first structure. Simply following the same reasoning why the api designers chose the first structure. Whatever reasoning it may have been...</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-03T22:08:47.453",
"Id": "452242",
"Score": "0",
"body": "thanks for the reply. about the SKU object, i created a SKU interface, so all the SKU Items can implement the toArray method."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-03T22:11:26.803",
"Id": "452243",
"Score": "0",
"body": "so as you say that this has nothing to do with the request, i should not create a method called \"toJson\" in the Product object? should i create a ProductJson, that receives a Product and build the keys and convert to JSON?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-04T06:35:12.280",
"Id": "452285",
"Score": "1",
"body": "@NBAYoungCode No dont create toJson method. toArray() is actualy fine, but it could be finer if you used the JsonSerializable instead. It offers jsonSerialize() which would just be the same implementation as your toArray(), just different name. And it can then be used like this `json_encode($object)`, where the $object implements JsonSerializable. Not really different from json_encode($object->toArray()), but the intent is more clear...."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-04T06:37:10.100",
"Id": "452286",
"Score": "1",
"body": "@NBAYoungCode No i dont think you should create ProductJSON and Product class separately. It's actualy the ProductJSON class what you have, but it should not be a problem to just call it Product, because in the context, probably everything is json.... Actualy the most precise naming would be ProductJsonRequestBuilder, but depends on how far you wanna go. Just `Product` would be pretty fine IMO, given the context ofc.."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-04T06:39:17.817",
"Id": "452287",
"Score": "1",
"body": "@NBAYoungCode you might start considering to split it only if you have multiple apis with the same structure, but each using different keys. But thats probably never gonna happen. The keys are like constants and that's why it may be good to define them as constants of the classes as well. It's not really something that will ever change. And if it will, it will be BC break anyway - both on the API and library side..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-04T21:05:42.037",
"Id": "452432",
"Score": "0",
"body": "do you have an exemple on how this JsonSerializable implementation should be? because i'd still have to define its indexes, right?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-04T21:06:53.420",
"Id": "452433",
"Score": "0",
"body": "nevermind, fount it here: https://www.sitepoint.com/use-jsonserializable-interface/"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-05T17:51:37.473",
"Id": "452544",
"Score": "1",
"body": "@NBAYoungCode Yea, you cannot avoid the keys, they are part of the request. But only those builder classes need to know and it should be static constants of the bulder classes. It can even be private to them, since the consumers of the builder objects need not worry about the keys at all... Btw if you are satisfied with my answer, please consider marking it as accepted :)"
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-03T07:11:05.843",
"Id": "231767",
"ParentId": "231651",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "231767",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-01T04:36:07.353",
"Id": "231651",
"Score": "4",
"Tags": [
"php",
"object-oriented"
],
"Title": "Good practices in an API Wrapper Class"
}
|
231651
|
<p>This snippet uses a string as an output. As we iterate through the input string, I just keep appending a character to the string and I know this just pretty much creates a new string everything I add a new character since strings are immutable in Python.</p>
<pre><code>def snake_string(s):
res = ''
for i in range(1, len(s), 4):
res += s[i]
for j in range(0, len(s), 2):
res += s[j]
for k in range(3, len(s), 4):
res += s[k]
return res
</code></pre>
<p>This uses a list as the output structure and use <code>join</code> to return a string at the end:</p>
<pre><code>def snake_string(s):
result = []
# Outputs the first row, i.e., s[1], s[5], s[9], ...
for i in range(1, len(s), 4):
result.append(s[i])
# Outputs the second row, i.e., s[0], s[2], s[4], ...
for i in range(0, len(s), 2):
result.append(s[i])
# Outputs the third row, i.e., s[3], s[7], s[11], ...
for i in range(3, len(s), 4):
result.append(s[i])
return ''.join(result)
</code></pre>
<p>I wonder how these two implementations differ in time and space complexity and which one a better way to do. I feel like the second one is better in terms of space because it just initializes on the list and keeps adding a new character to it, but I assume that the join at the end will cause another <span class="math-container">\$O(N)\$</span> time. Is this correct?</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-01T07:08:08.187",
"Id": "231655",
"Score": "2",
"Tags": [
"python",
"comparative-review",
"complexity"
],
"Title": "Snake string implementations"
}
|
231655
|
<p>I'm reading <em>Structure and Interpretation of Computer Programs</em>. In the first exercise, I came across a programming problem to add the squares of the 2 bigger numbers out of 3 numbers.</p>
<p>I came up with the following procedure:</p>
<pre><code>(define (sum-of-larger-two a b c)
(
if (> a b)
(if (> b c)
(+ (* a a) (* b b))
(+ (* a a) (* c c))
)
(if (> c a)
(+ (* b b) (* c c))
(+ (* b b) (* a a))
)
)
)
</code></pre>
<p>Is there a more succinct way to write this program?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-01T11:28:11.117",
"Id": "451974",
"Score": "0",
"body": "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](//codereview.meta.stackexchange.com/q/2436) for guidance on writing good question titles."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-01T11:52:45.203",
"Id": "451978",
"Score": "0",
"body": "@TobySpeight Does the new title solve the issue."
}
] |
[
{
"body": "<p>One of the ways of obtaining concision is by “astracting” a repeated operation to define a new function. For instance in this case you could use the <code>square</code> function previously defined in that chapter.</p>\n\n<p>But if you look at the expression <code>(square a)</code> you will discover that it is longer then <code>(* a a)</code>, even it is, in some sense, more readable (has a minor number of symbols, so it is simpler to understand).</p>\n\n<p>But having a function to abstract an operation could have other benefits that an immediate reduction in the count of the characters. Consider that in your example you are comparing two numbers to find the larger between them: in other words, you are looking for their maximum. </p>\n\n<p>So, let's define a new maximum operator:</p>\n\n<pre><code>(define (max a b)\n (if (> a b) a b)\n</code></pre>\n\n<p>Then, having the functions <code>square</code> and <code>max</code> you can now combine them, like, for instance, in:</p>\n\n<pre><code>(define (sum-of-larger-two a b c)\n (if (> a b)\n (+ (square a)\n (square (max b c)))\n (+ (square b)\n (square (max a c)))))\n</code></pre>\n\n<p>Or you can rearrange the operations in this way:</p>\n\n<pre><code>(define (sum-of-larger-two a b c)\n (+ (square (max a b))\n (square (if (= (max a b) a)\n (max b c)\n (max a c)))))\n</code></pre>\n\n<p>Note that we are reducing the number of conditions to check in the function <code>sum-of-larger-two</code> (in addition to reducing the number of lines and symbols), and so we are simplifying it, improving both its readability as well as its maintainability.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-01T14:45:48.810",
"Id": "231680",
"ParentId": "231665",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-01T11:20:51.200",
"Id": "231665",
"Score": "2",
"Tags": [
"scheme"
],
"Title": "Calculate the sum of the square of two biggest numbers out of three"
}
|
231665
|
<p>You can set any size of the field and any number of bombs. I think I got a pretty flexible program again(<a href="https://codereview.stackexchange.com/questions/231632/i-created-the-game-tic-tac-toe-in-java-in-the-console">Tic tac toe game for the console</a>). What do you think about the code? I would like to know if I made mistakes in program design.</p>
<p>skeleton:</p>
<pre><code>public class Minesweeper {
public static void play(){
final int HOWMANYBOMBS;
boolean isItWin;
Area[][] area;
final Scanner SCANNER = new Scanner(System.in);
final String greeting = "Hi, lets play minesweeper!";
System.out.println(greeting);
area = pickLengthsOfArea(SCANNER);
HOWMANYBOMBS = getHowManyBombs(area,SCANNER);
System.out.println("hi");
fillArea(area,HOWMANYBOMBS);
while(true) {
printPole(area);
if(playerTurnsAndIsPlayersTurnInBomb(area,SCANNER)) {
isItWin=false;
break;
}
if(weHaveNotGotAnyEmptyAreaThatNotCheckedAndWeMarkedOnlyBombs(area)) {
isItWin=true;
break;
}
}
if(isItWin) {
System.out.println("U won!");
}
else {
System.out.println("Defieat!");
}
}
private static boolean weHaveNotGotAnyEmptyAreaThatNotCheckedAndWeMarkedOnlyBombs(Area[][] area) {}
private static boolean playerTurnsAndIsPlayersTurnInBomb(Area[][] area,Scanner scanner) {}
private static void openAllAround(int x, int y, Area[][] area,ArrayList<AreaWithXandY> weOpenedThese) { // do you know another implementation?
AreaWithXandY[] areasAround = getAllAreasAroundWithTheirXandY(area,x,y);
for(AreaWithXandY a:areasAround) {
if(!weOpenedThese.contains(a)) {
a.getArea().setStatusOfArea(StatusOfArea.OPENED);
weOpenedThese.add(a);
if(a.getArea().getValueOfArea()==ValueOfArea.NOONEBOMBAROUND) {
openAllAround(a.getX(),a.getY(),area,weOpenedThese);
}
}
}
}
private static void printPole(Area[][] area) {}
private static void fillArea(Area[][] area, int howManyBombs) {
fillAreaWithBombs(area,howManyBombs);
fillAreaWithEmptyArea(area);
}
private static void fillAreaWithEmptyArea(Area[][] area) {}
private static Area[] getAllAreasAround(Area[][] area,int x,int y) {}
private static AreaWithXandY[] getAllAreasAroundWithTheirXandY(Area[][] area,int x,int y) {}
private static void fillAreaWithBombs(Area[][] area, int howManyBombs) {}
private static int getHowManyBombs(Area[][] area, Scanner scanner) {}
private static Area[][] pickLengthsOfArea(Scanner scanner) {}
private static boolean isXandYIn(int turnX,int turnY, Area[][] area) {}
public static boolean isNumeric(String strNum) {}
}
class Area{
private final ValueOfArea valueOfArea;
private StatusOfArea statusOfArea;
{
statusOfArea = StatusOfArea.CLOSED;
}
Area(ValueOfArea valueOfArea){
this.valueOfArea = valueOfArea;
}
ValueOfArea getValueOfArea() {
return valueOfArea;
}
StatusOfArea getStatusOfArea() {
return statusOfArea;
}
void setStatusOfArea(StatusOfArea statusOfArea) {
this.statusOfArea = statusOfArea;
}
}
class AreaWithXandY{
private int x,y;
Area area;
AreaWithXandY(int x,int y,Area area){
this.area = area;
this.x = x;
this.y = y;
}
int getX() {
return x;
}
int getY() {
return y;
}
Area getArea() {
return area;
}
@Override
public boolean equals(Object obj) {
if(obj==null) {
return false;
}
if(false==(obj instanceof AreaWithXandY)) {
return false;
}
AreaWithXandY object = (AreaWithXandY) obj;
if(object.getX()==x && object.getY()==y) { //its enouth
return true;
}
else {
return false;
}
}
}
enum StatusOfArea{
MARKEDASBOMB,OPENED,CLOSED
}
enum ValueOfArea{
BOMB("@"),
NOONEBOMBAROUND("0"),ONEBOMBAROUND("1"),TWOBOMBAROUND("2"),TREEBOMBAROUND("3"),FOURBOMBAROUND("4"),FIVEBOMBAROUND("5"),SIXBOMBAROUND("6"),SEVENBOMBAROUND("7"),EIGHTBOMBAROUND("8");
private String icon;
ValueOfArea(String icon){
this.icon = icon;
}
String getIcon() {
return icon;
}
static ValueOfArea getValueOfAreaByString(String value) {
ValueOfArea[] values = ValueOfArea.values();
for(int i=0;i<values.length;i++) {
if(values[i].getIcon().equals(value)) {
return values[i];
}
}
System.err.println("ERROR in getValueOfAreaByString(String value), we could not find this value");
return null;
}
}
</code></pre>
<p>fullcode:</p>
<pre><code>public class Minesweeper {
public static void play(){
final int HOWMANYBOMBS;
boolean isItWin;
Area[][] area;
final Scanner SCANNER = new Scanner(System.in);
final String greeting = "Hi, lets play minesweeper!";
System.out.println(greeting);
area = pickLengthsOfArea(SCANNER);
HOWMANYBOMBS = getHowManyBombs(area,SCANNER);
System.out.println("hi");
fillArea(area,HOWMANYBOMBS);
while(true) {
printPole(area);
if(playerTurnsAndIsPlayersTurnInBomb(area,SCANNER)) {
isItWin=false;
break;
}
if(weHaveNotGotAnyEmptyAreaThatNotCheckedAndWeMarkedOnlyBombs(area)) {
isItWin=true;
break;
}
}
if(isItWin) {
System.out.println("U won!");
}
else {
System.out.println("Defieat!");
}
}
private static boolean weHaveNotGotAnyEmptyAreaThatNotCheckedAndWeMarkedOnlyBombs(Area[][] area) {
for(int y = 0;y<area.length;y++) {
for(int x = 0;x<area[0].length;x++) {
if(area[y][x].getValueOfArea()!=ValueOfArea.BOMB/*is not bomb*/ && (area[y][x].getStatusOfArea()==StatusOfArea.CLOSED || area[y][x].getStatusOfArea()==StatusOfArea.MARKEDASBOMB) ) {
return false;
}
}
}
return true;
}
private static boolean playerTurnsAndIsPlayersTurnInBomb(Area[][] area,Scanner scanner) {
while(true) {
System.out.println("Print \"open x y\", if u want open this area, print \"mark x y\", if u want mark this area as bomb or unmark this area");
String[] commandAndXAndY = scanner.nextLine().split(" ");
if(commandAndXAndY.length!=3) {
System.out.println("fill out the form correctly!");
}
else if(!commandAndXAndY[0].equals("open") && !commandAndXAndY[0].equals("mark")) {
System.out.println("first work should be equal \"open\" or \"mark\"!");
}
else if(!isNumeric(commandAndXAndY[1]) || !isNumeric(commandAndXAndY[2])) {
System.out.println("x and y should be numbers!");
}
else if(!isXandYIn(Integer.parseInt(commandAndXAndY[1]),Integer.parseInt(commandAndXAndY[2]),area)) {
System.out.println("x and y should be in area! P.S.: area.lengthY="+area.length+", area.lengthX="+area[0].length);
}
else {
int y = Integer.parseInt(commandAndXAndY[2]),x = Integer.parseInt(commandAndXAndY[1]);
if(commandAndXAndY[0].equals("open")) {
if(area[y][x].getValueOfArea()==ValueOfArea.BOMB) {
return true;
}
else {
area[y][x].setStatusOfArea(StatusOfArea.OPENED);
if(area[y][x].getValueOfArea()==ValueOfArea.NOONEBOMBAROUND) {
openAllAround(x,y,area, new ArrayList<>());
}
return false;
}
}
else { // mark
area[y][x].setStatusOfArea(StatusOfArea.MARKEDASBOMB);
return false;
}
}
}
}
private static void openAllAround(int x, int y, Area[][] area,ArrayList<AreaWithXandY> weOpenedThese) {
AreaWithXandY[] areasAround = getAllAreasAroundWithTheirXandY(area,x,y);
for(AreaWithXandY a:areasAround) {
if(!weOpenedThese.contains(a)) {
a.getArea().setStatusOfArea(StatusOfArea.OPENED);
weOpenedThese.add(a);
if(a.getArea().getValueOfArea()==ValueOfArea.NOONEBOMBAROUND) {
openAllAround(a.getX(),a.getY(),area,weOpenedThese);
}
}
}
}
private static void printPole(Area[][] area) {
System.out.println();
for(int y = 0;y<area.length;y++) {
for(int x=0;x<area[0].length;x++) {
if(area[y][x].getStatusOfArea()==StatusOfArea.CLOSED) {
System.out.print("?");
}
else if(area[y][x].getStatusOfArea()==StatusOfArea.OPENED) {
System.out.print(area[y][x].getValueOfArea().getIcon());
}
else if(area[y][x].getStatusOfArea()==StatusOfArea.MARKEDASBOMB) {
System.out.print("*");
}
}
System.out.println();
}
}
private static void fillArea(Area[][] area, int howManyBombs) {
fillAreaWithBombs(area,howManyBombs);
fillAreaWithEmptyArea(area);
}
private static void fillAreaWithEmptyArea(Area[][] area) {
for(int y = 0;y<area.length;y++) {
for(int x=0;x<area[0].length;x++) {
if(area[y][x] == null) {
int howManyBombsAround=0;
Area[] areasAround = getAllAreasAround(area,x,y);
for(Area a:areasAround) {
if(a!=null && a.getValueOfArea()==ValueOfArea.BOMB) {
howManyBombsAround++;
}
}
area[y][x] = new Area(ValueOfArea.getValueOfAreaByString(Integer.toString(howManyBombsAround)));
}
}
}
}
private static Area[] getAllAreasAround(Area[][] area,int x,int y) {
Area[] areasAround = new Area[8];
int i=0;
if(y!=0 && x!=0) { //left up
areasAround[i] = area[y-1][x-1];
i++;
}
if(y!=0) { // up
areasAround[i] = area[y-1][x];
i++;
}
if(x!=area[0].length-1 && y!=0) { //right up
areasAround[i] = area[y-1][x+1];
i++;
}
if(x!=0) { // left
areasAround[i] = area[y][x-1];
i++;
}
if(x!=area[0].length-1) { //right
areasAround[i] = area[y][x+1];
i++;
}
if(x!=0 && y!=area.length-1) { // left down
areasAround[i] = area[y+1][x-1];
i++;
}
if(y!= area.length-1) { //down
areasAround[i] = area[y+1][x];
i++;
}
if(x!=area[0].length-1 && y!=area.length-1) { // right down
areasAround[i] = area[y+1][x+1];
i++;
}
Area[] areasAroundWhithoutNullObjects = new Area[i];
for(int b = 0;b<i;b++) {
areasAroundWhithoutNullObjects[b] = areasAround[b];
}
return areasAroundWhithoutNullObjects;
}
private static AreaWithXandY[] getAllAreasAroundWithTheirXandY(Area[][] area,int x,int y) {
AreaWithXandY[] areasAroundWithXandY = new AreaWithXandY[8];
int i=0;
if(y!=0 && x!=0) { //left up
areasAroundWithXandY[i] = new AreaWithXandY(x-1,y-1,area[y-1][x-1]);
i++;
}
if(y!=0) { // up
areasAroundWithXandY[i] = new AreaWithXandY(x,y-1,area[y-1][x]);
i++;
}
if(x!=area[0].length-1 && y!=0) { //right up
areasAroundWithXandY[i] = new AreaWithXandY(x+1,y-1,area[y-1][x+1]);
i++;
}
if(x!=0) { // left
areasAroundWithXandY[i] = new AreaWithXandY(x-1,y,area[y][x-1]);
i++;
}
if(x!=area[0].length-1) { //right
areasAroundWithXandY[i] = new AreaWithXandY(x+1,y,area[y][x+1]);
i++;
}
if(x!=0 && y!=area.length-1) { // left down
areasAroundWithXandY[i] = new AreaWithXandY(x-1,y+1,area[y+1][x-1]);
i++;
}
if(y!= area.length-1) { //down
areasAroundWithXandY[i] = new AreaWithXandY(x,y+1,area[y+1][x]);
i++;
}
if(x!=area[0].length-1 && y!=area.length-1) { // right down
areasAroundWithXandY[i] = new AreaWithXandY(x+1,y+1,area[y+1][x+1]);
i++;
}
AreaWithXandY[] areasAroundWithXandYWhithoutNullObjects = new AreaWithXandY[i];
for(int b = 0;b<i;b++) {
areasAroundWithXandYWhithoutNullObjects[b] = areasAroundWithXandY[b];
}
return areasAroundWithXandYWhithoutNullObjects;
}
private static void fillAreaWithBombs(Area[][] area, int howManyBombs) {
ArrayList<Integer> listOfAllNumbers = new ArrayList<>(area.length*area[0].length);
for(int i=0;i<area.length*area[0].length;i++) {
listOfAllNumbers.add(i,i);
}
int tempId,y,x;
for(int i=0;i<howManyBombs;i++) {
tempId = listOfAllNumbers.get((int) (Math.random()*listOfAllNumbers.size()));
listOfAllNumbers.remove(new Integer(tempId));
y = ((int)tempId/area[0].length);
x = tempId%area[0].length;
area[y][x] = new Area(ValueOfArea.BOMB);
}
}
private static int getHowManyBombs(Area[][] area, Scanner scanner) {
while(true) {
System.out.println("print number of bombs: ");
String howManyBombsString = scanner.nextLine();
if(!isNumeric(howManyBombsString)) {
System.out.println("it should be number!");
}
else if(false==(0<Integer.parseInt(howManyBombsString) && Integer.parseInt(howManyBombsString)<area.length*area[0].length)) {
System.out.println("it should be positive and it should not exceed the field capacity!");
}
else {
return Integer.parseInt(howManyBombsString);
}
}
}
private static Area[][] pickLengthsOfArea(Scanner scanner) {
String[] turnXandY;
while(true) {
System.out.println("Pick x.length and y.length of area(print \"x y\"): ");
turnXandY = scanner.nextLine().split(" ");
if(turnXandY.length != 2) {
System.out.println("print: \"x y\"!");
}
else if(!isNumeric(turnXandY[0]) || !isNumeric(turnXandY[1])) {
System.out.println("x and y should be numbers!");
}
else if(Integer.parseInt(turnXandY[0]) <= 0 || Integer.parseInt(turnXandY[1]) <= 0) {
System.out.println("x and y should be >0!");
}
else {
return new Area[Integer.parseInt(turnXandY[0])][Integer.parseInt(turnXandY[1])];
}
}
}
private static boolean isXandYIn(int turnX,int turnY, Area[][] area) {
if(turnX<0 || area[0].length<=turnX) {
return false;
}
if(turnY<0 || area.length<=turnY) {
return false;
}
return true;
}
public static boolean isNumeric(String strNum) {
try {
Integer.parseInt(strNum);
} catch (NumberFormatException | NullPointerException nfe) {
return false;
}
return true;
}
}
class Area{
private final ValueOfArea valueOfArea;
private StatusOfArea statusOfArea;
{
statusOfArea = StatusOfArea.CLOSED;
}
Area(ValueOfArea valueOfArea){
this.valueOfArea = valueOfArea;
}
ValueOfArea getValueOfArea() {
return valueOfArea;
}
StatusOfArea getStatusOfArea() {
return statusOfArea;
}
void setStatusOfArea(StatusOfArea statusOfArea) {
this.statusOfArea = statusOfArea;
}
}
class AreaWithXandY{
private int x,y;
Area area;
AreaWithXandY(int x,int y,Area area){
this.area = area;
this.x = x;
this.y = y;
}
int getX() {
return x;
}
int getY() {
return y;
}
Area getArea() {
return area;
}
@Override
public boolean equals(Object obj) {
if(obj==null) {
return false;
}
if(false==(obj instanceof AreaWithXandY)) {
return false;
}
AreaWithXandY object = (AreaWithXandY) obj;
if(object.getX()==x && object.getY()==y) { //its enouth
return true;
}
else {
return false;
}
}
}
enum StatusOfArea{
MARKEDASBOMB,OPENED,CLOSED
}
enum ValueOfArea{
BOMB("@"),
NOONEBOMBAROUND("0"),ONEBOMBAROUND("1"),TWOBOMBAROUND("2"),TREEBOMBAROUND("3"),FOURBOMBAROUND("4"),FIVEBOMBAROUND("5"),SIXBOMBAROUND("6"),SEVENBOMBAROUND("7"),EIGHTBOMBAROUND("8");
private String icon;
ValueOfArea(String icon){
this.icon = icon;
}
String getIcon() {
return icon;
}
static ValueOfArea getValueOfAreaByString(String value) {
ValueOfArea[] values = ValueOfArea.values();
for(int i=0;i<values.length;i++) {
if(values[i].getIcon().equals(value)) {
return values[i];
}
}
System.err.println("ERROR in getValueOfAreaByString(String value), we could not find this value");
return null;
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-01T16:51:47.050",
"Id": "452033",
"Score": "0",
"body": "To keep it short - your identifiers are way too long e.g. `playerTurnsAndIsPlayersTurnInBomb` which could also be split in two methods - one to check if user input was valid, the other to make the actual move. Also - you pass `Area[][]` around a lot. If you wrapped it in a class and exposed some methods the code would become a bit cleaner. It would also be easier to name the methods then."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-02T07:19:50.140",
"Id": "452097",
"Score": "0",
"body": "Please look around CodeReview or Goole for Java naming conventions and make sure you follow them."
}
] |
[
{
"body": "<ul>\n<li><p>When declaring variables, move the declaration towards the first usage. Moving declaration away from usage makes it harder to understand how your variables are actually being used.</p>\n</li>\n<li><p>When declaring variables, prefer <code>final</code> whenever possible. If you know that a value won't change, it's one less thing to keep track of as you're trying to read and understand code. For very short methods, this might not matter (since you can clearly see the whole method and therefore that it's not changed) but for long ones it's almost always better. This <em>doesn't</em> mean you need to declare them in <code>ALL_CAPS</code>. That's only appropriate for actual constants, not values that just happen to not be reassigned.</p>\n</li>\n<li><p>Use whitespace consistently and liberally around operators and punctuation. Every <code>=</code> should generally be surrounded by space, and every <code>,</code> should be followed by space. Similarly, you should have space inside <code>if (</code> and <code>while (</code>. If possible, use an auto-formatter, which will handle this automatically and save you time.</p>\n</li>\n<li><p>Identifiers should be clear (avoiding the use of unnecessary abbreviations) but don't need to be as long as the ones you're using. This could be an indication that your functions are doing too much (meaning that they take on many <em>unrelated</em> responsibilities, so it's difficult to describe what they <em>mean</em>).</p>\n</li>\n</ul>\n<p>Apply the first and second points to <code>Minesweeper.play</code>, we get:</p>\n<pre class=\"lang-java prettyprint-override\"><code> public static void play() {\n final Scanner scanner = new Scanner(System.in);\n \n final String GREETING = "Hi, lets play minesweeper!";\n System.out.println(GREETING);\n final Area[][] area = pickLengthsOfArea(SCANNER);\n final int HOWMANYBOMBS = getHowManyBombs(area, scanner);\n System.out.println("hi");\n fillArea(area, HOWMANYBOMBS);\n\n final boolean isItWin;\n while (true) {\n printPole(area);\n if (playerTurnsAndIsPlayersTurnInBomb(area, scanner)) {\n isItWin = false;\n break;\n }\n if (weHaveNotGotAnyEmptyAreaThatNotCheckedAndWeMarkedOnlyBombs(area)) {\n isItWin = true;\n break;\n }\n }\n if (isItWin) {\n System.out.println("U won!");\n }\n else {\n System.out.println("Defieat!");\n }\n }\n</code></pre>\n<ul>\n<li><p><code>GREETING</code>, <code>area, </code>isItWin<code>should be</code>final<code>. </code>scanner<code>should be lowercase, since it's not a constant (it's just a</code>Scanner<code>that happens to not be reassigned) but</code>GREETING` likely should be all-caps since it's actually a constant.</p>\n</li>\n<li><p>Variable declarations are moved down when possible (in particular, <code>Area[][] area; area = ...</code> is combined into <code>final Area[][] area = ...</code>)</p>\n<p>The <code>while (true)</code> loop to initialize `isItWin is a bit awkward, and is a good candidate for splitting into a new function (which is frequently the case when you find yourself needing to initialize a value inside a loop):</p>\n</li>\n</ul>\n<pre class=\"lang-java prettyprint-override\"><code> private static playUntilWinOrLoss(Area[][] area, Scanner scanner) {\n while (true) {\n printPole(area);\n if (playerTurnsAndIsPlayersTurnInBomb(area, scanner)) {\n return false;\n }\n if (weHaveNotGotAnyEmptyAreaThatNotCheckedAndWeMarkedOnlyBombs(area)) {\n return true;\n }\n }\n }\n</code></pre>\n<p>Next we can just to <code>printPole</code> and take a look. We can see that there's some "symmetry" in the code, but it's not being exploited fully:</p>\n<pre class=\"lang-java prettyprint-override\"><code> if(area[y][x].getStatusOfArea()==StatusOfArea.CLOSED) {\n System.out.print("?");\n }\n else if(area[y][x].getStatusOfArea()==StatusOfArea.OPENED) {\n System.out.print(area[y][x].getValueOfArea().getIcon());\n }\n else if(area[y][x].getStatusOfArea()==StatusOfArea.MARKEDASBOMB) {\n System.out.print("*");\n }\n</code></pre>\n<p>all three lines are of the form <code>System.out.print( ... )</code>, and they all inspect <code>area[y][x]</code> This suggests that the responsibility of identifying the appearance of the area should belong to the <code>Area</code> itself:</p>\n<pre class=\"lang-java prettyprint-override\"><code>class Area {\n private final ValueOfArea value;\n private StatusOfArea status = StatusOfArea.CLOSED;\n\n Area(ValueOfArea value){\n this.value = value;\n }\n ValueOfArea getValue() {\n return value;\n }\n StatusOfArea getStatus() {\n return status;\n }\n void setStatus(StatusOfArea status) {\n this.status = status;\n }\n String getAppearance() {\n if (status == StatusOfArea.CLOSED) {\n return "?";\n }\n if (status == StatusOfArea.MARKEDASBOMB) {\n return "*";\n }\n return value.getIcon();\n }\n}\n</code></pre>\n<p>Here we can make several improvements. First, adding <code>_OfArea</code> to the end of each name doesn't make anything clearer - they are all members of the <code>Area</code> class, so we already know that they belong to the <code>Area</code>. Making these names shorter allows us to scan faster without worrying about problems.</p>\n<p>The <code>status</code> member variable can be initialized in one line as <code>private StatusOfArea status = StatusOfArea.CLOSED;</code></p>\n<p>The new <code>getAppearance()</code> method can be used by <code>printPole</code>:</p>\n<pre class=\"lang-java prettyprint-override\"><code> private static void printPole(Area[][] area) {\n System.out.println();\n for (int y = 0; y < area.length; y++) {\n for (int x = 0; x < area[0].length; x++) {\n System.out.print(area[y][x].getAppearance());\n }\n System.out.println();\n }\n }\n</code></pre>\n<p>Next, we can examine <code>playerTurnsAndIsPlayersTurnInBomb</code>.</p>\n<ul>\n<li><p>Instead of using a chain of <code>else</code>s, we can instead use <code>continue</code> to retry the loop.</p>\n</li>\n<li><p><code>parseInt</code> gets called 6 times when you only really need it twice: once for <code>x</code> and once for <code>y</code> (this is not about "efficiency"; it's about clarity: we're doing the same work over and over, so we could accidentally introduce an inconsistency between the call sites if any logic needed to be changed)</p>\n</li>\n<li><p>The name doesn't accurately describe what the function does. <code>makeMove</code> accurately described what it actually does; since the return value is vague we can make an enum for <code>HIT</code> or <code>NOHIT</code>:</p>\n</li>\n</ul>\n<p>The result is that we can remove entirely the function <code>isXandYIn</code>, and obtain the now-clearer:</p>\n<pre class=\"lang-java prettyprint-override\"><code> enum MoveHitsBomb {\n HIT, NOHIT\n }\n\n private static MoveHitsBomb makeMove(Area[][] area, Scanner scanner) {\n while(true) {\n System.out.println("Print \\"open x y\\", if u want open this area, print \\"mark x y\\", if u want mark this area as bomb or unmark this area");\n String[] commandAndXAndY = scanner.nextLine().split(" ");\n if (commandAndXAndY.length != 3) {\n System.out.println("fill out the form correctly!");\n continue;\n }\n\n final String action = commandAndXAndY[0];\n if (!action.equals("open") && !action.equal("mark")) {\n System.out.println("first work should be equal \\"open\\" or \\"mark\\"!");\n continue;\n }\n\n final int x;\n try {\n x = Integer.parseInt(commandAndXAndY[1]);\n } catch (NumberFormatException | NullPointerException nfe) {\n System.out.println("x should be a number!");\n continue;\n }\n\n final int y;\n try {\n y = Integer.parseInt(commandAndXAndY[2]);\n } catch (NumberFormatException | NullPointerException nfe) {\n System.out.println("y should be a number!");\n continue;\n }\n\n if (y < 0 || area.length <= y) {\n System.out.println("y should be between 0 and " + area.length-1);\n continue;\n }\n if (x < 0 || area[0].length <= x) {\n System.out.println("x should be between 0 and " + area[0].length-1);\n continue;\n }\n \n \n if (action.equals("open")) {\n if (area[y][x].getValue() == ValueOfArea.BOMB) {\n return MoveHitsBomb.HIT;\n }\n \n area[y][x].setStatus(StatusOfArea.OPENED);\n if (area[y][x].getValue() == ValueOfArea.NOONEBOMBAROUND) {\n openAllAround(x, y, area, new ArrayList<>());\n }\n return MoveHitsBomb.NOHIT;\n }\n else { // mark\n area[y][x].setStatusOfArea(StatusOfArea.MARKEDASBOMB);\n return MoveHitsBomb.NOHIT;\n }\n }\n</code></pre>\n<p>Next we might as well look at <code>weHaveNotGotAnyEmptyAreaThatNotCheckedAndWeMarkedOnlyBombs</code>. This function's name is describing what it <em>does</em> (which we can figure out by reading its code) but not what it <em>means</em> (which tells callers how to use it). <code>isWinningBoard</code> seems like a much more accurate name</p>\n<ul>\n<li><code>cell.getValueOfArea() != ValueOfArea.BOMB /* is not a bomb */</code> is not a useful comment, since it's repeating what the code does. We can simplify to:</li>\n</ul>\n<pre class=\"lang-java prettyprint-override\"><code> private static boolean isWinningBoard(Area[][] area) {\n for (int y = 0; y < area.length; y++) {\n for (int x = 0; x < area[0].length; x++) {\n Area cell = area[y][x];\n if (cell.getValue() != ValueOfArea.BOMB && cell.getStatus() != StatusOfArea.OPENED) {\n return false;\n }\n }\n }\n return true;\n }\n</code></pre>\n<p>It's less obvious where to go next to make minor cleanups, so I'm instead going to tackle <code>AreaWithXandY</code>: it probably shouldn't exist. It's clear why you're using it, but you just really don't actually want it to exist.</p>\n<p>The main problem is your <code>Area[][]</code> array that you pass around everywhere. It's certainly useful, but it's not really pulling its weight. We can make a <code>Board</code> class that encapsulates the relevant information. This ends up having wide-reaching consequences for your program as a whole.</p>\n<p>We don't actually need <code>Area</code> or <code>AreaWithXandY</code>. Once we have a <code>Board</code> class, we realize that we only really need <code>StatusOfArea</code> and <code>ValueOfArea</code>. We should <em>also</em> realize that we don't need any numbers in <code>ValueOfArea</code>; we just need <code>EMPTY</code> or <code>BOMB</code>. That's because the number that shows up is entirely presentational, and can be figured out by looking at the neighbors (from <code>Board</code>) rather than storing any additional info in the cell.</p>\n<p>First, we need a position class:</p>\n<pre class=\"lang-java prettyprint-override\"><code>\nfinal class Pos {\n public final int x;\n public final int y;\n Pos(int x, int y) {\n this.x = x;\n this.y = y;\n }\n}\n</code></pre>\n<p>(if this was being used for something larger, I'd add an <code>equals</code> and <code>hashCode</code> implementation, but we don't need either for this small program). Note that we know the representation is definitely not changing (if it did, we'd have to rewrite a lot of stuff anyway) so it's fine to just make <code>x</code> and <code>y</code> into <code>public final</code> fields and skip the getters/setters.</p>\n<p>We have the new enums</p>\n<pre class=\"lang-java prettyprint-override\"><code>enum StatusOfArea {\n MARKEDASBOMB, OPENED, CLOSED\n}\nenum ValueOfArea {\n EMPTY, BOMB\n}\n</code></pre>\n<p>and the <code>Board</code>:</p>\n<pre class=\"lang-java prettyprint-override\"><code>class Board {\n private final ValueOfArea[][] values;\n private final StatusOfArea[][] statuses;\n\n public final int width;\n public final int height;\n\n Board(ValueOfArea[][] values) {\n this.values = values;\n this.height = values.length;\n this.width = values[0].length;\n this.statuses = new StatusOfArea[height][width];\n for (StatusOfArea[] row : statuses) {\n Arrays.fill(row, StatusOfArea.CLOSED);\n }\n }\n public String appearanceAt(Pos p) {\n if (statuses[p.y][p.x] == StatusOfArea.CLOSED) {\n return "?";\n }\n if (statuses[p.y][p.x] == StatusOfArea.MARKEDASBOMB) {\n return "*";\n }\n int count = countMineNeighbors(p);\n if (count == 0) {\n return "-";\n }\n return "" + count;\n }\n public boolean inBounds(Pos p) {\n return p.x >= 0 && p.x < width && p.y >= 0 && p.y < height;\n }\n public int countMineNeighbors(Pos p) {\n int count = 0;\n for (int dx = -1; dx <= 1; dx++) {\n for (int dy = -1; dy <= 1; dy++) {\n Pos neighbor = new Pos(p.x + dx, p.y + dy);\n if (this.inBounds(neighbor) && this.isBombAt(neighbor)) {\n count++;\n }\n }\n }\n return count;\n }\n public boolean isBombAt(Pos p) {\n return this.values[p.y][p.x] == ValueOfArea.BOMB;\n }\n public boolean isOpenAt(Pos p) {\n return this.statuses[p.y][p.x] == StatusOfArea.OPENED;\n }\n\n public void markAsBombAt(Pos p) {\n this.statuses[p.y][p.x] = StatusOfArea.MARKEDASBOMB;\n }\n public void open(Pos p) {\n if (this.statuses[p.y][p.x] == StatusOfArea.OPENED) {\n return;\n }\n this.statuses[p.y][p.x] = StatusOfArea.OPENED;\n\n if (this.countMineNeighbors(p) == 0) {\n for (int dx = -1; dx <= 1; dx++) {\n for (int dy = -1; dy <= 1; dy++) {\n Pos neighbor = new Pos(p.x + dx, p.y + dy);\n if (this.inBounds(neighbor)) {\n this.open(neighbor);\n }\n }\n }\n }\n }\n}\n</code></pre>\n<p>The <code>Board</code> constructor asks for the values to fill the grid with, and then it does the rest. In particular, it creates the <code>statuses</code> array and fills it with <code>StatusOfArea.CLOSED</code>.</p>\n<p>Counting neighbors is important for the <code>getAppearance()</code> method, so that's provided as a convenience. It's also used inside the <code>open()</code> method, which is responsible for opening cells up <em>and</em> for performing the flood-fill (look how much shorter it is, now that it's in the right place, and our data reflects our usage!)</p>\n<p>Everything else needs to be adjusted slightly (mostly to use <code>Board</code> methods instead of directly reading <code>Area</code>, which no longer exists) and to clean up the creation of the board.</p>\n<p>The only one I really want to draw your attention to is <code>fillAreaWithBombs</code>, which uses an entirely different approach. In particular, it makes a list of locations and then shuffles them, filling the first <code>howManyBombs</code> items. This is much, much faster for large grids, because <code>remove</code> is linear (e.g. for a grid with 1,000,000 cells, this will be roughly 1,000,000 times faster).</p>\n<pre class=\"lang-java prettyprint-override\"><code> private static ValueOfArea[][] fillAreaWithBombs(int width, int height, int howManyBombs) {\n ValueOfArea[][] area = new ValueOfArea[width][height];\n ArrayList<Pos> listOfAllPositions = new ArrayList<>();\n for (int y = 0; y < area.length; y++) {\n for (int x = 0; x < area.length; x++) {\n area[y][x] = ValueOfArea.EMPTY;\n listOfAllPositions.add(new Pos(x, y));\n }\n }\n Collections.shuffle(listOfAllPositions);\n\n for (int i = 0; i < listOfAllPositions.size() && i < howManyBombs; i++) {\n area[listOfAllPositions.get(i).y][listOfAllPositions.get(i).x] = ValueOfArea.BOMB;\n }\n\n return area;\n }\n</code></pre>\n<p>Here's the whole program:</p>\n<pre class=\"lang-java prettyprint-override\"><code>import java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.Collections;\n\nimport java.util.Scanner;\n\npublic class Minesweeper {\n public static void main(String[] args) {\n final Scanner scanner = new Scanner(System.in);\n \n final String GREETING = "Hi, lets play minesweeper!";\n System.out.println(GREETING);\n \n Pos corner = chooseSize(scanner);\n final int HOWMANYBOMBS = getHowManyBombs(corner.x, corner.y, scanner);\n \n final ValueOfArea[][] rawValues = fillAreaWithBombs(corner.x, corner.y, HOWMANYBOMBS);\n\n final boolean isItWin = playUntilWinOrLoss(new Board(rawValues), scanner);\n if (isItWin) {\n System.out.println("U won!");\n }\n else {\n System.out.println("Defieat!");\n }\n }\n\n private static boolean playUntilWinOrLoss(Board area, Scanner scanner) {\n while (true) {\n printPole(area);\n if (makeMove(area, scanner) == MoveHitsBomb.HIT) {\n return false;\n }\n if (isWinningBoard(area)) {\n return true;\n }\n }\n }\n\n private static boolean isWinningBoard(Board board) {\n for (int y = 0; y < board.height; y++) {\n for (int x = 0; x < board.width; x++) {\n if (!board.isBombAt(new Pos(x, y)) && !board.isOpenAt(new Pos(x, y))) {\n return false;\n }\n }\n }\n return true;\n }\n\n\n enum MoveHitsBomb {\n HIT, NOHIT\n }\n\n private static MoveHitsBomb makeMove(Board area, Scanner scanner) {\n while(true) {\n System.out.println("Print \\"open x y\\", if u want open this area, print \\"mark x y\\", if u want mark this area as bomb or unmark this area");\n String[] commandAndXAndY = scanner.nextLine().split(" ");\n if (commandAndXAndY.length != 3) {\n System.out.println("fill out the form correctly!");\n continue;\n }\n\n final String action = commandAndXAndY[0];\n if (!action.equals("open") && !action.equals("mark")) {\n System.out.println("first work should be equal \\"open\\" or \\"mark\\"!");\n continue;\n }\n\n final int x;\n try {\n x = Integer.parseInt(commandAndXAndY[1]);\n } catch (NumberFormatException | NullPointerException nfe) {\n System.out.println("x should be a number!");\n continue;\n }\n\n final int y;\n try {\n y = Integer.parseInt(commandAndXAndY[2]);\n } catch (NumberFormatException | NullPointerException nfe) {\n System.out.println("y should be a number!");\n continue;\n }\n\n if (y < 0 || area.height <= y) {\n System.out.println("y should be between 0 and " + (area.height-1));\n continue;\n }\n if (x < 0 || area.width <= x) {\n System.out.println("x should be between 0 and " + (area.width-1));\n continue;\n }\n \n \n if (action.equals("open")) {\n if (area.isBombAt(new Pos(x, y))) {\n return MoveHitsBomb.HIT;\n }\n \n area.open(new Pos(x, y));\n return MoveHitsBomb.NOHIT;\n }\n else { // mark\n area.markAsBombAt(new Pos(x, y));\n return MoveHitsBomb.NOHIT;\n }\n }\n }\n\n private static void printPole(Board area) {\n System.out.println();\n for (int y = 0; y < area.height; y++) {\n for (int x = 0; x < area.width; x++) {\n System.out.print(area.appearanceAt(new Pos(x, y)));\n }\n System.out.println();\n }\n }\n\n private static ValueOfArea[][] fillAreaWithBombs(int width, int height, int howManyBombs) {\n ValueOfArea[][] area = new ValueOfArea[width][height];\n ArrayList<Pos> listOfAllPositions = new ArrayList<>();\n for (int y = 0; y < area.length; y++) {\n for (int x = 0; x < area.length; x++) {\n area[y][x] = ValueOfArea.EMPTY;\n listOfAllPositions.add(new Pos(x, y));\n }\n }\n Collections.shuffle(listOfAllPositions);\n\n for (int i = 0; i < listOfAllPositions.size() && i < howManyBombs; i++) {\n area[listOfAllPositions.get(i).y][listOfAllPositions.get(i).x] = ValueOfArea.BOMB;\n }\n\n return area;\n }\n private static int getHowManyBombs(int width, int height, Scanner scanner) {\n while(true) {\n System.out.println("print number of bombs: ");\n String howManyBombsString = scanner.nextLine();\n if(!isNumeric(howManyBombsString)) {\n System.out.println("it should be number!");\n }\n else if(false==(0<Integer.parseInt(howManyBombsString) && Integer.parseInt(howManyBombsString) < width * height)) {\n System.out.println("it should be positive and it should not exceed the field capacity!");\n }\n else {\n return Integer.parseInt(howManyBombsString);\n }\n }\n }\n\n private static Pos chooseSize(Scanner scanner) {\n while (true) {\n System.out.println("Pick x.length and y.length of area(print \\"x y\\"): ");\n final String[] turnXandY = scanner.nextLine().split(" "); \n if (turnXandY.length != 2) {\n System.out.println("print: \\"x y\\"!");\n continue;\n }\n if (!isNumeric(turnXandY[0]) || !isNumeric(turnXandY[1])) {\n System.out.println("x and y should be numbers!");\n continue;\n }\n if (Integer.parseInt(turnXandY[0]) <= 0 || Integer.parseInt(turnXandY[1]) <= 0) {\n System.out.println("x and y should be >0!");\n continue;\n }\n return new Pos(Integer.parseInt(turnXandY[0]), Integer.parseInt(turnXandY[1]));\n }\n }\n\n public static boolean isNumeric(String strNum) {\n try {\n Integer.parseInt(strNum);\n } catch (NumberFormatException | NullPointerException nfe) {\n return false;\n }\n return true;\n }\n}\n\nfinal class Pos {\n public final int x;\n public final int y;\n Pos(int x, int y) {\n this.x = x;\n this.y = y;\n }\n}\n\nenum StatusOfArea {\n MARKEDASBOMB, OPENED, CLOSED\n}\nenum ValueOfArea {\n EMPTY, BOMB\n}\n\nclass Board {\n private final ValueOfArea[][] values;\n private final StatusOfArea[][] statuses;\n\n public final int width;\n public final int height;\n\n Board(ValueOfArea[][] values) {\n this.values = values;\n this.height = values.length;\n this.width = values[0].length;\n this.statuses = new StatusOfArea[height][width];\n for (StatusOfArea[] row : statuses) {\n Arrays.fill(row, StatusOfArea.CLOSED);\n }\n }\n public String appearanceAt(Pos p) {\n if (statuses[p.y][p.x] == StatusOfArea.CLOSED) {\n return "?";\n }\n if (statuses[p.y][p.x] == StatusOfArea.MARKEDASBOMB) {\n return "*";\n }\n int count = countMineNeighbors(p);\n if (count == 0) {\n return "-";\n }\n return "" + count;\n }\n public boolean inBounds(Pos p) {\n return p.x >= 0 && p.x < width && p.y >= 0 && p.y < height;\n }\n public int countMineNeighbors(Pos p) {\n int count = 0;\n for (int dx = -1; dx <= 1; dx++) {\n for (int dy = -1; dy <= 1; dy++) {\n Pos neighbor = new Pos(p.x + dx, p.y + dy);\n if (this.inBounds(neighbor) && this.isBombAt(neighbor)) {\n count++;\n }\n }\n }\n return count;\n }\n public boolean isBombAt(Pos p) {\n return this.values[p.y][p.x] == ValueOfArea.BOMB;\n }\n public boolean isOpenAt(Pos p) {\n return this.statuses[p.y][p.x] == StatusOfArea.OPENED;\n }\n\n public void markAsBombAt(Pos p) {\n this.statuses[p.y][p.x] = StatusOfArea.MARKEDASBOMB;\n }\n public void open(Pos p) {\n if (this.statuses[p.y][p.x] == StatusOfArea.OPENED) {\n return;\n }\n this.statuses[p.y][p.x] = StatusOfArea.OPENED;\n\n if (this.countMineNeighbors(p) == 0) {\n for (int dx = -1; dx <= 1; dx++) {\n for (int dy = -1; dy <= 1; dy++) {\n Pos neighbor = new Pos(p.x + dx, p.y + dy);\n if (this.inBounds(neighbor)) {\n this.open(neighbor);\n }\n }\n }\n }\n }\n}\n<span class=\"math-container\">```</span>\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-03T14:32:17.350",
"Id": "452198",
"Score": "0",
"body": "Great analysis!\nBut I can’t understand why we need to constantly count how many bombs are around? This value is constant for each field, and its score is very expensive. I would like to make a good structure, but bombs should not have this element. I can not imagine the right abstraction for this."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-03T15:33:30.357",
"Id": "452199",
"Score": "0",
"body": "Why don't we show the first variables that will be used in the program? Wouldn't that improve code readability?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-03T19:18:44.953",
"Id": "452233",
"Score": "0",
"body": "The runtime cost of computing bomb-count numbers on-the-fly is very low (only 9 array accesses and some increments!) so it's unlikely to have a large impact on program performance (and you'd need to benchmark and measure before assuming that it's actually a problem)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-03T19:21:17.583",
"Id": "452234",
"Score": "0",
"body": "I'm not exactly sure what you mean by your second comment. When you're reading a block of code, you're expecting to learn the \"how\" by just looking at the code. Well-structured code makes the \"why\" clear. If you put all your variables at the top of the function, the reader has no idea why they're there until they're used in context. Then when they're reading the code, they have to remind themselves whether this is the first assignment, or a reassignment, or whatever, instead of just knowing that \"oh, at this point it makes sense to give this value a name\"."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-04T05:38:02.607",
"Id": "452284",
"Score": "0",
"body": "Java SE, Documentation: \"6.3 Placement\nPut declarations only at the beginning of blocks. (A block is any code surrounded by curly braces \"{\" and \"}\".) Don't wait to declare variables until their first use; it can confuse the unwary programmer and hamper code portability within the scope.\""
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-04T18:26:39.710",
"Id": "452412",
"Score": "0",
"body": "That documentation is _incredibly_ old (https://www.oracle.com/technetwork/java/javase/documentation/codeconventions-141270.html last updated 1999) and no longer authoritative. The \"[confused] unwary programmer\" would likely be coming from C89, where doing otherwise is illegal. But that was 20 years ago, and no longer the best advice. See e.g. https://stackoverflow.com/questions/1411463"
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-02T21:39:05.170",
"Id": "231756",
"ParentId": "231668",
"Score": "2"
}
},
{
"body": "<h2>Afterthought / tldr;</h2>\n\n<p>If you start naming your methods & variables descriptively, using the suggestions below & finding more information/examples online it will be a huge 'level up' in your programming. Everything else will become easier.</p>\n\n<h2>General coding standards</h2>\n\n<p>Use <code>static final</code> variables for messages. Alternatively these could be taken from a properties file</p>\n\n<p>Variable names that are multiple words are always separated somehow. With static final variables are all caps separated by a <code>_</code>. Class names are UpperCamelCase & variables are lowerCamelCase.</p>\n\n<p>Declare variables when they are used. As locally scoped as possible</p>\n\n<p>Separate arguments/parameters with a space</p>\n\n<p>Use the condition inside the while/do while loop. Try to avoid <code>while(true)</code>.</p>\n\n<p>Use spaces before/after <code>=</code>.</p>\n\n<p>Don't use magic Strings/numbers</p>\n\n<p>Use a white space to separate conditionals</p>\n\n<p>Use a line of white space to separate methods</p>\n\n<p>Don't do this:</p>\n\n<pre><code>private StatusOfArea statusOfArea;\n{\n statusOfArea = StatusOfArea.CLOSED;\n}\n</code></pre>\n\n<p>Each class/enum should be in it's own Java file.</p>\n\n<p><code>Command</code> (Open / Mark) should be it's own ENUM or class.</p>\n\n<p>Take advantage of the <code>toString()</code> method. Also keep logic contained in the proper class/enum. You should be printing the grid by calling the <code>toString()</code> on each object. Note that <code>System.out.print</code> will invoke the <code>toString</code> method.</p>\n\n<p>You can compare Strings without worrying about case by using the String method <code>equalsIgnoreCase</code>.</p>\n\n<p>I am not sure what <code>printPole</code> means but it looks like it's printing out the grid. Even if you want the icon representing the item and what's printed out to be different, the logic/symbols should be contained in the Enum itself. For example, by having another property on the ENUM.</p>\n\n<p>Separate unrelated logic into a separate class. For example, <code>Minesweeeper</code> should not be responsible for checking if a String is numeric. I mentioned this in the other CR linked. </p>\n\n<p>Although it's kind of cheating, (doesn't technically follow best practices (single responsibility)) An easy way to do this is to have a <code>Helper</code> class or a <code>Util</code> class. This class can include all of your functions such as checking if a String is numeric. It would not validating a Move for example, though. That would either be in a <code>MoveValidation</code> class, or the <code>Minesweeper</code> class. If you are confused as what can go in this Utility class, leave it for last and put all \"Other\" methods in it. (Methods that you can't find a class for or justify creating a class for)</p>\n\n<p>It's better to be converting a String all in one place. For example maybe one day you have troubles with certain input being formatted wrong or certain numbers are throwing an error. It's much easier if you have a single method. </p>\n\n<p>It's also good when the method changes often. An example is if you've had to change methods often, such as moving away from <code>apache.utils.String</code>. Your class would be a simple wrapper for some or all of the functions.</p>\n\n<p>Never put <code>== true</code> or <code>== false</code> in a condition. It's redundant. Use <code>!</code> for false.</p>\n\n<p>Don't run methods multiple times when you don't need to. For example in your if statement you're parsing the input as <code>int</code> twice.</p>\n\n<p>Printing an error and returning null could lead to a <code>NullPointerException</code> or other issues. It's possible you may just look at the last error & not see your error message. I suggest throwing an Exception instead. You could throw a <code>RuntimeException</code> if you want.</p>\n\n<p>Here we want the numberOfBombs selected by the user to be less than the total area. It's not crystal clear though. You could make a variable named <code>totalSpacedOnGrid</code>, or you could create a method called <code>getTotalNumberOfSpaces</code> and input area as a paramater. However I think a comment is best in this situation.</p>\n\n<p>(area.length * area[0].length) >= numberOfBombsSelectedByUser</p>\n\n<p>Users prefer reading \"greater than\" rather than \">\" in messages that the user sees.</p>\n\n<p>Declare variables as locally as possible.</p>\n\n<p>Take advantage of <code>String.format</code>. Lots to be said here, information available online.</p>\n\n<h2>Java Streams</h2>\n\n<p>Lots of cases here are good candidates for using Streams if you're using Java 8+</p>\n\n<h2>Naming variables</h2>\n\n<p>Avoid \"I\" or \"we\" in naming variables/methods.</p>\n\n<p><code>Coordinate</code> is a better name than <code>AreaWithXAndY</code>. The alternative to this class is an array of 2 ints. (<code>int[2]</code>)</p>\n\n<p><code>isItWin</code> should be renamed <code>isWin</code>.</p>\n\n<p>Avoid double negatives. <code>weHaveNotGotAnyEmptyAreaThatNotCheckedAndWeMarkedOnlyBombs</code> is an awkward read. If you are checking if the player has won or not, you can name the method <code>playerHasWon</code> then use a JavaDoc to explain the conditions.</p>\n\n<p><code>howManyBombs</code> reads like a question. It should not be a variable name. A better one would be <code>numberOfBombs</code>. If you'd like to be explicit that it was chosen from the user, <code>numberOfBombsSelectedByUser</code>. However note your naming should only relate to the scope it's in, not the whole class. So in your <code>fillAreaWithBomb</code> method, we don't care if the parameter came from the user or not. So don't name it in relation to where it came from.</p>\n\n<p>HOW_MANY_BOMBS is not a static constant, so it should be named howManyBombs. (But changed again as I mentioned above). For more info on naming conventions for 'final but not static' <a href=\"https://softwareengineering.stackexchange.com/questions/252243/naming-convention-final-fields-not-static\">see here</a>.</p>\n\n<p><code>Area</code> is not a good class name. It only represents one spot in the total area. Tbh I cannot think of a good name. It's a \"Square\" or a \"Mark\" I guess.</p>\n\n<h2>playerTurnsAndIsPlayersTurnInBomb</h2>\n\n<p><code>playerTurnsAndIsPlayersTurnInBomb</code> is not correct. By the name it suggests it'll return false if it's not the players turn (but it's always the players turn since theirs only 1 player). This method should also be broken up.</p>\n\n<p>This method should not be determining a loss. It's doing way too much. Try to think in terms of the method, rather than the whole class.</p>\n\n<h2>Use Objects, don't list all methods as static</h2>\n\n<p>A common beginner mistake is to make all methods <code>static</code> since you get a warning when calling them in the main method. This is a bad habit, you should stop it now. </p>\n\n<p>The best way to break out of bad habits is to never learn them (You can't unlearn things but just wanted to mention you've learned the wrong way to get around that warning). Instead you should be calling the methods on an instance of a <code>Minesweeper</code> object</p>\n\n<h2>Don't over complicate logic</h2>\n\n<p>Methods should be doing 1 thing. Validation could be a method (I mentioned this in the other Codereview).</p>\n\n<p>Never do <code>false == 0 <..</code> or <code>!0 < ...</code>. Instead use the <code>>=</code> (greater than or equal to) symbol.</p>\n\n<h2>Don't ignore warnings</h2>\n\n<p>When you see depreciated warnings assuming you are using an IDE you should go into the method and see what alternative method you should be using. If you're not using an IDE try googling the method to see a non-depreciated alternative.</p>\n\n<h2>Don't repeat yourself</h2>\n\n<p>Your <code>fillAreaWithBombs</code> and <code>fillAreaWithEmptyArea</code> could be refactored to reduce repeating yourself. What if you had a method that filled an area with the value passed as a parameter. You could also have a boolean to only set if the field is null.</p>\n\n<p>Either set all fields to 'empty' then add bombs (no checking for null fields), or set appropriate bombs then add the null fields to 'empty' (with checking to ensure you don't overwrite bombs).</p>\n\n<p>A third option is to use <code>null</code> as your <code>EMPTY</code>. Then just fill bombs.</p>\n\n<h2>Main logic is overly complicated</h2>\n\n<p>Your area classes are overly complicated. You should just have an ENUM which states what a space could be, then have a 2d array of that enum.</p>\n\n<p>If you want the mark/spot to have an X/Y that could be a property of the ENUM, or you could make it a class instead of an ENUM (As you have now). However I don't see it being necessary. Since it's inside a 2d array, you need the X/Y to access it anyway. So you'll never need to get it from the spot.</p>\n\n<p>No need to use an ArrayList for filling the 2D array. Whenever you write this kind of logic (In this case, getting X random numbers between y-z without duplicates), it should be placed into it's own method and be documented or clearly written. Unless you are sure it's the 'best way' of doing it, chances are it could be refactored later. It's also important for other developers reading it to understand it.</p>\n\n<p>I don't know what <code>getAllAreasAround</code> is doing exactly but you don't need it. It's overly complicated. Same for <code>getAllAreasAroundWithTheirXandY</code>.</p>\n\n<h2>Suggestions for additional features</h2>\n\n<p>Don't let the player select the same place twice</p>\n\n<p>Count how many turns the player has made. Alternatively you could count based on what the board looks like at the end</p>\n\n<p>Add a debug option to let you see the bombs on the grid. For example, if an argument is given on the command line to 'debug'.</p>\n\n<p>Add a timer & 'number of bombs not flagged' counter just like Microsoft minesweeper.</p>\n\n<p>Show the full grid when the player loses/wins.</p>\n\n<h2>Modified code:</h2>\n\n<pre><code>package Test;\n\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.Collections;\nimport java.util.List;\nimport java.util.Scanner;\nimport static Test.Utility.isNumeric;\nimport static Test.Utility.convertSingleDigitIntegerToCharacter;\nimport static Test.Utility.getRandomCoordinatesWithoutDuplicates;\n\npublic class Minesweeper {\n private static final String GREETING_MESSAGE = \"Hi, lets play minesweeper!\";\n private static final String PICK_X_AND_Y_AREA_MESSAGE = \"Pick x.length and y.length of area(print \\\"x y\\\"): \";\n private static final String NUMBER_OF_BOMBS_PROMPT = \"print number of bombs: \";\n private static final String PROMPT_USER_FOR_COMMAND = \"Print \\\"open x y\\\", if u want open this area, print \\\"mark x y\\\", if u want mark this area as bomb or unmark this area\";\n\n private static final String INCORRECT_COMMAND_NUMBER_OF_ARGUMENTS = \"fill out the form correctly!\";\n private static final String INVALID_COMMAND = \"first work should be equal \\\"open\\\" or \\\"mark\\\"!\";\n private static final String COMMAND_NOT_A_NUMBER = \"x and y should be numbers!\";\n private static final String INVALID_COORDINATE = \"x and y should be in area! P.S.: area.lengthY=%s. area.lengthX=%s\";\n\n private static final Scanner SCANNER = new Scanner(System.in);\n\n public void play() {\n boolean isWin = false;\n\n System.out.println(GREETING_MESSAGE);\n Mark[][] grid = getLengthsOfAreaFromUser(SCANNER);\n\n final int numberOfBombs = getNumberOfBombsFromUser(grid, SCANNER);\n System.out.println(\"hi\");\n fillArea(grid, numberOfBombs);\n\n while(true) {\n printGrid(grid, true);\n\n Mark mark = playerMakeAMove(grid, SCANNER);\n\n if(mark == Mark.BOMB) {\n isWin = false;\n break;\n }\n else if(playerHasWonGame(grid)) {\n isWin = true;\n break;\n }\n }\n\n if(isWin) {\n printGrid(grid, false);\n System.out.println(\"U won!\");\n }\n else {\n printGrid(grid, false);\n System.out.println(\"Defieat!\");\n }\n }\n\n private boolean playerHasWonGame(Mark[][] area) {\n for (Mark[] markArray : area) {\n for (Mark mark : markArray) {\n if (mark == Mark.EMPTY) {\n return false;\n }\n }\n }\n\n return true;\n }\n\n /**\n * Prompt the user to open a location or mark a location & return the updated {@link Mark} at the location \n */\n private Mark playerMakeAMove(Mark[][] area, Scanner scanner) {\n CommandSelected selectedCommand = getValidCommandFromUser(scanner, area);\n int x = selectedCommand.getCoordinate().getX();\n int y = selectedCommand.getCoordinate().getY();\n\n Mark markOnArea = area[y][x];\n if(selectedCommand.getUserOption() == UserOption.OPEN) {\n if(markOnArea == Mark.BOMB) {\n return Mark.BOMB;\n }\n else {\n int numberOfBombsSurrounding = countBombsAtLocations(area, getSurroundingCoordinates(area, false, selectedCommand.getCoordinate()));\n\n if (numberOfBombsSurrounding == 0) {\n area[y][x] = Mark.OPEN;\n openAllAround(x, y, area);\n }\n else {\n // E.G convert from 1 to \"Mark.ONE_BOMB\".\n char character = convertSingleDigitIntegerToCharacter(numberOfBombsSurrounding);\n area[y][x] = Mark.valueOf(character);\n }\n\n return area[y][x];\n }\n }\n else {\n area[y][x] = Mark.MARKED_AS_BOMB;\n return Mark.MARKED_AS_BOMB;\n }\n }\n\n private CommandSelected getValidCommandFromUser(Scanner scanner, Mark[][] area) {\n while (true) {\n System.out.println(PROMPT_USER_FOR_COMMAND);\n String[] commandAndXAndY = scanner.nextLine().split(\" \");\n\n if(commandAndXAndY.length != 3) {\n System.out.println(INCORRECT_COMMAND_NUMBER_OF_ARGUMENTS);\n }\n else {\n String commandSelected = commandAndXAndY[0];\n String xSelected = commandAndXAndY[1];\n String ySelected = commandAndXAndY[2];\n\n if(!commandSelected.equalsIgnoreCase(\"open\") && commandSelected.equalsIgnoreCase(\"mark\")) {\n System.out.println(INVALID_COMMAND);\n }\n else if(!isNumeric(xSelected) || !isNumeric(ySelected)) {\n System.out.println(COMMAND_NOT_A_NUMBER);\n }\n else if(!isValidCoordinate(Integer.parseInt(xSelected), Integer.parseInt(ySelected), area)) {\n System.out.print(String.format(INVALID_COORDINATE, area.length, area[0].length));\n }\n else {\n return new CommandSelected(UserOption.fromValue(commandSelected), new Coordinate(Integer.parseInt(xSelected), Integer.parseInt(ySelected)));\n }\n }\n }\n }\n\n private void openAllAround(int x, int y, Mark[][] area) {\n List<Coordinate> coordinatesInArea = getAllSurroundingCoordinates(area, false, x, y);\n\n for(Coordinate coordinate : coordinatesInArea) {\n Mark markAtLocation = area[coordinate.getY()][coordinate.getX()];\n\n if (!hasLocationBeenMarked(markAtLocation) && Mark.BOMB != markAtLocation) {\n int numberOfBombsSurrounding = countBombsAtLocations(area, getSurroundingCoordinates(area, false, coordinate));\n\n if (numberOfBombsSurrounding == 0) {\n area[coordinate.getY()][coordinate.getX()] = Mark.OPEN;\n openAllAround(coordinate.getX(), coordinate.getY(), area);\n }\n else {\n // E.G convert from 1 to \"Mark.ONE_BOMB\".\n char character = convertSingleDigitIntegerToCharacter(numberOfBombsSurrounding);\n area[coordinate.getY()][coordinate.getX()] = Mark.valueOf(character);\n }\n }\n }\n }\n\n private boolean hasLocationBeenMarked(Mark location) {\n final List<Mark> LOCATIONS_THAT_SHOULD_NOT_BE_MARKED = Arrays.asList(\n Mark.MARKED_AS_BOMB,\n Mark.ONE_BOMB_AROUND,\n Mark.TWO_BOMB_AROUND,\n Mark.THREE_BOMB_AROUND,\n Mark.FOUR_BOMB_AROUND,\n Mark.FIVE_BOMB_AROUND,\n Mark.SIX_BOMB_AROUND,\n Mark.SEVEN_BOMB_AROUND,\n Mark.EIGHT_BOMB_AROUND,\n Mark.OPEN\n );\n\n return LOCATIONS_THAT_SHOULD_NOT_BE_MARKED.contains(location);\n }\n\n /**\n * Returns all valid unmarked coordinates surrounding the area of the coordinate passed\n */\n private List<Coordinate> getAllSurroundingCoordinates(Mark[][] area, boolean includeCoordinatePassed, int xCoord, int yCoord) {\n List<Coordinate> validCoordinatesInArea = new ArrayList<Coordinate>();\n\n // We want the coord itself, the coord -1 and the coord + 1 to get the full area\n for (int x = xCoord - 1; x <= xCoord + 1; x++) {\n for (int y = yCoord - 1; y <= yCoord + 1; y++) {\n // Skip this coordinate if appropriate\n if (includeCoordinatePassed || xCoord != x || yCoord != y) {\n if (isValidCoordinate(x, y, area)) {\n validCoordinatesInArea.add(new Coordinate(x, y));\n }\n }\n }\n }\n\n return validCoordinatesInArea;\n }\n\n private List<Coordinate> getSurroundingCoordinates(Mark[][] area, boolean includeCoordinatePassed, Coordinate coordinate) {\n return getAllSurroundingCoordinates(area, includeCoordinatePassed, coordinate.getX(), coordinate.getY());\n }\n\n private int countBombsAtLocations(Mark[][] grid, Coordinate... coordinatesToCountBombsIn) {\n int numberOfBombs = 0;\n\n for (Coordinate coordinate : coordinatesToCountBombsIn) {\n if (grid[coordinate.getY()][coordinate.getX()] == Mark.BOMB) {\n numberOfBombs++;\n }\n }\n\n return numberOfBombs;\n }\n\n private int countBombsAtLocations(Mark[][] grid, List<Coordinate> coordinatesToCountBombsIn) {\n Coordinate[] coordinateList = new Coordinate[coordinatesToCountBombsIn.size()];\n return countBombsAtLocations(grid, coordinatesToCountBombsIn.toArray(coordinateList));\n }\n\n private static void printGrid(Mark[][] grid, boolean hideBombs) {\n System.out.println();\n for(int y = 0; y < grid.length; y++) {\n for(int x=0; x < grid[0].length; x++) {\n if (hideBombs && grid[y][x] == Mark.BOMB) {\n System.out.print(Mark.EMPTY);\n }\n else {\n System.out.print(grid[y][x]);\n }\n\n }\n System.out.println();\n }\n }\n\n private static void fillArea(Mark[][] area, int numberOfBombs) {\n fillArea(area, Mark.EMPTY);\n\n // fill area with bombs\n fillAreaWithRandomMarks(area, numberOfBombs, Mark.BOMB);\n }\n\n private static void fillArea(Mark[][] area, Mark mark) {\n for (int y = 0; y < area.length; y++) {\n for (int x = 0; x < area[y].length; x++) {\n area[x][y] = mark;\n }\n }\n }\n\n private static void fillAreaWithRandomMarks(Mark[][] area, int numberOfBombs, Mark mark) {\n int[][] bombLocations = getRandomCoordinatesWithoutDuplicates(numberOfBombs, area.length, area[0].length);\n\n for (int i = 0; i < bombLocations.length; i ++) {\n int x = bombLocations[i][0];\n int y = bombLocations[i][1];\n\n area[x][y] = mark;\n }\n }\n\n private int getNumberOfBombsFromUser(Object[][] area, Scanner scanner) {\n int numberOfBombs = -1;\n boolean isValidNumberOfBombs = false;\n\n do\n {\n numberOfBombs = getValidNumberFromUser(scanner, NUMBER_OF_BOMBS_PROMPT);\n isValidNumberOfBombs = isValidNumerOfBombs(numberOfBombs, area);\n\n if (!isValidNumberOfBombs) {\n System.out.println(\"it should be positive and it should not exceed the field capacity!\");\n }\n } while (!isValidNumberOfBombs);\n\n return numberOfBombs;\n }\n\n private int getValidNumberFromUser(Scanner scanner, String prompt) {\n System.out.println(prompt);\n String inputFromUser = scanner.nextLine();\n\n while (inputFromUser == null || !isNumeric(inputFromUser)) {\n System.out.println(\"it should be number!\");\n inputFromUser = scanner.nextLine();\n }\n\n return Integer.parseInt(inputFromUser);\n }\n\n private boolean isValidNumerOfBombs(int numberOfBombs, Object[][] area) {\n // Between 1 and the max number of spaces\n return numberOfBombs > 0 && (area.length * area[0].length) >= numberOfBombs;\n }\n\n private static Mark[][] getLengthsOfAreaFromUser(Scanner scanner) {\n Mark[][] gridCreated = null;\n while(gridCreated == null) {\n System.out.println(PICK_X_AND_Y_AREA_MESSAGE);\n String[] turnXandY = scanner.nextLine().split(\" \"); \n\n if(turnXandY.length != 2) {\n System.out.println(\"print: \\\"x y\\\"!\");\n }\n else if(!isNumeric(turnXandY[0]) || !isNumeric(turnXandY[1])) {\n System.out.println(\"x and y should be numbers!\");\n }\n else if(Integer.parseInt(turnXandY[0]) <= 0 || Integer.parseInt(turnXandY[1]) <= 0) {\n System.out.println(\"x and y should be greater than 0!\");\n }\n else {\n gridCreated = new Mark[Integer.parseInt(turnXandY[0])][Integer.parseInt(turnXandY[1])];\n }\n }\n\n return gridCreated;\n }\n\n private static boolean isValidCoordinate(int x, int y, Mark[][] area) {\n if(x < 0 || area[0].length <= x) {\n return false;\n }\n if(y < 0 || area.length <= y) {\n return false;\n }\n return true;\n }\n}\n\nclass Coordinate {\n int x, y;\n\n public Coordinate(int x, int y) {\n this.x = x;\n this.y = y;\n }\n\n public int getX() {\n return this.x;\n }\n\n public int getY() {\n return this.y;\n }\n\n public int[] toArray() {\n return new int[]{x, y};\n }\n}\n\nenum UserOption {\n MARK(\"MARK\"),\n OPEN(\"OPEN\");\n\n private String option;\n\n UserOption(String option) {\n this.option = option;\n }\n\n public static UserOption fromValue(String option) {\n for (UserOption userOption : values()) {\n if (userOption.option.equalsIgnoreCase(option)) {\n return userOption;\n }\n }\n\n return null;\n }\n}\n\nclass CommandSelected {\n private UserOption optionSelected;\n private Coordinate coordinateSelected;\n\n public UserOption getUserOption() {\n return this.optionSelected;\n }\n\n public Coordinate getCoordinate() {\n return this.coordinateSelected;\n }\n\n public CommandSelected(UserOption option, Coordinate coordinate) {\n this.optionSelected = option;\n this.coordinateSelected = coordinate;\n }\n}\n\nclass Utility {\n public static boolean isNumeric(String input) {\n try {\n Integer.parseInt(input);\n } catch (NumberFormatException | NullPointerException nfe) {\n return false;\n }\n return true;\n }\n\n public static int[][] getRandomCoordinatesWithoutDuplicates(int numberOfCoordinates, int widthOfGrid, int heightOfGrid) {\n List<Coordinate> cordinates = new ArrayList<Coordinate>();\n int[][] randomCoordinates = new int[numberOfCoordinates][2];\n\n // Get a list of all possible coordinates\n for (int x = 0; x < widthOfGrid; x++) {\n for (int y = 0; y < heightOfGrid; y++) {\n cordinates.add(new Coordinate(x, y));\n }\n }\n\n // shuffle aka randomize the list\n Collections.shuffle(cordinates);\n\n // Take top X\n for (int i = 0; i < numberOfCoordinates; i++) {\n randomCoordinates[i] = cordinates.get(i).toArray();\n }\n\n return randomCoordinates;\n }\n\n public static char convertSingleDigitIntegerToCharacter(int number) {\n return String.valueOf(number).charAt(0);\n }\n}\n\n// A placement can either be a Bomb, marked by user, selected by user, or \"empty\" aka untouched & not a bomb\nenum Mark{\n BOMB('@'), \n MARKED_AS_BOMB('X'), \n EMPTY('_'), \n OPEN('W'),\n ONE_BOMB_AROUND('1'),\n TWO_BOMB_AROUND('2'),\n THREE_BOMB_AROUND('3'),\n FOUR_BOMB_AROUND('4'),\n FIVE_BOMB_AROUND('5'),\n SIX_BOMB_AROUND('6'),\n SEVEN_BOMB_AROUND('7'),\n EIGHT_BOMB_AROUND('8');\n\n char character;\n\n Mark(char character) {\n this.character = character;\n }\n\n public static Mark valueOf(char character) {\n for (Mark mark : values()) {\n if (character == mark.character) {\n return mark;\n }\n }\n\n return null;\n }\n\n @Override\n public String toString() {\n return String.valueOf(character);\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-03T21:43:03.067",
"Id": "231799",
"ParentId": "231668",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "231756",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-01T12:07:28.013",
"Id": "231668",
"Score": "1",
"Tags": [
"java",
"game",
"console",
"minesweeper"
],
"Title": "Minesweeper game for the console"
}
|
231668
|
<p>Given multiple sorted integer vectors, the goal is to merge them into a single vector and eliminate duplicate values. We've already achieved some improvements over the most simple approaches, but overall the operation is still very expensive and we're not sure if we're missing something, there must be a way to perform this efficiently. A simplified example is:</p>
<pre class="lang-cpp prettyprint-override"><code>{ {0, 3, 7, 12, 19, 28}, {2, 3, 12, 17}, {7, 40} }
// should be merged into
{0, 2, 3, 7, 12, 17, 19, 28, 40}
</code></pre>
<p>The approaches that we tried are:</p>
<ol>
<li><code>std::set</code> - collect values and eliminate duplicates</li>
<li><code>std::inplace_merge</code> - essentially do the merge part of the merge-sort algorithm</li>
<li><code>std::vector<bool></code> - set bits on positions indicated by the integer values, then collect the indices where those bits were true</li>
</ol>
<p>The following code listing contains the three approaches that we have tried, with randomly generated data that is representative of our cases. Likewise, the following link contains the same code where the benchmark may be evaluated: <a href="http://quick-bench.com/0SNjMyrkqm2N1ugjJb2OwZ5zVWc" rel="nofollow noreferrer">http://quick-bench.com/0SNjMyrkqm2N1ugjJb2OwZ5zVWc</a></p>
<pre class="lang-cpp prettyprint-override"><code>// Google benchmark library
#include <benchmark/benchmark.h>
#include <algorithm>
#include <iostream>
#include <numeric>
#include <random>
#include <set>
#include <vector>
template<typename T>
class RndGen {
public:
RndGen(T start, T end) : mersenne_engine{rnd_device()},
dist{start, end} {
}
T operator()() {
return dist(mersenne_engine);
}
private:
std::random_device rnd_device;
std::mt19937 mersenne_engine;
std::uniform_int_distribution<T> dist;
};
template<typename T>
std::vector<T> gen_random_range(std::size_t count, T start, T end) {
std::vector<T> vec(count);
RndGen<T> generator{start, end};
auto gen = [&generator]() {
return generator();
};
std::generate(std::begin(vec), std::end(vec), gen);
std::sort(vec.begin(), vec.end());
return vec;
}
template<typename T>
std::vector<T> reversed(const std::vector<T>& src) {
auto result = src;
std::reverse(result.begin(), result.end());
return result;
}
std::vector<std::vector<int> > gen_ranges(const std::vector<std::size_t> range_sizes) {
std::vector<std::vector<int> > ranges;
ranges.reserve(range_sizes.size());
for (std::size_t i = 0ul; i < range_sizes.size(); ++i) {
ranges.push_back(gen_random_range(range_sizes[i], 0, static_cast<int>(range_sizes[i])));
}
return ranges;
}
struct TestData {
std::size_t range_count;
std::vector<std::size_t> range_sizes;
std::size_t max_possible_size;
std::vector<std::vector<int> > ranges;
explicit TestData(std::size_t range_count_) : range_count{range_count_},
range_sizes{reversed(gen_random_range(range_count, 5000ul, 35000ul))},
max_possible_size{std::accumulate(range_sizes.begin(), range_sizes.end(), 0ul)},
ranges{gen_ranges(range_sizes)} {
}
};
static const TestData& get_test_data() {
static TestData test_data{4ul /* RndGen<std::size_t>{3ul, 6ul} (); */};
return test_data;
}
void dump_results(const std::vector<int>& result) {
for (auto v : result) {
std::cout << v << ", ";
}
std::cout << std::endl;
}
/*
* Generate a vector of int vectors, where these sub-vector are all already sorted in ascending order, e.g.:
*
* { {0, 3, 7, 12, 19, 28}, {2, 3, 12, 17}, {7, 40} }
*
* The size of these sub-vectors in the above example are representative of the actual data,
* as the first vector will always be the largest, with smaller vectors following it.
* Usually the first vector has around 25000 elements, the second vector around 13000, and the third vector 7000.
*
* The goal is to merge these lists into one sorted-contiguous chunk, and eliminate duplicates. For the above example it would be:
*
* {0, 2, 3, 7, 12, 17, 19, 28, 40}
*
*/
static void merge_with_set(benchmark::State& state) {
const auto& test_data = get_test_data();
std::set<int> sorted_distinct_numbers;
for (auto _ : state) {
sorted_distinct_numbers.clear();
for (const auto& r : test_data.ranges) {
sorted_distinct_numbers.insert(r.begin(), r.end());
}
std::vector<int> result{sorted_distinct_numbers.begin(), sorted_distinct_numbers.end()};
// return dump_results(result);
benchmark::DoNotOptimize(result);
}
}
BENCHMARK(merge_with_set);
static void merge_with_inplace_merge(benchmark::State& state) {
const auto& test_data = get_test_data();
std::vector<std::size_t> chunk_sizes;
chunk_sizes.resize(test_data.ranges.size());
for (auto _ : state) {
std::vector<int> result;
result.reserve(test_data.max_possible_size);
for (std::size_t i = 0ul; i < test_data.ranges.size(); ++i) {
result.insert(result.end(), test_data.ranges[i].begin(), test_data.ranges[i].end());
chunk_sizes[i] = result.size();
}
const auto begin = result.begin();
const auto end = result.end();
auto start = end;
// Chunks towards the end are smaller than at the beginning, thus for our data
// it's actually faster to merge those first
for (auto it = chunk_sizes.rbegin(); it != chunk_sizes.rend(); ++it) {
auto middle = start;
start = begin + *it;
std::inplace_merge(start, middle, end);
}
std::inplace_merge(begin, start, end);
// Eliminate duplicates
result.erase(std::unique(result.begin(), result.end()), result.end());
// return dump_results(result);
benchmark::DoNotOptimize(result);
}
}
BENCHMARK(merge_with_inplace_merge);
static void merge_with_vector_of_bool(benchmark::State& state) {
const auto& test_data = get_test_data();
std::vector<bool> sorted_distinct_numbers;
sorted_distinct_numbers.resize(test_data.max_possible_size);
for (auto _ : state) {
std::fill(sorted_distinct_numbers.begin(), sorted_distinct_numbers.end(), false);
for (const auto& r : test_data.ranges) {
for (const auto value : r) {
sorted_distinct_numbers[value] = true;
}
}
std::vector<int> result;
result.reserve(test_data.max_possible_size);
for (std::size_t i = 0ul; i < sorted_distinct_numbers.size(); ++i) {
if (sorted_distinct_numbers[i] == true) {
result.push_back(static_cast<int>(i));
}
}
// return dump_results(result);
benchmark::DoNotOptimize(result);
}
}
BENCHMARK(merge_with_vector_of_bool);
BENCHMARK_MAIN();
</code></pre>
<p><del>The <code>std::vector<bool></code> approach is the fastest of all, though still a very expensive operation.</del></p>
<p>EDIT: Based on @vvtoan's comment, the <code>std::vector<char></code> approach is the fastest currently, about 15-20% faster than <code>std::vector<bool></code>, though the fundamental approach hasn't changed, and overall the operation is still expensive.</p>
<p>EDIT2: The integers generated for the test data really are between <code>0</code> and <code>max_possible_size</code>, this is not by mistake. When I said <em>randomly generated data that is representative of our cases</em>, I really meant the data is accurate, and the existing implementations are correct for exploiting these properties.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-01T14:21:58.457",
"Id": "452002",
"Score": "0",
"body": "The code is missing the required header `numeric`, `#include <numeric>`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-01T14:33:15.730",
"Id": "452004",
"Score": "0",
"body": "Apologies and thanks, edited the code to include it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-01T15:14:39.047",
"Id": "452014",
"Score": "0",
"body": "Leaving aside the matter of algorithms, an obvious improvement would be using a vector<int> instead of vector<bool>."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-03T18:45:14.370",
"Id": "452229",
"Score": "0",
"body": "Stating the constraints would help. How many arrays are we talking about? How large they are? What is the typical distribution of their sizes? Do you have to do it in place?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-03T20:53:28.473",
"Id": "452240",
"Score": "0",
"body": "@vnp: The random test data that is being generated in the provided code is representative of the actual data being used. On average, there are 3-6 arrays of integers, with the first array always being the largest, and each subsequent one is smaller than the previous. The largest array has around 25000 integers, the next one 15000, then 10000, and it keeps decreasing by a couple thousand with each next array. In-place merge is not mandatory. The only goal is to make the solution faster than the existing ones shown in the code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-05T07:46:06.790",
"Id": "452459",
"Score": "0",
"body": "@vvotan, changing the `vector<bool>` to a `vector<char>` storage indeed helped, there is a 15-20% improvement in performance, thanks!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-05T14:06:12.160",
"Id": "452503",
"Score": "0",
"body": "The merge of several vectors can be reduced to the merge of two vectors and then merging that vector with the remaining ones. And _skip lists_ can speed up merging. For instance implemented as splitting the vectors in value ranges, pieces."
}
] |
[
{
"body": "<p>It's not clear what benefit the code is receiving by using the Google Benchmark Library, there are other ways to measure the elapsed time of each of the merges. C++ provides time measurement functionality.</p>\n\n<pre><code> std::chrono::time_point<std::chrono::system_clock> start, end;\n start = std::chrono::system_clock::now();\n // execute merge here;\n end = std::chrono::system_clock::now();\n\n std::chrono::duration<double> elapsed_seconds = end-start;\n std::time_t end_time = std::chrono::system_clock::to_time_t(end);\n</code></pre>\n\n<p>The function <code>static const TestData& get_test_data()</code> violates the Single Responsibility Principle because it is responsible for constructing the <code>TestData</code> struct as well as returning it. This may lead to a one time performance hit while the struct is being created.</p>\n\n<p>It might be better if <code>main()</code> or a sub-function that main calls constructed the test data once and then passed the test data into each of the separate merge functions.</p>\n\n<p>Creating the <code>result</code> vector with the sum of all the sizes of the contributory vectors will decrease or eliminate the number of memory allocations necessary when adding the data from the test vectors to the result.</p>\n\n<p>Profiling each of the merge algorithms will help find bottle necks that you may be able to optimize out.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-01T16:57:12.647",
"Id": "452035",
"Score": "0",
"body": "Sorry if I wasn't clear enough in the question, and thanks for taking the time to look at it and write an answer. The reason google benchmark code is included is to help potential reviewers easily benchmark the approaches. I am not looking for a code review about whether the code is clean or elegant, I agree it could be cleaner, but it gets through the point of the approaches simply enough. At the moment I'm interested in only making it as fast as possible. Of course i have profiled it many times already, the approaches shown are the result of such profiling / tuning iterations over it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-01T17:00:11.163",
"Id": "452036",
"Score": "1",
"body": "One additional note, the creation of the struct is outside the benchmark loop, so the one-time hit's penalty won't be taken into account when measuring the performance. The reason it's a function local static is to use the same test data in all benchmarks within a single benchmarking session, since the data is randomly generated."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-01T16:04:33.990",
"Id": "231687",
"ParentId": "231671",
"Score": "2"
}
},
{
"body": "<p>The functions cheat their benchmarks by allocating their auxiliary storage outside of the timing loop. That's not reasonable unless you can arrange for the "real life" versions to have their own (per-thread?) long-lived auxiliary storage.</p>\n<p>I think there's a problem with the <code>vector<bool></code> version that's masked by the test data (which always keeps the element values between 0 and <code>test_data.max_possible_size</code>. Perhaps that's how the real-life input data are naturally distributed, but the constraint needs to be clearly specified. For a more general case, we would need to arrange bool storage from the min to max values of all the inputs (and memory exhaustion becomes much more likely).</p>\n<p>I did manage to improve the inplace-merge version by using a heap to identify the current lowest iterator among all inputs, for about 20% speedup:</p>\n<pre><code>#include <queue>\n\ntemplate<typename Container>\nusing QueueItem = std::pair<typename Container::const_iterator,\n typename Container::const_iterator>;\n\nstatic void merge_with_heap_merge(benchmark::State& state)\n{\n const auto& test_data = get_test_data();\n\n for (auto _ : state) {\n\n auto compare = [](auto a, auto b) { return *(a.first) < *(b.first); };\n std::priority_queue<QueueItem<std::vector<int>>,\n std::vector<QueueItem<std::vector<int>>>,\n decltype(compare)>\n heap(compare);\n\n std::vector<int> result;\n result.reserve(test_data.max_possible_size);\n\n for (auto const& r: test_data.ranges) {\n heap.emplace(r.begin(), r.end());\n }\n\n while (!heap.empty()) {\n auto item = heap.top();\n heap.pop();\n if (!result.empty() && result.back() != *(item.first))\n result.push_back(*(item.first));\n if (++item.first != item.second) {\n heap.emplace(item);\n }\n }\n\n // return dump_results(result);\n\n benchmark::DoNotOptimize(result);\n }\n}\n</code></pre>\n<p>The speedup comes primarily from avoiding repeated copying, and in particular, the final deduplication pass.</p>\n<hr />\n<h2>Style and other issues</h2>\n<p>Equality comparisons with boolean constants are usually redundant:</p>\n<blockquote>\n<pre><code> if (sorted_distinct_numbers[i] == true)\n</code></pre>\n</blockquote>\n<p>can be simply <code>if (sorted_distinct_numbers[i])</code></p>\n<p><code>gen_random_range()</code> doesn't need an lvalue <code>RndGen</code>, so we can simplify a lot:</p>\n<pre><code>template<typename T>\nstd::vector<T> gen_random_range(std::size_t count, T start, T end) {\n std::vector<T> vec(count);\n std::generate(vec.begin(), vec.end(), RndGen<T>{start, end});\n std::sort(vec.begin(), vec.end());\n\n return vec;\n}\n</code></pre>\n<p>The <code>RndGen</code> doesn't need to store a random device:</p>\n<pre><code>template<typename T>\nclass RndGen {\npublic:\n RndGen(T start, T end)\n : mersenne_engine{std::random_device{}()},\n dist{start, end}\n {\n }\n\n T operator()()\n {\n return dist(mersenne_engine);\n }\n\nprivate:\n std::mt19937 mersenne_engine;\n std::uniform_int_distribution<T> dist;\n};\n</code></pre>\n<p>If we make <code>reversed()</code> accept argument by value, that means we don't need to explicitly copy it:</p>\n<pre><code>template<typename T>\nstd::vector<T> reversed(std::vector<T> v) {\n std::reverse(v.begin(), v.end());\n return v;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-05T13:32:03.117",
"Id": "452497",
"Score": "0",
"body": "Thanks for answering, I've extended the question with a confirmation about the test input data. Regarding the auxiliary storage, I consider it not cheating since they do not affect the results of the algorithm, and such optimizations are allowed / encouraged if they can help in achieving better results."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-05T13:43:50.543",
"Id": "452499",
"Score": "0",
"body": "The point wasn't about affecting the results; it was about affecting the *timing*. I think it's more honest to include the allocation within the loop, so that its time is measured as part of the run, as I have done in the code I show here."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-05T14:14:19.947",
"Id": "452504",
"Score": "0",
"body": "With the input distribution that you have, I think you're unlikely to improve on the `std::vector<char>` mapping. I did try parallelising the population of this bit map, but for these data, the thread creation overheads appear to be a net loss."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-05T14:54:19.757",
"Id": "452508",
"Score": "0",
"body": "All right, thanks for looking into it, I'll let the question sit a bit more since the bounty ends in 7 days, but if no other, better answers come in, I'll grant it to you."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-05T12:24:01.610",
"Id": "231884",
"ParentId": "231671",
"Score": "4"
}
},
{
"body": "<p>If your real data has indeed the same pattern as the test data, I think using a vector<> is a reasonable solution. You can probably try micro-optimizing it.\nI quickly tried some loop-unrolling and shortcuts, which allowed me to improve 3x over the original vector version. Sorry for the code quality, this is just to illustrate the concept (<a href=\"http://quick-bench.com/c3tnWIXA_CDEcKWzOepIR91XoV0\" rel=\"nofollow noreferrer\">http://quick-bench.com/c3tnWIXA_CDEcKWzOepIR91XoV0</a>):</p>\n\n<pre><code>template <class C> static void add(C &result, uint64_t val, uint64_t offs, int i){\n const auto v = val & (0xFFull << (offs*8));\n if(v!=0) result.push_back(i*8 + offs);\n}\n\nstatic void merge_with_vector_of_int2(benchmark::State& state) {\n const auto& test_data = get_test_data();\n\n std::vector<char> sorted_distinct_numbers;\n sorted_distinct_numbers.resize(test_data.max_possible_size);\n\n for (auto _ : state) {\n std::fill(sorted_distinct_numbers.begin(), sorted_distinct_numbers.end(), false);\n for (const auto& r : test_data.ranges) {\n for (const auto value : r) {\n sorted_distinct_numbers[value] = 1;\n }\n }\n\n std::vector<int> result;\n result.reserve(test_data.max_possible_size);\n int i = 0;\n char* pSrc = &sorted_distinct_numbers[0];\n for (; i < sorted_distinct_numbers.size() / 8; ++i) {\n uint64_t val = *((uint64_t*)(pSrc + i * 8));\n if(val == 0){\n continue;\n }\n int64_t lo = val & 0xFFFFFFFFull;\n int64_t hi = val & (0xFFFFFFFFull << 32ull);\n if(lo!=0){\n add(result, val, 0, i);\n add(result, val, 1, i);\n add(result, val, 2, i);\n add(result, val, 3, i);\n }\n if(hi!=0){\n add(result, val, 4, i);\n add(result, val, 5, i);\n add(result, val, 6, i);\n add(result, val, 7, i);\n }\n }\n\n for (int j = i*8+1; j < sorted_distinct_numbers.size(); ++j) {\n if (sorted_distinct_numbers[j] == 1) {\n result.push_back(j);\n }\n }\n\n //return dump_results(result);\n //return result;\n benchmark::DoNotOptimize(result);\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-05T16:23:30.650",
"Id": "231903",
"ParentId": "231671",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "231884",
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-01T12:32:27.403",
"Id": "231671",
"Score": "2",
"Tags": [
"c++",
"performance",
"benchmarking"
],
"Title": "Merging sorted integer vectors in C++"
}
|
231671
|
<p>Here is the task description for the codility's stonewall problem. I would like to get a feedback on my code, and I specify at the bottom what the title states. (I had to make the figure by hand, because I couldn't paste the site's one for some reason, but it can be seen <a href="https://app.codility.com/programmers/lessons/7-stacks_and_queues/stone_wall/" rel="nofollow noreferrer">here</a>, if mine doesn't look right)</p>
<blockquote>
<p><strong><em>Task description</em></strong> </p>
</blockquote>
<hr>
<blockquote>
<p>You are going to build a stone wall. The wall should
be straight and N meters long, and its thickness should be constant;
however, it should have different heights in different places. The
height of the wall is specified by an array H of N positive integers.
H[I] is the height of the wall from I to I+1 meters to the right of
its left end. In particular, H[0] is the height of the wall's left end
and H[N−1] is the height of the wall's right end.</p>
<p>The wall should be built of cuboid stone blocks (that is, all sides of
such blocks are rectangular). Your task is to compute the minimum
number of blocks needed to build the wall.</p>
<p>Write a function:</p>
<p>class Solution { public int solution(int[] H); }</p>
<p>that, given an array H of N positive integers specifying the height of
the wall, returns the minimum number of blocks needed to build it.</p>
<p>For example, given array H containing N = 9 integers:</p>
<p><code>H[0] = 8 H[1] = 8 H[2] = 5 H[3] = 7</code>
<code>H[4] = 9 H[5] = 8 H[6] = 7 H[7] = 4 H[8] = 8</code>
the function should return 7. The shows one possible arrangement of seven
blocks.</p>
<p><a href="https://i.stack.imgur.com/bjr5g.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/bjr5g.png" alt="enter image description here"></a></p>
<p>Write an efficient algorithm for the following assumptions:</p>
<p>N is an integer within the range [1..100,000]; each element of array H
is an integer within the range [1..1,000,000,000].</p>
</blockquote>
<p>And here is my 100% O(N) time complexity solution.
As the title says, I find it kinda weird that different paths do the same thing. Should I fix that? if so... how? the logic is correct. And should I care? Thinking in bigger problems, if many paths do the same thing, and requirements change, I should change code in many places, which is not recommended.</p>
<pre><code>using System;
using System.Collections.Generic;
using System.Linq;
class Solution {
public int solution(int[] H) {
Stack<int> heightsStack = new Stack<int>();
int blocksCounter = 0;
for (int height = 0; height < H.Length; height++)
{
if (heightsStack.Count > 0)
{
while (heightsStack.Count > 0 && heightsStack.Peek() > H[height])
{
heightsStack.Pop();
}
if (heightsStack.Count > 0)
{
if (heightsStack.Peek() < H[height])
{
blocksCounter++;
heightsStack.Push(H[height]);
}
}
else
{
blocksCounter++;
heightsStack.Push(H[height]);
}
}
else
{
blocksCounter++;
heightsStack.Push(H[height]);
}
}
return blocksCounter;
}
}
</code></pre>
|
[] |
[
{
"body": "<p>Some of these branches can be eliminated. Let's see:</p>\n\n<pre><code>if (heightsStack.Count > 0)\n{\n if (heightsStack.Peek() < H[height])\n {\n blocksCounter++;\n heightsStack.Push(H[height]);\n }\n}\nelse\n{\n blocksCounter++;\n heightsStack.Push(H[height]);\n}\n</code></pre>\n\n<p>Here, there are two conditions where we execute the two common lines: <code>heightsStack.Count <= 0</code> or <code>heightsStack.Peek() < H[height]</code>. Since <code>Count</code> can't be negative, let's rewrite it as such:</p>\n\n<pre><code>if (heightsStack.Count == 0 || heightsStack.Peek() < H[height])\n{\n blocksCounter++;\n heightsStack.Push(H[height]);\n}\n</code></pre>\n\n<hr>\n\n<pre><code>if (heightsStack.Count > 0)\n{\n while (heightsStack.Count > 0 && heightsStack.Peek() > H[height])\n {\n</code></pre>\n\n<p>The first if-statement is redundant. If <code>heightStack.Count > 0</code> is false, the while statement will be false as well. We would immediately fall through and end up at the if-statement in the section above. This if-statement would evaluate to true, since <code>heightStack.Count == 0</code> still. And it would execute the two common lines.</p>\n\n<p>This would leave the body of the for-loop as follows:</p>\n\n<pre><code>while (heightsStack.Count > 0 && heightsStack.Peek() > H[height])\n{\n heightsStack.Pop();\n}\nif (heightsStack.Count == 0 || heightsStack.Peek() < H[height])\n{\n blocksCounter++;\n heightsStack.Push(H[height]);\n}\n</code></pre>\n\n<p>Note, that we only have one branch with the two common lines.</p>\n\n<hr>\n\n<p>There's one last thing. You're using a for-loop, and only using the looped variable to index directly. Instead, consider using a foreach loop:</p>\n\n<pre><code>public int solution(int[] H)\n{\n Stack<int> heightsStack = new Stack<int>();\n int blocksCounter = 0;\n\n foreach(int height in H)\n {\n while (heightsStack.Count > 0 && heightsStack.Peek() > height)\n {\n heightsStack.Pop();\n }\n if (heightsStack.Count == 0 || heightsStack.Peek() < height)\n {\n blocksCounter++;\n heightsStack.Push(height);\n }\n }\n return blocksCounter;\n}\n</code></pre>\n\n<hr>\n\n<p>As far as algorithm goes, you do what I would have come up with, so I have nothing more to say about that.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-01T13:44:31.627",
"Id": "231676",
"ParentId": "231672",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "231676",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-01T13:09:11.033",
"Id": "231672",
"Score": "1",
"Tags": [
"c#",
"performance",
"beginner",
"programming-challenge",
"stack"
],
"Title": "Codility's stonewall 100% solution - different paths such as if,else if,etc, do the same thing"
}
|
231672
|
<p>I have a tableView, which auto locates back at indexPath after user has dragged it.</p>
<p>In other words, bouncing the tableView back into its bounds, after user dragged it out.</p>
<p>Here is the code:</p>
<pre><code>// ...
var tracking = false
var currentPath = 0
@objc func updateRecorder(_ timer: Timer){
currentPath = somethingCalculated
}
// ...
extension ViewController: UITableViewDelegate{
func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
// when the scene is in a special state
tracking = true
}
}
func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
// when the scene is in the same special state
if tracking == true{
tracking = false
scrollToRow(at: IndexPath(row: currentPath, section: 0), at: UITableView.ScrollPosition.middle, animated: true)
}
}
}
</code></pre>
<p>In fact, it is a music tracking app. People sing a song, the lyric tableView tracks the voice, and it auto scrolls to current line.</p>
<p>When tracking, and people scrolls by hand, the lyric tableView should bounces back to it ought to be.</p>
<p>The code above works.</p>
<p>Any other ideas?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-01T14:17:30.060",
"Id": "452001",
"Score": "0",
"body": "The purpose is not yet entirely clear to me. After a user scrolls the tableview, it always scrolls back?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-01T18:57:58.060",
"Id": "452051",
"Score": "0",
"body": "YES, there is a timer and a AVAudioEngine. the AVAudioEngine has a tap to get the current PCM buffer, the timer regularly calls analyzing the PCM buffer, to get the current line of the lyric, indexPath. So after the user scrolls the lyric tableView, it always scrolls back to the line of the lyric calculated ."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-01T19:07:01.983",
"Id": "452053",
"Score": "0",
"body": "But you don't want to *disable* user scrolling?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-02T05:20:38.783",
"Id": "452093",
"Score": "0",
"body": "Yes, the user can scroll to see the lyrics , if they want"
}
] |
[
{
"body": "<p>A couple of observations:</p>\n\n<ol>\n<li><p>You are handling <code>scrollViewDidEndDecelerating</code>. But what if there was no deceleration? E.g. you’d generally want to call some common routine, e.g. <code>didFinishUserScroll</code>, either way:</p>\n\n<pre><code>func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {\n if !decelerate {\n didFinishUserScroll()\n }\n}\n\nfunc scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {\n didFinishUserScroll()\n}\n</code></pre></li>\n<li><p>It looks like you are scrolling as soon as deceleration finishes. I would suggest that you only want to scroll at the end of the user gesture (whether decelerating or not) only if there is an update to the position in the lyrics in the intervening period of time.</p>\n\n<p>E.g. you’re bopping along in a song, the drummer goes off into some lengthy, lyric-free solo, so the bored user starts scrolling through the lyrics themselves. When they let go, if the drum solo is still in progress, I’d suggest that you might not want to scroll back until the singing resumes. I wouldn’t necessarily scroll back immediately.</p>\n\n<p>Now maybe you’ve got the sort of logic in the code you didn’t share with us, and if so, don’t worry about it. But, frankly, the fact that <code>tracking</code> is so ambiguous is code smell. (I.e., is it a boolean whether a touch gesture is in progress? is it indicating that we’re following along with lyrics at all? is it that there are updates to progress in the song that requires update of the position?) The fact that the intent of <code>tracking</code> is so ambiguous suggests you might consider a better name for it.</p></li>\n<li><p>It looks like <code>currentPath</code> is an <code>Int</code>, a row number. So I wouldn’t call it <code>currentPath</code>, but rather <code>currentRow</code>.</p></li>\n<li><p>When you have a boolean, you generally just check the value, not compare it to another boolean. So, for example, instead of:</p>\n\n<pre><code>if tracking == true {\n tracking = false\n scrollToRow(at: IndexPath(row: currentPath, section: 0), at: UITableView.ScrollPosition.middle, animated: true)\n}\n</code></pre>\n\n<p>You would do:</p>\n\n<pre><code>if tracking {\n tracking = false\n scrollToRow(at: IndexPath(row: currentPath, section: 0), at: .middle, animated: true)\n}\n</code></pre>\n\n<p>I also removed the redundant <code>UITableView.ScrollPosition</code> reference.</p></li>\n<li><p>This is beyond the scope of this question, but the fact that you’re calling <code>scrollToRow(at:at:animated:)</code> without referencing the table view worries me, making me wonder whether you have all of this business logic buried inside your table view. We generally strive to isolate our UI from business logic of the app.</p></li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-02T18:06:03.763",
"Id": "452140",
"Score": "0",
"body": "Your insight is impressive. ` I’d suggest that you might not want to scroll back until the singing resumes. I wouldn’t necessarily scroll back immediately.` , our company product logic has not planned so sweetly yet. The rest of insights are also nice."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-02T16:50:36.107",
"Id": "231740",
"ParentId": "231673",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "231740",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-01T13:13:50.510",
"Id": "231673",
"Score": "2",
"Tags": [
"swift",
"uikit"
],
"Title": "UITableView, auto locate back at indexPath when user drags it"
}
|
231673
|
<p>Some background: The counter was first made as a joke because we have a lecturer who repeats the 9 phrases found in the program over and over during lectures and I thought it would be funny to create a program that (using user input) would count the number of times the lecturer said these phrases. Two days later (and working on it almost the entire time) I ended up with this. </p>
<p>How clean is this code? How can it be improved? Any suggestions accepted and appreciated. I also used a tool called Eclipse Window Builder to help me with the GUI since I'd only used AWT before and wanted to learn Swing due to its greater support.</p>
<p>LoadingScreen.java;</p>
<pre class="lang-java prettyprint-override"><code>import java.awt.EventQueue;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import javax.swing.JFrame;
import javax.swing.JPanel;
import java.awt.Color;
import javax.swing.JLabel;
import javax.swing.ImageIcon;
import javax.swing.SwingConstants;
import javax.swing.border.LineBorder;
import javax.swing.JProgressBar;
public class LoadingScreen extends JFrame {
/**
*
*/
private static final long serialVersionUID = 1L;
private JPanel contentPane;
private JLabel imageLabel;
private JProgressBar progressBar;
private ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
LoadingScreen frame = new LoadingScreen();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
* © Bernard Borg 2019
*/
public LoadingScreen() {
setAlwaysOnTop(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(320, 369);
setUndecorated(true);
setLocationRelativeTo(null);
contentPane = new JPanel();
contentPane.setBackground(Color.WHITE);
contentPane.setBorder(new LineBorder(Color.BLUE, 10));
contentPane.setLayout(null);
setContentPane(contentPane);
init();
}
public void init() {
progressBar = new JProgressBar();
progressBar.setForeground(Color.BLUE);
progressBar.setBackground(Color.WHITE);
progressBar.setStringPainted(true);
progressBar.setBounds(120, 325, 175, 25);
imageLabel = new JLabel("");
imageLabel.setVerticalAlignment(SwingConstants.TOP);
imageLabel.setIcon(new ImageIcon("img/stainesPic.jpg"));
imageLabel.setBounds(10, 10, 300, 350);
contentPane.add(progressBar);
contentPane.add(imageLabel);
progressBarStuff();
}
public void progressBarStuff() {
Runnable myRunnable = new Runnable() {
public void run() {
int i = progressBar.getValue();
i++;
progressBar.setValue(i);
if (progressBar.getValue() == 100) {
executor.shutdown();
loadMain();
}
}
};
executor.scheduleAtFixedRate(myRunnable, 0, 30, TimeUnit.MILLISECONDS);
}
public void loadMain() {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
MainFrame frame = new MainFrame();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
dispose();
}
}
</code></pre>
<p>MainFrame.java (Main Program)</p>
<pre class="lang-java prettyprint-override"><code>import java.awt.BorderLayout;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JButton;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.util.ArrayList;
import java.util.Date;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.GridLayout;
import javax.swing.border.LineBorder;
import java.awt.Font;
import javax.swing.JTextArea;
import java.awt.Toolkit;
import java.awt.datatransfer.StringSelection;
import javax.swing.border.CompoundBorder;
import java.awt.CardLayout;
import java.awt.FlowLayout;
import javax.swing.BoxLayout;
import javax.swing.ImageIcon;
import javax.swing.JScrollPane;
import javax.swing.ScrollPaneConstants;
public class MainFrame extends JFrame implements KeyListener, ActionListener{
private static final long serialVersionUID = 1L;
private static final String version = "v0.2.1 [BETA]";
private JPanel contentPane;
private JPanel topPanel;
private JPanel middlePanel;
private JPanel bottomPanel;
private JPanel bottomLeftPanel;
private JPanel bottomRightPanel;
private JButton ummmButton;
private JButton understandButton;
private JButton okButton;
private JButton noButton;
private JButton huhButton;
private JButton staresButton;
private JButton questionsButton;
private JButton clearButton;
private JButton keyButton;
private JButton reportButton;
private JButton copyButton;
private JButton saveButton;
private JButton settingsButton;
private JButton undoButton;
private JButton resetButton;
private JTextArea textArea;
private JScrollPane scrollPane;
private int ummmCounter = 0;
private int understandCounter = 0;
private int okCounter = 0;
private int noCounter = 0;
private int huhCounter = 0;
private int staresCounter = 0;
private int questionsCounter = 0;
private int clearCounter = 0;
private int keyCounter = 0;
private boolean isSaved = true;
private ArrayList <String> wordList;
/**
* Create the frame.
*/
public MainFrame() {
setIconImage(Toolkit.getDefaultToolkit().getImage("img/logo.png"));
setBackground(Color.WHITE);
setTitle("Staines Counter " + version);
addKeyListener(this);
setFocusable(true);
requestFocus();
setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
setSize(700, 700);
setMinimumSize(new Dimension (700, 700));
setLocationRelativeTo(null);
addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent windowEvent) {
if(isSaved == false) {
int choice = JOptionPane.showConfirmDialog(null, "Do you want to save?", "Save", JOptionPane.YES_NO_OPTION,JOptionPane.QUESTION_MESSAGE);
if (choice == JOptionPane.YES_OPTION){
saveAction();
} else if (choice == JOptionPane.NO_OPTION){
System.exit(0);
} else {
}
} else {
System.exit(0);
}
}
});
contentPane = new JPanel();
contentPane.setForeground(new Color(128, 0, 0));
contentPane.setBackground(Color.WHITE);
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
contentPane.setLayout(new BorderLayout(0, 0));
setContentPane(contentPane);
init();
}
public void init() {
//Buttons
ummmButton = new JButton("Ummm");
ummmButton.setForeground(Color.WHITE);
ummmButton.setBackground(new Color(128, 0, 0));
ummmButton.addActionListener(this);
understandButton = new JButton("Understand?");
understandButton.setForeground(Color.WHITE);
understandButton.setBackground(new Color(128, 0, 0));
understandButton.addActionListener(this);
okButton = new JButton("Ok");
okButton.setForeground(Color.WHITE);
okButton.setBackground(new Color(128, 0, 0));
okButton.addActionListener(this);
noButton = new JButton("No?");
noButton.setForeground(Color.WHITE);
noButton.setBackground(new Color(128, 0, 0));
noButton.addActionListener(this);
huhButton = new JButton("Huh");
huhButton.setForeground(Color.WHITE);
huhButton.setBackground(new Color(128, 0, 0));
huhButton.addActionListener(this);
staresButton = new JButton("*stares*");
staresButton.setForeground(Color.WHITE);
staresButton.setBackground(new Color(128, 0, 0));
staresButton.addActionListener(this);
questionsButton = new JButton("Questions?");
questionsButton.setForeground(Color.WHITE);
questionsButton.setBackground(new Color(128, 0, 0));
questionsButton.addActionListener(this);
clearButton = new JButton("It is clear?");
clearButton.setForeground(Color.WHITE);
clearButton.setBackground(new Color(128, 0, 0));
clearButton.addActionListener(this);
keyButton = new JButton("Key Point");
keyButton.setForeground(Color.WHITE);
keyButton.setBackground(new Color(128, 0, 0));
keyButton.addActionListener(this);
copyButton = new JButton("Copy Text");
copyButton.setForeground(Color.WHITE);
copyButton.setBackground(new Color(128, 0, 0));
copyButton.addActionListener(this);
reportButton = new JButton("Get Report");
reportButton.setForeground(Color.WHITE);
reportButton.setBackground(new Color(128, 0, 0));
reportButton.addActionListener(this);
settingsButton = new JButton("");
settingsButton.setForeground(Color.WHITE);
settingsButton.setBackground(Color.WHITE);
settingsButton.setIcon(new ImageIcon("img/settings.png"));
settingsButton.setBounds(80, 0, 35, 35);
settingsButton.setToolTipText("Settings");
settingsButton.addActionListener(this);
settingsButton.setBorderPainted(false);
saveButton = new JButton("Save");
saveButton.setBackground(new Color(128, 0, 0));
saveButton.setForeground(Color.WHITE);
saveButton.addActionListener(this);
resetButton = new JButton("Clear");
resetButton.setForeground(Color.WHITE);
resetButton.setBackground(new Color(128, 0, 0));
resetButton.addActionListener(this);
undoButton = new JButton("");
undoButton.setBackground(Color.WHITE);
undoButton.setIcon(new ImageIcon("img/undoIcon.png"));
undoButton.setBounds(35, 0, 35, 35);
undoButton.setBorderPainted(false);
undoButton.addActionListener(this);
//Text Area
textArea = new JTextArea();
textArea.setFont(new Font("Dialog", Font.PLAIN, 14));
textArea.setRows(20);
textArea.setWrapStyleWord(true);
textArea.setForeground(new Color(128, 0, 0));
textArea.setEditable(false);
textArea.setLineWrap(true);
scrollPane = new JScrollPane(textArea);
scrollPane.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
//Panels
topPanel = new JPanel();
topPanel.setForeground(new Color(128, 0, 0));
topPanel.setBackground(Color.WHITE);
topPanel.setLayout(new GridLayout(0, 3, 10, 10));
topPanel.add(ummmButton);
topPanel.add(understandButton);
topPanel.add(okButton);
topPanel.add(noButton);
topPanel.add(huhButton);
topPanel.add(staresButton);
topPanel.add(questionsButton);
topPanel.add(clearButton);
topPanel.add(keyButton);
middlePanel = new JPanel();
middlePanel.setBorder(new CompoundBorder(new EmptyBorder(10, 10, 10, 10), new LineBorder(new Color(0, 0, 0))));
middlePanel.setForeground(new Color(128, 0, 0));
middlePanel.setBackground(Color.WHITE);
middlePanel.setLayout(new CardLayout(10, 10));
middlePanel.add(scrollPane, "name_272268444365100");
bottomLeftPanel = new JPanel();
bottomLeftPanel.setBackground(Color.WHITE);
FlowLayout fl_bottomLeftPanel = (FlowLayout) bottomLeftPanel.getLayout();
fl_bottomLeftPanel.setHgap(25);
bottomLeftPanel.add(copyButton);
bottomLeftPanel.add(reportButton);
bottomLeftPanel.add(saveButton);
bottomLeftPanel.add(resetButton);
bottomRightPanel = new JPanel();
bottomRightPanel.setBackground(Color.WHITE);
bottomRightPanel.setLayout(null);
bottomRightPanel.add(settingsButton);
bottomRightPanel.add(undoButton);
bottomPanel = new JPanel();
bottomPanel.setForeground(new Color(128, 0, 0));
bottomPanel.setBackground(Color.WHITE);
bottomPanel.setLayout(new BoxLayout(bottomPanel, BoxLayout.X_AXIS));
bottomPanel.add(bottomLeftPanel);
bottomPanel.add(bottomRightPanel);
contentPane.add(topPanel, BorderLayout.NORTH);
contentPane.add(middlePanel, BorderLayout.CENTER);
contentPane.add(bottomPanel, BorderLayout.SOUTH);
wordList = new ArrayList <String> ();
}
@Override
public void actionPerformed (ActionEvent e) {
if(e.getSource() == ummmButton) {
ummmAction();
} else if (e.getSource() == understandButton) {
understandAction();
} else if (e.getSource() == okButton) {
okAction();
} else if (e.getSource() == noButton) {
noAction();
} else if (e.getSource() == huhButton) {
huhAction();
} else if (e.getSource() == staresButton) {
staresAction();
} else if (e.getSource() == questionsButton) {
questionsAction();
} else if (e.getSource() == clearButton) {
clearAction();
} else if (e.getSource() == keyButton) {
keyAction();
} else if (e.getSource() == reportButton) {
reportAction();
} else if (e.getSource() == copyButton) {
copyAction();
} else if (e.getSource() == saveButton) {
saveAction();
} else if (e.getSource() == settingsButton) {
settingsAction();
} else if (e.getSource() == resetButton) {
resetAction();
} else if (e.getSource() == undoButton) {
undoAction();
}
this.requestFocus();
}
@Override
public void keyPressed (KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_NUMPAD1) {
questionsAction();
} else if (e.getKeyCode() == KeyEvent.VK_NUMPAD2) {
clearAction();
} else if (e.getKeyCode() == KeyEvent.VK_NUMPAD3) {
keyAction();
} else if (e.getKeyCode() == KeyEvent.VK_NUMPAD4) {
noAction();
} else if (e.getKeyCode() == KeyEvent.VK_NUMPAD5) {
huhAction();
} else if (e.getKeyCode() == KeyEvent.VK_NUMPAD6) {
staresAction();
} else if (e.getKeyCode() == KeyEvent.VK_NUMPAD7) {
ummmAction();
} else if (e.getKeyCode() == KeyEvent.VK_NUMPAD8) {
understandAction();
} else if (e.getKeyCode() == KeyEvent.VK_NUMPAD9) {
okAction();
}
}
@Override
public void keyTyped (KeyEvent e) {
}
@Override
public void keyReleased(KeyEvent e) {
}
public void ummmAction() {
textArea.setText(textArea.getText() + "ummm...");
ummmCounter++;
wordList.add("ummm...");
isSaved = false;
}
public void understandAction() {
textArea.setText(textArea.getText() + "understand?...");
understandCounter++;
wordList.add("understand?...");
isSaved = false;
}
public void okAction() {
textArea.setText(textArea.getText() + "ok...");
okCounter++;
wordList.add("ok...");
isSaved = false;
}
public void noAction() {
textArea.setText(textArea.getText() + "no...");
noCounter++;
wordList.add("no...");
isSaved = false;
}
public void huhAction() {
textArea.setText(textArea.getText() + "huh...");
huhCounter++;
wordList.add("huh...");
isSaved = false;
}
public void staresAction() {
textArea.setText(textArea.getText() + "*stares*...");
staresCounter++;
wordList.add("*stares*...");
isSaved = false;
}
public void questionsAction() {
textArea.setText(textArea.getText() + "Any questions?...");
questionsCounter++;
wordList.add("Any questions?...");
isSaved = false;
}
public void clearAction() {
textArea.setText(textArea.getText() + "Is it clear?...");
clearCounter++;
wordList.add("Is it clear?...");
isSaved = false;
}
public void keyAction() {
textArea.setText(textArea.getText() + "Did you understand this KEY POINT?...");
keyCounter++;
wordList.add("Did you understand this KEY POINT?...");
isSaved = false;
}
public void reportAction() {
JOptionPane.showMessageDialog(null, "ummm(s): " + ummmCounter + "\nUnderstand?(s): " + understandCounter + "\nOk(s): " + okCounter
+ "\nNo?(s): " + noCounter + "\nHuh(s): " + huhCounter + "\n*stares*: " + staresCounter + "\nQuestions?: " + questionsCounter
+ "\nIt is clear?(s): " + clearCounter + "\nKey point(s): " + keyCounter, "Staines Counter Report", JOptionPane.PLAIN_MESSAGE);
}
public void copyAction() {
Toolkit.getDefaultToolkit().getSystemClipboard().setContents(new StringSelection(textArea.getText()), null);
}
public void saveAction() {
try{
DateFormat dateFormat = new SimpleDateFormat("dd.MM.yyyy");
Date date = new Date();
BufferedWriter bw = new BufferedWriter (new FileWriter ("logs/" + dateFormat.format(date) + ".txt"));
bw.write(dateFormat.format(date));
bw.newLine();
bw.write(String.valueOf("Ummm(s): " + ummmCounter));
bw.newLine();
bw.write(String.valueOf("Understand?(s): " + understandCounter));
bw.newLine();
bw.write(String.valueOf("Ok(s): " + okCounter));
bw.newLine();
bw.write(String.valueOf("No?(s): " + noCounter));
bw.newLine();
bw.write(String.valueOf("Huh(s): " + huhCounter));
bw.newLine();
bw.write(String.valueOf("*stares*:" + staresCounter));
bw.newLine();
bw.write(String.valueOf("Questions?:" + questionsCounter));
bw.newLine();
bw.write(String.valueOf("It is clear?(s): " + clearCounter));
bw.newLine();
bw.write(String.valueOf("Key point(s): " + keyCounter));
bw.newLine();
bw.close();
} catch (Exception e){
JOptionPane.showMessageDialog (null, e.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
}
isSaved = true;
}
public void settingsAction() {
JOptionPane.showMessageDialog(null, "This feature is not yet available!", "Unavailable Feature", JOptionPane.PLAIN_MESSAGE);
}
public void resetAction() {
textArea.setText("");
wordList.clear();
ummmCounter = 0;
understandCounter = 0;
okCounter = 0;
noCounter = 0;
huhCounter = 0;
staresCounter = 0;
questionsCounter = 0;
clearCounter = 0;
keyCounter = 0;
isSaved = true;
}
public void undoAction() {
switch(wordList.get(wordList.size()-1)) {
case "ummm...":
ummmCounter--;
break;
case "understand?...":
understandCounter--;
break;
case "ok...":
okCounter--;
break;
case "no...":
noCounter--;
break;
case "huh...":
huhCounter--;
break;
case "*stares*...":
staresCounter--;
break;
case "Any questions?...":
questionsCounter--;
break;
case "Is it clear?...":
clearCounter--;
break;
case "Did you understand this KEY POINT?...":
keyCounter--;
break;
}
wordList.remove(wordList.size()-1);
textArea.setText("");
for(String w : wordList) {
textArea.setText(textArea.getText() + w);
}
isSaved = false;
}
}
<span class="math-container">```</span>
</code></pre>
|
[] |
[
{
"body": "<p>I'm on mobile so I'll be brief...</p>\n\n<p>You have 9 copy pasted buttons with identical behaviour, just a different label. Turn those into a reusable class that take the label and action listener as parameters. Instead of hard coding the phrase buttons into instance fields, define the phrases as array of strings and create the buttons from the array. You'll be able to introduce phrases like \"I know you post to CodeReview\" later. Stuff the JButtons into a list if you need to refer to them later (you probably don't need to).</p>\n\n<p>You've put all your code into the GUI classes. Refactor the counter into a separate model class to adhere to the single responsibility principle. It'll also move your code closer to the MVC model.</p>\n\n<p>The action listener should be it's own class. The UI classes should just be about setting up the components.</p>\n\n<p>What the heck does your loading screen do? Loading screens are evil. Apps should start instantly. Kill it with fire and never do it again. :)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-03T10:02:16.637",
"Id": "452172",
"Score": "0",
"body": "Thank you for this feedback, will do :)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-02T07:12:06.623",
"Id": "231721",
"ParentId": "231674",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "231721",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-01T13:35:06.850",
"Id": "231674",
"Score": "2",
"Tags": [
"java",
"swing"
],
"Title": "GUI for counting the number of times a word is said (with added features)"
}
|
231674
|
<p>I'm trying to have one WPF application to communicate with an other application when something change on the UI. For example : a slider changes and I send the new value or a textbox input change and I send the new input value. </p>
<p>The second application is listening and receive those changes to use them in some way, doesn't really matter how in this case.</p>
<p>To achieve this I'm using NetMQ following the Actor pattern example from the documentation : <a href="https://netmq.readthedocs.io/en/latest/actor/" rel="nofollow noreferrer">https://netmq.readthedocs.io/en/latest/actor/</a></p>
<p>Right now I have these Client/Server class :</p>
<p>The Server :</p>
<pre><code>public class NetMQServer
{
public class ShimHandler : IShimHandler
{
private PairSocket shim;
private NetMQPoller poller;
private PublisherSocket publisher;
public void Initialise(object state)
{
}
public void Run(PairSocket shim)
{
using (publisher = new PublisherSocket())
{
publisher.Bind("tcp://127.0.0.1:7777");
publisher.Options.SendHighWatermark = 1000;
this.shim = shim;
shim.ReceiveReady += OnShimReady;
shim.SignalOK();
poller = new NetMQPoller { shim, publisher };
poller.Run();
}
}
private void OnShimReady(object sender, NetMQSocketEventArgs e)
{
Console.WriteLine("Publisher ShimReady");
string command = e.Socket.ReceiveFrameString();
switch (command)
{
case NetMQActor.EndShimMessage:
poller.Stop();
break;
case "UpdateString":
string stringMessage = e.Socket.ReceiveFrameString();
publisher.SendMoreFrame("UpdateString").SendFrame(stringMessage);
break;
}
}
private void UpdateString(string stringmessage, string propertyToUpdate)
{
propertyToUpdate = stringmessage;
}
}
private NetMQActor actor;
public void Start()
{
if (actor != null)
return;
actor = NetMQActor.Create(new ShimHandler());
}
public void Stop()
{
if (actor != null)
{
actor.Dispose();
actor = null;
}
}
public void SendStringMessage(string stringToSend)
{
if (actor == null)
return;
var message = new NetMQMessage();
message.Append("UpdateString");
message.Append(stringToSend);
actor.SendMultipartMessage(message);
}
}
</code></pre>
<p>Here when the property of a control change I call <code>SendStringMessage(string stringToSend)</code> function and it is sending with the NetMQ publisher (the string is only for testing, I could send whatever object as byte too).</p>
<p>Anyway, here is the client running on the second app :</p>
<pre><code>public class NetMQClient
{
public StringMessage StringMessage { get; set; }
public string ReceivedString { get; set; }
public CerasSerializer Serializer { get; set; }
public NetMQClient()
{
Serializer = new CerasSerializer();
StringMessage = new StringMessage("");
}
public class ShimHandler : IShimHandler
{
private PairSocket shim;
private NetMQPoller poller;
private SubscriberSocket subscriber;
private StringMessage stringMessage;
public ShimHandler(StringMessage stringMessage)
{
this.stringMessage = stringMessage;
}
public void Initialise(object state)
{
}
public void Run(PairSocket shim)
{
using (subscriber = new SubscriberSocket())
{
subscriber.Connect("tcp://127.0.0.1:7777");
subscriber.Subscribe("UpdateString");
subscriber.Options.ReceiveHighWatermark = 1000;
subscriber.ReceiveReady += OnSubscriberReady;
this.shim = shim;
shim.ReceiveReady += OnShimReady;
shim.SignalOK();
poller = new NetMQPoller { shim, subscriber };
poller.Run();
}
}
private void OnSubscriberReady(object sender, NetMQSocketEventArgs e)
{
string topic = subscriber.ReceiveFrameString();
if (topic == "UpdateString")
{
string received = subscriber.ReceiveFrameString();
stringMessage.Message = received;
}
}
private void OnShimReady(object sender, NetMQSocketEventArgs e)
{
string command = e.Socket.ReceiveFrameString();
if (command == NetMQActor.EndShimMessage)
{
poller.Stop();
}
}
}
public string GetPayLoad()
{
return actor.ReceiveFrameString();
}
private NetMQActor actor;
public void Start()
{
if (actor != null)
return;
actor = NetMQActor.Create(new ShimHandler(StringMessage));
}
public void Stop()
{
if (actor != null)
{
actor.Dispose();
actor = null;
}
}
}
</code></pre>
<p>So far this is working but there is something I'm really not sure I'm doing correctly. I'm using the <code>StringMessage</code> property inside <code>OnSubscriberReady</code> but is this really how it should be done ?</p>
<p>If the Server is sending through its Actor, shouldn't it be the same for Client ? receiving data through its actor as well ?</p>
<p>Thanks</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-01T13:49:26.250",
"Id": "231677",
"Score": "3",
"Tags": [
"c#"
],
"Title": "NetMQ Actor pattern"
}
|
231677
|
<p>I've built this little C++ program just to take some rust off my coding skills
since it's been ages since the last time I coded something.</p>
<p>The purpose is to organize my music, so I've built the classes
'song' and 'playlist' with some methods which could come in handy - maybe -
such as printing on file the list of songs in the playlist and so on.
I'm not sure that <code>std::vector</code> is the right choice to store the songs in the
playlist (as private member). Would a <code>std::set</code> be more efficient?</p>
<p>Given a list of songs I wanted to sort out if each and every
one of the songs in the list appeared at least in one playlist,
with each playlist representing a musical genre.</p>
<p>I was also interested in listing the "overlaps" between two different
playlists, to get a sort of Venn Diagram of my music. I've accomplished
that by overloading the operators + and - for the playlist, and by
defining a function "intersection".</p>
<p>I'm defenetly not sure about the best way to handle the <code>const</code> functions.</p>
<p>I've used the following libraries:</p>
<pre><code>#include <fstream>
#include <map>
#include <vector>
#include <set>
#include <iostream>
#include <string>
#include <sstream>
</code></pre>
<p>Here it is the implementation of the class song:</p>
<pre><code>class song {
private:
std::string title;
std::string author;
std::string album;
public:
song(std::string tit) : title(tit), author("? "), album("? ") { }
song(std::string tit, std::string au, std::string al) : title(tit), author(au), album(al) { }
const std::string gettitle() {return title;}
const std::string getauthor() {return author;}
const std::string getalbum() {return album;}
const bool operator==(song & a) {
if(title == a.gettitle()) {
if(author == a.getauthor()) {
if(album == a.getalbum()) {
return true;
}
}
}else{ return false; }
}
void playsong() {
std::cout << std::endl;
std::cout << "\"" << title << "\"" << ", by " << author << ", \n";
std::cout << "from the album \"" << album << "\"." << std::endl;
}
void showtitle() { std::cout << title << std::endl; }
void showauthor() { std::cout << author << std::endl; }
void showalbum() { std::cout << album << std::endl; }
void showall() {
std::cout << title << " | " << author;
std::cout << " | " << album << std::endl;
}
};
</code></pre>
<p>And of the class playlist:</p>
<pre><code>class playlist {
private:
std::string name;
std::vector<song> list;
public:
playlist() : name(" ") {}
playlist(std::string nam) : name(nam) {}
playlist(playlist & x, std::string nam) {
name = nam;
list = x.getlist();
}
playlist operator=(const playlist & x) {
list = x.getlist();
name = x.getname();
return *this;
}
const playlist operator+( const playlist & x) {
playlist z(*this);
for(int i=0; i<(x.getlist()).size(); i++) {
if (false == this->findsong((x.getlist())[i])){
z.addsong((x.getlist())[i]);
}
}
z.setname(this->getname() + "+" + x.getname());
return z;
}
const playlist operator-(const playlist & x) {
playlist z(*this);
for(int i=0; i<(x.getlist()).size(); i++) {
if (this->findsong((x.getlist())[i])){
z.deletesong((x.getlist())[i]);
}
}
z.setname(this->getname() + "-" + x.getname());
return z;
}
std::vector<song> getlist() const { return list; }
std::string getname() const { return name; }
song getsong(std::vector<song>::iterator it) const { return *it; }
std::vector<song>::iterator getsong(song & x) {
std::vector<song>::iterator it;
it = list.begin();
while (it != list.end()) {
if(*(it) == x) break;
it ++;
}
return it;
}
void setname(std::string nam) { name = nam; }
void addlist(std::string file) {
std::ifstream in(file);
std::string line;
while(std::getline(in, line)) {
std::stringstream linestream(line);
std::string tit, au, al;
getline(linestream, tit, '\t');
getline(linestream, au, '\t');
getline(linestream, al);
song x(tit, au, al);
this->addsong(x);
}
in.close();
}
void addsong(song x) { list.push_back(x); }
void deletesong(song x) {
int cont=0;
std::vector<song>::iterator it;
it = list.begin();
for(auto el : list) {
if(el == x){
list.erase(it);
std::vector<song>::iterator it;
it = list.begin() + cont;
}
cont ++;
}
}
bool findsong(song x) {
bool tobe = false;
for (auto el : list) {
if(el == x) tobe = true;
}
return tobe;
}
void showplaylist() {
int cont=0;
std::vector<song>::iterator it;
it = list.begin();
std::cout << std::endl << name << std::endl << std::endl;
while (it != list.end()) {
cont++;
std::cout << cont << ") ";
it->showall();
it++;
}
}
void playplaylist() {
int cont=0;
std::vector<song>::iterator it;
it = list.begin();
std::cout << std::endl << name << std::endl << std::endl;
while (it != list.end()) {
cont++;
std::cout << cont << ") ";
it->playsong();
it++;
}
}
std::ofstream printplaylist(std::string nam) {
std::ofstream out(nam + ".dat");
std::vector<song>::iterator it;
it = list.begin();
out << std::endl << name << std::endl << std::endl;
while (it != list.end()) {
out << it->gettitle() << "\t";
out << it->getauthor() << "\t";
out << it->getalbum() << std::endl;
it++;
}
out.close();
return out;
}
};
</code></pre>
<p>This is the only function I wrote:</p>
<pre><code>playlist intersection(playlist & x, playlist & y) {
playlist z, q, t;
z = x + y;
t = x - y;
q = y - x;
z = z - q;
z = z - t;
z.setname("(" + x.getname() + ")^(" + y.getname() + ")" );
return z;
}
</code></pre>
<p>In the <code>main</code> I tried my methods to check if they worked fine. The playlist are "loaded" in my program through some files.dat wich have the following structure:</p>
<blockquote>
<p>Title \tab Author \tab Album</p>
</blockquote>
|
[] |
[
{
"body": "<p>Single-responsibility: the <code>show*()</code> methods in <code>song</code> don't provide any benefit, since we already have suitable <code>get*()</code> methods which can be used more flexibly. Thus, <code>song</code> needn't require <code><iostream></code> or the like.</p>\n\n<p>Returning <code>const std::string</code> here probably isn't what you meant:</p>\n\n<blockquote>\n<pre><code>const std::string gettitle() {return title;}\nconst std::string getauthor() {return author;}\nconst std::string getalbum() {return album;}\n</code></pre>\n</blockquote>\n\n<p>More useful would be</p>\n\n<pre><code>std::string gettitle() const {return title;}\nstd::string getauthor() const {return author;}\nstd::string getalbum() const {return album;}\n</code></pre>\n\n<p>This misplaced <code>const</code> also affects operator <code>==</code>, which also has scope to be simpler and clearer. Any time we have an <code>if</code>/<code>else</code> where the branches return <code>true</code> or <code>false</code> consider just using a boolean expression directly for <code>return</code>:</p>\n\n<pre><code>bool operator==(const song& a) const\n{\n return title == a.title\n && author == a.author\n && album == a.album;\n}\n</code></pre>\n\n<p>We can also access the private members of <code>a</code>, since it's of our class.</p>\n\n<p>Consider providing operator <code>!=</code>, too:</p>\n\n<pre><code>bool operator!=(const song& a) const\n{ return !(*this == a); }\n</code></pre>\n\n<p>The constructors of <code>song</code> accept <code>std::string</code> by value; we should use <code>std::move</code> to avoid copying again (and we can use default arguments to reduce duplication):</p>\n\n<pre><code>explicit song(std::string title, std::string author = \"? \", std::string album = \"? \")\n : title(std::move(title)),\n author(std::move(author)),\n album(std::move(album))\n{ }\n</code></pre>\n\n<p>(Note <code>explicit</code>, because we don't want this class to be considered for implicit conversion from string).</p>\n\n<hr>\n\n<p>One of the <code>playlist</code> constructors doesn't initialise members, but uses assignment in the body instead. Prefer initialisers, and consolidate using default arguments:</p>\n\n<pre><code>explicit playlist(std::string name = \"\")\n : name(std::move(name)),\n list()\n{}\nplaylist(const playlist & x, std::string name)\n : name(std::move(name)),\n list(x.list)\n{}\n</code></pre>\n\n<p>Operator <code>=</code> should return a <em>reference</em> rather than a copy (<code>g++ -Weffc++</code> catches this):</p>\n\n<pre><code>playlist& operator=(const playlist & x) {\n// ^^^\n</code></pre>\n\n<p>But there's absolutely no need to declare this operator - follow the Rule of Zero, and let the compiler generate it and the copy/move constructors too.</p>\n\n<p>Operator <code>+</code> performs set addition, which surprised me - normally, I would expect concatenation, like my existing Empeg Car player. Even if that's what's required, we can improve it. Any time we use a loop like <code>for (std::size_t i=0; i < container.size(); ++i)</code> and then only use <code>i</code> for indexing, we can replace with a range-based <code>for</code> loop:</p>\n\n<pre><code>playlist operator+(const playlist& x) const\n{\n playlist z(*this, name + \"+\" + x.name);\n for (auto& song: x.list) {\n if (!findsong(song)) {\n z.addsong(song);\n }\n }\n return z;\n}\n</code></pre>\n\n<p>This still scales poorly, as the linear search in <code>findsong</code> is performed for each song to be added. If we make <code>song</code> sortable or hashable, we could use a <code>std::set</code> to identify duplicates, at a cost of some overhead initialising the set.</p>\n\n<p>I don't see why we have this method in the public interface:</p>\n\n<blockquote>\n<pre><code>song getsong(std::vector<song>::iterator it) const { return *it; }\n</code></pre>\n</blockquote>\n\n<p>That's something any calling code can do much more simply, and I'd argue that we probably shouldn't be giving out such iterators anyway.</p>\n\n<p>The other <code>getsong</code> seems to exactly implement <code>std::find()</code>, and I don't see the value to users.</p>\n\n<p>In <code>removesong</code>, we don't need to keep count with <code>cont</code>. The right way to cope with iterator invalidation is to use the return value from <code>erase()</code>:</p>\n\n<pre><code>void deletesong(const song& x)\n{\n auto it = list.begin();\n while (it != list.end()) {\n if (*it == x){\n it = list.erase(it);\n } else {\n ++it;\n }\n }\n}\n</code></pre>\n\n<p>However, with that said, the real way to implement \"remove all matching\" is to use the <a href=\"https://en.wikipedia.org/wiki/Erase%E2%80%93remove_idiom\" rel=\"nofollow noreferrer\">Erase-remove idiom</a>:</p>\n\n<pre><code>#include <algorithm>\n\nvoid deletesong(const song& x)\n{\n list.erase(std::remove(list.begin(), list.end(), x), list.end());\n}\n</code></pre>\n\n<p>In a similar vein, <code>findsong()</code> can be simplified using <code>std::find()</code>:</p>\n\n<pre><code>bool findsong(const song& x) const\n{\n return std::find(list.begin(), list.end(), x) != list.end();\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-01T16:22:48.157",
"Id": "231690",
"ParentId": "231678",
"Score": "2"
}
},
{
"body": "<h1>Constructors</h1>\n<p>The better way to write the constructor is</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>song(std::string tit, std::string au = "? ", std::string al = "? ")\n : title(tit), author(au), album(al) { }\n</code></pre>\n<p>That way specifying the title and the author but leaving the album default is possible. Also you only need a single constructor now. You can further improve by using <code>title(std::move(tit))</code> to skip a memory allocation.</p>\n<h1>Privacy</h1>\n<p>Through keeping <code>title</code>, <code>author</code> and <code>album</code> <code>private</code> and only providing functions like <code>gettitle</code> and <code>showtitle</code> you sort of made those read-only. Why? What is the danger having a <code>song</code> and setting the title of it? If someone wants to do it they can do</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>s = song{"new title", s.getauthor(), s.getalbum()};\n</code></pre>\n<p>which is just awkward. You didn't actually gain privacy while inconveniencing your users. I'd make all the members <code>public</code> and remove the getters until there is internal logic that keeps the members synchronized and you cannot guarantee it when users can change the members.</p>\n<h1>Warnings</h1>\n<p>Enable them. They are really useful. There is a bug in <code>const bool operator==(song & a)</code> but it's not really worth learning about because <a href=\"https://coliru.stacked-crooked.com/a/5218fe771890c162\" rel=\"nofollow noreferrer\">a compiler can spot it</a> so you don't have to.</p>\n<h1>Const correctness</h1>\n<p>When comparing 2 <code>song</code>s those should not change and only being able to compare modifiable <code>song</code>s is weird. The correct signature for that is <code>bool operator==(const song & a) const</code>. The <code>const</code> on the right refers to <code>*this</code>, meaning when you do <code>s1 == s2</code> then <code>s1</code> is allowed to be <code>const</code>. The <code>const</code> in the middle refers to the right side, <code>s2</code> in the example which we also want to allow to be <code>const</code>. The <code>const</code> in the front you had refers to the <code>bool</code> and besides very weird edge cases you don't want to return <code>const</code> objects by value. The same applies to <code>gettitle</code> and arguably those functions should return a <code>const std::string &</code> to avoid making a copy.</p>\n<h1>Comparisons</h1>\n<p>If you want lexicographic compares you can use</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>return std::tie(title, author, album) == std::tie(a.gettitle(), a.getauthor(), a.getalbum());\n</code></pre>\n<p>It doesn't look that much better than what you wrote, but it fixed the bug I hinted at when talking about warnings and when doing <code>operator <</code> this becomes much easier than doing it by hand. C++20 is not that far away and then defaulting <code>operator <=></code> should make this convenient.</p>\n<h1>Separation of Concerns</h1>\n<p><code>song</code> prints to <code>std::cout</code>. It really shouldn't. As a user of your class I should be the one who decides how and where things are printed to. I want to print to <code>std::clog</code> for example. For that you can add a function <code>std::ostream &operator <<(std::ostream &os, const song &s)</code> which prints its elements to <code>os</code>. Through inheritance I can now do <code>std::cout << song{};</code> or <code>std::fstream("/tmp/songs.txt") << song{};</code> or whatever I want. Although if you make the members <code>public</code> this is probably no longer necessary. Also users can add their own way of printing.</p>\n<h1>Extra Parenthesis</h1>\n<p><code>x.getlist()</code> has lots of extra parenthesis around making the code less readable. I find <code>findsong((x.getlist())[i])</code> particularly jarring. <code>findsong(x.getlist()[i])</code> is better.</p>\n<h1><a href=\"https://en.wikipedia.org/wiki/Yoda_conditions\" rel=\"nofollow noreferrer\">Yoda Conditions</a></h1>\n<p><code>if (false == this->findsong((x.getlist())[i]))</code> should better be written as <code>if (not findsong(x.getlist()[i]))</code>. Using <code>not</code> over <code>!</code> is a style choice some people find weird and you don't need to follow it, but yoda conditions are harmful to readability and with warnings enabled have no upside.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-01T16:23:33.877",
"Id": "452027",
"Score": "1",
"body": "I don't have time for `playlist` right now, but maybe it's a start."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-01T20:49:25.673",
"Id": "452065",
"Score": "0",
"body": "Thank you for the suggestions, I'll start by improving the song class. If you have time later to check also the playlist class it would be awesome"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-04T16:54:01.110",
"Id": "452386",
"Score": "1",
"body": "@Gitana The other answer pretty much covered that already, but I added 2 points I didn't see there. `for (auto &element : container)` is a generally useful idiom to use for iterating over elements of a container."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-01T16:23:12.077",
"Id": "231691",
"ParentId": "231678",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "231691",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-01T13:59:45.430",
"Id": "231678",
"Score": "2",
"Tags": [
"c++",
"c++11",
"vectors",
"overloading"
],
"Title": "Operator overloading in C++ to manage playlists of music"
}
|
231678
|
<p>I have a complex array function that takes way too much time to calculate, which is why I'm looking for ways to make it more efficient. Basically, I have a transaction sheet in which I list all goods sold in a bunch of different stores. The formula that I've written picks the <strong>last</strong> stock amount in the list where a <strong>specific good</strong> was sold at a <strong>specific store</strong>. An index match doesn't work here as I have 2 different row arguments. The formula looks as follows:</p>
<pre><code>{=INDEX($O$20:O57,MAX(IF($K$20:K57=K58,IF($D$20:D57=D58,ROW($O$20:O57)-MIN(ROW($O$20:O57))+1))),1)}
</code></pre>
<p>To explain in more detail:</p>
<ul>
<li>In column O is the amount of stock after each transaction listed (of which I need the last entry in the list)</li>
<li>In column K is the item code for the specific good</li>
<li>In column D is the name of the branch where the good was sold</li>
</ul>
<p>With increasing transactions, the sheet grows quite substantially and becomes already with ~1,000 rows a time-consuming nightmare. I have written a vba code that copies the entire table except for the last few rows and pastes everything as values back into the table to avoid having too many array formulas in the table, but I can still watch the extended Lord of the Ring cuts while it's computing.</p>
<p>I appreciate any ideas, I'm sure there are ways to make this thing a little faster ;)</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-02T21:33:42.950",
"Id": "452149",
"Score": "0",
"body": "Since you're using VBA in your workbook anyway, have you tried to replace the complex array formula with a VBA-coded UDF ?"
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-01T14:43:43.790",
"Id": "231679",
"Score": "3",
"Tags": [
"performance",
"array",
"excel"
],
"Title": "Speeding up a complex array function in excel"
}
|
231679
|
<p>Somehow this code looks messy to me:</p>
<pre><code> var results = query.GroupBy(x => x.ProductStatusId == ProductStatus.Sold || x.ProductStatusId == ProductStatus.OnHold ? "Delivered" :
x.ProductStatusId == ProductStatus.Shiped ? "Shiped" :
x.ProductStatusId == ProductStatus.NotAvailable ? "NotAvailable" :
x.ProductStatusId == ProductStatus.Paid ? "Paid" : "New").Where(g => g.Key != "New")
</code></pre>
<p>Is it possible to extract this ternary operator in independent statement.</p>
<p>Thanks!</p>
<p>Cheers</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-01T14:57:52.237",
"Id": "452008",
"Score": "0",
"body": "How about switch case or the new switch expression?"
}
] |
[
{
"body": "<p>You could do <code>query.GroupBy(MyTernaryWrapperMethod)</code> and declare that method as</p>\n\n<pre><code>string MyTernaryWrapperMethod(xVariableType x)\n{\n if(x.ProductStatusId == ProductStatus.Sold || x.ProductStatusId == ProductStatus.OnHold) return \"Delivered\";\n\n if(x.ProductStatusId == ProductStatus.Shiped) return \"Shiped\";\n\n if(x.ProductStatusId == ProductStatus.NotAvailable) return \"NotAvailable\";\n\n if(x.ProductStatusId == ProductStatus.Paid) return \"Paid\";\n\n return \"New\"\n}\n</code></pre>\n\n<p>But, that method seems to return something being an actual property of x. So maybe you should add a new method to x's type. Also it would be better to use <code>swicth/case</code> instead of those <code>if</code>s:</p>\n\n<pre><code>public string ProductStatusName()\n{\n switch (ProductStatusId)\n {\n case ProductStatus.Sold:\n case ProductStatus.OnHold: return \"Delivered\";\n case ProductStatus.Shiped: return \"Shiped\";\n case ProductStatus.NotAvailable: return \"NotAvailable\";\n case ProductStatus.Paid: return \"Paid\";\n default: return \"New\"\n }\n}\n</code></pre>\n\n<p>And then you do:</p>\n\n<pre><code>var results = query.GroupBy(x => x.ProductStatusName()).Where(g => g.Key != \"New\")\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-01T15:21:20.370",
"Id": "231684",
"ParentId": "231682",
"Score": "5"
}
},
{
"body": "<p>Another alternative to the switch statement suggested by jakubiszon is a dictionary:</p>\n\n<pre><code>var statusMap = new Dictionary<ProductStatus, string>\n{\n [ProductStatus.Sold] = \"Delivered\",\n [ProductStatus.OnHold] = \"Delivered\",\n [ProductStatus.Shiped] = \"Shiped\",\n [ProductStatus.NotAvailable] = \"NotAvailable\",\n [ProductStatus.Paid] = \"Paid\",\n}\n\nvar results = query\n .Where(i => statusMap.ContainsKey(i.ProductStatusId)\n .GroupBy(x => statusMap[i.ProductStatusId]);\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-01T18:57:56.477",
"Id": "231694",
"ParentId": "231682",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "231694",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-01T14:54:40.743",
"Id": "231682",
"Score": "3",
"Tags": [
"c#"
],
"Title": "How May I extract this ternary operator in independent statement"
}
|
231682
|
<p>I am having severe problems with performance on a WEB API helper method, the performance is simply dreadful, 1-2 connections / second, I am trying to make 40k API calls and 5 hours later it is still going.</p>
<p>I added and set the proxy property of the request to null as per other answers on SE but it doesn't seem to help much, I have a feeling the issue might be that I am re creating the httpwebrequest for every iteration of the loop but I am not sure so posting here for some guidance and review</p>
<p>The two methods are as follows with the first one showing the loop and the second one being my DataFetcher helper that performs so slow</p>
<pre><code> private async Task<List<String>> FetchDocumentsAndBuildList(string brand)
{
using (var client = new DocumentClient(new Uri(cosmosDBEndpointUrl), cosmosDBPrimaryKey))
{
List<string> formattedList = new List<string>();
FeedOptions queryOptions = new FeedOptions
{
MaxItemCount = -1,
PartitionKey = new PartitionKey(brand)
};
var query = client.CreateDocumentQuery<Document>(UriFactory.CreateDocumentCollectionUri(cosmosDBName, cosmosDBCollectionNameRawData), $"SELECT * from c where c.brand = '{brand}'", queryOptions).AsDocumentQuery();
while(query.HasMoreResults)
{
foreach (Document singleDocument in await query.ExecuteNextAsync<Document>())
{
JObject originalData = singleDocument.GetPropertyValue<JObject>("BasicData");
if(originalData != null)
{
var artNo = originalData.GetValue("artno");
if(artNo != null)
{
string strArtNo = artNo.ToString();
string productNumber = strArtNo.Substring(0, 7);
string colorNumber = strArtNo.Substring(7, 3);
string XXYYYUrl = $"https://www.xyz.com/{strArtNo}/en";
string XXXApiUrl = $"https://www.xyz.com/
string HttpFetchMethod = "GET";
JObject detailedDataResponse = await DataFetcher(XXXYYYUrl, HttpFetchMethod);
JObject inventoryData = await DataFetcher(XXXApiUrl, HttpFetchMethod);
if(detailedDataResponse != null)
{
JObject productList = (JObject)detailedDataResponse["product"];
if(productList != null)
{
var selectedIndex = productList["articlesList"].Select((x, index) => new { code = x.Value<string>("code"), Node = x, Index = index })
.Single(x => x.code == strArtNo)
.Index;
detailedDataResponse = (JObject)productList["articlesList"][selectedIndex];
}
}
singleDocument.SetPropertyValue("DetailedData", detailedDataResponse);
singleDocument.SetPropertyValue("InventoryData", inventoryData);
singleDocument.SetPropertyValue("consumer", "akqa");
}
}
formattedList.Add(Newtonsoft.Json.JsonConvert.SerializeObject(singleDocument));
}
}
return formattedList;
}
}
static public async Task<JObject> DataFetcher(string apiUrl, string fetchType)
{
try
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(apiUrl);
request.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
request.UserAgent = "Test";
request.ContentType = "application/json; charset=utf-8";
request.Method = fetchType;
request.Proxy = null;
using (HttpWebResponse response = (HttpWebResponse)await request.GetResponseAsync())
using (Stream stream = response.GetResponseStream())
using (StreamReader reader = new StreamReader(stream))
{
string apiReturnStr = await reader.ReadToEndAsync();
JObject apiReturnObjectJobject = JObject.Parse(apiReturnStr);
return apiReturnObjectJobject;
}
}
catch (WebException e)
{
JObject emptyObject = null;
return emptyObject;
}
}
</code></pre>
<p>--- EDIT ---
The Method is called in an azure function every morning at 5 AM, the CosmosDB query completes in less than 10 second and returns avg 40 000 documents, I then need to loop through each document and do two web api calls in order to get additional information and add that to the document and finally add the modified document to a string list to be used by the CosmosDB bulkImport method.</p>
<p>If I limit the query to 20 documents it finishes extremely fast, just a few seconds, if I do 100 documents its still extremely fast, I haven't tested larger steps other then the full set after that.</p>
<p>The document I am fetching is 3-4 levels deep JSON object, and I am parsing an array on the second level in the document
--- EDIT ---</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-01T15:32:31.277",
"Id": "452019",
"Score": "0",
"body": "Welcome to Code Review! Can you tell us more about how the code is being used/called and what the data you query looks like (how big? much nesting?) to improve the context of your question? Please see our [FAQ on asking questions](https://codereview.meta.stackexchange.com/q/2436/52915). Is it possible to de-obfuscate the variable names you changed?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-01T15:34:08.617",
"Id": "452020",
"Score": "0",
"body": "You say 40k profile calls is a problem. Have you tried what happens with 10? 100? Is the latter 10x as long as the former or is there another difference? If it takes a second per call, 40k calls is 11 hours."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-01T15:41:26.927",
"Id": "452021",
"Score": "0",
"body": "@mast 20 documents to loop through finishes very quickly, the avg API delay is 250ms so I expected to get at least 4 calls per second but then would it not fan out and run multiple connections in parallell? since they are async calls each iteration of the loop does not have to wait for the call to finish? or am I misunderstanding that part? And no the time taken is not linear it increases exponentially"
}
] |
[
{
"body": "<h1>General Feedback</h1>\n<p>There is a lot of work going on in the <code>FetchDocumentsAndBuildList</code> Method. Consider breaking it up into smaller methods that make the main method easier to read and isolate units of work. One example would be to move the entire contents of the <code>foreach</code> into a method that could be named <code>FetchDocumentAsync</code>.</p>\n<p>In general, async method names should end with Async. This means that <code>DataFetcher</code> would be named <code>DataFetcherAsync</code>. <a href=\"https://stackoverflow.com/a/24627122/7412948\">See this answer for more information.</a></p>\n<h1>Performance Feedback</h1>\n<p>If performance is a real concern then you should consider profiling the application to see where the bottlenecks are. Even with a low volume of documents you should be able to get a general grasp of where the code is taking the longest. It is possible that performance issues only arise from a high document count in which case it would be best to profile in a similar scenario.</p>\n<h3>Some potential improvements</h3>\n<ol>\n<li>The two <code>HttpWebRequest</code>s per <code>Document</code> are being run serially (that is, one must finish before the next one beings). Consider calling both DataFetcher calls and then later awaiting the results. This will cause both Http Requests to be sent and then later when the value is needed it will wait for a response. Theoretically doubling the speed. <a href=\"https://softwareengineering.stackexchange.com/a/376392/317394\">See this answer for a more detailed explanation.</a></li>\n</ol>\n<pre><code>var detailedDataResponseTask = DataFetcher(XXXYYYUrl, HttpFetchMethod);\nvar inventoryDataTask = DataFetcher(XXXApiUrl, HttpFetchMethod);\n\nvar detailedDataResponse = await detailedDataResponseTask\nif(detailedDataResponse != null)\n\n...\n\nsingleDocument.SetPropertyValue("InventoryData", await inventoryDataTask);\n</code></pre>\n<ol start=\"2\">\n<li>A very small performance improvement could be done by taking <code>productList</code> code and removing the projection being done to get the index of an item.</li>\n</ol>\n<pre><code>// Original\nvar selectedIndex = productList["articlesList"]\n .Select((x, index) => new { code = x.Value<string>("code"), Node = x, Index = index })\n .Single(x => x.code == strArtNo)\n .Index;\ndetailedDataResponse = (JObject)productList["articlesList"][selectedIndex];\n\n// New\ndetailedDataResponse = productList["articlesList"].Single(x => x.Value<string>("code") == strArtNo);\n</code></pre>\n<ol start=\"3\">\n<li>The final suggestion I have for performance, which probably needs some more careful planning to not have 80,000 tasks in progress, is to do the same optimization as before with <code>await</code>ing the <code>HttpWebRequest</code>s. Each document can be gathered and processed independently of each other document. A naive example of how to do this would be:</li>\n</ol>\n<pre><code>var tasks = new List<Task<string>>();\nforeach(var singleDocument in await query.ExecuteNextAsync<Document>())\n tasks.Add(FetchDocumentAsync(singleDocument));\n\nwhile(tasks.Count > 0)\n{\n Task<string> finishedTask = await Task.WhenAny(tasks);\n tasks.Remove(finishedTask);\n formattedList.Add(await finishedTask);\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-02T04:25:13.803",
"Id": "231717",
"ParentId": "231683",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "231717",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-01T15:03:56.950",
"Id": "231683",
"Score": "3",
"Tags": [
"c#",
"https",
"azure-cosmosdb"
],
"Title": "Speeding up HTTPS API Call helper method"
}
|
231683
|
<p>Here is the part of working code:</p>
<pre><code> function SelectPoints(lat,lon){
var dist = document.getElementById("miles").value;
xy = [lat,lon]; //center point of circle
var theRadius = parseInt(dist) * 1609.34 //1609.34 meters in a mile
//dist is a string so it's convered to an Interger.
selPts.length =0; //Reset the array if selecting new points
job.eachLayer(function (layer) {
// Lat, long of current point as it loops through.
layer_lat_long = layer.getLatLng();
// Distance from our circle marker To current point in meters
distance_from_centerPoint = layer_lat_long.distanceTo(xy);
// See if meters is within radius, add the to array
if (distance_from_centerPoint <= theRadius && $('#cf').is(":checked")) {
selPts.push(layer.feature);
}
})
job2.eachLayer(function (layer) {
// Lat, long of current point as it loops through.
layer_lat_long = layer.getLatLng();
// Distance from our circle marker To current point in meters
distance_from_centerPoint = layer_lat_long.distanceTo(xy);
// See if meters is within radius, add the to array
if (distance_from_centerPoint <= theRadius && $('#vm').is(":checked")) {
selPts.push(layer.feature);
}
})
job3.eachLayer(function (layer) {
// Lat, long of current point as it loops through.
layer_lat_long = layer.getLatLng();
// Distance from our circle marker To current point in meters
distance_from_centerPoint = layer_lat_long.distanceTo(xy);
// See if meters is within radius, add the to array
if (distance_from_centerPoint <= theRadius && $('#bt').is(":checked")) {
selPts.push(layer.feature);
}
})
</code></pre>
<p>but it looks like it's going to be repeatable over next few layers. So far is only 3 layers job, job2 and job3, what doesn't look bad, but I am worried about the future.</p>
<p>Does anyone knows how to make this code a bit shorter?</p>
<p>Thanks & Regards,</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-01T16:37:38.580",
"Id": "452030",
"Score": "2",
"body": "I would rather return a new array of points instead of resetting a global variable."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-01T16:53:14.337",
"Id": "452034",
"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)*. Next time, please include all relevant code in the first revision."
}
] |
[
{
"body": "<p>A short review;</p>\n\n<ul>\n<li><code>selPts.length = 0; //Reset the array if selecting new points</code> always resets the array, even if no points will be added, also <code>selPts = []</code> is more idiomatic</li>\n<li>Seems like <code>xy</code> is not declared there, and it probably should be. Nor is <code>selPts</code></li>\n<li>I feel <code>center</code> describes more accurately the purpose of <code>xy</code></li>\n<li>Idiomatic JavaScript uses lowerCamelCase, so <code>layer_lat_long</code> -> <code>layerLatLong</code> etc. </li>\n<li>In the end I went with <code>layerLatLng</code> since you get it from a function called <code>getLatLng</code></li>\n<li>I only knew <code>selPts</code> was <code>selectedPoints</code> due to comments, I think you should spell it out completely</li>\n<li>You can extract the common logic into a function and pass that function to <code>.eachLayer()</code></li>\n</ul>\n\n<p>Obligatory rewrite:</p>\n\n<pre><code>function SelectPoints(latitude, longitude) {\n var dist = document.getElementById(\"miles\").value,\n theRadius = parseInt(dist, 10) * 1609.34; //1609.34 meters in a mile\n\n center = [latitude, longitude]; //center point of circle\n selectedPoints.length = []; //Reset the array if selecting new points\n\n function updateSelectedPoints(layer){\n // Lat, long of current point as it loops through.\n layerLatLng = layer.getLatLng();\n // Distance from our circle marker To current point in meters\n distanceFromCenter = layerLatLng.distanceTo(center);\n // See if meters is within radius, add the to array\n if (distanceFromCenter <= theRadius){\n selectedPoints.push(layer.feature);\n }\n }\n\n if($('#cf').is(\":checked\")){\n job.eachLayer(updateSelectedPoints);\n }\n if($('#vm').is(\":checked\")){\n job2.eachLayer(updateSelectedPoints);\n }\n if($('#bt').is(\":checked\")){\n job3.eachLayer(updateSelectedPoints);\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-01T16:35:56.320",
"Id": "452029",
"Score": "0",
"body": "Your solution doesn't work. I believe, that it's my fault, because I haven't attached a full code. Now my query has been edited. Could you please look on it again?\nThank you very much."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-01T16:39:19.537",
"Id": "452031",
"Score": "0",
"body": "The point would not be to copy paste the approach (I clearly was not able to test it, you can't trust that code), but to give you an idea on how to solve the issue. Are you saying that you can not extract the common functionality in a common function?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-01T17:51:48.477",
"Id": "452041",
"Score": "0",
"body": "@MariuszKrukar, how it does not work? Add more context and description of where it fails"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-01T16:24:32.287",
"Id": "231692",
"ParentId": "231686",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-01T15:56:01.207",
"Id": "231686",
"Score": "1",
"Tags": [
"javascript",
"leaflet"
],
"Title": "Leaflet map distance from the onclick marker"
}
|
231686
|
<p>I finished Python Principles and this is my first program I've done (mostly) from scratch since, having to get some outside help on the loop to repeat the program, and I saw a nifty thing about using modular math to figure out the results so I did that to save a bunch of lines.</p>
<p>I'm just looking for any comments, improvements, bad habits, any comments at all!</p>
<pre><code>import random
options = ['rock', 'paper', 'scissors']
def pickRando(): #set random choice for CPU
global randoPick
randoPick = random.choice(options)
def game(): #start up the game
global player
print('Rock, Paper, Scissors:')
player = input("Choose wisely: ") #get player input
player = player.lower()
if player in options:
check = True
print("Okay, you picked " + player + ' and I picked ' + randoPick + '!')
return check
else:
print('You have not chosen a viable option! Try again')
check = False
return check
def convertible(swap): #changing the word into a number
if swap == 'rock':
swap = 0
elif swap == 'paper':
swap = 1
else:
swap = 2
return swap
def combatCheck(a, b): #determine the results of the choices
a = convertible(a)
b = convertible(b)
result = (a - b) % 3 #modmath
return result
def finish(z): # report the results
global wins
global losses
global ties
if z == 0:
print('A tie! You are a most worthy opponent! Go again?')
ties = ties + 1
if z == 1:
print('You win! My honor demands a rematch!')
wins = wins + 1
if z == 2:
print('Haha, I am victorious! Dare you challenge me again?')
losses = losses + 1
print('You have ' + str(wins) + ' wins, ' + str(losses) + ' losses and, ' + str(ties) + ' ties!')
wins = 0
losses = 0
ties = 0
while True :
pickRando()
check = False
while check == False:
check = game()
finish(combatCheck(player, randoPick))
while True: #looping
global answer
answer = input('Run again? (y/n): ')
if answer in ('y', 'n'):
break
print('Invalid input.')
if answer == 'y':
continue
else:
print('You are weak!')
break
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-01T20:31:07.137",
"Id": "452061",
"Score": "0",
"body": "What exactly did \"Python Principles\" cover? Did it cover classes as well? If it did, I'll write my review/answer up because I kiiiinda rewrote your program with classes, which removes a lot of the global complexity and rewrites a good bit of your code so you don't need code repetition or the use of functions to determine numeric values. If it did not cover classes, then I'll not share my rewrite because you don't know the basic principles of it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-01T20:43:22.647",
"Id": "452064",
"Score": "0",
"body": "@ChaosHat, do you think that between our three answers, there is anything else that you'd like explained more in depth so that you have some more context or so that it is easier to understand? Do you have any feedback on our answers? I hope everything thus far has helped you."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-01T20:57:49.057",
"Id": "452067",
"Score": "1",
"body": "@ThomasWard it did not include classes, but please do that anyways! I could benefit from such a direct example to learn from."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-01T20:58:59.693",
"Id": "452068",
"Score": "1",
"body": "@TrevorPaulMartin I am reading everything over now having got home from work. Everyone has been very helpful in pointing things out and a lot of comments reinforce similar points so at least it seems like the feedback is useful. At first I was thinking about rewriting the program after feedback but I feel like maybe it would be best to move on for now, and then revisit it again in a few months and just see how different it is."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-01T21:03:08.863",
"Id": "452071",
"Score": "1",
"body": "@ChaosHat OK, I wanted to make sure I wasn't going to overload your understandings by rewriting it as a Python class to handle the actual game object/mechanics while only handing off 'replay' to the actual 'python' program outside of the class. https://gist.github.com/teward/d303af90949b39a1f94dce84da973ac8 contains all the code, but I also posted this as https://codereview.stackexchange.com/questions/231706/python-rock-paper-scissors-via-a-class-to-handle-the-game to get input on how to improve my variant too :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-01T21:13:27.353",
"Id": "452074",
"Score": "0",
"body": "@ChaosHat ... and I just dumped the rewrite (with docstrings but little-to-no explanation of what the rewritten code does) as an answer. This said, it basically mimics a lot of your game mechanics, but removes a lot of code complexity. My answer does not contain the thoroughly-commented variant of the program, but the Gist does. And I link to it. (And my rags-to-riches request for a review of my rewrite of your code is also linked)"
}
] |
[
{
"body": "<p>Minor improvements to documentation and structure but otherwise no significant improvements. I am sure there are optimization suggestions to be made but this seems small enough a program so as to not really benefit too much from these suggestions. If you want to be pedantic you could use type checking by importing the typing module.</p>\n\n<p><strong>Suggestion 1</strong></p>\n\n<p>Keep two lines between dependencies (import) and the rest of the code like this: </p>\n\n<pre><code>import random\n\n\noptions = ['rock', 'paper', 'scissors']\n</code></pre>\n\n<p>as well as between methods.</p>\n\n<pre><code> # ...\n result = (a - b) % 3 #modmath\n return result\n# space 1\n# space 2\ndef finish(z): # report the results\n global wins\n # ...\n</code></pre>\n\n<p>For reference on stylist things such as this check out \n<a href=\"https://www.python.org/dev/peps/pep-0008/#imports\" rel=\"nofollow noreferrer\">https://www.python.org/dev/peps/pep-0008/#imports</a></p>\n\n<p><strong>Suggestion 2</strong></p>\n\n<p>You can use docs strings to describe a function or method instead of lone comments. Doc strings are for \"documentation\" and help people better understand your methods or blocks of code. The # comments are for commenting on a single or several lines of code and understanding each's specific functionality, say in context of the method as a whole. </p>\n\n<p>Example: </p>\n\n<pre><code>def combatCheck(a, b):\n'''Determines combat choice and returns the result'''\n a = convertible(a)\n b = convertible(b)\n result = (a - b) % 3 #modmath # <-- this comment \"modmath\" is not too helpful \n return result\n</code></pre>\n\n<p><strong>Suggestion 3</strong></p>\n\n<p>You can use type checking to show people what type of data goes into your methods.</p>\n\n<p>For this include:</p>\n\n<pre><code>import typing\n</code></pre>\n\n<p>Examples:</p>\n\n<pre><code># the line below tells people the param and return types, and doesn't\n# affect how the code runs\ndef combatCheck(a: str, b: str) -> int: \n a = convertible(a)\n b = convertible(b)\n result = (a - b) % 3 #modmath\n return result\n</code></pre>\n\n<p>Since finish just prints a statement we type check it as such</p>\n\n<pre><code>def finish(z: int) -> None: \n'''Method to print results to user'''\n global wins\n global losses\n global ties\n# etc...\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-01T21:00:20.080",
"Id": "452069",
"Score": "0",
"body": "I'll check out typing. I'm not familiar with it but it seems helpful."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-01T20:08:13.847",
"Id": "231700",
"ParentId": "231695",
"Score": "4"
}
},
{
"body": "<p>This code reads like beginner code. Good beginner code, but there are a few habits you're getting into that are systemic among beginners and <strong>will</strong> screw you over later down the line.</p>\n\n<p>First, your function names are somewhat confusing. I would rename <code>pickRando</code> to <code>computerChoice</code>, <code>combatCheck</code> to <code>game</code>, and <code>finish</code> to something like <code>printRecord</code>. Once you do that, you shouldn't need the comments describing them. Comments are good, but shouldn't be used in lieu of descriptive names.</p>\n\n<p>Second, avoid global variables. It will cause confusing issues later down the line, so please get into the habit of not using them. In order to avoid the global variables <code>wins</code>, <code>losses</code>, and <code>ties</code>, you would need to restructure a lot of code and it may not be worth it for this small of a code base. Exercise to the reader, I guess. But the other globals can easily be removed. I would change <code>pickRando</code> to</p>\n\n<pre><code>def computerChoice():\n return random.choice(options)\n</code></pre>\n\n<p>The concept behind the input check is good, but I would heavily modify the structure. Here's a better way to do that</p>\n\n<pre><code>while True:\n [...]\n print(\"Rock, Paper, Scissors:\")\n\n playerChoice = input('choose wisely')\n while not playerChoice in options:\n print \"invalid input\"\n playerChoice == input('choose wisely')\n print(\"Okay, you picked \" + playerChoice + ' and I picked ' + computerChoice + '!')\n</code></pre>\n\n<p>This restructuring should make what it's actually doing clearer.</p>\n\n<p>Next: the <code>convertible</code> method is a very good solution if you don't know about the built-in method <code>index</code>. You can change the <code>combatCheck</code> method to something like this.</p>\n\n<pre><code>a = options.index(a)\nb = options.index(b)\nreturn (a-b) % 3\n</code></pre>\n\n<p>I would also comment the last line with something more descriptive than <code>modmath</code>. I might say something like <code>uses modular arithmetic to calculate results</code>.</p>\n\n<p>I like that you put <code>combatCheck</code> in its own function from the perspective of the teacher, because it shows that you use functions, but I think it's unnecessary here, because you only use that bit of code once and it's only a few lines.</p>\n\n<p>You definitely have some really great foundations. Most of your mistakes are mistakes I made in my early days of Python, and I like to think I'm a pretty OK programmer. I think with practice and time, you'll turn into an amazing programmer.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-01T21:09:14.867",
"Id": "452073",
"Score": "1",
"body": "I think a lot of my bad variable or method names (like finish) came from my iterative process. Some did different things and as I added more stuff (replays/score tally/final clean up) the methods added or changed. Should have touched on it in clean up.\n\nIndex is useful for this so thanks for that. I thought about a dictionary but I couldn't find a simple way to look a thing up and swap it for the value in the dictionary.\n\nCombat check originally did more, and got pared down. I'm looking for the sweet spot of \"should this be a function, part of another, or just not at all.\""
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-02T11:37:28.663",
"Id": "452104",
"Score": "1",
"body": "To add to the content of this post, please see [PEP8](https://www.python.org/dev/peps/pep-0008/#function-and-variable-names) for function naming guidelines."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-05T21:08:05.357",
"Id": "456469",
"Score": "0",
"body": "@ChaosHat unfortunately, the only way to find that sweet spot is **lots** of practice."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-01T20:08:50.383",
"Id": "231702",
"ParentId": "231695",
"Score": "13"
}
},
{
"body": "<p>You are abusing <code>global</code>s here. Ideally, functions should take in data using parameters, and return data they produce. Reassigning globals like you are makes it much more difficult to tell what a function does when reading code.</p>\n\n<p>For example, instead of</p>\n\n<pre><code>def pickRando():\n global randoPick\n randoPick = random.choice(options)\n\n. . .\n\nfinish(combatCheck(player, randoPick))\n</code></pre>\n\n<p>You should get rid of the global <code>randoPick</code> and just do:</p>\n\n<pre><code>def pickRando():\n # The data is simply returned instead of altering a global\n return random.choice(options) \n\n. . .\n\nrandoPick = pickRando() # local instead of global\nfinish(combatCheck(player, randoPick))\n</code></pre>\n\n<p>The less \"behind-the-scenes\" data manipulation you do, the better. Code is much easier to reason about when function calls are simply an in/out flow of information.</p>\n\n<hr>\n\n<p>There's multiple odd things going on with <code>game</code>.</p>\n\n<ul>\n<li><p>It alters the global <code>check</code>, then returns <code>check</code>, then you do <code>check = game()</code> again when calling <code>game</code>.</p></li>\n<li><p>You're returning whether or not the input failed, then dealing with a bad result externally when calling <code>game</code>.</p></li>\n</ul>\n\n<p>I would make a helper to take input in a loop, and eliminate the global <code>check</code>. We just need a function that will loop for us while the input is invalid. Something like:</p>\n\n<pre><code>from typing import Callable\n\ndef get_valid_input(ask_message: str, error_message: str, validator: Callable[[str], bool]):\n while True:\n user_input = input(ask_message)\n\n if validator(user_input):\n return user_input\n\n else:\n print(error_message)\n</code></pre>\n\n<p>It loops for you until <code>validator</code> returns <code>True</code>. <code>validator</code> is a function that we supply that tells it if an input is valid or not.</p>\n\n<p>I'd also re-jig things a bit and alter the responsibility of <code>game</code>. Once you make the changes I suggested, you're basically just left with:</p>\n\n<pre><code>def game(): #start up the game\n print('Rock, Paper, Scissors:')\n player = get_valid_input(\"Choose wisely: \",\n 'You have not chosen a viable option! Try again',\n lambda move: move.lower() in options)\n\n print(\"Okay, you picked \" + player + ' and I picked ' + randoPick + '!')\n</code></pre>\n\n<p>It doesn't seem to have much point. I'd change this to something like a <code>play_round</code> function that handles the entirety of one round:</p>\n\n<pre><code>def play_round():\n computer_move = pickRando()\n\n print('Rock, Paper, Scissors:')\n player_move = get_valid_input(\"Choose wisely: \",\n 'You have not chosen a viable option! Try again',\n lambda move: move.lower() in options)\n\n print(\"Okay, you picked \" + player_move + ' and I picked ' + computer_move + '!')\n\n finish(combatCheck(player_move, computer_move))\n</code></pre>\n\n<p>This eliminates multiple globals, and makes the calling code make a lot more sense:</p>\n\n<pre><code>while True:\n play_round()\n\n answer = get_valid_input(\"Run again? (y/n): \",\n \"Invalid input.\",\n lambda a: a in {'y', 'n'})\n\n if answer == 'y':\n continue\n\n else:\n print('You are weak!')\n break\n</code></pre>\n\n<p>Now you aren't needing to manually validate input, which gets rid of a lot of messy looping.</p>\n\n<hr>\n\n<hr>\n\n<p>This still has a lot that can be commented on:</p>\n\n<ul>\n<li><p>There's still some globals in charge of keeping track of the scores. I would bundle those scores into a class or tuple or something, and pass them into and out of <code>play_round</code>.</p></li>\n<li><p><code>convertible</code> can be simply made into a dictionary:</p>\n\n<pre><code>{'rock': 0,\n 'paper', 1,\n 'scissors', 2}\n</code></pre>\n\n<p>Then you can do <code>a = convertible[a]</code>. Note though that this will raise an error instead of defaulting to <code>2</code> if somehow bad input makes its way through. This is arguably a good thing though.</p></li>\n<li><p>A lot of your comments are useless. Comments like in <code>(a - b) % 3 #modmath</code> and <code>input(\"Choose wisely: \") #get player input</code> are just repeating what the code says. Comments should explain <em>why</em> code is as it is; if that's necessary. Ideally, your code should be \"fluent\" enough that you don't need to comment what a code does because it's obvious already.</p></li>\n</ul>\n\n<p>I hate to rush reviews, but FedEx just got here with my new laptop :D</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-01T20:53:11.020",
"Id": "452066",
"Score": "0",
"body": "Thanks! I know I'm using too many globals. I had more, and then I felt removing the last couple meant rewriting all of it. My prior experience is couple 200 level Java classes a few years ago so I think the way I think about variables stem from that.\n\nAs far as your randoPick fix, I did think of that but I wasn't sure whether or not it would be as bad to nest a ton of functions as far as readability. Any solution beyond renesting it felt like a rewrite. I also thought of a dictionary, I wasn't sure if it was better, worse, or just different. It seemed like an overall same amount of effort."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-01T21:02:49.613",
"Id": "452070",
"Score": "0",
"body": "@ChaosHat Calling functions inside of other functions is fine. If each function has a well-defined purpose, \"nesting\" functions will be a lot more readable than trying to do everything manually. Unless you don't define your own functions (which isn't a good idea), you'll *always* be calling functions from within other functions. And in this case, whether or not you use `if`s or a dictionary is a matter of taste since performance isn't a concern. You could have also used an `enum`."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-01T20:08:52.577",
"Id": "231703",
"ParentId": "231695",
"Score": "7"
}
},
{
"body": "<p>Just for the record, when I saw the abuse of <code>global</code> arguments above and a ton of Python program level looping just to handle a lot of the game functionality, etc., I immediately thought this could be completely redesigned around a <strong><code>class</code></strong> to handle the actual game itself, track score, etc. for the entire game, and pretty much eliminate the reliance on globals and passing variables around outside the class.</p>\n\n<p>As your Python Principles course didn't touch upon <code>class</code> objects, W3Schools has a half-decent rough explanation of a class and how it works with internal variables and methods/functions <a href=\"https://www.w3schools.com/python/python_classes.asp\" rel=\"nofollow noreferrer\">here</a>, though you're bound to learn classes in-depth if you take more advanced Python courses.</p>\n\n<p>This said, using a <code>class</code> to instantiate the game itself actually alleviates much of your <code>global</code> abuse and much of the passing of score objects around as 'program level' objects, and keeps everything as part of a singular <code>game</code> object when you use a <code>class</code> to define the game object, its mechanics, and its variables internal to itself, so it's available to the <code>game</code> object as you go. Also makes having to pass data between the various functions and methods a <em>lot</em> easier, since everything's referred to as an object within the <code>game</code> instance of <code>RockPaperScissors</code> itself! Cool, huh?</p>\n\n<hr>\n\n<p><strong>Anyways</strong>, I rewrote your game mechanics and functionality as a <code>class</code>, and kept all the base functionality you do for your game mechanics as part of the class (choosing randomly, checking if a win/loss/tie and keeping track of scores, actually running the game, and actually handling 'wrong' inputs of choices), but made a much simpler mechanism to handle the mapping of string-to-numeric-value mapping of choices using a <code>dict</code>ionary instead within the class.</p>\n\n<p>I moved the checking for continuing playing, however, to outside the class as part of the actual Python 'program' execution.</p>\n\n<p>The <code>game</code> is initially created as an instance of the <code>RockPaperScissors</code> class, and we just straight refer to the <code>game</code> object outside the class for running a round of RPS and outputting the current scores; everything in terms of score, game mechanics, etc. is all kept within the <code>game</code> object as variables or methods within the class itself.</p>\n\n<p>I also rewrite your functions for the mechanics to be <code>snake_case</code> instead of <code>camelCase</code>, but keep most of the stuff the same, just slightly more Pythonic (with <code>if</code>/<code>elif</code> instead of more than one if statement, etc.)</p>\n\n<pre><code>import random\n\n\nclass RockPaperScissors:\n \"\"\"\n Class to handle an instance of a Rock-Paper-Scissors game\n with unlimited rounds.\n \"\"\"\n\n def __init__(self):\n \"\"\"\n Initialize the variables for the class\n \"\"\"\n self.wins = 0\n self.losses = 0\n self.ties = 0\n self.options = {'rock': 0, 'paper': 1, 'scissors': 2}\n\n def random_choice(self):\n \"\"\"\n Chooses a choice randomly from the keys in self.options.\n :returns: String containing the choice of the computer.\n \"\"\"\n\n return random.choice(list(self.options.keys()))\n\n def check_win(self, player, opponent):\n \"\"\"\n Check if the player wins or loses.\n :param player: Numeric representation of player choice from self.options\n :param opponent: Numeric representation of computer choice from self.options\n :return: Nothing, but will print whether win or lose.\n \"\"\"\n\n result = (player - opponent) % 3\n if result == 0:\n self.ties += 1\n print(\"The game is a tie! You are a most worthy opponent!\")\n elif result == 1:\n self.wins += 1\n print(\"You win! My honor demands a rematch!\")\n elif result == 2:\n self.losses += 1\n print(\"Haha, I am victorious! Dare you challenge me again?\")\n\n def print_score(self):\n \"\"\"\n Prints a string reflecting the current player score.\n :return: Nothing, just prints current score.\n \"\"\"\n print(f\"You have {self.wins} wins, {self.losses} losses, and \"\n f\"{self.ties} ties.\")\n\n def run_game(self):\n \"\"\"\n Plays a round of Rock-Paper-Scissors with the computer.\n :return: Nothing\n \"\"\"\n while True:\n userchoice = input(\"Choices are 'rock', 'paper', or 'scissors'.\\n\"\n \"Which do you choose? \").lower()\n if userchoice not in self.options.keys():\n print(\"Invalid input, try again!\")\n else:\n break\n opponent_choice = self.random_choice()\n print(f\"You've picked {userchoice}, and I picked {opponent_choice}.\")\n self.check_win(self.options[userchoice], self.options[opponent_choice])\n\n\nif __name__ == \"__main__\":\n # Initialize an instance of RockPaperScissors for us to refer to\n game = RockPaperScissors()\n # Keep playing the came repeatedly, stop playing by just exiting\n # the entire program directly.\n while True:\n game.run_game() # Run a round of RPS\n game.print_score() # Print the score(s) after the round\n\n # Find out if we want to continue playing or not.\n while True:\n continue_prompt = input('\\nDo you wish to play again? (y/n): ').lower()\n if continue_prompt == 'n':\n # Exit the game directly after printing a response.\n print(\"You are weak!\")\n exit()\n elif continue_prompt == 'y':\n # Break the continue prompt loop and keep playing.\n break\n else:\n # Bad input was given, re-request if we want to play again.\n print(\"Invalid input!\\n\")\n continue\n</code></pre>\n\n<hr>\n\n<p>Now, this code has absolutely no explanation of what each function does, etc. per line of code within the class (though I provide docstrings to explain things!), even though I comment what we do in the outer block that actually runs the code.</p>\n\n<p>THIS BEING SAID, I have a version of this that has much more thorough comments throughout the entire codebase (including docstrings)</p>\n\n<p>A complete explanation of the code and what each bit does is detailed in a GitHub GIST <a href=\"https://gist.github.com/teward/d303af90949b39a1f94dce84da973ac8#file-rps-py\" rel=\"nofollow noreferrer\">located here as the <code>rps.py</code> file in the Gist</a> because the number of lines doubles when you include all my comments.</p>\n\n<p>(This also has a <a href=\"/questions/tagged/rags-to-riches\" class=\"post-tag\" title=\"show questions tagged 'rags-to-riches'\" rel=\"tag\">rags-to-riches</a> request for a review of this rewrite at <a href=\"https://codereview.stackexchange.com/questions/231706/python-rock-paper-scissors-via-a-class-to-handle-the-game\">Python Rock-Paper-Scissors via a class to handle the game</a> if you want to see people review it! I'll also provide the polished version later in a separate gist!)</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-01T21:11:59.510",
"Id": "231707",
"ParentId": "231695",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-01T19:11:50.227",
"Id": "231695",
"Score": "15",
"Tags": [
"python",
"beginner",
"rock-paper-scissors"
],
"Title": "First attempt: Python Rock Paper Scissors"
}
|
231695
|
<p>I wrote a brute-force algorithm which shall find all possible combinations of ASCII-values that can sum up to a specific value (<code>int hashval</code>). </p>
<p>The algorithm is derived from a recursive algorithm that could print all binary numbers that are possible within a specific length <code>characters</code>. I modified it, so it now iterates over all <code>ints</code> between <code>first</code> and <code>last</code>, thus building all combinations there are. If the sum of the combination is equal to <code>hashval</code>, then the combination is saved in <code>vector<vector<int[]>> combinations</code>. When all possible combinations are found the content of combinations is printed into a file.</p>
<p>I already use some little tricks I learned for competitive programming, but the algorithm is still too slow. At the moment it is running for approximately 3 hours for no more than 13 characters, with no end in sight, file I/O hasn't even started yet. I know that its Big-O for runtime is horrible, no doubt. (if I get it right it is O(m^n) ).</p>
<p>I considered adding a check for n=1 since that would leave only one possibility for the last character, saving some recursive calls, but that would add another if to be called in every function call, either.</p>
<p>What more ways are there to improve the speed? Any improvements are not bound to C++, I will take a look at every programming language which might be more efficient in this case, though I guess there scarcely will be one.</p>
<p>The algorithm:</p>
<pre><code>#include <iostream>
#include <vector>
#include <bits/stdc++.h>
#include <cstdio>
using namespace std;
using namespace std::chrono;
//values in decimal
int first = 32, last = 126, characters = 13, hashval = 1207;
vector<vector<int>> combinations;
void brute(int n, int it, vector<int> values) {
if (n == 0) {
int sum = 0;
//sum up recent values
for (int j = 0; j < characters; ++j) {
sum += values[j];
}
//save values if matching to hash
if (sum == hashval) {
combinations.push_back(values);
}
} else {
for (int i = first; i <= last; ++i) {
values[it] = i;
brute(n - 1, it + 1, values);
}
}
}
</code></pre>
<p>Printing the output to a file:</p>
<pre><code>void printToFile(){
freopen("fileContent.brute", "w", stdout);
cout << "\n\nFound " << combinations.size() << " combinations." << endl;
int counter = 0;
for (auto combo = combinations.begin(); combo != combinations.end(); ++combo){
for (int i = 0; i < characters; ++i) {
cout << (char) combinations.at(counter).at(i) << " ";
}
cout<< "\r\n";
counter++;
}
}
</code></pre>
<p>The main-method:</p>
<pre><code>int main() {
auto start = high_resolution_clock::now();
//characters = 3, first = 0, last = 3, hashval = 6;
ios_base::sync_with_stdio(false);
cin.tie(nullptr);
vector<int> values;
for (int i = 0; i < characters; ++i) {
values.push_back(first);
}
brute(characters, 0, values);
printToFile();
auto stop = high_resolution_clock::now();
auto duration = duration_cast<seconds>(stop - start);
cout << "Brute-forcing needed " << duration.count() << " seconds.\r\n";
cout.flush();
return 0;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-02T01:30:51.367",
"Id": "452084",
"Score": "3",
"body": "Please don't modify/add code in the question once answers have come in. If you have an improved version you want to put up for review, please wait a day or so, post it as a new question and link back to this one for bonus context."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-02T12:00:49.437",
"Id": "452106",
"Score": "0",
"body": "I am assuming that the theoretical model of a 4GHz machine performing a hash comparison in _one clock cycle_ and running for 208 days straight before failing is \"sufficient\" as a solution? That means you need no container at all, only a `uint64_t` and a bitmask to clear out the uppermost bit of every byte (since ASCII is desired). That'll be a 56-bit counter to cycle through, which takes way, way long enough either way. Length is implicit (can be told from the number)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-02T15:31:39.033",
"Id": "452123",
"Score": "0",
"body": "Although I am volunteeringly writing this for an assignment (for which I am free to set the parameters in a way I can force the algorithm to stop in finite time), I have no real use case for the algorithm at the moment. I am looking for even better ways to do the above task for learning purposes ;)\nI will reask the question with the updated code some time later."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-02T17:32:23.433",
"Id": "452134",
"Score": "1",
"body": "Do you actually need all possible permutations of a set of characters that sum to `hashval`? I mean if `hashval` is 65, then you would have both 32,33 and 33,32 as possible results. If you only need one of those, you can speed up your algorithm quite a lot."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-03T16:02:05.867",
"Id": "452207",
"Score": "1",
"body": "It came to my mind already some time ago that it might be more efficient to start with a string that sums up to hashval and find all the other possible solutions with +1/-1 operations in the limits of first and last character. I haven't yet figured though how that algorithm would need to look like to make sure it finally stops and doesn't run in cycles. I will try that later, though when I have time to come back to that algorithm."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-03T18:30:33.297",
"Id": "452227",
"Score": "0",
"body": "Since your algorithm is just a sum, it's independent of order, so you should only bother testing strings where each value is >= the previous one. Then you can go through this list of sorted strings and add every permutation of each if you like. You can also early exit when (partial_sum + remaining * first > hashval) || (partial_sum + remaining * last < hashval)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-04T00:47:24.227",
"Id": "452264",
"Score": "0",
"body": "@patstew: Better still to only iterate over the valid ranges: http://coliru.stacked-crooked.com/a/73a9dcef46c759fc"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-04T01:08:31.853",
"Id": "452267",
"Score": "0",
"body": "The first problem I see is that you're allocating ~58820137000000000000000000 `values` vectors in memory."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-04T01:11:30.733",
"Id": "452268",
"Score": "0",
"body": "The `combinations` vector holds over 36GB of data, so unless you have that much memory, the operating system is probably pausing your program every once in a while to copy all the vector data to the hard drive, so that it can reuse the.RAM. streaming straight to disk will lead to significant performance gains."
}
] |
[
{
"body": "<h1>Use a better container</h1>\n\n<p>The main issue is that <code>std::vector<int></code> is a bad container for storing a set of ASCII characters. Every vector allocates on the heap, and an empty vector is likely 24 bytes in size. So this is huge waste. Why not use a container designed to hold a series of ASCII characters, like... <code>std::string</code>!</p>\n\n<h1>Do you need to store all possible combinations in memory?</h1>\n\n<p>You are first building a vector of all possible combinations with the desired sum. But the only thing you are doing with it afterwards is writing the result to a file. That's a huge waste of memory, and maintaining the vector of vectors in itself costs some CPU time as well. Why not write the results to a file immediately?</p>\n\n<h1>Exit early when your combination has already exceeded the desired sum</h1>\n\n<p>You always try to fill the vector <code>values</code> with <code>characters</code> elements, and try each possible element at each position. However, in <code>brute()</code>, you should calculate the partial sum of elements 0 up to <code>n</code>, and then just check in the for loop whether adding <code>i</code> to that sum would be equal to or higher than the desired sum. If so, if it's equal output the combination, but in any case return at that point instead of trying other values.</p>\n\n<h1>Use <code>\\n</code> consistently to end lines</h1>\n\n<p>You are mixing <code>\\n</code>, <code>\\r\\n</code> and <code>std::endl</code> in your code. Stick to <code>\\n</code>, it is the standard way of ending a line in C and C++. The underlying I/O routines will automatically convert the newlines to <code>\\r\\n</code> on Windows.</p>\n\n<p><code>std::endl</code> is equivalent to <code>\\n</code> plus a call to <code>flush()</code>. Unless there is a good reason to, you don't want this extra flushing to happen, since it reduces the performance of your program. Normally, <code>std::cout</code> is line-buffered, so if something ends with a <code>\\n</code>, it is already flushed automatically. This also means you should remove the explicit call to <code>cout.flush()</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-01T20:21:33.353",
"Id": "452060",
"Score": "2",
"body": "Adding `char`s isn't necessarily faster or slower than adding `int`s. Since you are already timing it, test it out with a smaller `hashval` and see if it makes any difference. Also, as a bonus, printing a `std::string` is trivial compared to `std::vector<int>` :) Furthermore, file-IO will be done buffered, so the overhead should be negligable."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-03T04:40:25.117",
"Id": "452163",
"Score": "0",
"body": "`std::string` also allocates on the heap."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-03T11:23:22.610",
"Id": "452182",
"Score": "0",
"body": "Further to @HongOoi 's comment, an empty `std::string` is likely also at least 24 bytes (unless it's the old, non-C++11-conforming Copy-On-Write `std::string` from GCC 4 and earlier)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-03T22:42:06.867",
"Id": "452248",
"Score": "0",
"body": "@HongOoi: except that since C++11, there is the small-string optimization that avoids heap allocations. On 64-bit platforms, strings up to 22 characters avoid allocations."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-01T20:08:26.620",
"Id": "231701",
"ParentId": "231696",
"Score": "17"
}
},
{
"body": "<p>put something like this at the beginning of your brute function and you'll see the problem pretty quick. if i had to guess this is going to take a few centuries to complete. </p>\n\n<pre><code>std::printf(\"brute(%d, %d, %s)\\n\", n, it, join(values).c_str());\n</code></pre>\n\n<p>ed: it's actually far worse than i imagined. on my computer it took 37.4 seconds to get one tick in the 9th cell. since you need 94 such ticks to budge the 8th cell, it will be 3520 seconds for that.</p>\n\n<p>eventually you get to the 6th cell, which takes 1 year to tick. you can see now the 5th cell is going to take roughly one century.</p>\n\n<p>689 billion years is a round figure to finish. </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-04T17:57:30.317",
"Id": "452402",
"Score": "1",
"body": "@MelissaLoos \"I know that it is inefficient, that is why I started the question\": of course, but the point about calculating *just how inefficient it is* is well taken. It can also help you identify where and why it is inefficient. Armed with that technique, you can learn how to write more efficient algorithms more effectively."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-01T22:52:28.273",
"Id": "231710",
"ParentId": "231696",
"Score": "6"
}
},
{
"body": "<p>This shouldn't be in your program:</p>\n\n<pre><code>#include <bits/stdc++.h>\n</code></pre>\n\n<p>You should <em>never</em> <code>#include <bits/stdc++.h></code>. It is not even proper C++. It ruins portability and fosters terrible habits. See <a href=\"https://stackoverflow.com/q/31816095\">Why should I not <code>#include <bits/stdc++.h></code></a>.</p>\n\n<p>This is also questionable:</p>\n\n<pre><code>using namespace std;\nusing namespace std::chrono;\n</code></pre>\n\n<p>Using using directives globally is considered bad practice because it introduces name clashes and defeats the purpose of namespaces. You will encounter problems when you try to utilize an identifier as innocent as <code>size</code> or <code>count</code>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-02T11:50:29.310",
"Id": "231730",
"ParentId": "231696",
"Score": "8"
}
},
{
"body": "<p>Searching that way is futile, the number of candidate solutions grows exponentially with the number of characters, I would ballpark over 10^20 candidate solutions for 13 characters (an average of (95^13 / (95 * 13)) = 4.15x10^22 but it strongly depends on the value of hashval). The solutions of the equation a_1 + a_2 + ... + a_n = x form an hyperplane of dimension n - 1.</p>\n\n<p>If you know that your plaintext contains only english words limit your search to these.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-03T15:57:44.680",
"Id": "452206",
"Score": "0",
"body": "I cannot limit them to english words and thus no dictionary approach seems possible."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-03T20:23:00.697",
"Id": "452239",
"Score": "0",
"body": "If you don't know enough information about the plain text to limit it somehow then I don't see how you will know which of the countless candidates is the correct."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-12T22:00:42.943",
"Id": "453514",
"Score": "0",
"body": "I got a mixed view on this. On one side, there absolutely are cases where you know how to limit the results. I already knew when writing the brute force-algorithm, that a dictionary attack would be far more efficient for the use case I was looking at. On the other side I did not want to limit my algorithm to some expected outcome, as there might be cases where I'd want to manually go over the results given by the algorithm. I see it like the comparison between RNA-seq and microarray; though you'd most commonly use the one, there are cases where you need to use the other."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-02T23:56:43.870",
"Id": "231759",
"ParentId": "231696",
"Score": "2"
}
},
{
"body": "<p>Here are a number of ideas that may help you improve your program.</p>\n\n<h2>Don't abuse <code>using namespace std</code></h2>\n\n<p>Putting <code>using namespace std</code> at the top of every program is <a href=\"http://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice\">a bad habit</a> that you'd do well to avoid. Know when to use it and when not to (as when writing include headers). In this particular case, I happen to think it's perfectly appropriate because it's a single short program that and not a header. Some people seem to think it should never be used under any circumstance, but my view is that it can be used as long as it is done responsibly and with full knowledge of the consequences. </p>\n\n<h2>Don't <code>#include <bits/stdc++.h></code></h2>\n\n<p>This is not a standard header and it is poor practice to include a <code>gcc</code> specific header in your program. See <a href=\"https://stackoverflow.com/Questions/31816095/Why-Should-I-Not-Include-Bits-Stdc-H.\">this question</a> for elaboration on why you should not do that.</p>\n\n<h2>Avoid the use of global variables</h2>\n\n<p>My rewrite of this code uses no global variables, so clearly they are neither faster nor necessary. Eliminating them allows your code to be more readable and maintainable, both of which are important characteristics of well-written code. Global variables introduce messy linkages that are difficult to spot and error prone.</p>\n\n<h2>Use <code>iostreams</code></h2>\n\n<p>Using both <code>iostreams</code> and <code>cstdio</code> functions is not really helpful. It's easy enough and usually cleaner to use only <code>iostreams</code> in modern C++ programs.</p>\n\n<h2>Use <code>constexpr</code> where appropriate</h2>\n\n<p>In this program, the values of <code>first</code>, <code>last</code>, <code>characters</code> and <code>hashval</code> are never altered, so we can easily enable some compiler optimizations by declaring them all <code>constexpr</code>. </p>\n\n<h2>Use a class</h2>\n\n<p>C++ is an object oriented language, and it seems natural for this problem to use an object to represent an array with the given number of characters. I implemented such a thing and the class header looks like this:</p>\n\n<pre><code>#ifndef REVERSE_HASHER2_H\n#define REVERSE_HASHER2_H\n#include <iostream>\n#include <string>\n\nclass ReverseHasher {\npublic:\n explicit ReverseHasher(char first, char last, char len, int hashval); \n ReverseHasher& operator++();\n bool isMax() const { return !more; }\n friend std::ostream& operator<<(std::ostream& out, const ReverseHasher& fh);\nprivate:\n bool more{true};\n const char first;\n const char last;\n const char characters;\n std::string values;\n};\n\n#endif // REVERSE_HASHER2_H\n</code></pre>\n\n<p>As you can see, the constructor is given all of the relevant numbers and contains a single string of <code>values</code> (as per the original code) which contains the hashed string. I'll show a bit more of how this works a little later.</p>\n\n<h2>Use a better algorithm</h2>\n\n<p>The algorithm used here is much slower than it needs to be and there are several things we could do to speed things up. First, we can check that the hash is even possible by quickly calculating the minimum and maximum values for the given character range. If the desired hash is not within that range, there are zero combinations and we're done in microseconds. Second, we can easily calculate a value that satisfies the hash value. </p>\n\n<p>For instance, let's say there are <span class=\"math-container\">\\$n = 10\\$</span> characters and the values range from <span class=\"math-container\">\\$a = 0\\$</span> to <span class=\"math-container\">\\$b = 9\\$</span> inclusive. It's easy to understand that the minimum hash value is <span class=\"math-container\">\\$x_{\\text{min}} = n * a = 10 * 0 = 0\\$</span> and the maximum value would be <span class=\"math-container\">\\$x_\\text{max} = n * b = 10 * 9 = 90\\$</span>. For any hash value <span class=\"math-container\">\\$x\\$</span> in that range, we could simply fill <span class=\"math-container\">\\$\\lfloor \\frac{x}{b-a} \\rfloor\\$</span> characters with <span class=\"math-container\">\\$b\\$</span> and fill one character with the remainder of that division (if any) and the rest with the minimum value <span class=\"math-container\">\\$a\\$</span>. We can embody all of that in a constructor for the class shown above: </p>\n\n<pre><code>ReverseHasher::ReverseHasher(char first, char last, char len, int hashval) : \n first{first}, last{last}, characters{len}, values(characters, first) \n{\n const int minval{characters * first};\n const int maxval{characters * last};\n const int range{last - first};\n if (hashval < minval) {\n throw std::domain_error(\"hashvalue too low; no combinations possible\\n\");\n }\n if (hashval > maxval) {\n throw std::domain_error(\"hashvalue too high; no combinations possible\\n\");\n }\n hashval -= minval;\n std::generate(values.rbegin(), values.rend(), [&hashval,first,range](){\n auto digitval = std::min(hashval, range);\n hashval -= digitval;\n return first + digitval;\n });\n}\n</code></pre>\n\n<p>The effect is that this code either creates a sequence with the given <code>hashval</code> or if that's not possible, it <code>throw</code>s an exception to indicate what's wrong. </p>\n\n<h2>Increment intelligently</h2>\n\n<p>Rather than simply incrementing values and hoping to eventually encounter a string with the same sum, we can be a lot smarter about incrementing so that we <em>only</em> have valid values. Conceptually this is not hard. If we have, for instance a string of three digits, 0-9 that must sum to 11, by the previous point, we can easily come up with a valid value <code>029</code> that sums to that value. It would be nice if we increment so that the values are in numeric sequence; that is, if the values come out already sorted. So in this case, the next value would be <code>038</code>. If you work through this particular example, you'll see that the next values are <code>047</code>, <code>056</code>, <code>065</code>, <code>074</code>, <code>083</code> and <code>092</code>. The pattern is that we subtract one from the lowest digit and add one to the next digit. If we always subtract and add the same amounts, it's obvious we will always maintain a valid value. The algorithm is a bit tricky, but here's how it can be implemented in C++:</p>\n\n<pre><code>ReverseHasher& ReverseHasher::operator++() {\n // from the right, try +1, -1 until it works\n auto it{values.rbegin()};\n auto end{values.rend()};\n auto movable{0};\n for (auto prev{it++}; it != end; ++it) {\n if (*it != last && *prev != first) {\n ++(*it);\n --(*prev);\n if (movable != 0) { //propagate to the right\n auto debt{movable};\n while (movable && prev != values.rbegin()) {\n auto delta{std::min(*prev - first, movable)};\n *prev -= delta;\n movable -= delta;\n --prev;\n }\n debt -= movable;\n for (auto ptr{values.rbegin()}; debt; ++ptr) {\n auto delta{std::min(last - *ptr, debt)};\n *ptr += delta;\n debt -= delta;\n }\n }\n return *this;\n }\n movable += last - *prev;\n prev = it;\n }\n more = false;\n return *this;\n}\n</code></pre>\n\n<p>Essentially what this does it to keep trying to do the <span class=\"math-container\">\\$+1, -1\\$</span> on consecutive digits, sliding to the left until it's possible to do that. But there's another step needed to make sure everything comes out in order. If we consider that the next step after <code>092</code> in the previous example would be <code>182</code> if we just did the increment in that way. That's a valid value, but in fact, the next one <em>in sorted order</em> would instead be <code>128</code> so we need to do a little adjustment. Essentially, as we're looking for a value to increment, each value to the right of that which isn't at the maximum value (<code>last</code> in the code) represents a lower value (numerically sorted). The code above keeps track of the sum of those residual values in the variable <code>movable</code> and then essentially redistributes that value over the next digits after the incremented one such that the largest digits are to the right and the lowest numbers are to the left, thus insuring that the terms are created in ascending order.</p>\n\n<h2>Putting it all together</h2>\n\n<p>Here's a <code>main</code> function that uses this:</p>\n\n<h3>main.cpp</h3>\n\n<pre><code>#include <iostream>\n#include <chrono>\n#include \"ReverseHasher2.h\"\n\nint main() {\n using namespace std;\n using namespace std::chrono;\n auto start = high_resolution_clock::now();\n ios_base::sync_with_stdio(false);\n cerr.imbue(locale(\"\")); // get pretty local formatting for numeric values\n int count{0};\n for (ReverseHasher fh(32, 32+5, 13, 450); !fh.isMax(); ++fh) {\n ++count;\n std::cout << fh << '\\n';\n }\n auto stop = high_resolution_clock::now();\n auto duration = duration_cast<milliseconds>(stop - start);\n cerr << \"Found \" << count << \" solutions in \" << double(duration.count()/1000.0) << \" seconds.\\r\\n\";\n}\n</code></pre>\n\n<p>Here's the full header file:</p>\n\n<h3>ReverseHasher2.h</h3>\n\n<pre><code>#ifndef REVERSE_HASHER2_H\n#define REVERSE_HASHER2_H\n#include <iostream>\n#include <string>\n\nclass ReverseHasher {\npublic:\n explicit ReverseHasher(char first, char last, char len, int hashval); \n ReverseHasher& operator++();\n bool isMax() const { return !more; }\n friend std::ostream& operator<<(std::ostream& out, const ReverseHasher& fh);\nprivate:\n bool more{true};\n const char first;\n const char last;\n const char characters;\n std::string values;\n};\n\n#endif // REVERSE_HASHER2_H\n</code></pre>\n\n<p>And finally the full implementation of this, as mostly already listed above:</p>\n\n<h3>ReverseHasher2.cpp</h3>\n\n<pre><code>#include \"ReverseHasher2.h\"\n#include <iostream>\n#include <iterator>\n#include <algorithm>\n#include <string>\n\nReverseHasher::ReverseHasher(char first, char last, char len, int hashval) : \n first{first}, last{last}, characters{len}, values(characters, first) \n{\n const int minval{characters * first};\n const int maxval{characters * last};\n const int range{last - first};\n if (hashval < minval) {\n throw std::domain_error(\"hashvalue too low; no combinations possible\\n\");\n }\n if (hashval > maxval) {\n throw std::domain_error(\"hashvalue too high; no combinations possible\\n\");\n }\n hashval -= minval;\n std::generate(values.rbegin(), values.rend(), [&hashval,first,range](){\n auto digitval = std::min(hashval, range);\n hashval -= digitval;\n return first + digitval;\n });\n}\n\nReverseHasher& ReverseHasher::operator++() {\n // from the right, try +1, -1 until it works\n auto it{values.rbegin()};\n auto end{values.rend()};\n auto movable{0};\n for (auto prev{it++}; it != end; ++it) {\n if (*it != last && *prev != first) {\n ++(*it);\n --(*prev);\n if (movable != 0) { //propagate to the right\n auto debt{movable};\n while (movable && prev != values.rbegin()) {\n auto delta{std::min(*prev - first, movable)};\n *prev -= delta;\n movable -= delta;\n --prev;\n }\n debt -= movable;\n for (auto ptr{values.rbegin()}; debt; ++ptr) {\n auto delta{std::min(last - *ptr, debt)};\n *ptr += delta;\n debt -= delta;\n }\n }\n return *this;\n }\n movable += last - *prev;\n prev = it;\n }\n more = false;\n return *this;\n}\n\nstd::ostream& operator<<(std::ostream& out, const ReverseHasher& fh) {\n return out << fh.values;\n}\n</code></pre>\n\n<h2>Results</h2>\n\n<p>I noticed this in one of the comments:</p>\n\n<blockquote>\n <p>the outcome for parameters characters = 13, last = first+5, hashval = 450 was: 9 minutes runtime</p>\n</blockquote>\n\n<p>I wrote a streamlined and simplified version using the same algorithm as your original and got this result:</p>\n\n<blockquote>\n <p>Found 812,525,155 solutions in 257.426 seconds.</p>\n</blockquote>\n\n<p>I piped the result to <code>/dev/null</code> (I'm running this on a 64-bit Linux machine) because I didn't really want to waste drive space on the resulting >10GiB file. That's over 4 minutes.</p>\n\n<p>With the code posted above, I got this result:</p>\n\n<blockquote>\n <p>Found 812,525,155 solutions in 31.458 seconds.</p>\n</blockquote>\n\n<p>In other words, it's over eight times faster.</p>\n\n<h2>Going further</h2>\n\n<p>There are still enhancements that could be done, such as doing parallel processing, but they are not likely to buy much overall performance because the I/O is likely to be the bottleneck at this point. It's an interesting intellectual puzzle, but you probably don't really need a 10GiB file on your computer either, so it may be worth pondering in more detail what you're really trying to do, especially since this represents only a very tiny subset of the range your code was originally using. Some benchmarking and estimation of how many solutions there might be and how much space they'll require is likely to be useful in determining whether or not it's even worthwhile writing a program to do this.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-12T21:55:38.817",
"Id": "453511",
"Score": "0",
"body": "Thanks <3 I learned a lot from your answer. The question is more of curiosity and has no explicit usage at the moment. All I wanted was writing a general brute force algorithm which I can adjust for specific use cases. I will take a closer look at your code and might come back to that. I am still new to C++, so I will take this as an opportunity, too, to improve my C++ coding skills."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-12T21:57:27.547",
"Id": "453512",
"Score": "2",
"body": "It was fun thinking about the problem. Thanks for asking an interesting question!"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-04T02:47:40.123",
"Id": "231809",
"ParentId": "231696",
"Score": "9"
}
}
] |
{
"AcceptedAnswerId": "231809",
"CommentCount": "9",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-01T19:22:30.767",
"Id": "231696",
"Score": "12",
"Tags": [
"c++",
"performance",
"algorithm",
"recursion",
"io"
],
"Title": "Brute-Force algorithm in C++"
}
|
231696
|
<p>I'm asked to print the sentences from the corpus containing the word(s) with the greatest number of distinct tags. I already got the top 6 words with most distinct tags (5 tags). My questions are:</p>
<ol>
<li>I don't know how to get the words without using "len(cfd[key])>4"? Because I've tried using max() function but it doesn't work.</li>
<li>I want to print the sentences that include these words. But it prints all sentences that include the non-exact words. For example, I just want to print sentences included only EXACT word: "round", but the code also print the sentences that included "around" (because "round" is part of "around"). What do I have to add? </li>
</ol>
<p>This is my code:</p>
<pre><code>import nltk
from nltk.probability import FreqDist
from nltk.probability import ConditionalFreqDist
from nltk.corpus import*
from nltk.book import*
from nltk.tag import pos_tag
from nltk.tokenize import word_tokenize
import string
import re
cfd = nltk.ConditionalFreqDist((word,tag) for (word, tag) in
brown.tagged_words(tagset='universal'))
homographs = [(key, len(cfd[key])) for key in cfd.keys() if len(cfd[key])>4]
words = [key for key in cfd.keys() if len(cfd[key])>4]
print("Word(s) with the greatest number of distinct tags:", homographs)
print("List of sentences containing the word: ")
txt = brown.sents()
for sentence in txt:
if list(set(words) & set(sentence)):
result = "".join([" "+i if not i.startswith("'") and i not in string.punctuation else i for i in sentence]).strip()
print(result)
</code></pre>
<p>Anyone can help me, how to solve these problems? Thank you for your effort.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-02T00:04:26.457",
"Id": "452080",
"Score": "1",
"body": "Welcome to code review where we review working code and provide suggestions on how the code can be improved. Unfortunately this question is off-topic because the code isn't working."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-02T01:17:32.750",
"Id": "452083",
"Score": "0",
"body": "@pacmaninbw thank you, I already edited and improved some code. Please take a look :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-04T08:44:03.580",
"Id": "452301",
"Score": "0",
"body": "The code still doesn't work according to specification, does it? Feel free to come back once it does."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-04T15:14:26.080",
"Id": "452363",
"Score": "0",
"body": "thank you, I forgot to add the last line into the loop. I hope now it's working @Mast"
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-01T20:01:43.800",
"Id": "231699",
"Score": "1",
"Tags": [
"python"
],
"Title": "Python print the sentences from the corpus containing the word"
}
|
231699
|
<blockquote>
<p>Original inspiration was by this Python beginner, and it prompted me to rewrite a bunch of stuff with my flair and my Python experience: <a href="https://codereview.stackexchange.com/questions/231695/first-attempt-python-rock-paper-scissors">First attempt: Python Rock Paper Scissors</a></p>
</blockquote>
<p>Okay, so I looked at the aforementioned post, and was <strong>bored</strong> and needed to kill an hour at work. So I killed an hour - I took their RPS game and turned it into a class, and made it look less evil/ugly.</p>
<p>While this is by no means a fully-fledged program that I've cleanly created and really thoroughly tested, this <em>is</em> something that I can at least ask for input on.</p>
<p>Runs pretty cleanly, and uses a lot of strings that the OP of the original inspiration post had. But, it has a lot of docstrings, too. And the entire game resides in a class, and calls via the class and such.</p>
<p><strong>Because this version uses f-strings, you must have Python 3.6 or newer to use this program/code.</strong></p>
<p><code>rps.py</code>:</p>
<pre><code>import random
class RockPaperScissors:
"""
Class to handle an instance of a Rock-Paper-Scissors game
with unlimited rounds.
"""
def __init__(self):
"""
Initialize the variables for the class
"""
self.wins = 0
self.losses = 0
self.ties = 0
self.options = {'rock': 0, 'paper': 1, 'scissors': 2}
def random_choice(self):
"""
Chooses a choice randomly from the keys in self.options.
:returns: String containing the choice of the computer.
"""
return random.choice(list(self.options.keys()))
def check_win(self, player, opponent):
"""
Check if the player wins or loses.
:param player: Numeric representation of player choice from self.options
:param opponent: Numeric representation of computer choice from self.options
:return: Nothing, but will print whether win or lose.
"""
result = (player - opponent) % 3
if result == 0:
self.ties += 1
print("The game is a tie! You are a most worthy opponent!")
elif result == 1:
self.wins += 1
print("You win! My honor demands a rematch!")
elif result == 2:
self.losses += 1
print("Haha, I am victorious! Dare you challenge me again?")
def print_score(self):
"""
Prints a string reflecting the current player score.
:return: Nothing, just prints current score.
"""
print(f"You have {self.wins} wins, {self.losses} losses, and "
f"{self.ties} ties.")
def run_game(self):
"""
Plays a round of Rock-Paper-Scissors with the computer.
:return: Nothing
"""
while True:
userchoice = input("Choices are 'rock', 'paper', or 'scissors'.\n"
"Which do you choose? ").lower()
if userchoice not in self.options.keys():
print("Invalid input, try again!")
else:
break
opponent_choice = self.random_choice()
print(f"You've picked {userchoice}, and I picked {opponent_choice}.")
self.check_win(self.options[userchoice], self.options[opponent_choice])
if __name__ == "__main__":
game = RockPaperScissors()
while True:
game.run_game()
game.print_score()
while True:
continue_prompt = input('\nDo you wish to play again? (y/n): ').lower()
if continue_prompt == 'n':
print("You are weak!")
exit()
elif continue_prompt == 'y':
break
else:
print("Invalid input!\n")
continue
</code></pre>
<p>Any suggestions and input are welcome, as this is a rough attempt. :)</p>
|
[] |
[
{
"body": "<p>I think it makes sense to use dictionaries to store values for win/tie/loss:</p>\n\n<pre><code> def __init__(self):\n \"\"\"\n Initialize the variables for the class\n \"\"\"\n self.options = {'rock': 0, 'paper': 1, 'scissors': 2}\n self.outcome_count = {\n \"tie\": 0,\n \"win\": 0,\n \"loss\": 0,\n }\n</code></pre>\n\n<p>This makes <code>check_win</code> a bit more \"mechanical\" since you can now refer to the outcomes by name and by looking things up in static data, instead of needing a bunch of if/else:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code> def check_win(self, player, opponent):\n \"\"\"\n Check if the player wins or loses.\n :param player: Numeric representation of player choice from self.options\n :param opponent: Numeric representation of computer choice from self.options\n :return: Nothing, but will print whether win or lose.\n \"\"\"\n\n result = [\"tie\", \"win\", \"loss\"][(player - opponent) % 3]\n\n self.outcome_count[result] += 1\n\n outcome_message = {\n \"tie\": \"The game is a tie! You are a most worthy opponent!\",\n \"win\": \"You win! My honor demands a rematch!\",\n \"loss\": \"Haha, I am victorious! Dare you challenge me again?\",\n }\n print(outcome_message[result])\n</code></pre>\n\n<p>though of course it ends up making <code>print_score</code> less self-explanatory:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code> def print_score(self):\n \"\"\"\n Prints a string reflecting the current player score.\n :return: Nothing, just prints current score.\n \"\"\"\n wins = self.outcome_count[\"win\"]\n losses = self.outcome_count[\"loss\"]\n ties = self.outcome_count[\"tie\"]\n print(f\"You have {wins} wins, {losses} losses, and {ties} ties.\")\n</code></pre>\n\n<p>Lastly, I think that the <code>run_game</code> loop can be made slightly clearer by writing instead</p>\n\n<pre class=\"lang-py prettyprint-override\"><code> while True:\n userchoice = input(\"Choices are 'rock', 'paper', or 'scissors'.\\nWhich do you choose? \").lower()\n if userchoice in self.options.keys():\n break\n print(\"Invalid input, try again!\")\n</code></pre>\n\n<p>I find an explicit \"early-exit\" with no <code>else</code> to be easier to follow [note that the condition is not inverted, which I think helps for clarity in this case] though this could be jarring if it's not conventional for the larger codebase.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-02T19:56:13.360",
"Id": "231750",
"ParentId": "231706",
"Score": "3"
}
},
{
"body": "<h1>Formatting & naming</h1>\n\n<ul>\n<li>According to PEP 8, <a href=\"https://www.python.org/dev/peps/pep-0008/#maximum-line-length\" rel=\"nofollow noreferrer\">all lines should be <= 79 characters</a>.</li>\n<li><code>userchoice</code> -> <code>user_choice</code> (given that you have <code>opponent_choice</code>)</li>\n<li><code>continue_prompt</code> -> <code>user_choice</code> (in the context of where it's being used, it's actually the user's choice/response to the continue prompt, not the continue prompt itself)</li>\n</ul>\n\n<h1>Documentation</h1>\n\n<p>The docstring for <code>random_choice</code> could be improved. Instead of repeating verbatim what is happening in the code (implementation), prefer documenting it in a way so the reader doesn't need to read the implementation to know what the method will do:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>def random_choice(self) -> str:\n \"\"\"\n Randomly chooses rock, paper, or scissors.\n :return: 'rock', 'paper', or 'scissors'\n \"\"\"\n</code></pre>\n\n<h1>Clean/normalize user input</h1>\n\n<p>It's good that you are already calling <code>lower()</code> on the user input, but you should also be calling <code>strip()</code> on it as well. Otherwise, a user choice with leading or trailing whitespace is treated as invalid input (e.g. ' rock' or 'rock ', ' y' or 'y ').</p>\n\n<h1>Efficiency</h1>\n\n<p>Each call to <code>random_choice</code> calls <code>list()</code> on the <code>self.options</code> dictionary, which is re-creating the same list of choices on each call. Consider only creating the list once in <code>__init__</code>:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>def __init__(self):\n ...\n self.options = {'rock': 0, 'paper': 1, 'scissors': 2}\n self.choices = list(self.options.keys())\n</code></pre>\n\n<p>Then we can use it in <code>random_choice</code>:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>def random_choice(self):\n return random.choice(self.choices)\n</code></pre>\n\n<p>And when validating user input for choosing 'rock', 'paper', or 'scissors':</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>if user_choice in self.choices:\n ...\n</code></pre>\n\n<h1>Class structure</h1>\n\n<p>Since your class is already handling interactive user input, I think the code where you prompt the user to play another round should live inside the class. Then anyone who wants to use your class to launch an interactive multi-round game of rock-paper-scissors need only do <code>game.run_game()</code>.</p>\n\n<p>For the same reason, the call to <code>print_score()</code> should be within the game coordination logic inside your class; a client of your class shouldn't need to call it directly.</p>\n\n<p>I think it would be easier to read if you extracted the interactive prompting and retrieval of user input into their own methods, e.g.</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>def player_choice(self) -> str:\n \"\"\"\n Prompts player for choice of rock, paper, or scissors.\n :return: 'rock', 'paper', or 'scissors'\n \"\"\"\n while True:\n user_choice = input(\"Choices are 'rock', 'paper', or 'scissors'.\\n\"\n \"Which do you choose? \").lower().strip()\n if user_choice in self.choices:\n return user_choice\n\n print(\"Invalid input, try again!\")\n</code></pre>\n\n<pre class=\"lang-py prettyprint-override\"><code>def player_wants_to_play_again(self) -> bool:\n \"\"\"\n Prompts player to play again.\n :return: True if the player wants to play again.\n \"\"\"\n prompt = \"\\nDo you wish to play again? (y/n): \"\n valid_choices = {'y', 'n'}\n while True:\n user_choice = input(prompt).lower().strip()\n if user_choice in valid_choices:\n return user_choice == 'y'\n\n print(\"Invalid input!\")\n</code></pre>\n\n<p>Then your main game methods could look something like this:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>def run_one_round(self):\n user_choice = self.player_choice()\n opponent_choice = self.random_choice()\n print(f\"You've picked {user_choice}, and I picked {opponent_choice}.\")\n self.check_win(self.options[user_choice],\n self.options[opponent_choice])\n self.print_score()\n\ndef run_game(self):\n while True:\n self.run_one_round()\n if not self.player_wants_to_play_again():\n print(\"You are weak!\")\n break\n</code></pre>\n\n<p>By structuring things like this, we no longer need to call <code>exit()</code> (which exits the Python interpreter) to break out of the main game loop. Note that it's generally considered bad form to use <code>exit()</code> for handling non-exceptional scenarios in your program flow, i.e. if it's possible to allow your program to terminate normally without having to resort to <code>exit()</code>, you should do that.</p>\n\n<h1>Bonus: Improving clarity with a custom <code>Enum</code></h1>\n\n<p>In the original program, the implicit contract is that the exact strings <code>rock</code>, <code>paper</code>, and <code>scissors</code> represent the choices each player can make, and are thus special. One can observe this by looking at the dictionary <code>self.options</code>, which has the above strings mapped to integers so we can compare them later on using modular arithmetic in <code>check_win</code>. This sounds like a case where having a custom <a href=\"https://docs.python.org/3/library/enum.html\" rel=\"nofollow noreferrer\"><code>enum.Enum</code></a> type might help make things more explicit.</p>\n\n<p>Let's define an <code>Enum</code> called <code>Choice</code> which can take one of three values: <code>ROCK</code>, <code>PAPER</code>, or <code>SCISSORS</code>. What's cool is that we can have <code>Choice</code> be responsible for all of the following:</p>\n\n<ul>\n<li>conversion from <code>str</code> to <code>Choice</code> (if the provided string cannot be converted, throw an exception)</li>\n<li>define a canonical string representation for each <code>Choice</code>, e.g. \"rock\", \"paper\", and \"scissors\" (conversion from <code>Choice</code> to <code>str</code>)</li>\n<li>make <code>Choice</code>s comparable, such that if you have two <code>Choice</code>s X and Y, you can compare them to determine which one would win</li>\n</ul>\n\n<p>The code:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>from enum import Enum\n\n\nclass Choice(Enum):\n ROCK = 0\n PAPER = 1\n SCISSORS = 2\n\n @classmethod\n def from_str(cls, s: str) -> \"Choice\":\n try:\n return {\n \"r\": cls.ROCK,\n \"rock\": cls.ROCK,\n \"p\": cls.PAPER,\n \"paper\": cls.PAPER,\n \"s\": cls.SCISSORS,\n \"scissors\": cls.SCISSORS\n }[s.strip().lower()]\n except KeyError:\n raise ValueError(f\"{s!r} is not a valid {cls.__name__}\")\n\n def __str__(self) -> str:\n return self.name.lower()\n\n def beats(self, other: \"Choice\") -> bool:\n return (self.value - other.value) % 3 == 1\n</code></pre>\n\n<p>Interactive session showing it in action:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>>>> list(Choice)\n[<Choice.ROCK: 0>, <Choice.PAPER: 1>, <Choice.SCISSORS: 2>]\n\n>>> Choice.from_str('rock')\n<Choice.ROCK: 0>\n\n>>> Choice.from_str('paper')\n<Choice.PAPER: 1>\n\n>>> Choice.from_str('scissors')\n<Choice.SCISSORS: 2>\n\n>>> print(Choice.ROCK)\nrock\n\n>>> print(Choice.PAPER)\npaper\n\n>>> print(Choice.SCISSORS)\nscissors\n\n>>> Choice.ROCK == Choice.ROCK\nTrue\n\n>>> Choice.ROCK.beats(Choice.SCISSORS)\nTrue\n\n>>> Choice.PAPER.beats(Choice.ROCK)\nTrue\n\n>>> Choice.SCISSORS.beats(Choice.PAPER)\nTrue\n</code></pre>\n\n<p>Let's use it in <code>RockPaperScissors</code> to see how it looks. Here's <code>__init__</code>:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>def __init__(self):\n self.wins = 0\n self.losses = 0\n self.ties = 0\n self.choices = list(Choice)\n</code></pre>\n\n<p>Now <code>random_choice</code> and <code>player_choice</code> both return a <code>Choice</code> instead of a <code>str</code>, making the type signatures of these methods much more expressive:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>def random_choice(self) -> Choice:\n return random.choice(self.choices)\n\ndef player_choice(self) -> Choice:\n prompt = (\"\\nChoices are 'rock', 'paper', or 'scissors'.\\n\"\n \"Which do you choose? \")\n while True:\n try:\n return Choice.from_str(input(prompt))\n except ValueError:\n print(\"Invalid input, try again!\")\n</code></pre>\n\n<p>When we were returning strings from the above two methods, it was necessary to clarify in the documentation that only one of three strings would be returned: 'rock', 'paper', or 'scissors'. With <code>Choice</code>, we no longer need to do that since all of that information is explicitly laid out in its definition.</p>\n\n<p>Similarly, <code>check_win</code> now takes in as parameters two <code>Choice</code>s instead of two <code>int</code>s. The code is practically self-documenting at this point:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>def check_win(self, player_choice: Choice, opponent_choice: Choice):\n if player_choice == opponent_choice:\n self.ties += 1\n print(\"The game is a tie! You are a most worthy opponent!\")\n elif player_choice.beats(opponent_choice):\n self.wins += 1\n print(\"You win! My honor demands a rematch!\")\n else:\n self.losses += 1\n print(\"Haha, I am victorious! Dare you challenge me again?\")\n</code></pre>\n\n<p>The full code using <code>Choice</code> can be found <a href=\"https://gist.github.com/AnotherTermina/7fd7650a4198b49d431e810fec839bef\" rel=\"nofollow noreferrer\">in this gist</a>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-03T04:17:10.010",
"Id": "452162",
"Score": "0",
"body": "Partially wrong on PEP8 - PEP8 allows <100 if the sole/exclusive maintainer/team maintaining it agrees. \"For code maintained exclusively or primarily by a team that can reach agreement on this issue, it is okay to increase the line length limit up to 99 characters, provided that comments and docstrings are still wrapped at 72 characters.\""
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-03T04:55:25.190",
"Id": "452164",
"Score": "0",
"body": "@ThomasWard I don't believe I am misrepresenting PEP8. My wording of \"should\" (and not \"must\") is consistent with PEP8's standard _recommendation_ of 79 characters or less for line length. It is also consistent with linters that check code against PEP8's style conventions, e.g. `pycodestyle` flags any lines longer than 79 characters by default. As a code reviewer, I see no issue in supplying the standard recommendation, given that I don't have any other context to base my review on. I also do not disagree that teams can have their own project-specific conventions -- and neither does PEP8."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-02T22:59:17.550",
"Id": "231757",
"ParentId": "231706",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-01T21:00:18.347",
"Id": "231706",
"Score": "6",
"Tags": [
"python",
"python-3.x",
"object-oriented",
"rock-paper-scissors",
"rags-to-riches"
],
"Title": "Python Rock-Paper-Scissors via a class to handle the game"
}
|
231706
|
<p>I have unstructured input-output data, f=f(x). I want to estimate the range of f as a function of x, given limited sampled. So, I tried to discretize the data use small bins in x to estimate the variance of f associated with that bin. After a lot of work, I cobbled together a working code. But, I'm sure there must be a better way. My results are very sensitive to the bin size. Please review my approach and let me know how it can be improved.</p>
<pre><code>from scipy.stats import binned_statistic
import matplotlib.pyplot as plt
import numpy as np
# Choose the number of bins
NBINS = 100
# define custom function for findin range
def myrangefunciton(arrA):
return(np.max(arrA) - np.min(arrA))
# set seed for reproducability, there is nothing special about this seed
np.random.seed(1)
# generate sample data
x = np.random.normal(3, 1, 1000)
f = np.random.normal(0, np.max([x, np.zeros(x.size)], 0))
# compute ranges of f across x
stats, binEdges, binNum = binned_statistic(x, f,
statistic=myrangefunciton, bins=100)
# scatter data
plt.scatter(x, f, s=0.5, label='Observed f(x) Data', c='k')
# transform the bin edges to centered x values
rangeX = binEdges[:-1] + (binEdges[1] - binEdges[0]) / 2.
# plot ranges to envelop the mean, which is 0.
plt.plot(rangeX, stats / 2, label='Estimated Range', c='blue')
plt.plot(rangeX, -1 * stats / 2, c='blue')
# complete summary plot
plt.title("%i bins" % NBINS)
plt.legend(prop={'size': 4})
plt.xlabel('x')
plt.savefig('rangeEx')
plt.clf()
</code></pre>
<p><a href="https://i.stack.imgur.com/C85ow.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/C85ow.png" alt="enter image description here"></a></p>
<p><a href="https://i.stack.imgur.com/L4LvY.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/L4LvY.png" alt="enter image description here"></a></p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-01T22:29:36.940",
"Id": "231709",
"Score": "2",
"Tags": [
"python",
"statistics",
"vectors",
"interval"
],
"Title": "Using python to estimate the range of unstructured data"
}
|
231709
|
<p>My lead developer has commented that the code I write is hard to understand and that I "overcomplicate things". I'm willing to accept this and improve but I'm not sure if this is genuinely the case or if his personal preferences are seeping into his judgement.</p>
<p>A red flag for me was the following situation: We're receiving database entries in the form of an array of dictionaries called <code>columns</code>. We then make HTML templating decisions based on their contents. Note that "special" types such as files or map coordinates are really text fields with an additional <code>type_[name]</code> array field for validation.</p>
<pre><code>columns = someDBData
for column in columns:
column_type = column['data_type']
isValid = Someclass.perform_some_validation(column_type) # returns a boolean
isCalendar = Someclass.is_calendar(column_type) # returns true if it's a time, datetime or datetime-local data type
isString = Someclass.is_string(column_type) # ditto but with text, mediumtext or varchar
isHidden = True if column['hidden'] != 0 else False
isReadOnly = True if (configuracion_open == "" and column['open_insert'] == 0) or (configuracion_open == "Editando_registro" and column['open_edit'] == 0) else False
isFile = True if column_type == "text" and column['type_file'] is True else False
isGeo = True if column_type == "text" and column['type_geo'] is True else False
isGeneric = True if isCalendar or isString and not isFile else False
# repeat for other validations and then do templating stuff
</code></pre>
<p>When reviewing my work, he claimed that using "long ternary operators such as these" would be confusing for other people maintaining the code in the future. It seems as if he'd prefer to use a more verbose if/elif/else structure for readability, even though giving the program unnecessary verticality will also result in a readability problem in the future, at least in my opinion. In summary, should I reserve ternary operators for short and simple validations?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-04T12:36:56.707",
"Id": "452338",
"Score": "0",
"body": "We don't review stub code, and this is stub code. So this will get closed unless you can put some real code here. Still, I am no Python expert, should you not write `isHidden = True if column['hidden'] != 0 else False` as `isHidden = (column['hidden'] != 0)` ? Beyond that, yes, long ternaries are a pain to understand."
}
] |
[
{
"body": "<p>I think there is nothing wrong with using boolean-valued expressions to compute boolean results, instead of <code>if</code>/<code>elif</code>/<code>else</code> statements. However, it is still important to write these expressions clearly. Most of your expressions can be simplified, and none of your expressions actually require using the ternary operator.</p>\n\n<p>If you write a ternary operator where the true-branch has the value <code>True</code> and the false-branch has the value <code>False</code>, then the ternary operator is superfluous.</p>\n\n<p>If the condition is a boolean already, such as <code>True if column['hidden'] != 0 else False</code>, then you can simply write <code>column['hidden'] != 0</code> as this will already be either <code>True</code> or <code>False</code> as required.</p>\n\n<p>If the condition is not necessarily a boolean, e.g. <code>True if my_list else False</code> (not from your example) where <code>my_list</code> is a list and the condition tests if it is non-empty, then you can simply write <code>bool(my_list)</code> to calculate the boolean result you want.</p>\n\n<p>When you have a condition like <code>isCalendar or isString and not isFile</code> which has both <code>and</code> and <code>or</code>, I recommend <em>always</em> using brackets to clarify the order of operations. Not everyone knows that <code>and</code> takes precedence over <code>or</code>, and even if they do know this, they may not know that <em>you</em> knew, and might trust the code less. Write <code>isCalendar or (isString and not isFile)</code> to make clear what this code does; or if you wanted it to be <code>(isCalendar or isString) and not isFile</code>, write that.</p>\n\n<p>The expression for <code>isReadOnly</code> is very long, so I suggest splitting this over multiple lines. If an expression is inside <code>(</code>parentheses<code>)</code>, then you can space it across multiple lines however you wish.</p>\n\n<p>By the way, <code>column['type_file'] is True</code> is redundant, assuming <code>column['type_file']</code> is always a boolean. If it's <code>True</code>, then <code>True is True</code> results in <code>True</code>, while <code>False is True</code> results in <code>False</code>; either way, the result is the same as the original value of <code>column['type_file']</code>. Imagine writing <code>x + 0</code> where <code>x</code> is a number; it won't change the result, so you might as well just write <code>x</code>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-02T00:15:15.047",
"Id": "231716",
"ParentId": "231712",
"Score": "4"
}
},
{
"body": "<p>You may proceed with ternary operators in your case, as the original intention might be applying <em>\"Replace nested conditional with guard classes\"</em> which is good and well-known refactoring technique.</p>\n\n<p>As was mentioned, the condition itself is evaluated to boolean/logical value, no need to duplicate the <em>\"evidence\"</em> like <code>var_name = True if True else False</code>.</p>\n\n<p>Additionally, the condition <code>column_type == \"text\"</code> is duplicated and can be consolidated/extracted into a separate flag <code>isTextType</code>:</p>\n\n<pre><code>for column in columns:\n column_type = column['data_type']\n isTextType = column_type == \"text\"\n isValid = Someclass.perform_some_validation(column_type) # returns a boolean\n isCalendar = Someclass.is_calendar(column_type) # returns true if it's a time, datetime or datetime-local data type\n isString = Someclass.is_string(column_type) # ditto but with text, mediumtext or varchar\n\n isHidden = column['hidden'] != 0\n isReadOnly = (configuracion_open == \"\" and not column['open_insert']) \\\n or (configuracion_open == \"Editando_registro\" and not column['open_edit'])\n isFile = isTextType and column['type_file']\n isGeo = isTextType and column['type_geo']\n isGeneric = isCalendar or (isString and not isFile)\n</code></pre>\n\n<p>Furthermore, your validation logic goes within a <code>for</code> loop, but what if the program would need to validate a single column/record in some other place within application?<br>\nTo make it more unified and scalable it's better to extract the validation logic into a separate function applying <em>Extract function</em> technique.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-02T10:11:20.063",
"Id": "231727",
"ParentId": "231712",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "231716",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-01T23:46:00.540",
"Id": "231712",
"Score": "3",
"Tags": [
"python"
],
"Title": "Legibility of code with ternary operators in Python"
}
|
231712
|
<p>For my first CodeReview, I would like to present my FizzBuzz solution in C#. My design has all of the rule logic about when to display what in separate classes through an interface. This design should be able to handle the common follow-up changes (ie. mod 7 instead of mod 3, bazz, etc.) for this problem by simply adding another rule to the game. Below is the problem statement.</p>
<p>And as I am not a professional developer, I am especially interested in additional feedback on style, formatting, and adherence to SOLID principles, as well as limitations of this design.</p>
<p><strong>Problem:</strong>
Write a short program that prints each number from 1 to 100 on a new line.
For each multiple of 3, print "Fizz" instead of the number.
For each multiple of 5, print "Buzz" instead of the number.
For numbers which are multiples of both 3 and 5, print "FizzBuzz" instead of the number.</p>
<p><strong>Solution:</strong></p>
<pre><code>class Program
{
static void Main(string[] args)
{
var rules = new List<IRule>
{
new FizzMod3Rule(),
new BuzzMod5Rule(),
new BazzMod7Rule()
};
new FizzBuzzGame(rules).Play();
Console.ReadKey();
}
}
public class FizzBuzzGame
{
private List<IRule> _rules;
public FizzBuzzGame(List<IRule> rules)
{
_rules = rules ?? new List<IRule>();
}
public void Play(int numberOfRounds = 100)
{
for (var i = 1; i <= numberOfRounds; i++)
{
var output = string.Empty;
foreach (var rule in _rules) { output += rule.Run(i); }
if (output == string.Empty) { output += new EmptyRule().Run(i); }
Console.WriteLine(output);
}
}
}
public interface IRule
{
string Run(double number);
}
public class FizzMod3Rule : IRule
{
public string Run(double number)
{
return (number % 3) == 0 ? "Fizz" : string.Empty;
}
}
public class BuzzMod5Rule : IRule
{
public string Run(double number)
{
return (number % 5) == 0 ? "Buzz" : string.Empty;
}
}
public class BazzMod7Rule : IRule
{
public string Run(double number)
{
return (number % 7) == 0 ? "Bazz" : string.Empty;
}
}
public class EmptyRule : IRule
{
public string Run(double number)
{
return number.ToString();
}
}
</code></pre>
<p><strong>Output:</strong></p>
<pre><code>1
2
Fizz
4
Buzz
Fizz
Bazz
8
Fizz
Buzz
11
Fizz
13
Bazz
FizzBuzz
16
17
Fizz
19
Buzz
FizzBazz
...
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-02T01:58:18.753",
"Id": "452085",
"Score": "2",
"body": "That's a well written first question!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-02T07:56:30.710",
"Id": "452100",
"Score": "0",
"body": "Using the `EmptyRule` class just to append a number to an empty string is an overkill. You should simply do `output = i.toString()`"
}
] |
[
{
"body": "<p>The intention of classes in object oriented programming is not to replace <code>if</code> sentences, but to model code that differs in behavior. Your 4 classes can be merged into 2, since the first 3 of them use structurally identical code. The code could then be:</p>\n\n<pre><code>var rules = new List<IRule>\n{\n new ModWordRule(3, \"Fizz\"),\n new ModWordRule(5, \"Buzz\"),\n new ModWordRule(7, \"Bazz\")\n};\n</code></pre>\n\n<hr>\n\n<p>On second sight, your code completely misses the point of the task. The task says:</p>\n\n<blockquote>\n <p>Write a short program.</p>\n</blockquote>\n\n<p>Your program has 74 lines, and I'm not even counting the <code>using</code> declarations that you omitted at the top of the file. You should not omit these when you post your code for code review.</p>\n\n<p>I just wrote the same program in 20 lines, without all the \"object oriented\" boilerplate. It is easier readable, and equally easy to extend to more rules.</p>\n\n<p>I don't see any point in adding so many interfaces and classes if the problem can be solved in a few lines of code, especially if the simple code is easily testable.</p>\n\n<p>The argument of \"don't modify the existing classes when adding features\" is moot here since adding a \"7 Bazz\" rule obviously has to modify the output, and that output has to be assembled by some class. In the FizzBuzz example the code is still simple enough to go into a single function instead of spreading it over 4 classes.</p>\n\n<p>The task does not mention the <code>ReadKey</code> anywhere, therefore you should omit it.</p>\n\n<p>The task says to output \"7\" for the number 7, your program outputs \"Bazz\". This latter word is mentioned nowhere in the task.</p>\n\n<p>When dealing with collections of things, it is a common assumption that these collections are never <code>null</code>. Therefore there's no need to check for that condition in the <code>FizzBuzzGame</code> constructor. Just let the program crash in such a case. It's a serious programming mistake, and it must be fixed. Your current code only <em>hides</em> the bug.</p>\n\n<p>As I said above, I prefer code that is to the point, while still testable. Such as the following:</p>\n\n<pre><code>using System;\n\nnamespace FizzBuzz231713\n{\n class Program\n {\n static object FizzBuzz(int n)\n {\n var fizz = n % 3 == 0 ? \"Fizz\" : \"\";\n var buzz = n % 5 == 0 ? \"Buzz\" : \"\";\n var word = fizz + buzz;\n return word != \"\" ? word : (object)n;\n }\n\n static void Main()\n {\n for (int i = 0; i < 100; i++)\n Console.WriteLine(FizzBuzz(i + 1));\n }\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-02T15:15:55.307",
"Id": "452121",
"Score": "0",
"body": "Not wishing to take anything any from the point of this answer, I'd take issue with _\" It is [..] equally easy to extend to more rules.\"_ since it requires recompiling `FizzBuzz`, which would seem to be the point of the OP's efforts, regardless of the __problem__ section."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-02T17:19:05.417",
"Id": "452132",
"Score": "1",
"body": "@VisualMelon In the OP's code adding another rule would require adding a class and recompiling both the added class and `Main`. How is that an improvement?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-02T17:33:32.977",
"Id": "452135",
"Score": "0",
"body": "The code could be used from another assembly, and new rules provided without recompiling the assembly containing `FizzBuzzGame`... but yeah, the spec is asking for a program and not a library, so I'm looking at this the wrong way."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-04T19:35:15.627",
"Id": "452422",
"Score": "0",
"body": "@RolandIllig Thanks for the good feedback! I don't wish to spark another \"overkill OO\" discussion. This may not be the best candidate for OOP. But from what I have read on other \"interview questions\" here, interviewers not only look for the ability to write an algorithm, but that one has considered future changes and understands OO principles. And I interpret the Open/Closed principle to not apply to the `Main` method, just the `FizzBuzzGame` class and the `IRule` classes. Otherwise, you couldn't modify anything."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-05T20:19:24.663",
"Id": "452575",
"Score": "0",
"body": "*interpret Open/Closed principle to not apply to the `Main`* O/C is not a \"don't touch this\" on/off switch. And it is absolutely not an absolute dictate. Rather, it is a question: \"Why do I have to modify this class?\" or \"Why so often?\" There are good reasons, but not here. The top level of `FizzBuzz` is not in the `FizzBuzz` class. `FizzBuzz` is not reusable because the top level of it must be rewritten every time - let's say this is the practical perspective of the Single Responsibility Principle. `Main` should only ever start the program."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-02T05:18:37.573",
"Id": "231719",
"ParentId": "231713",
"Score": "7"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-01T23:49:40.933",
"Id": "231713",
"Score": "8",
"Tags": [
"c#",
"programming-challenge",
"interview-questions",
"fizzbuzz"
],
"Title": "FizzBuzz in Csharp"
}
|
231713
|
<p>Leaflet is an open-source JavaScript library used to generate mobile-friendly interactive maps. For more information go to <a href="https://leafletjs.com" rel="nofollow noreferrer">leafletjs.com</a> as well as <a href="https://github.com/Leaflet/Leaflet" rel="nofollow noreferrer">the Github page for Leaflet</a>.</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-01T23:59:53.633",
"Id": "231714",
"Score": "0",
"Tags": null,
"Title": null
}
|
231714
|
Leaflet is an open-source JavaScript library used to generate mobile-friendly interactive maps.
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-01T23:59:53.633",
"Id": "231715",
"Score": "0",
"Tags": null,
"Title": null
}
|
231715
|
<p>I've seen a few TTT related posts recently, and thought I might learn something or be reminded of certain techniques from attempting my own rendition. Here is that attempt! Hopefully any new coders can benefit from this as well. Any improvement suggestions are welcome, and <code>numpy</code>, <code>scipy</code> & bitwise operations are open to aid optimization.</p>
<p><strong>ttt.py</strong></p>
<pre class="lang-py prettyprint-override"><code>import numpy as np
from random import randint
def print_board(board):
print("""
+---+---+---+
c | {} {} {} |
+ + + +
b | {} {} {} |
+ + + +
a | {} {} {} |
+---+---+---+
1 2 3
""".format(*list(x if x != '0' else ' ' for x in board)))
def check_for_win(board):
def check_diagonal(dia):
return '0' not in dia and len(set(dia)) == 1
a = np.array(board).reshape(3, 3)
# check lr diagonal
if check_diagonal(a.diagonal()):
return True
# check rl diagonal
if check_diagonal(np.fliplr(a).diagonal()):
return True
# check rows & cols
for matr in [a, np.transpose(a)]:
for row in matr:
if '0' not in row and len(set(row)) == 1:
return True
return False
if __name__ == "__main__":
board = ['0'] * 9
codes = ('c1', 'c2', 'c3', 'b1', 'b2', 'b3', 'a1', 'a2', 'a3')
turn, user = 1, 'X' if bool(randint(0, 1)) else 'O'
print('Welcome! First to play is %s!' % user)
print_board(board)
while True:
print('Player %s: ' % user)
code = input().strip().lower()
if code in codes:
idx = codes.index(code)
board[idx] = user
print_board(board)
if turn >= 5:
if '0' not in board:
print("Aw, it's a draw!")
exit()
elif check_for_win(board):
print('%s won in %d turns! Congratulations!' % (user, turn))
exit()
user = 'X' if user == 'O' else 'O'
turn = turn + 1
else:
print("Hmm, that's not a valid input.")
</code></pre>
|
[] |
[
{
"body": "<h2>Input Validation</h2>\n\n<p>You aren’t completely validating input</p>\n\n<ul>\n<li>X: a1</li>\n<li>O: b2</li>\n<li>X: a2</li>\n<li>O: a3 (block)</li>\n<li>X: a3 <strong>For the Win!?</strong></li>\n</ul>\n\n<h2>Invalid Win/Draw Detection Logic:</h2>\n\n<pre><code>X O X\nO O\nX O X\n</code></pre>\n\n<p>Last move in centre: “Aw, it’s a draw!”??? </p>\n\n<h2><code>exit()</code></h2>\n\n<p>This is a bad function to use. It exits the Python interpreter. Unconditionally. Period. </p>\n\n<p>When you want to change your code to play repeated games, run unit tests, etc., you won’t be able to. Nothing will execute after <code>exit()</code>.</p>\n\n<p>Better would be to move the code into a function, and simply <code>return</code> to force an exit of the current local context, instead of an exit of the entire interpreter. </p>\n\n<h2>f-strings</h2>\n\n<p>You are using <code>{}</code> and <code>.format()</code> in <code>print_board</code>, and using <code>%s</code> and <code>%d</code> in <code>\"...\" % (...)</code> expressions. Usually, you should try to avoid mixing formatting methods. Both are awkward to use, as the value and the place the value goes are far apart in the code. Avoid using the <code>%</code> style.</p>\n\n<p>Additionally, instead of:</p>\n\n<pre><code>print('%s won in %d turns! Congratulations!' % (user, turn))\n</code></pre>\n\n<p>using an f-string moves the variables inside the format string:</p>\n\n<pre><code>print(f'{user} won in {turn} turns! Congratulations!')\n</code></pre>\n\n<p>(I’d leave the <code>print_board</code> function alone, but in other print formatting, f-strings are a win. )</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-02T20:47:09.097",
"Id": "452148",
"Score": "0",
"body": "The mention of f-strings is certainly a good reminder! I've fixed the input validation & win detection bugs now; ty for isolating the edgiest of cases. B/c this is a loop in the main program and I need some variables to persist, I've opted to go for `break` over `exit()`, which should be more clean."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-03T01:09:13.847",
"Id": "452155",
"Score": "0",
"body": "I appreciate the green checkmark, but Code Review is not a high volume site. You should leave your question open for more than 19 hours, in order to accumulate additional reviews. I’m sure there are more things to comment on in the code, but accepting an answer will typically discourage additional reviews."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-02T18:31:28.203",
"Id": "231744",
"ParentId": "231718",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "231744",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-02T05:06:15.413",
"Id": "231718",
"Score": "4",
"Tags": [
"python",
"python-3.x",
"numpy",
"tic-tac-toe"
],
"Title": "Back to Basics - Tic Tac Toe"
}
|
231718
|
<p>What's up smart people. A little backstory for context: I'm a completely self taught dev, and the only person ever looking at my code for the past 6 years is myself. I realize that's not the best idea moving forward, since I now know that this is what I love doing, and what I want to make a career out of. I'd like to fill in the gaps in my knowledge, and become a well rounded developer.</p>
<p>So, I developed this project template over the years, and recently I updated it to be a class by default. The reasoning is that I think classes are easier to work with, since it's easier to reference variables if I just make them part of the class.</p>
<p>I should note that there are some general functions in my toolset I've developed that are called in this template. I think it should be clear what they do.</p>
<p>I also use three modules by default that are not my own, which are simple-settings, logzero, and consolemenu. I have not integrated testing into this yet, because I'm behind in that particular area, but I plan to do so asap.</p>
<p>My questions are:</p>
<ol>
<li><p>Is this the right way of thinking for a class?</p></li>
<li><p>Should I have one template for a class, one for a non-class project, such as for simple scripts? If so, what are some examples that I might use for each?</p></li>
<li><p>I'm big on simplifying for optimization, quick development, easy bug fixing, and readability. What could I simplify or change to improve those things? </p></li>
<li><p>Are there are tools, modules, or strategies that I could be using to make development quicker, easier, more readable, etc?</p></li>
<li><p>It seems like it's time to make the switch to python 3, but I'm afraid I'll lose too many modules I use in my projects. I'm worried that in any given project, I might end up with a mix of python 2 AND 3 modules that I need to use, such as a module that hasn't ported to 3, or never will (I think most have, but I'm not sure). Is all this true? Should I make the switch, obviously starting with this template?</p></li>
<li><p>I tend to grab and save modules I use often for safe keeping, as I'm sortof a content hoarder, a bit afraid something might vanish never to be seen again if I need it in the future. Is this a good practice for very general modules like the settings, logging, and console menu modules I use?</p></li>
<li><p>I've recently started being more formal about logging, and good logging practices, and it makes debugging much easy. I know that it's also good practice to code testing in as I go as well, but testing evades me <em>still</em>. I remember that I seem to run into problems importing my chunks of code when using a class. I believe this is because I have a hard time knowing how it would work in my own code, or something about classes that makes it a bit more complex than I know what to do with. I'd like to go as simple and foolproof as possible here, as with everything, so a module that made things easier would be great.</p></li>
<li><p>Is my code/style messy and/or bloated?</p></li>
<li><p>Just curious, but based on this template, am I at a decent spot considering that I'm self taught, and have only programmed off and on over the last 6 years? Should I be farther along than I am? Or is this not enough to go on to make that judgement?</p></li>
<li><p>Any other thoughts, ideas, tips, tricks that would be of obvious help to improve the template and/or my general code based on what you see in this template?</p></li>
</ol>
<p>Thanks guys</p>
<pre><code>#! python2.7
# -*- coding: utf-8 -*-
import sys, os, traceback
sys.path.insert(0, 'B:\path-to-tools\PyTools')
from tools import *
## In tools.py: sys.path.insert(0, os.path.realpath(__file__))
"""
Template v4
This is a class template for python programs. It aims to be a simple yet robust python class to get up and running quickly.
Featuring a very helpful toolset for easy coding, it's also fully set up for logging and settings, as well as building default absolute paths.
"""
class Main(object):
def __init__(self):
print_startup_info()
self.pp = pprint.PrettyPrinter(indent=4)
## ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ##
## ~~~~~~~~~~ Settings ~~~~~~~~~~~ ##
## ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ##
self.settings_list = [
'global_settings',
'default_paths'
]
self.sett = load_settings(self.settings_list)
## After loading settings, check the directory structure for missing dirs, and fix
#self.check_directory_structure()
self.sett = build_abs_paths(self.sett)
self.finish_abs_paths()
## ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ##
## ~~~~~~~~~~ Logging ~~~~~~~~~~~ ##
## ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ##
self.handle_init_logging()
## ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ##
## ~~~~~~~~~~ Testing ~~~~~~~~~~~ ##
## ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ##
if self.sett.MAIN_TESTING:
self.l.info('''
__file__: {}
TEST MODE
LOGGER LEVEL: {}
OVERRIDE LOG LEVEL: {}'''.format(
__file__,
self.sett.MAIN_LOG_LVL,
self.sett.LOG_LVL_OVERRIDE))
## ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ##
## ~~~~~~~~~~ Load DB ~~~~~~~~~~~ ##
## ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ##
self.db = self.load_db()
## ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ##
## ~~~~~~~~~ Main Menu ~~~~~~~~~~ ##
## ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ##
self.main_menu()
def handle_init_logging(self):
self.l,self.LOG_LVL = init_logging(
self.sett.FNAME_LOG_MAIN,
self.sett.MAIN_LOG_LVL,
self.sett.LOG_LVL_OVERRIDE
)
self.l.info(
'''
## ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ##
## ~~~~~~~~ Init PROGRAM ~~~~~~~~ ##
## ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ##
''')
self.l.debug(
'Loaded {} Settings\n{}'.format(
self.__class__.__name__,
self.pp.pformat(sorted(
self.sett.as_dict()))))
#logzero.loglevel(self.LOG_LVL)
self.check_log_lvl()
def finish_abs_paths(self):
self.l.debug("Project Abs: {}".format(self.sett.PROJECT_ABS))
self.sett.APP_ABS = self.sett.PROJECT_ABS+__file__
self.sett.MAIN_LOG_ABS = self.sett.LOG_ABS + self.sett.FNAME_LOG_MAIN
self.sett.FIN_LOG_ABS = self.sett.LOG_ABS + self.sett.FNAME_LOG_FIN
def restart(self):
os.system(os.path.basename(__file__))
## ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ##
## ~~~~~~~~~ Database ~~~~~~~~~~ ##
## ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ##
def load_db(self):
self.l.info("Loading database...")
with open(self.sett.DB_ABS, 'r') as f:
db = json_easy_load(f.read())
self.l.debug(
"Database: \n\n{}".format(db))
return db
def check_log_lvl(self):
self.l.debug('Log Level: {}'.format(self.LOG_LVL))
## ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ##
## ~~~~~~~~ ** Main Menu ** ~~~~~~~~~ ##
## ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ##
def main_menu(self):
## Formatting usage not in docs. You have to look at class in consolemenu.menu_formatting.py
formatter = MenuFormatBuilder().set_bottom_margin(1).set_top_margin(1).set_right_margin(10).set_header_top_padding(2).set_header_left_padding(4).set_border_style_type(1)
menu = ConsoleMenu(
'Title',
'Main Menu',
formatter = formatter,
clear_screen = False
)
f_item = FunctionItem(
'Menu Option 1',
self.function_1,
args=[
"arg1"
]
)
restart = FunctionItem(
'Restart',
self.restart
)
menu.append_item(f_item)
menu.append_item(restart)
menu.start()
menu.join()
def sub_menu(self):
menu_items = ['Sub Menu Option 1']
menu = SelectionMenu(menu_items, 'Main Menu')
## Submenu
submenu = SelectionMenu(menu_items, 'Sub Menu')
submenu_item = SubmenuItem("Show a submenu", submenu, menu=menu)
menu.append_item(submenu_item)
menu.show()
selection = menu.selected_option
self.l.debug("Selection: {}".format(selection))
if selection == 0:
self.l.info("Selected Option 1")
self.function_2(
"arg1",
"arg2"
)
else:
self.l.info("\nNot Option 1\n"
if __name__ == '__main__':
try:
main = Main()
except:
log_traceback()
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-02T07:12:48.317",
"Id": "452096",
"Score": "1",
"body": "Welcome to Code Review! Unfortunately there are still modules that haven't been ported yet (and those tend to be too big to port yourself). For a definitive answer on that, you'd need a list and check them all."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-02T05:32:36.197",
"Id": "231720",
"Score": "5",
"Tags": [
"python",
"python-2.x",
"template"
],
"Title": "Python Project Template"
}
|
231720
|
<p><strong>Update: The code below has some obvious problems, and it is not allowed to revise code in the original question, so I have to post a new question, <a href="https://codereview.stackexchange.com/questions/231732/simple-shared-pointer-implementation-in-single-threaded-environment-revised">the revised code is here</a>.</strong></p>
<p><code>std::shared_ptr</code> has the potential problem that two pointer point to the same object but to different control blocks. And its atomic operation is pure overhead in a single threaded environment. So I wrote the following version to avoid these problems. This implementation also has the advantage that an empty pointer is the same size as a <code>void *</code>.</p>
<pre><code>template <typename T>
struct ThreadUnsafeSharedPtr {
private:
struct Pair {
T data;
size_t cnt;
template <typename ... Args>
Pair(Args && ... args): data(std::forward<Args>(args)...), cnt(1) {}
};
Pair *ptr;
public:
template <typename ... Args>
static ThreadUnsafeSharedPtr make(Args && ... args) {
ThreadUnsafeSharedPtr p;
p.ptr = new Pair(std::forward<Args>(args)...);
return p;
}
ThreadUnsafeSharedPtr() : ptr(nullptr) {}
ThreadUnsafeSharedPtr(const ThreadUnsafeSharedPtr & other) : ptr(other.ptr) {
if (ptr && &other != this) {
++(ptr->cnt);
}
}
ThreadUnsafeSharedPtr & operator=(const ThreadUnsafeSharedPtr & other) {
ptr = other.ptr;
if (ptr && &other != this) {
++(ptr->cnt);
}
return *this;
}
ThreadUnsafeSharedPtr(ThreadUnsafeSharedPtr && other) : ptr(other.ptr) {
if (&other != this) {
other.ptr = nullptr;
}
}
ThreadUnsafeSharedPtr & operator=(ThreadUnsafeSharedPtr && other) {
if (&other != this) {
ptr = other.ptr;
other.ptr = nullptr;
}
return *this;
}
~ThreadUnsafeSharedPtr() {
if (ptr) {
if(--ptr->cnt == 0) {
delete ptr;
}
}
}
};
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-02T12:10:49.433",
"Id": "452107",
"Score": "1",
"body": "Welcome to Code Review! I have reverted the changes which invalidates the answer. 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>Your implementation misses to implement pointer semantics in the form of an overloaded <code>operator->()</code> and <code>operator*()</code>.</p>\n\n<p>Isn't that the whole point of a <em>pointer</em> surrogate?</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-02T09:21:16.047",
"Id": "231726",
"ParentId": "231724",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "231726",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-02T09:03:57.337",
"Id": "231724",
"Score": "4",
"Tags": [
"c++",
"memory-management"
],
"Title": "simple shared pointer implementation in single threaded environment"
}
|
231724
|
<p>I have a scenario and I am not sure what possibly could be the effective way to filter hashmap and update the same map. Here is my hashmap; Map> mappedProducts = new HashMap<>(); I have put out the keys and values in mappedProducts in some method. Now in another method, I am trying to filter out the list of products based on if my key value is bigger than product's property weight. This is how I have done it, though it works perfectly fine but I am not sure if this is the most effective and efficient way to do it. Have a look at the following code;</p>
<pre><code> this.mappedProducts.entrySet().stream().filter(packList ->{
mappedProducts.put(packList.getKey(), packList.getValue().stream().filter(pack ->{
if(pack.getWeight() <= packList.getKey())
return true;
return false;
}).collect(Collectors.toList()));
return true;
}).collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
System.out.println("Filtered Products"+mappedProducts);
</code></pre>
<p>Is there any other better way to get this done?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-02T12:16:57.010",
"Id": "452108",
"Score": "0",
"body": "It would be much better if the entire class was provided for review, the question as it stands does not provide enough code to do a code review. The title is also off-topic because it does not indicate what the code does (why is there any filtering going on)?"
}
] |
[
{
"body": "<p>I haven’t a clue what your code is supposed to be doing — there isn’t enough context — but from what I can see, I can tell that the code is horrible.</p>\n\n<hr>\n\n<p>The code reads roughly:</p>\n\n<pre><code>this.mappedProducts.entrySet.stream().filter(...).collect(...);\nSystem.out.println(...);\n</code></pre>\n\n<p>The method <code>collect()</code> returns a collection, which is not being assigned to anything, so the result of the <code>.collect(...)</code> call is discarded.</p>\n\n<p>Why collect something when you are not going to keep it?</p>\n\n<hr>\n\n<p>The outer-most filter reads roughly:</p>\n\n<pre><code>packList -> {\n code_with_side_effects();\n return true;\n}\n</code></pre>\n\n<p>A filter which unconditionally returns <code>true</code> is not a filter.</p>\n\n<p>Filters should not have side-effects.</p>\n\n<hr>\n\n<p>The inner filter reads roughly:</p>\n\n<pre><code>pack -> {\n if (boolean_condition)\n return true;\n return false;\n}\n</code></pre>\n\n<p>This is excessively verbose. Your filter lambda could simply be:</p>\n\n<pre><code>pack -> boolean_condition\n</code></pre>\n\n<hr>\n\n<h2>Summary</h2>\n\n<ul>\n<li>Don’t <code>collect()</code> something you are not going to keep.</li>\n<li>Don’t write filters which don’t do any filtering</li>\n<li>Don’t put side effects in filters</li>\n<li>If you want to returns true if a boolean condition is true, and false otherwise, just return the boolean condition.</li>\n</ul>\n\n<hr>\n\n<p>I’d love to help you improve the code, but I can’t tell what it is actually supposed to be doing, so I can’t actually write anything meaningful. Please, add context.</p>\n\n<p>Technically, you can’t edit the question after an answer has been given to the question, but for all intents and purposes, this isn’t an answer. It is just a rant, and I’d love for it to be invalidated. I’d be more than happy to delete it and answer a proper question, and actually help you improve the code, instead of just pointing out how flawed and broken it is.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-03T04:49:28.417",
"Id": "231763",
"ParentId": "231729",
"Score": "2"
}
},
{
"body": "<p>The fact that Streams exist doesn't mean you should use them everywhere. Having streams inside streams is a sign that things have gone off the rails badly. Try doing this without streams and it'll be much easier to refactor it into maintainable code.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-03T06:40:38.787",
"Id": "231765",
"ParentId": "231729",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-02T11:12:29.600",
"Id": "231729",
"Score": "-1",
"Tags": [
"java"
],
"Title": "How to filter and update the hashmap in java 8 streams?"
}
|
231729
|
<p><code>std::shared_ptr</code> does not stop you from having the same resource managed by multiple control-blocks (and thus independent sets of shared-pointers), even though it is illegal and leads to double-deletes. Additionally, atomic reference-counts don't have any advantage in single-threaded environments but are still more expensive. Thus I wrote the following version to avoid these problems. </p>
<p>(This is a follow-up to: <a href="https://codereview.stackexchange.com/questions/231724/simple-shared-pointer-implementation-in-single-threaded-environment">simple shared pointer implementation in single threaded environment</a>)</p>
<pre><code>template <typename T>
struct ThreadUnsafeSharedPtr {
private:
struct Pair {
T data;
size_t cnt;
template <typename ... Args>
Pair(Args && ... args): data(std::forward<Args>(args)...), cnt(1) {}
};
Pair *ptr;
public:
template <typename ... Args>
static ThreadUnsafeSharedPtr make(Args && ... args) {
ThreadUnsafeSharedPtr p;
p.ptr = new Pair(std::forward<Args>(args)...);
return p;
}
ThreadUnsafeSharedPtr() : ptr(nullptr) {}
ThreadUnsafeSharedPtr(const ThreadUnsafeSharedPtr & other) : ptr(other.ptr) {
if (ptr && &other != this) {
++(ptr->cnt);
}
}
ThreadUnsafeSharedPtr & operator=(const ThreadUnsafeSharedPtr & other) {
if (ptr && &other != this) {
ptr = other.ptr;
++(ptr->cnt);
}
return *this;
}
ThreadUnsafeSharedPtr(ThreadUnsafeSharedPtr && other) : ptr(other.ptr) {
if (&other != this) {
other.ptr = nullptr;
}
}
ThreadUnsafeSharedPtr & operator=(ThreadUnsafeSharedPtr && other) {
if (&other != this) {
ptr = other.ptr;
other.ptr = nullptr;
}
return *this;
}
~ThreadUnsafeSharedPtr() {
if (ptr) {
if(--ptr->cnt == 0) {
delete ptr;
}
}
}
T & operator* () {
return ptr->data;
}
T * operator-> () {
return &(ptr->data);
}
};
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-02T18:20:45.603",
"Id": "452141",
"Score": "0",
"body": "Add test cases as well to see what all you have tested?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-10T02:54:46.177",
"Id": "453119",
"Score": "0",
"body": "I have implemented the shared pointer version I talked about. You can find it in https://codereview.stackexchange.com/q/232130/211223 . To make it optimized for single thread simply chance refcount in `resource` from atomic to native type."
}
] |
[
{
"body": "<p>Your implementation of the dereferencing operators misses to check for a valid <code>ptr</code>. It should rather look like this:</p>\n\n<pre><code>T & operator* () {\n if(ptr) {\n return ptr->data;\n }\n throw std::runtime_error(\"Dereferencing invalid ThreadUnsafeSharedPtr.\");\n}\n\nT * operator-> () {\n if(ptr) {\n return &(ptr->data);\n }\n throw std::runtime_error(\"Dereferencing invalid ThreadUnsafeSharedPtr.\");\n}\n</code></pre>\n\n<hr>\n\n<p>Also your implementation of copy constructor and assignment don't check if the incoming <code>ThreadUnsafeSharedPtr</code> is pointing to a valid <code>other</code> pointing to data, respectively if <code>ptr</code> is already shared.<br>\nI am not sure if you intended to increment the counter for such case.</p>\n\n<p>I'd rather write these like:</p>\n\n<pre><code>ThreadUnsafeSharedPtr(const ThreadUnsafeSharedPtr & other) : ptr(nullptr) {\n if (other.ptr && &other != this) {\n ptr = other.ptr;\n ++(ptr->cnt);\n }\n}\nThreadUnsafeSharedPtr & operator=(const ThreadUnsafeSharedPtr & other) {\n if (other.ptr && &other != this) {\n if(ptr && ptr->cnt > 1) { // Counter must be decremented if it is already shared\n --(ptr->cnt);\n }\n ptr = other.ptr;\n ++(ptr->cnt);\n }\n return *this;\n}\n</code></pre>\n\n<hr>\n\n<p>Generally I'd be cautious with such hand rolled micro optimizations in favor of the usage of standard library classes.</p>\n\n<p>It may be flawed from pitfalls as shown above, and makes your code less portable (e.g. if some stuff should be reused in multithreaded environments).</p>\n\n<p>The overhead introduced with <code>std::shared_ptr</code> is fairly small.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-02T13:29:16.867",
"Id": "452114",
"Score": "4",
"body": "I think checking nullptr in deference function might cause some performance problem, so I intentionally did not do so, BTW I should have provided a `operator bool() const` method. The rest of your answer is very helpful."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-02T13:35:08.153",
"Id": "452115",
"Score": "0",
"body": "@frank Well one could consider to omit that check for release compiling mode (or replace it with an `assert()`). It makes it unnecessarily hard to debug such errors otherwise. As you're so obsessed with _micro-optimizations_, are you working in an embedded environment?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-02T14:28:24.570",
"Id": "452120",
"Score": "1",
"body": "Micro-optimisation? Hardly. There's a reason those operations and other simple accessors are *not* checked in any(?) standard library (outside special opt-in debug modes)."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-02T12:34:59.990",
"Id": "231733",
"ParentId": "231732",
"Score": "3"
}
},
{
"body": "<p>Unless this is just for learning, always remember that adding yet another smart-pointer will seriously hinder interaction with anyone expecting a different one.</p>\n\n<p>The Design:</p>\n\n<ol>\n<li><p>The maker-function is mandatory:</p>\n\n<ol>\n<li>Cannot use a different allocator.</li>\n<li>Cannot generally be used to allow sharing across DLL boundaries, as DLLs (in contrast to SOs) don't do symbol unification.</li>\n<li>Cannot be used with already-allocated resources, or those needing different deallocation.</li>\n</ol></li>\n<li><p>Your shared-pointers must always point to the full object. Interior pointers are not allowed, nor are base-pointers.</p></li>\n<li><p>You don't allow for weak pointers at all.</p></li>\n<li><p>As an aside, the overhead of using atomic reference-counts is small enough that the standard library eschews the complication of adding single-threaded shared-pointers. Consider whether that's really the part you should save on.</p></li>\n</ol>\n\n<p>The Implementation:</p>\n\n<ol>\n<li><p>Using in-class-initializers allows you to simplify the ctors.</p></li>\n<li><p>You could use aggregate-initialization with <code>Pair</code>, no need for a custom ctor.</p></li>\n<li><p>Explicitly testing for self-assignment is a bad idea, as it pessimises the common case. Anyway, it's completely useless in a ctor!</p></li>\n<li><p>You should know that <code>-></code> binds stronger than anything but scope-resolution <code>::</code>. If you need to, there are many places to look up <a href=\"https://en.cppreference.com/w/cpp/language/operator_precedence\" rel=\"nofollow noreferrer\">the operator precedence rules</a>.</p></li>\n<li><p>Your move-assignment-operator leaks the assignee's state. Fix it by just doing an unconditional swap instead.</p></li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-02T17:12:15.533",
"Id": "231742",
"ParentId": "231732",
"Score": "4"
}
},
{
"body": "<p>The biggest problem in the design is lack of option for casting and the smart pointer cannot hold properly an interface class. To fix it you need a redesign.</p>\n\n<p><code>std::shared_ptr</code> deals with it by storing control block separately. It is a control block and not just reference counter, it stores pointer to deleter and has two reference counters for <code>std::weak_ptr</code> support.</p>\n\n<p>Just a few days ago I posted on code review another lightweight version of <code>std::shared_ptr</code>... it has a few issues currently which I'll fix and make another post by the end of the week. You can change it to single-threaded version by simply changing the type of reference counter.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-04T16:19:45.317",
"Id": "231841",
"ParentId": "231732",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "231742",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-02T12:28:36.357",
"Id": "231732",
"Score": "4",
"Tags": [
"c++",
"memory-management",
"pointers"
],
"Title": "Simple shared pointer implementation in a single threaded environment (revised)"
}
|
231732
|
<p>I've reproduced the example of this <a href="https://youtu.be/NnZZMkwI6KI?list=PLLWMQd6PeGY3ob0Ga6vn1czFZfW6e-FLr" rel="nofollow noreferrer">video</a> where dependency inversion principle is explained by Tim Corey based on C#</p>
<blockquote>
<p>I had some trouble understanding the scope of the <em>Logger</em> and <em>MessageSender</em> properties and how to set them with the <em>Create</em> function inside the <em>Chore</em> class</p>
</blockquote>
<p>Also:</p>
<blockquote>
<p>With Rubberduck inspections I receive Property *** has no getter</p>
</blockquote>
<p>I would appreciate your feedback over the implementation</p>
<p>Link to the <a href="https://1drv.ms/x/s!ArAKssDW3T7wnK9PYaYjQoXNIjraxg" rel="nofollow noreferrer">finished file</a> (Dependency inversion principle applied)</p>
<p>Link to the <a href="https://1drv.ms/x/s!ArAKssDW3T7wnK9MYSr-YWCe0nBvsg" rel="nofollow noreferrer">initial file</a> (Before DIP applied)</p>
<p>Note: Used <a href="http://rubberduckvba.com/" rel="nofollow noreferrer">Rubberduck VBA</a> to set the attributes</p>
<p>To reproduce just run the TestProgram sub in the Macros module</p>
<p><strong>Module:Macros</strong></p>
<pre><code>'@Folder("Program")
Option Explicit
Public Sub TestProgram()
Dim programtest As New Program
programtest.Main
End Sub
</code></pre>
<p><strong>Class:Chore</strong></p>
<pre><code>'@Folder("Chores")
'@PredeclaredID
Option Explicit
Private Type TChore
ChoreName As String
Owner As person
HoursWorked As Double
IsComplete As Boolean
Logger As ILogger
MessageSender As IMessageSender
End Type
Private this As TChore
Implements IChore
Public Sub PerformedWork(ByVal hours As Double)
this.HoursWorked = this.HoursWorked + hours
this.Logger.Log "Performes work on " & this.ChoreName
End Sub
Public Sub CompleteChore()
IsComplete = True
this.Logger.Log "Completed " & this.ChoreName
this.MessageSender.SendMessage this.Owner, "The chore " & this.ChoreName & " is complete"
End Sub
Public Property Set Logger(ByVal Logger As ILogger)
Set this.Logger = Logger
End Property
Public Property Set MessageSender(ByVal MessageSender As IMessageSender)
Set this.MessageSender = MessageSender
End Property
Public Property Get Self() As Chore
Set Self = Me
End Property
Public Function Create(ByVal Logger As ILogger, ByVal MessageSender As IMessageSender) As Chore
With New Chore
Set .Logger = Logger
Set .MessageSender = MessageSender
Set Create = .Self
End With
End Function
Public Property Get Owner() As IPerson
Set Owner = this.Owner
End Property
Public Property Let Owner(ByVal value As IPerson)
Set this.Owner = value
End Property
Public Property Get ChoreName() As String
ChoreName = this.ChoreName
End Property
Public Property Let ChoreName(ByVal value As String)
this.ChoreName = value
End Property
Public Property Get HoursWorked() As Double
HoursWorked = this.HoursWorked
End Property
Public Property Let HoursWorked(ByVal value As Double)
this.HoursWorked = value
End Property
Public Property Get IsComplete() As Boolean
IsComplete = this.IsComplete
End Property
Public Property Let IsComplete(ByVal value As Boolean)
this.IsComplete = value
End Property
Private Property Set IChore_Owner(ByVal Owner As IPerson)
Set this.Owner = Owner
End Property
Private Property Get IChore_Owner() As IPerson
Set IChore_Owner = this.Owner
End Property
Private Sub IChore_PerformedWork(ByVal hours As Double)
PerformedWork hours
End Sub
Private Sub IChore_CompleteChore()
CompleteChore
End Sub
Private Property Get IChore_ChoreName() As String
IChore_ChoreName = this.ChoreName
End Property
Private Property Let IChore_ChoreName(ByVal value As String)
this.ChoreName = value
End Property
Private Property Get IChore_HoursWorked() As Double
IChore_HoursWorked = this.HoursWorked
End Property
Private Property Let IChore_HoursWorked(ByVal value As Double)
this.HoursWorked = value
End Property
Private Property Get IChore_IsComplete() As Boolean
IChore_IsComplete = this.IsComplete
End Property
Private Property Let IChore_IsComplete(ByVal value As Boolean)
this.IsComplete = value
End Property
</code></pre>
<p><strong>Class:Emailer</strong></p>
<pre><code>'@Folder("MessageSenders")
'@PredeclaredID
Option Explicit
Implements IMessageSender
Public Sub SendMessage(ByVal person As IPerson, ByVal message As String)
Debug.Print "Simulating sending an email to " & person.EmailAddress & " saying " & message
End Sub
Private Sub IMessageSender_SendMessage(ByVal person As IPerson, ByVal message As String)
SendMessage person, message
End Sub
</code></pre>
<p><strong>Class:Factory</strong></p>
<pre><code>'@Folder("Program")
'@PredeclaredID
Option Explicit
Public Function CreatePerson() As IPerson
Set CreatePerson = New person
End Function
Public Function CreateChore() As IChore
Set CreateChore = Chore.Create(CreateLogger, CreateMessageSender)
End Function
Public Function CreateLogger() As ILogger
Set CreateLogger = New Logger
End Function
Public Function CreateMessageSender() As IMessageSender
Set CreateMessageSender = New Emailer
End Function
</code></pre>
<p><strong>Class:IChore</strong></p>
<pre><code>'@Folder("Chores")
Option Explicit
Public Sub PerformedWork(ByVal hours As Double)
End Sub
Public Sub CompleteChore()
End Sub
Public Property Get ChoreName() As String
End Property
Public Property Let ChoreName(ByVal value As String)
End Property
Public Property Get HoursWorked() As Double
End Property
Public Property Let HoursWorked(ByVal value As Double)
End Property
Public Property Get IsComplete() As Boolean
End Property
Public Property Let IsComplete(ByVal value As Boolean)
End Property
Public Property Get Owner() As IPerson
End Property
Public Property Set Owner(ByVal value As IPerson)
End Property
</code></pre>
<p><strong>Class:ILogger</strong></p>
<pre><code>'@Folder("Loggers")
Option Explicit
Public Sub Log(ByVal message As String)
End Sub
</code></pre>
<p><strong>Class:IMessageSender</strong></p>
<pre><code>'@Folder("MessageSenders")
Option Explicit
Public Sub SendMessage(ByVal person As IPerson, ByVal message As String)
End Sub
</code></pre>
<p><strong>Class:IPerson</strong></p>
<pre><code>'@Folder("People")
Option Explicit
Public Property Get FirstName() As String
End Property
Public Property Let FirstName(ByVal value As String)
End Property
Public Property Get LastName() As String
End Property
Public Property Let LastName(ByVal value As String)
End Property
Public Property Get PhoneNumber() As String
End Property
Public Property Let PhoneNumber(ByVal value As String)
End Property
Public Property Get EmailAddress() As String
End Property
Public Property Let EmailAddress(ByVal value As String)
End Property
</code></pre>
<p><strong>Class:Logger</strong></p>
<pre><code>'@Folder("Loggers")
'@PredeclaredID
Option Explicit
Implements ILogger
Public Sub Log(ByVal message As String)
Debug.Print "Write to console: " & message
End Sub
Private Sub ILogger_Log(ByVal message As String)
Log message
End Sub
</code></pre>
<p><strong>Class:Person</strong></p>
<pre><code>'@Folder("People")
Option Explicit
Private Type TPerson
FirstName As String
LastName As String
PhoneNumber As String
EmailAddress As String
End Type
Private this As TPerson
Implements IPerson
Public Property Get FirstName() As String
FirstName = this.FirstName
End Property
Public Property Let FirstName(ByVal value As String)
this.FirstName = value
End Property
Public Property Get LastName() As String
LastName = this.LastName
End Property
Public Property Let LastName(ByVal value As String)
this.LastName = value
End Property
Public Property Get PhoneNumber() As String
PhoneNumber = this.PhoneNumber
End Property
Public Property Let PhoneNumber(ByVal value As String)
this.PhoneNumber = value
End Property
Public Property Get EmailAddress() As String
EmailAddress = this.EmailAddress
End Property
Public Property Let EmailAddress(ByVal value As String)
this.EmailAddress = value
End Property
Private Property Get IPerson_FirstName() As String
IPerson_FirstName = this.FirstName
End Property
Private Property Let IPerson_FirstName(ByVal value As String)
FirstName = value
End Property
Private Property Get IPerson_LastName() As String
IPerson_LastName = this.LastName
End Property
Private Property Let IPerson_LastName(ByVal value As String)
LastName = value
End Property
Private Property Get IPerson_PhoneNumber() As String
IPerson_PhoneNumber = this.PhoneNumber
End Property
Private Property Let IPerson_PhoneNumber(ByVal value As String)
PhoneNumber = value
End Property
Private Property Get IPerson_EmailAddress() As String
IPerson_EmailAddress = this.EmailAddress
End Property
Private Property Let IPerson_EmailAddress(ByVal value As String)
EmailAddress = value
End Property
</code></pre>
<p><strong>Class:Program</strong></p>
<pre><code>'@Folder("Program")
Option Explicit
Public Sub Main()
Dim Owner As IPerson
Set Owner = Factory.CreatePerson
Owner.FirstName = "Tim"
Owner.LastName = "Corey"
Owner.EmailAddress = "tim@iamtimcorey.com"
Owner.PhoneNumber = "555-1212"
Dim newChore As IChore
Set newChore = Factory.CreateChore
newChore.ChoreName = "Take out the trash"
Set newChore.Owner = Owner
newChore.PerformedWork 3
newChore.PerformedWork 1.5
newChore.CompleteChore
End Sub
</code></pre>
<p><strong>Class:Texter</strong></p>
<pre><code>'@Folder("MessageSenders")
'@PredeclaredID
Option Explicit
Implements IMessageSender
Public Sub SendMessage(ByVal person As IPerson, ByVal message As String)
Debug.Print "I am texting " & person.FirstName & " to say " & message
End Sub
Private Sub IMessageSender_SendMessage(ByVal person As IPerson, ByVal message As String)
SendMessage person, message
End Sub
</code></pre>
|
[] |
[
{
"body": "<p>An observation on your class constructors. At the moment you are using public properties to allow you to set the value of properties of a class after it has been created. You can take this to the next step which allows you to delete the setters for the public class members by passing the create parameters to the Self function.</p>\n\n<p>In this way you can create objects with immutable properties from parameters that are provided at the time of object creation.</p>\n\n<pre><code>Public Function Create(ByVal Logger As ILogger, ByVal MessageSender As IMessageSender) As Chore\n\n With New Chore\n\n Set Create = .Self(Logger, MessageSender)\n\n End With\n\nEnd Function\n\n\nPublic Function Self(ByVal Logger As ILogger, ByVal MessageSender As IMessageSender) As Chore\n' This code runs internal to the newly created instance\n Set this.Logger = Logger\n Set this.MessageSender = MessageSender\n Set Self = Me\n\n End Property\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-02T16:28:03.613",
"Id": "452128",
"Score": "1",
"body": "Except `Self` is a good name for a `Property Get` procedure that returns `Me` and does nothing else - I like the idea/approach very much, but it needs a name that better conveys the nature of the side-effects here, like `Init` or `Initialize`, maybe."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-02T17:12:23.033",
"Id": "452131",
"Score": "1",
"body": "I had a think for a name and with the idea of something finished and ready to be presented I came up with Debutante?"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-02T14:18:46.770",
"Id": "231738",
"ParentId": "231735",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "231738",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-02T13:44:53.947",
"Id": "231735",
"Score": "4",
"Tags": [
"object-oriented",
"vba",
"excel",
"dependency-injection",
"rubberduck"
],
"Title": "OOP Dependency inversion principle VBA"
}
|
231735
|
<p>I am interesting in the topic of <strong>finite automata</strong>, so I started over by implementing a parking machine from this video: <a href="https://youtu.be/vhiiia1_hC4" rel="noreferrer">Computers Without Memory - Computerphile</a> to understand conceptions. Didn't do much of an error checking - have made a minimal working version.</p>
<p><strong>Short description of the task, but for better understanding watch the video:</strong></p>
<ol>
<li>You have the parking machine which is implemented by the finite automaton.</li>
<li>The parking lot costs 25 pence. The machine takes only 5, 10, 20 pence coins. Thus, any combination of these coins can be used to pay for parking.</li>
<li>After a sum of coins has reached 25 pence, the ticket is issued.</li>
<li>The machine gobble up all extra money above the 25 pence, like 20 + 20 pence = the ticket only, no change are given.</li>
</ol>
<p><strong>Questions:</strong></p>
<ul>
<li>What do you think about my approach? </li>
<li>Is it optimal, extendable, suitable for real world applications or this technique has limiting factors and an another should be used?</li>
<li>How would you implement this machine? It will be good to see another solutions.</li>
</ul>
<p>It is possible to do this by such way: <a href="https://en.wikipedia.org/wiki/Automata-based_programming#Explicit_state_transition_table" rel="noreferrer">Explicit state transition table</a>, may be I will do this also. My target is to implement something more serious like a <strong>regex</strong> engine in the future, but I should read some books/articles before.</p>
<pre><code>#!/usr/bin/python3
def get_coin(current_sum, *functions):
print(f"Current sum = {current_sum} pence")
coin = int(input("Insert coin\n"))
if coin == 5:
functions[0]()
elif coin == 10:
functions[1]()
elif coin == 20:
functions[2]()
else:
error(current_sum, functions)
def error(current_sum, functions):
print("Error: only 5, 10, 20 pence coins are allowed\n")
get_coin(current_sum, *functions)
def zero_pence():
get_coin("0", five_pence, ten_pence, twenty_pence)
def five_pence():
get_coin("5", ten_pence, fifteen_pence, twenty_five_pence)
def ten_pence():
get_coin("10", fifteen_pence, twenty_pence, give_ticket)
def fifteen_pence():
get_coin("15", twenty_pence, twenty_five_pence, give_ticket)
def twenty_pence():
get_coin("20", twenty_five_pence, give_ticket, give_ticket)
def twenty_five_pence():
input("Current sum = 25 pence, press the 'return' button to pay")
give_ticket()
def give_ticket():
print("""\nTake your ticket:
Date: 1 November 2019
Start time: \t20:21
End time: \t22:21\n
""")
def parking_machine():
prompt = """\n\tThe parking machine.
Information:
1. The machine takes 5, 10, 20 coins.
2. The machine doesn't give a change.
3. The parking costs 25 pence.
Press 's' button to start inserting of coins.
"""
prompt = '#' * 80 + prompt + '#' * 80 + '\n'
while True:
button = input(prompt)
if button == 's':
zero_pence()
parking_machine()
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-02T17:20:38.793",
"Id": "452133",
"Score": "2",
"body": "Please summarize the task from the video for all those who don't want to watch it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-02T17:38:37.230",
"Id": "452136",
"Score": "0",
"body": "@RolandIllig It doesn't need to watch the whole video. From `1:00` to `3:00` minutes will be enough. Do you think the people who don't want watch the 2 minutes of video will be spending time to read my summarization and answering me? I don't think so. But if the rules of this site requires a textual presentation of the task, I will do this. But the video explanation is better anyway."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-02T18:57:57.907",
"Id": "452142",
"Score": "1",
"body": "@RolandIllig Summarization is added. I have decided that it is better to have all information in the question. Thanks for the hint."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-02T19:19:33.687",
"Id": "452143",
"Score": "3",
"body": "The point is that the video is 9 minutes and I don't know which part of it is the relevant part. Therefore I would need to spend 9 minutes until I know whether this code review is interesting to me. On the other hand, scanning a textual description of the task takes 10 seconds, which is much less."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-03T01:14:15.683",
"Id": "452156",
"Score": "1",
"body": "Links to external sites can break over time. Putting all of the information in the question prevents the question from becoming incomplete in the future."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-03T01:20:19.580",
"Id": "452157",
"Score": "1",
"body": "The question description says “5, 10, and 20 pence coins”, the prompt says 1, 5 & 10 pence coins”, and the error message claims “1, 5, and 20 pence coins”. Would you like to clarify which of the 3 the program is supposed to be using?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-03T10:10:53.280",
"Id": "452174",
"Score": "0",
"body": "@AJNeufeld Fixed. Don't know how this happened :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-16T21:27:29.457",
"Id": "454076",
"Score": "0",
"body": "@MiniMax, is reviewing still actual?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-16T22:44:31.763",
"Id": "454083",
"Score": "0",
"body": "@RomanPerekhrest Yes, why not? It is always interesting to see comments and others solutions. But I have switched from the **finite automata** topic to others at this moment. I were going to improve my knowledge and answer to this question myself in the future, if no one gives an answer especially. Now, I see one big drawback in implementation by function calls - if it will be a real application with a long sequence of state changing, it will retain a function in the call stack after every state changing and these functions can't be closed before program's exit."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-26T14:56:20.967",
"Id": "455272",
"Score": "0",
"body": "@MiniMax Not true. After `give_ticket()` is called, the stack unwinds to the main `while True` loop. The stack only holds unclosed functions while a balance is held."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-26T17:31:28.750",
"Id": "455298",
"Score": "0",
"body": "@AJNeufeld Yes, in this case the drawback will not appear, but I wrote: \"*if it will be a real application with a long sequence of state changing*\". Imagine a regex engine implemented by this way, that processes a long regular expression. The stack will unwind after whole expression will be processed only."
}
] |
[
{
"body": "<ul>\n<li><p>For the first question: Your implementation is really good.</p></li>\n<li><p>For the second question: Yes, I believe this is suitable for real world applications, though it won't work without knowing mechanical engineering.</p></li>\n<li><p>For the third question: I've added my implementation at the bottom of the answer!</p></li>\n</ul>\n\n<p>Here's how we can improve your current code:</p>\n\n<p>Let's analyze the functions <code>get_coin</code>, <code>give_ticket</code>, and <code>parking_machine</code> as all others are just really simple functions.</p>\n\n<h2><code>get_coin</code></h2>\n\n<p>You don't have to use the function <code>error</code>! Instead, use:</p>\n\n<pre><code>while coin not in [5, 10, 20]:\n print(\"Error: only 5, 10, 20 pence coins are allowed\\n\")\n coin = int(input(\"Insert coin\\n\"))\n</code></pre>\n\n<p>If you want, you can replace</p>\n\n<pre><code>if coin == 5:\n functions[0]()\nelif coin == 10:\n functions[1]()\nelif coin == 20:\n functions[2]()\n</code></pre>\n\n<p>with</p>\n\n<pre><code>functions[int(coin >= 10) + int(coin >= 20)]()\n</code></pre>\n\n<p>Though it impacts the readability of that part. If I were you, I'd use a comment to explain what that part does!</p>\n\n<h2><code>give_ticket</code></h2>\n\n<p>Instead of</p>\n\n<pre><code> print(\"\"\"\\nTake your ticket:\n\nDate: 1 November 2019\nStart time: \\t20:21\nEnd time: \\t22:21\\n\n\"\"\")\n</code></pre>\n\n<p>I'd rather use </p>\n\n<pre><code> print(\n \"\"\"\n Take your ticket:\n\n Date: 1 November 2019\n Start time: \\t20:21\n End time: \\t22:21\\n\n \"\"\")\n</code></pre>\n\n<p>With the space. I think it looks like a ticket only then!</p>\n\n<p>Anyway, if you don't want the space, just use <code>textwrap.dedent</code></p>\n\n<pre><code>def give_ticket():\n print(textwrap.dedent(\"\"\"\n Take your ticket:\n\n Date: 1 November 2019\n Start time: \\t20:21\n End time: \\t22:21\\n\n \"\"\"))\n</code></pre>\n\n<p>This would remove the leading space in every line.</p>\n\n<h2><code>parking_machine</code></h2>\n\n<p>Same as the last one, except you have to print <code>The parking machine.</code> separately as it requires <code>\\t</code> which <code>textwrap.dedent</code> would remove. Also, I'd add <code>seperate = '#' * 80</code> and use it instead</p>\n\n<p>Also, I'd rather add an option to quit as the only way to quit this program would be to close it.</p>\n\n<h2>General</h2>\n\n<p>Always have a <code>if __name__ == '__main__'</code> guard over your main code which will prevent it from running while imported from another module.</p>\n\n<p>So, </p>\n\n<pre><code>parking_machine()\n</code></pre>\n\n<p><strong>Should</strong> be</p>\n\n<pre><code>if __name__ == '__main__':\n parking_machine()\n</code></pre>\n\n<hr>\n\n<p>This is what the final code would look like:</p>\n\n<pre><code>import textwrap\n\ndef get_coin(current_sum, *functions):\n print(f\"Current sum = {current_sum} pence\")\n coin = int(input(\"Insert coin\\n\"))\n\n while coin not in [5, 10, 20]:\n print(\"Error: only 5, 10, 20 pence coins are allowed\\n\")\n coin = int(input(\"Insert coin\\n\"))\n\n functions[int(coin >= 10) + int(coin >= 20)]()\n\ndef zero_pence():\n get_coin(\"0\", five_pence, ten_pence, twenty_pence)\n\ndef five_pence():\n get_coin(\"5\", ten_pence, fifteen_pence, twenty_five_pence)\n\ndef ten_pence():\n get_coin(\"10\", fifteen_pence, twenty_pence, give_ticket)\n\ndef fifteen_pence():\n get_coin(\"15\", twenty_pence, twenty_five_pence, give_ticket)\n\ndef twenty_pence():\n get_coin(\"20\", twenty_five_pence, give_ticket, give_ticket)\n\ndef twenty_five_pence():\n input(\"Current sum = 25 pence, press the 'return' button to pay: \")\n give_ticket()\n\ndef give_ticket():\n print(textwrap.dedent(\"\"\"\n\n Take your ticket:\n\n Date: 1 November 2019\n Start time: 20:21\n End time: 22:21\n\n \"\"\"))\n\ndef parking_machine():\n prompt = textwrap.dedent(\n \"\"\"\n\n Information:\n 1. The machine takes 5, 10, 20 coins.\n 2. The machine doesn't give a change.\n 3. The parking costs 25 pence.\n\n Press 's' button to start inserting of coins or 'q' to quit.\n\n \"\"\")\n\n prompt = '\\n\\tThe parking machine.' + prompt\n\n seperate = '#' * 80 + '\\n'\n\n prompt = seperate + prompt + seperate\n\n while True:\n button = input(prompt)\n\n if button == 's':\n zero_pence()\n\n if button == 'q':\n print('Thanks for using this machine!')\n quit()\n\nif __name__ == '__main__':\n parking_machine()\n</code></pre>\n\n<p>I'll make sure to add more ideas when I get them!</p>\n\n<p>Hope this helps!</p>\n\n<p><strong>EDIT:</strong></p>\n\n<p>Here's how I'd implement it if I completely based inputs and outputs off of your program.</p>\n\n<pre><code>import textwrap\n\ndef give_ticket():\n print(\"\"\"\n\n Take your ticket:\n\n Date: 1 November 2019\n Start time: 20:21\n End time: 22:21\n\n \"\"\")\n\ndef parking_machine():\n prompt = textwrap.dedent(f\"\"\"\n {'#' * 80}\n\n The parking machine.\n\n Information:\n 1. The machine takes 5, 10, 20 coins.\n 2. The machine doesn't give a change.\n 3. The parking costs 25 pence.\n\n Press 's' button to start inserting of coins or 'q' to quit.\n\n {'#' * 80}\n \"\"\")\n\n while True:\n button = input(prompt)\n\n if button == 's':\n current_sum = 0\n\n while current_sum < 25:\n print(f\"Current sum = {current_sum} pence\")\n\n while True:\n coin = int(input(\"Insert coin\\n\"))\n\n if coin not in [5, 10, 20]:\n print(\"Error: only 5, 10, 20 pence coins are allowed\\n\")\n else:\n current_sum += coin\n break\n\n if current_sum == 25:\n input(\"Current sum = 25 pence, press the 'return' button to pay: \")\n\n give_ticket()\n\n if button == 'q':\n print('Thanks for using this machine!')\n quit()\n\nif __name__ == '__main__':\n parking_machine()\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-26T18:05:21.320",
"Id": "233012",
"ParentId": "231736",
"Score": "4"
}
},
{
"body": "<h3>Not a finite state machine</h3>\n\n<p>The state machine in the posted code has infinite states.\nThis is caused by the recursive calls of <code>get_coin</code> and <code>error</code>.\nConsider for example these states:</p>\n\n<ul>\n<li>zero-pence with nothing entered yet</li>\n<li>zero-pence, after zero-pence and an invalid input</li>\n<li>zero-pence, after zero-pence and an invalid input twice</li>\n<li>...</li>\n</ul>\n\n<p>And so on. You can see these are different states,\nbecause the content of the stack is different.</p>\n\n<p>There are theoretically infinite zero-pence, five-pence, etc, states.\nPractically there are finite, because after enough invalid inputs,\nthe stack will eventually overflow.</p>\n\n<p>There should be precisely one zero-pence, five-pence, etc, states.</p>\n\n<p>This is easy to fix by replacing the <code>error</code> function with a loop inside <code>get_coin</code>.</p>\n\n<h3>There are too many states</h3>\n\n<p>Even after making the states finite,\nthere will still be more states than required by the exercise.</p>\n\n<p>Why, again, because of the stack.\nFor example, there are two ways to reach 10 pence:</p>\n\n<ul>\n<li>0 -> 5 -> 5</li>\n<li>0 -> 10</li>\n</ul>\n\n<p>At this point, the machine should be in the 10 pence state,\nbut these two states are not the same,\nbecause the stack stores two different histories.</p>\n\n<p>If you want truly identical ten-pence, fifteen-pence, etc, states,\nyou have to eliminate history, you have to eliminate stack,\nyou have to eliminate function calls.</p>\n\n<p>This is easy to fix by implementing state transitions in a loop,\ninstead of through function calls.</p>\n\n<h3>Don't use varargs if you don't need it</h3>\n\n<p>The <code>get_coin</code> function takes a variable number of functions as arguments.\nBut in fact it will only ever use 3,\nand in fact it's only ever called with 3.\nTherefore, it would be more natural to give those parameters dedicated, descriptive names.</p>\n\n<h3>Why convert input to <code>int</code>?</h3>\n\n<p>The <code>get_coin</code> function converts input to <code>int</code>,\nbut doesn't actually perform any numeric operations with it.</p>\n\n<h3>Use a more portable shebang</h3>\n\n<p>Not all systems have Python 3 installed in <code>/usr/bin/python3</code>.\nA more robust, portable shebang would be:</p>\n\n<pre><code>#!/usr/bin/env python3\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-28T19:09:39.597",
"Id": "233131",
"ParentId": "231736",
"Score": "10"
}
},
{
"body": "<p>Given a state machine <em>p</em> which has initial state <em>s</em> and final state <em>f</em>, then it can only accept 0, 5, 10, 20 as inputs. This can be represented graphically as such:</p>\n\n<p><a href=\"https://i.stack.imgur.com/sn5qU.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/sn5qU.png\" alt=\"enter image description here\"></a></p>\n\n<p>Therefore, the machine must continue to run until the sum of the coins entered exceeds or equals 25. Therefore, the Python code can be written to be more faithful to the state machine as:</p>\n\n<pre><code>states = {\n \"s\": {0: \"s\", 5: \"q1\", 10: \"q2\", 20: \"q4\"},\n \"q1\": {0: \"q1\", 5: \"q2\", 10: \"q3\", 20: \"f\"},\n \"q2\": {0: \"q2\", 5: \"q3\", 10: \"q4\", 20: \"f\"},\n \"q3\": {0: \"q3\", 5: \"q4\", 10: \"f\", 20: \"f\"},\n \"q4\": {0: \"q4\", 5: \"f\", 10: \"f\", 20: \"f\"},\n \"f\": {0: \"f\"}\n}\n\ncurrent_state = \"s\"\n\nprompt = \"\"\"\\tThe parking machine.\n\nInformation:\n1. The machine takes 5, 10, 20 coins.\n2. The machine doesn't give a change.\n3. The parking costs 25 pence.\n\"\"\"\nprompt = '#' * 80 + prompt + '#' * 80 + '\\n'\nprint(prompt)\n\nwhile (current_state != \"f\"):\n try:\n current_state = states[current_state][int(input(\"Insert coin: \"))]\n except (ValueError, KeyError):\n print(\"Error: only 5, 10, 20 pence coins are allowed\\n\")\n\nprint(\"\"\"\\nTake your ticket:\n\nDate: 1 November 2019\nStart time: \\t20:21\nEnd time: \\t22:21\\n\n\"\"\")\n</code></pre>\n\n<p>This removes all issues with recursion and stack overflows as there is no history (it is impossible to determine if state <em>q1</em> was reached by accepting state 0 or 5, or any combination of those.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-01T21:56:22.103",
"Id": "455820",
"Score": "0",
"body": "You are missing return to the initial state after giving a ticket, so the next person can buy a ticket."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-01T22:00:10.747",
"Id": "455821",
"Score": "0",
"body": "Entering `25` will produce an uncaught `KeyError`, crashing the parking ticket machine."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-01T22:05:34.897",
"Id": "455822",
"Score": "1",
"body": "In the `q1` state, you permit an invalid coin `15` ... both in code and in the state transition diagram ... and deny (crash with a `KeyError`) the valid `20` coin input."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-01T22:39:51.610",
"Id": "455827",
"Score": "1",
"body": "Thanks for finding those bugs @AJNeufeld. I have added the return state to the diagram, removed the invalid 25 state and it doesn't crash on KeyError. I haven't added the go-to-initial-state in the program as I'm not sure if it should restart the program when the user has finished."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-01T17:57:56.017",
"Id": "233234",
"ParentId": "231736",
"Score": "7"
}
}
] |
{
"AcceptedAnswerId": "233131",
"CommentCount": "11",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-02T13:53:33.917",
"Id": "231736",
"Score": "10",
"Tags": [
"python",
"python-3.x",
"state-machine"
],
"Title": "The parking machine implementation"
}
|
231736
|
<p>I am making a Trello clone just for personal project and I wonder if my implementation on mutating the state is good.</p>
<p>My state is basically shaped like this:</p>
<pre><code>boards: [
{
id: Number,
title: String,
tasks: Array,
columns: Array,
columnOrder: Array
}
]
</code></pre>
<p>I want to mutate the state to add the new task to the tasks array given that the <code>payload</code> of the reducer has boardId, columnId, task.</p>
<p>My current implementation of adding a new object to an array:</p>
<pre><code>switch (action.type) {
case ADD_TASK: {
console.log(state)
let newBoard = state.boards.find(
board => board.id === action.payload.boardId
)
let column = newBoard.columns.find(
column => column.id === action.payload.columnId
)
column.tasks = [...column.tasks, action.payload.task]
newBoard.columns = [...newBoard.columns, column]
const addToBoard = state.boards.map(board => {
if (board.id === action.payload.boardId) {
board = newBoard
}
return board
})
const newState = {
boards: addToBoard
}
console.log(newState)
return newState
//code omitted
}
</code></pre>
<p>Is there a better way to mutate the state rather than my current implementation?</p>
|
[] |
[
{
"body": "<p><a href=\"https://redux.js.org/recipes/structuring-reducers/prerequisite-concepts\" rel=\"nofollow noreferrer\">Mutation is generally discouraged</a> in Redux (and React in general) because it breaks tooling/libraries that expect <code>x === y</code> to mean that <code>x</code> and <code>y</code> are the same <em>throughout time</em>.</p>\n\n<p>If you use the <code>React.useEffect</code> or <code>React.useMemo</code> or <code>React.useCallback</code> dependency arguments, or <code>React.memo</code>, you'll run into problems if you mutate objects that you're passing.</p>\n\n<p>We can clean up your code to avoid this mutation in several passes. First, we'll just remove the logs since they don't affect behavior (and they expose certain implementation details we'll want to change):</p>\n\n<pre class=\"lang-js prettyprint-override\"><code>switch (action.type) {\n case ADD_TASK: {\n\n let newBoard = state.boards.find(\n board => board.id === action.payload.boardId\n )\n\n let column = newBoard.columns.find(\n column => column.id === action.payload.columnId\n )\n column.tasks = [...column.tasks, action.payload.task]\n\n newBoard.columns = [...newBoard.columns, column]\n\n const addToBoard = state.boards.map(board => {\n if (board.id === action.payload.boardId) {\n board = newBoard\n }\n return board\n })\n\n const newState = {\n boards: addToBoard\n }\n return newState\n }\n //code omitted\n}\n</code></pre>\n\n<p>Next, let's inline some of these variables. <code>newState</code> and <code>addToBoard</code> are each only used once:</p>\n\n<pre class=\"lang-js prettyprint-override\"><code>switch (action.type) {\n case ADD_TASK: {\n\n let newBoard = state.boards.find(\n board => board.id === action.payload.boardId\n )\n\n let column = newBoard.columns.find(\n column => column.id === action.payload.columnId\n )\n column.tasks = [...column.tasks, action.payload.task]\n\n newBoard.columns = [...newBoard.columns, column]\n\n return {\n boards: state.boards.map(board => {\n if (board.id === action.payload.boardId) {\n board = newBoard\n }\n return board\n })\n }\n }\n //code omitted\n}\n</code></pre>\n\n<p>Next, consider this arrow function:</p>\n\n<pre class=\"lang-js prettyprint-override\"><code> board => {\n if (board.id === action.payload.boardId) {\n board = newBoard\n }\n return board\n }\n</code></pre>\n\n<p>You've made your control-flow more complicated by reassigning the parameter, when an early return would do just fine:</p>\n\n<pre class=\"lang-js prettyprint-override\"><code> board => {\n if (board.id === action.payload.boardId) {\n return newBoard\n }\n return board\n }\n</code></pre>\n\n<p>Also, we only actually need <code>newBoard</code> inside this function (it's never used more than once), so we can move it to where it's needed:</p>\n\n<pre class=\"lang-js prettyprint-override\"><code>switch (action.type) {\n case ADD_TASK: {\n return {\n boards: state.boards.map(board => {\n if (board.id === action.payload.boardId) {\n let newBoard = state.boards.find(\n _board => _board.id === action.payload.boardId\n )\n\n let column = newBoard.columns.find(\n column => column.id === action.payload.columnId\n )\n column.tasks = [...column.tasks, action.payload.task]\n\n newBoard.columns = [...newBoard.columns, column]\n return newBoard\n }\n return board\n })\n }\n }\n //code omitted\n}\n</code></pre>\n\n<p>Now we begin to see some redundancy! For example, <code>newBoard</code> is being initialized to \"the board with <code>id</code> equal to <code>action.payload.boardId</code>, but we already have a name for it: that's just <code>board</code>! So we can actually get rid of the name <code>newBoard</code> entirely:</p>\n\n<pre class=\"lang-js prettyprint-override\"><code>switch (action.type) {\n case ADD_TASK: {\n return {\n boards: state.boards.map(board => {\n if (board.id === action.payload.boardId) {\n let column = board.columns.find(\n column => column.id === action.payload.columnId\n )\n column.tasks = [...column.tasks, action.payload.task]\n\n board.columns = [...board.columns, column]\n return board\n }\n return board\n })\n }\n }\n //code omitted\n}\n</code></pre>\n\n<p>But now we need to deal with the unnecessary mutations. We don't want to <em>modify</em> <code>board</code> (or any of its fields, like <code>columns</code>). Instead, we want to return a <em>copy with changes</em>.</p>\n\n<p>We can do this in parts. For example, instead of</p>\n\n<pre class=\"lang-js prettyprint-override\"><code> board.columns = [...board.columns, column]\n return board\n</code></pre>\n\n<p>we can instead say</p>\n\n<pre class=\"lang-js prettyprint-override\"><code> return { ...board, columns: [...board.columns, column] }\n</code></pre>\n\n<p>which copies <code>board</code> and then replaces the <code>columns</code> field with the new given value.</p>\n\n<p>We now have</p>\n\n<pre class=\"lang-js prettyprint-override\"><code> let column = board.columns.find(\n column => column.id === action.payload.columnId\n )\n column.tasks = [...column.tasks, action.payload.task]\n return { ...board, columns: [...board.columns, column] }\n</code></pre>\n\n<p>and similarly, we can change the last two lines to obtain the non-modifying equivalent:</p>\n\n<pre class=\"lang-js prettyprint-override\"><code> let column = board.columns.find(\n column => column.id === action.payload.columnId\n )\n return {\n ...board,\n columns: [\n ...board.columns, { ...column, tasks: [...column.tasks, action.payload.task] }\n ]\n }\n</code></pre>\n\n<p>However, at this point, it seems likely that you have a bug here. This change duplicates the entire column, in addition to adding the single task to it! It seems that you instead wanted to just add a task to the one column with matching ID, which we can do instead:</p>\n\n<pre class=\"lang-js prettyprint-override\"><code>switch (action.type) {\n case ADD_TASK: {\n return {\n boards: state.boards.map(board => {\n if (board.id === action.payload.boardId) {\n return {\n ...board,\n columns: board.columns.map(column => {\n if (column.id === action.payload.columnId) {\n return { ...column, tasks: [...column.tasks, action.payload.task] };\n }\n return column;\n })\n }\n }\n return board\n })\n }\n }\n //code omitted\n}\n</code></pre>\n\n<p>This gives us a fully cleaned-up and immutable version of your code. Of course, you might rightfully observe that this is more-heavily nested than your original, which is a common result of switching to non-mutating state. You can use some existing ones or build your own.</p>\n\n<p>For example, in this case, you're frequently using the following pattern:</p>\n\n<ul>\n<li>find a matching object in an array</li>\n<li>return the array with all other objects unchanged, and apply a transformation to the one that matches</li>\n</ul>\n\n<p>This is easy to write as a helper function. Here <code>mapIf</code> is used to select the right board and then the right column:</p>\n\n<pre class=\"lang-js prettyprint-override\"><code>function mapIf(array, condition, transform) {\n return array.map(item => condition(item) ? transform(item) : item);\n}\n\nswitch (action.type) {\n case ADD_TASK: {\n return {\n boards: mapIf(state.boards, board => board.id === action.payload.boardId, board => ({\n ...board,\n columns: mapIf(board.columns, column => column.columnId === action.payload.columnId, column =>\n ({ ...column, tasks: [...column.tasks, action.payload.task] })\n ),\n })),\n }\n }\n //code omitted\n}\n</code></pre>\n\n<p>Even this is still a bit long, so you can write more helpers, like a <code>hasId</code> higher-order function:</p>\n\n<pre class=\"lang-js prettyprint-override\"><code>function hasId(id) {\n return item => item.id === id\n}\n</code></pre>\n\n<p><code>hasId</code> returns a function that checks whether its argument has the original <code>id</code>. So we can instead write:</p>\n\n<pre class=\"lang-js prettyprint-override\"><code>\nfunction mapIf(array, condition, transform) {\n return array.map(item => condition(item) ? transform(item) : item);\n}\n\nfunction hasId(id) {\n return item => item.id === id\n}\n\nswitch (action.type) {\n case ADD_TASK: {\n return {\n boards: mapIf(state.boards, hasId(action.payload.boardId), board => ({\n ...board,\n columns: mapIf(board.columns, hasId(action.payload.columnId), column =>\n ({ ...column, tasks: [...column.tasks, action.payload.task] })\n ),\n })),\n }\n }\n //code omitted\n}\n</code></pre>\n\n<p>Lastly, you frequently only want to touch one (or a couple) fields in an object. Here's one helper you can write to clean up access to the <code>tasks</code> and <code>columns</code> fields:</p>\n\n<pre><code>function onField(field, func) {\n return item => ({ ...item, [field]: func(item[field]) })\n}\n</code></pre>\n\n<p>this helper allows you to write (for example) <code>onField(\"x\", val => val + 1)</code> to get a function that increases the <code>.x</code> field of its argument by 1, leaving all the others alone. You can use it like so:</p>\n\n<pre class=\"lang-js prettyprint-override\"><code>function onField(field, func) {\n return item => ({ ...item, [field]: func(item[field]) })\n}\n\nfunction mapIf(array, condition, transform) {\n return array.map(item => condition(item) ? transform(item) : item);\n}\n\nfunction hasId(id) {\n return item => item.id === id\n}\n\nswitch (action.type) {\n case ADD_TASK: {\n return {\n boards: mapIf(\n state.boards,\n hasId(action.payload.boardId),\n onField('columns', columns => mapIf(\n columns,\n hasId(action.payload.columnId),\n onField('tasks', tasks => [...column.tasks, action.payload.task]),\n )),\n ),\n }\n }\n //code omitted\n}\n</code></pre>\n\n<p>This change suggests a new way to write <code>mapIf</code>, so that it works better with <code>onField</code>, by making it return a transforming function instead of directly taking the <code>array</code> as an argument:</p>\n\n<pre class=\"lang-js prettyprint-override\"><code>function onField(field, func) {\n return item => ({ ...item, [field]: func(item[field]) })\n}\n\nfunction mapperIf(condition, transform) {\n return array => array.map(item => condition(item) ? transform(item) : item);\n}\n\nfunction hasId(id) {\n return item => item.id === id\n}\n\nswitch (action.type) {\n case ADD_TASK: {\n return onField(\n 'boards',\n mapperIf(\n hasId(action.payload.boardId),\n onField(\n 'columns',\n mapperIf(\n hasId(action.payload.columnId),\n onField('tasks', tasks => [...column.tasks, action.payload.task]),\n )\n ),\n ),\n )(state);\n }\n //code omitted\n}\n</code></pre>\n\n<p>The main downside to <em>this</em> approach is that there's lots of nesting that can make it hard to understand what's going on. So if we make <em>one more</em> transformation, and write a <code>chain</code> helper, we can get the (in my opinion, rather beautiful):</p>\n\n<pre class=\"lang-js prettyprint-override\"><code>function onField(field) {\n return func => item => ({ ...item, [field]: func(item[field]) })\n}\n\nfunction mapperIf(condition) {\n return transform => array => array.map(item => condition(item) ? transform(item) : item);\n}\n\nfunction hasId(id) {\n return item => item.id === id\n}\n\nfunction apply(transform) {\n return func => item => transform(func(item));\n}\n\nfunction chain(func, ...funcs) {\n if (func === undefined && funcs.length === 0) {\n return item => item;\n }\n return func(chain(...funcs));\n}\n\nswitch (action.type) {\n case ADD_TASK: {\n return chain(\n onField(\"boards\"),\n mapperIf(hasId(action.payload.boardId)),\n onField(\"columns\"),\n mapperIf(hasId(action.payload.columnId)),\n onField(\"tasks\"),\n apply(tasks => [...tasks, action.payload.task]),\n )(state)\n }\n //code omitted\n}\n<span class=\"math-container\">```</span>\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-02T19:32:40.453",
"Id": "231747",
"ParentId": "231737",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "231747",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-02T14:10:31.567",
"Id": "231737",
"Score": "2",
"Tags": [
"javascript",
"react.js",
"redux"
],
"Title": "React Redux mutating implementation"
}
|
231737
|
<p>I wrote cat program in x64 FASM and I would like to know if there is anything that can be improved.</p>
<p>This implementation of cat supports:</p>
<ul>
<li>Reading from stdin.</li>
<li>Multiple arguments.</li>
</ul>
<p>I checked few cases and program behaves exactly like original cat command.</p>
<p>Is there anything I could do to improve performance of this program? I compared it to original cat and my program is around 200ms slower on 512MB file.</p>
<p>Code:</p>
<pre><code>format ELF64 executable 3
entry start
BUFSIZE equ 1048576
segment readable writeable
fd dq 0
buf rb BUFSIZE
segment readable executable
start:
mov rbx, 1
cmp [rsp], rbx
je read
open:
xor rsi, rsi ;fd=open(pathname,flags)
mov rdi, [rsp+rbx*8+8]
mov rax, 2
syscall
mov [fd], rax
read:
mov rdx, BUFSIZE ;bytes_read=read(fd,buf,BUFSIZE)
mov rsi, buf
mov rdi, [fd]
mov rax, 0
syscall
write:
mov rdx, rax ;write(STDOUT_FILENO,buf,bytes_read)
mov rsi, buf
mov rdi, 1
mov rax, 1
syscall
test rdx, rdx ;if(bytes_read!=0) goto read
jnz read
close:
mov rdi, [fd] ;close(fd)
mov rax, 3
syscall
inc rbx
cmp rbx, [rsp] ;if(rbx<argc)
jb open
exit:
xor rdi, rdi
mov rax, 60
syscall
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-03T09:40:39.350",
"Id": "452171",
"Score": "0",
"body": "I have rolled back your last edit. Please don't change or add to the code in your question after you have received answers. See [What should I do when someone answers my question?](https://codereview.stackexchange.com/help/someone-answers) Thank you."
}
] |
[
{
"body": "<p>Linux has the <code>sendfile</code> system call, which copies data between file descriptors instead of copying the data to userspace and back to kernel space. That may be more efficient.</p>\n\n<p>Your code looks very clean and organized. If you had used named constants instead of magic numbers, you might not even need some of the comments:</p>\n\n<pre class=\"lang-lisp prettyprint-override\"><code> mov rdx, tax\n mov rsi, but\n mov rdi, STDOUT_FILENO\n mov rax, SYS_write\n syscall\n</code></pre>\n\n<p>But I think even with these constants, the comments are still helpful, so I'd probably keep them anyway.</p>\n\n<p>You should add error handling for stdout write errors, such as <code>ENOSPACE</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-02T19:50:53.457",
"Id": "452145",
"Score": "0",
"body": "I wasn't aware of `sendfile` to be honest. I will try that and let you know if I see any difference in performance. My code looks very clean and organized thanks to [other user](https://codereview.stackexchange.com/users/62794/sep-roland). I wrote same program in x86 NASM before, but even back then my code wasn't that bad I think. These are not magic numbers as there are comments, but do you think its good idea to kinda rewrite needed constants that are defined in C and remove comments as everything will be clearly visible without them?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-02T19:51:00.037",
"Id": "452146",
"Score": "0",
"body": "In relation to error handling, I'm firstly making program work, then optimizing it and adding error handling at the end."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-02T23:13:49.997",
"Id": "452151",
"Score": "0",
"body": "I intentionally wrote \"you _might_ not need comments\". I'd say just give it a try and see which variant looks nicer. :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-02T23:34:41.013",
"Id": "452153",
"Score": "0",
"body": "I added improved code to the question, so you can tell me which variant looks nicer/more readable/cleaner to you. Personally code without comments looks cleaner to me, but thats my code, so it will always be clean to me (until I will leave it for week and then come back later of course)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-03T11:20:21.383",
"Id": "452181",
"Score": "0",
"body": "EDIT: you can find improved code here: https://pastebin.com/pS2ku0xz"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-02T19:39:14.310",
"Id": "231748",
"ParentId": "231745",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "231748",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-02T18:37:57.807",
"Id": "231745",
"Score": "6",
"Tags": [
"linux",
"assembly",
"amd64"
],
"Title": "Cat program in x64 FASM"
}
|
231745
|
<p>In Kotlin <a href="https://kotlinlang.org/docs/reference/operator-overloading.html#comparison" rel="noreferrer">comparison operators</a> can be used instead of <code>compareTo</code> method:</p>
<pre><code>a > b // a.compareTo(b) > 0
a < b // a.compareTo(b) < 0
a >= b // a.compareTo(b) >= 0
a <= b // a.compareTo(b) <= 0
</code></pre>
<p>It's convenient and makes comparisons a lot more readable. However, these operators cannot be used if there is no suitable <code>compareTo</code> method, but there is a suitable <code>Comparator</code>.</p>
<p>To make it possible to use them in this case, I've created a <code>use</code> extension function for a <code>Comparator</code> interface:</p>
<pre><code>inline fun <T, R> Comparator<T>.use(block: ComparatorDSL<T>.() -> R) =
ComparatorDSL(this).run(block)
</code></pre>
<p>Where <code>ComparatorDSL</code> is the following class:</p>
<pre><code>inline class ComparatorDSL<T>(private val comparator: Comparator<T>) {
operator fun T.compareTo(other: T) = comparator.compare(this, other)
}
</code></pre>
<p>Now I can use it like this:</p>
<pre><code>comparator.use { a > b } // comparator.compare(a, b) > 0
</code></pre>
<p><strong>Questions:</strong></p>
<ul>
<li>Is <code>comparator.use { a > b }</code> more readable than <code>comparator.compare(a, b) > 0</code>?</li>
<li>Is it a good idea to replace <code>use</code> with <code>invoke</code> operator or make this function <code>infix</code>?</li>
<li>Any improvement suggestions that you can think of</li>
</ul>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-15T14:20:58.313",
"Id": "453926",
"Score": "0",
"body": "Like the idea. Only thing I don't like is the name. Use in my eyes refers to the Closeable- interface. Maybe check is better, or just compare?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-17T11:27:17.717",
"Id": "454122",
"Score": "0",
"body": "@tieskedh That's a good point. But `check` doesn't make much sense if you use it not for one comparison but wrap the whole function with it. Maybe it's better to remove the name completely and use the `invoke` operator."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-18T13:05:48.190",
"Id": "454228",
"Score": "0",
"body": "I don't like that idea, as this implies that the main goal for the comparator is to function as an predicate, while I think sorting is as important as checking..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-09T07:31:28.010",
"Id": "460530",
"Score": "0",
"body": "I like the implementation for this use-case. The naming is always difficult, but I would suggest 1. 'test' as in Javas Predicate, or 2. 'isTrue' / 'isTrueFor' to indicate a boolean result"
}
] |
[
{
"body": "<h2>Is comparator.use { a > b } more readable than comparator.compare(a, b) > 0?</h2>\n\n<p>Readability is relative and more a point of view. Usually something is considered more readable, the more people say it is. </p>\n\n<p>In my personal opinion both solutions are easy to read, while I like the syntax of the first more. Actually something very similar exists in the language already: <a href=\"https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.comparisons/compare-by.html#compareby\" rel=\"nofollow noreferrer\">compareBy</a></p>\n\n<pre><code>list.sortedWith(\n compareBy{ it.a }.thenBy { it.b }.thenByDescending { it.c }\n)\n</code></pre>\n\n<p>It has all combinations you need and provides a nice, well readable syntax.</p>\n\n<h2>Is it a good idea to replace <code>use</code> with <code>invoke</code> operator or make this function <code>infix</code>?</h2>\n\n<ol>\n<li><code>use</code> isntead of <code>invoke</code></li>\n</ol>\n\n<p>It is opinion based, just like readability. Its up to you and your team.</p>\n\n<ol start=\"2\">\n<li>Infix</li>\n</ol>\n\n<p>Making a function an <code>infix</code> function is just another customisation option for your syntax. The only important thing to remeber is:</p>\n\n<blockquote>\n <p>Infix function calls have lower precedence than the arithmetic\n operators, type casts, and the rangeTo operator. The following\n expressions are equivalent:</p>\n \n <ul>\n <li>1 shl 2 + 3 is equivalent to 1 shl (2 + 3) </li>\n <li>0 until n * 2 is equivalent to 0 until (n * 2) </li>\n <li>xs union ys as Set<> is equivalent to xs union (ysas Set<>)</li>\n </ul>\n \n <p>On the other hand, infix function call's precedence is\n higher than that of the boolean operators && and ||, is- and\n in-checks, and some other operators. These expressions are equivalent\n as well:</p>\n \n <ul>\n <li>a && b xor c is equivalent to a && (b xor c) </li>\n <li>a xor b in c isequivalent to (a xor b) in c</li>\n </ul>\n</blockquote>\n\n<p><a href=\"https://kotlinlang.org/docs/reference/functions.html#infix-notation\" rel=\"nofollow noreferrer\">Kotlinlang.org</a></p>\n\n<p>-</p>\n\n<h2>Any improvement suggestions that you can think of</h2>\n\n<p>Strongly consider to use <a href=\"https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.comparisons/compare-by.html#compareby\" rel=\"nofollow noreferrer\">compareBy</a> like described before.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-18T13:00:05.693",
"Id": "454227",
"Score": "1",
"body": "compareBy gives great ways to create the comparators.\nThe post uses the comparetors to create predicates, to get a boolean value.\nTherefor, it's not a replacement for compareBy, but an addition to the Compareable interfaces.\nI do like your explanation for infix-functions; \nThis means that there aren't serious implications in this case."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-18T08:53:49.643",
"Id": "232577",
"ParentId": "231752",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-02T20:27:35.387",
"Id": "231752",
"Score": "5",
"Tags": [
"kotlin"
],
"Title": "More convenient way to use comparators in Kotlin"
}
|
231752
|
<p>How is this Implementation of a list in C?</p>
<p>Please tell me whether it is good or please mention any problems.
It is a singly linked List and I tried to do it recursively.</p>
<pre><code>#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
struct node{
int value;
struct node *next;
};
void add(struct node *lst, int num){
if(lst->next == NULL){
lst->value = num;
lst->next = (struct node*)malloc(sizeof(struct node*));
lst->next->next = NULL;
}else{
add(lst->next, num);
}
}
void print_lst(struct node *lst){
if(lst->next == NULL){
}else{
printf("\n%d", lst->value);
print_lst(lst->next);
}
}
int length(struct node *lst){
if(lst->next == NULL){
return 0;
}else{
return 1 + length(lst->next);
}
}
int get(struct node *lst, int pos){
if(pos < 0 || pos >= length(lst)){
fprintf(stderr ,"\nIndexOutOfBoundsException\n");
}else if(pos > 0 && pos <length(lst)){
pos += -1;
get(lst->next, pos);
} else if (pos == 0){
return lst->value;
}
}
int main ( ) {
struct node lst;
lst.next = NULL;
add(&lst, 13);
add(&lst, 12);
add(&lst, 1);
add(&lst, 10);
add(&lst, 10);
add(&lst, 4);
//print_lst(&lst);
printf("\n%d", get(&lst, 2));
printf("\n%d", get(&lst, 5));
printf("\n%d", get(&lst, 13));
printf("\n\n%d", length(&lst));
return 0;
}
</code></pre>
|
[] |
[
{
"body": "<ul>\n<li><p>Do not cast the result of <code>malloc</code>. If your code does <code>#include <stdlib.h></code>, the cast is redundant. If it does not, the cast just masks the warning, which may lead to hard to find bugs.</p></li>\n<li><p>Prefer <code>sizeof(object)</code> to <code>sizeof(type)</code>. The latter leads to the double maintenance problem, in case the type is changed.</p></li>\n<li><p>I strongly recommend to have a constructor-like function to create a node:</p>\n\n<pre><code>struct node * create_node(int num)\n{\n struct node * node = malloc(sizeof(*node));\n node->value = num;\n node->next = NULL;\n return node;\n}\n</code></pre>\n\n<p>It will spare you plenty of trouble when the definition of <code>struct node</code> changes.</p></li>\n<li><p>You should get a warning that <code>get</code> doesn't always return a value (if you do not, enable all warnings, or change the compiler). It is a very serious warning, and in real life the code with such a problem leads to some dire consequences. You <strong>must</strong> <code>return get(lst->next, pos);</code> in a recursive clause.</p>\n\n<p>The fact that your <code>main</code> printed expected values is an unlucky coincidence.</p>\n\n<p>What to return in the <code>IndexOutOfBound</code> situation is a different matter. Consider returning an error code along with the value.</p></li>\n<li><p>Calling <code>length(lst)</code> at each level of recursion degrades performance to quadratic.</p></li>\n<li><p>As a side note, rather than testing for <code>position < 0</code>, consider passing a position as some unsigned type. <code>size_t</code> is the most obvious candidate.</p></li>\n<li><p>Along the same line, a low level utility function such as <code>get</code> should refrain from printing anything.</p></li>\n<li><p>I strongly advise agains recursion when an iterative solution is immediately available.</p></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-03T13:05:58.687",
"Id": "452193",
"Score": "0",
"body": "Thanks for the statement. Now I can improve my List. Thanks"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-03T00:52:43.623",
"Id": "231761",
"ParentId": "231753",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "231761",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-02T20:34:51.423",
"Id": "231753",
"Score": "3",
"Tags": [
"c",
"linked-list"
],
"Title": "A singly linked list implementation in C"
}
|
231753
|
<p>This function determines which images should be loaded based on which image is currently in the viewport (array index), what direction the user is scrolling, and if the image has yet to be loaded. It has a bias for what direction the user is scrolling, and proximity to the current image in viewport (delta). It attempts to match the two closest elements before and after.</p>
<p>The logic is mostly a set of ugly <code>if</code> statements, which I hope could be improved upon. Perhaps here is an opportunity for me to learn and implement a new design pattern or algorithm?</p>
<p>Basic example of matches. </p>
<p>Legend: <code>_ = images</code>, <code>0 = array index</code> (image in viewport), <code>X = matches</code> (image to load)</p>
<pre><code>0 X _ _ _ _ _
0 X X _ _ _ _
X 0 X _ _ _ _
X X 0 X X _ _
_ X X 0 X X _
_ _ X X 0 X X
_ _ _ X X 0 X
_ _ _ _ X X 0
_ _ _ _ _ X 0
</code></pre>
<p>Above, it will match the two closest elements (if available) before and after the index given the delta (distance) from the index is the same for the before and after elements.</p>
<p>If the user is scrolling, there is a bias towards the direction they are scrolling if the delta between the before and after elements is not equal. Eg. Using 30% bias, If scrolling right, and the closest right-side elements are 12 and 13 units away, and the closest left-side element is 10 units away we only load the 12 and 13 elements.</p>
<p><code>Y = Miss</code> (closets element on respective before/after, but not matched due to scroll bias), <code>--> = scroll direction</code></p>
<pre><code>--> _ _ _ _ _ _ X X 0 X X _ _ _ _ _ _ _
--> _ _ _ _ Y Y _ _ _ 0 _ X X _ _ _ _ _
--> _ _ _ _ Y Y _ _ _ _ 0 _ _ X X _ _ _
--> _ _ _ _ Y Y _ _ _ _ 0 _ _ _ _ X X _
<-- _ _ _ _ X X _ _ _ 0 _ _ _ _ _ _ _ Y
<-- _ _ X X _ _ _ _ 0 _ _ _ _ _ _ _ _ Y
<-- X X _ _ _ _ _ _ 0 _ _ _ _ _ _ _ _ Y
</code></pre>
<p>Code:</p>
<pre><code>queueClosestComponent(){
//find our location in the array
let lastIndex = this.components.indexOf(this.lastComponentInViewport);
//creates an array of the closet items and their relative position to the last image in the viewport
let mapped = this.components
.map(function(item, index) {
//map the closeness of each item
return {
delta: Math.abs(lastIndex - index),
component: item,
position: Math.sign(lastIndex - index) === 1 ? "previous" : "next"
};
}, this)
.filter(function(item) {
//remove items that are loaded or currently loading
if (item.component.loadingState === null) {
return true;
}
})
.sortBy("delta");
let closestNext = mapped.filterBy("position", "next").firstObject;
let closestPrevious = mapped.filterBy("position", "previous").firstObject;
//second closest
let closest2ndNext = mapped.filterBy("position", "next").objectAt(1);
let closest2ndPrevious = mapped
.filterBy("position", "previous")
.objectAt(1);
//if there is no next or previous
if (!closestNext && !closestPrevious) {
return;
}
//if there is no previous
if (closestNext && !closestPrevious) {
//console.log("ADD: no previous: loading next");
this.addToQueue("background", closestNext.component);
if (closest2ndNext)
this.addToQueue("background", closest2ndNext.component);
return;
} else if (!closestNext && closestPrevious) {
//if there is no next
//console.log("ADD: no next: loading previous");
this.addToQueue("background", closestPrevious.component);
if (closest2ndPrevious)
this.addToQueue("background", closest2ndPrevious.component);
return;
}
//if next and previous are the same delta, and within 3 items away
if (
closestNext.delta === closestPrevious.delta &&
closestNext.delta <= 3
) {
//console.log("ADD: same delta");
this.addToQueue("background", closestNext.component);
this.addToQueue("background", closestPrevious.component);
return;
}
//when scrolling, give a preference to the item in the given direction, but regardless still try to load the closest
let directionalFavour = 1.3; //30% favour to the given direction
if (
closestNext.delta / directionalFavour <= closestPrevious.delta &&
this.direction === "next"
) {
//console.log("ADD: right/down next");
this.addToQueue("background", closestNext.component);
if (closest2ndNext)
this.addToQueue("background", closest2ndNext.component);
return;
} else if (
closestNext.delta / directionalFavour >= closestPrevious.delta &&
this.direction === "next"
) {
//console.log("ADD: right/down previous");
this.addToQueue("background", closestPrevious.component);
return;
}
if (
closestNext.delta >= closestPrevious.delta / directionalFavour &&
this.direction === "previous"
) {
this.addToQueue("background", closestPrevious.component);
if (closest2ndPrevious)
this.addToQueue("background", closest2ndPrevious.component);
//console.log("ADD: left/up previous ");
return;
} else if (
closestNext.delta <= closestPrevious.delta / directionalFavour &&
this.direction === "previous"
) {
//console.log("ADD: left/up next ");
this.addToQueue("background", closestNext.component);
return;
}
}
</code></pre>
|
[] |
[
{
"body": "<p>There are some things we can improve even while keeping the same algorithm:</p>\n\n<ul>\n<li>DRY repeated/inverted conditions</li>\n<li>DRY addToQueue() calls</li>\n<li>use a boolean <code>isNext</code> field instead of <code>position</code> string</li>\n<li>avoid creating four intermediate arrays to find closest items by using find() instead of filter()</li>\n<li>use arrow functions</li>\n<li>reduce the number of <code>return</code> statements to just one</li>\n</ul>\n\n<pre><code>class Foo {\n queueClosestComponent() {\n const lastIndex = this.components.indexOf(this.lastComponentInViewport);\n\n const mapped = this.components\n .map((component, index) => ({\n delta: Math.abs(lastIndex - index),\n isNext: index >= lastIndex,\n component,\n }))\n .filter(item => item.component.loadingState === null)\n .sortBy('delta');\n\n const next = mapped.find(m => m.isNext);\n const prev = mapped.find(m => !m.isNext);\n if (!next && !prev) {\n return;\n }\n const secondNext = mapped.find(m => m !== next && m.isNext);\n const secondPrev = mapped.find(m => m !== prev && !m.isNext);\n\n const directionalFavour = 1.3;\n let toAdd = [];\n\n if (next && !prev) {\n toAdd = [next, secondNext];\n } else if (!next && prev) {\n toAdd = [prev, secondPrev];\n } else if (next.delta === prev.delta && next.delta <= 3) {\n toAdd = [next, prev];\n } else if (this.direction === 'next') {\n toAdd = next.delta / directionalFavour <= prev.delta\n ? [next, secondNext]\n : [prev];\n } else if (this.direction === 'previous') {\n toAdd = prev.delta / directionalFavour <= next.delta\n ? [prev, secondPrev]\n : [next];\n }\n\n toAdd.forEach(item =>\n item && this.addToQueue('background', item.component)\n );\n },\n};\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-03T07:13:31.423",
"Id": "231768",
"ParentId": "231754",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "231768",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-02T21:22:31.170",
"Id": "231754",
"Score": "2",
"Tags": [
"javascript",
"beginner",
"algorithm",
"design-patterns"
],
"Title": "Find closest elements in an array relative to given index with a bias to distance from index and direction"
}
|
231754
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.