body stringlengths 25 86.7k | comments list | answers list | meta_data dict | question_id stringlengths 1 6 |
|---|---|---|---|---|
<p>I wrote a template class for a 2D vector that is intended to provide 2D vector arithmetic to be used in a Physics simulation program. Note that x and y are public or ease of use since encapsulation here would just decrease the readability of code that uses the class. </p>
<p>Is the general style of my code good and does it comply with modern C++ best practices? Thank you for the suggestions.</p>
<pre class="lang-c++ prettyprint-override"><code>template <typename T>
class Vector2D final {
public:
T x;
T y;
// Defaulted constructors
Vector2D(const Vector2D<T>& v) = default;
~Vector2D() = default;
Vector2D(T ix, T iy);
// Member Utility Functions
void Set(T ix, T iy);
T Magnitude();
// Overloaded Compound Operators
Vector2D<T>& operator+=(const Vector2D<T>& rhs);
Vector2D<T>& operator*=(const Vector2D<T>& rhs);
Vector2D<T>& operator-=(const Vector2D<T>& rhs);
Vector2D<T>& operator/=(const T& rhs);
Vector2D<T>& operator=(const Vector2D<T>& rhs);
};
// Non-Compound Operators.
template <typename T> Vector2D<T> operator+(Vector2D<T> lhs, const Vector2D<T>& rhs);
template <typename T> Vector2D<T> operator*(Vector2D<T> lhs, const Vector2D<T>& rhs);
template <typename T> Vector2D<T> operator-(Vector2D<T> lhs, const Vector2D<T>& rhs);
template <typename T> Vector2D<T> operator/(Vector2D<T> lhs, const T& rhs);
template <typename T>
Vector2D<T>::Vector2D(T ix, T iy)
: x(ix)
, y(iy)
{
}
template <typename T>
void Vector2D<T>::Set(T ix, T iy) {
x = ix;
y = iy;
}
template <typename T>
T Vector2D<T>::Magnitude() {
return x*x + y*y;
}
template <typename T>
Vector2D<T>& Vector2D<T>::operator+=(const Vector2D<T>& rhs) {
x += rhs.x;
y += rhs.y;
return *this;
}
template <typename T>
Vector2D<T>& Vector2D<T>::operator*=(const Vector2D<T>& rhs) {
x *= rhs.x;
y *= rhs.y;
return *this;
}
template <typename T>
Vector2D<T>& Vector2D<T>::operator-=(const Vector2D<T>& rhs) {
x -= rhs.x;
y -= rhs.y;
return *this;
}
template <typename T>
Vector2D<T>& Vector2D<T>::operator/=(const T& rhs) {
x /= rhs;
y /= rhs;
return *this;
}
template <typename T>
Vector2D<T>& Vector2D<T>::operator=(const Vector2D<T>& rhs) {
x = rhs.x;
y = rhs.y;
return *this;
}
template <typename T>
Vector2D<T> operator+(Vector2D<T> lhs, const Vector2D<T>& rhs) {
lhs += rhs;
return lhs;
}
template <typename T>
Vector2D<T> operator*(Vector2D<T> lhs, const Vector2D<T>& rhs) {
lhs *= rhs;
return lhs;
}
template <typename T>
Vector2D<T> operator-(Vector2D<T> lhs, const Vector2D<T>& rhs) {
lhs -= rhs;
return lhs;
}
template <typename T>
Vector2D<T> operator/(Vector2D<T> lhs, const T& rhs) {
lhs /= rhs;
return lhs;
}
</code></pre>
<p>Some examples of using this with float. I intend to only use it with floating point types (float, double, long double etc) and have tested it with other types but will present float here for brevity.</p>
<pre><code>Vector2D<float> v1 = {1.0, 2.0};
Vector2D<float> v2 = {2.0, 3.0};
v1 += v2;
assert(v1.x == 3.0 && v1.y == 5.0);
v1 -= v2;
assert(v1.x == 1.0 && v1.y == 2.0);
v1 *= v2;
assert(v1.x == 2.0 && v1.y == 6.0);
v1 /= 2.0;
assert(v1.x == 1.0 && v1.y == 3.0);
v1.Set(1.0, 2.0);
v2.Set(2.0, 3.0);
Vector2D<float> v3 = {0.0, 0.0};
v3 = v1 + v2;
assert(v3.x == 3.0 && v3.y == 5.0);
v3 = v1 - v2;
assert(v3.x == -1.0 && v3.y == -1.0);
v3 = v1 * v2;
assert(v3.x == 2.0 && v3.y == 6.0);
v3 = v1 / 2.0f;
assert(v3.x == 0.5 && v3.y == 1.0);
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-03T18:39:24.733",
"Id": "381258",
"Score": "0",
"body": "What are your testcases?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-03T19:17:47.780",
"Id": "381261",
"Score": "0",
"body": "I updat... | [
{
"body": "<p>This looks pretty good! I don't think you need to change much, but there are some things missing that you will likely need:</p>\n\n<ol>\n<li><code>normalize()</code> or <code>normal()</code> method to either normalize a vector or return a normalized version of the vector. If you're doing physics, ... | {
"AcceptedAnswerId": "197750",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-03T18:31:07.237",
"Id": "197747",
"Score": "3",
"Tags": [
"c++",
"vectors"
],
"Title": "Comment on the style of this C++ class for a 2D Vector"
} | 197747 |
<p>So I am making a little script to convert a string of a basic maths calculation eg: </p>
<p><code>"2+3+4-2+2-12+42"</code></p>
<p>and it should return the total. </p>
<p>What I have so far : </p>
<pre><code><?php
function my_operator($a, $b, $char) {
switch($char) {
case '-': return $a - $b;
case '+': return $a + $b;
default: return $a;
}
}
$string = "1+41-3+5-12+5+10";
//Ans = 47
$Arr = str_split($string);
$total = 0;
$cache1 = "";
$cache2 = "";
$lastOperator ="";
foreach ($Arr as $char) {
if ($char == "+") {
if ($cache2 == "") {
$total = $cache1;
}
$cache2 = $cache1;
$cache1 = "";
$total = my_operator($total, (int)$cache2, $lastOperator);
$lastOperator = "+";
} else if ($char == "-") {
if ($cache2 == "") {
$total = $cache1;
}
$cache2 = $cache1;
$cache1 = "";
$total = my_operator($total, (int)$cache2, $lastOperator);
$lastOperator = "-";
} else {
$cache1 = $cache1.$char;
}
}
$total = my_operator($total, (int)$cache1, $lastOperator);
echo $total;
</code></pre>
<p>What are some improvements I can make? Thanks.</p>
| [] | [
{
"body": "<p>I really should be discussing your code here, but ones I got started I took it a bit too far. So before I do that, let's talk about your code.</p>\n\n<h2>names</h2>\n\n<p>Names of variables and functions give meaning to your code. They should tell the reader exactly what is in them, or what they d... | {
"AcceptedAnswerId": "197815",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-03T19:53:58.100",
"Id": "197748",
"Score": "2",
"Tags": [
"php"
],
"Title": "PHP Script - Converting string of calculations to result"
} | 197748 |
<p>This is improved code from my <a href="https://codereview.stackexchange.com/questions/195112/android-game-inspired-by-space-invaders-and-moon-patrol">previous question.</a> This mini game which we call <a href="https://play.google.com/store/apps/details?id=dev.android.buggy" rel="nofollow noreferrer">"Moon Buggy" is available in beta</a> from the google playstore. </p>
<p><a href="https://i.stack.imgur.com/afLta.gif" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/afLta.gif" alt="enter image description here"></a></p>
<p>The action is that you control a vechicle on the moon and you defend yourself against evil UFO:s. </p>
<p>I have written a separate class for the UFO which is instanciated once for every UFO:</p>
<pre><code>import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.os.Handler;
import android.os.Looper;
import java.util.Random;
public class AttackingAlien extends Alien {
private Bitmap alien;
static boolean recent = true; // switch this in beginning
private long changeDirections = System.currentTimeMillis();
private long fireTimeout = System.currentTimeMillis();
private int screenWidth;
private int screenHeight;
private int ufoY = 0;
private int ufoX = 0;
private int missileX = 25;
private int deltaUfoY = 7;
private int deltaUfoX = 7;
private int missileOffSetY = 0;
private int missileYstart = 0;
private boolean wasHit = false;
private boolean alienexplode;
private boolean waitForTimer, waitForUfoTimer;
private boolean toggleDeltaY = true;
private boolean runOnce = true;
private boolean startMissile = true;
public AttackingAlien(ParallaxView view, Context context, String name, final int screenWidth, int screenHeight, int p) {
super(context, name);
this.deltaUfoY = p;
int alienResID = context.getResources().getIdentifier(name,
"drawable", context.getPackageName());
alien = BitmapFactory.decodeResource(context.getResources(), alienResID);
int max = (int) (0.75 * screenWidth);
int min = 20;
int diff = max - min;
Random rn = new Random();
int i5 = rn.nextInt(diff + 1);
i5 += min;
missileX = i5;
ufoX = missileX;
max = 200;
diff = max - min;
this.screenHeight = screenHeight;
this.screenWidth = screenWidth;
ufoY = 0;
waitForUfoTimer = true;
int max2 = 20000;
int min2 = 18000;
int diff2 = max2 - min2;
Random rn2 = new Random();
int result = rn2.nextInt(diff2 + 1);
result += min2;
Handler handler = new Handler(Looper.getMainLooper());
handler.postDelayed(new Runnable() {
@Override
public void run() {
missileX = ufoX;
setRecent();
waitForUfoTimer = false;
}
}, result);
}
private void changeDirections() {
int max2 = 500;
int min2 = 100;
int diff2 = max2 - min2;
Random rn2 = new Random();
int result = rn2.nextInt(diff2 + 1);
result += min2;
if (System.currentTimeMillis() - changeDirections >= result) {
// Change direction here
toggleDeltaY = !toggleDeltaY;
changeDirections = System.currentTimeMillis();
}
}
public void update(Canvas canvas, Paint paint, boolean toggleDeltaY, int screenWidth, int screenHeight) {
if (ufoX > screenWidth - 250 || ufoX < 10) { // UFO change horizontal direction
deltaUfoX = -deltaUfoX;
}
//make sure UFO does not move too low
if (ufoY >= 20) {
deltaUfoY = -deltaUfoY;
}
if ((ufoY + screenHeight / 100 * 25) <= 0) // don't move outside the top
deltaUfoY = -deltaUfoY;
if (!waitForUfoTimer && Background.checkpoint >= 'A') { // && sectionComplete > 0) {
runOnce = true;
//alienY++;
canvas.drawBitmap(alien, ufoX + 10, ufoY + screenHeight / 100 * 25, paint);
}
//missileX = missileX + speedAlienX;
ufoX = ufoX + deltaUfoX;
if (waitForTimer) missileX = ufoX;
if (toggleDeltaY) {
deltaUfoY = -deltaUfoY;
}
ufoY = ufoY + deltaUfoY;
changeDirections();
}
public void checkBeingHit(int[] missiles, int buggyXDisplacement, double buggyXDistance, Canvas canvas, Bitmap explode2, Paint paint, int score, ParallaxView pview, int i1, int xbuggy2) {
// if UFO is being hit by buggy
if (!waitForTimer && java.lang.Math.abs(ufoX + 10 - 400 - buggyXDistance) * 2 < (alien.getWidth()) && java.lang.Math.abs(ufoY + screenHeight / 100 * 25 - (screenHeight / 100 * 95 - missiles[i1] - xbuggy2)) * 2 < (alien.getHeight())) {
missileOffSetY = -9999;
canvas.drawBitmap(explode2, ufoX + 10, ufoY + screenHeight / 100 * 25, paint);
if (runOnce) {
ParallaxView.score = ParallaxView.score + 100;
Handler handler = new Handler(Looper.getMainLooper());
handler.postDelayed(new Runnable() {
@Override
public void run() {
int max = (int) (0.75 * screenWidth);
int min = 20;
int diff = max - min;
Random rn = new Random();
int i5 = rn.nextInt(diff + 1);
i5 += min;
missileX = i5;//25;
ufoX = missileX;
ufoY = 0;
alienexplode = false;
waitForTimer = false;
waitForUfoTimer = false;
startMissile = true;
}
}, 3000);
}
runOnce = false;
waitForUfoTimer = true;
startMissile = false;
waitForTimer = true;
if (!alienexplode) {
pview.changeText();
}
alienexplode = true;
}
}
private void checkFire() {
int max = 15000;
int min = 12000;
int diff = max - min;
Random rn = new Random();
int i5 = rn.nextInt(diff + 1);
i5 += min;
if (System.currentTimeMillis() - fireTimeout >= i5) { // means how often the alien fires
fireTimeout = System.currentTimeMillis();
missileOffSetY = 0;
missileX = ufoX;
}
}
private void setRecent() {
AttackingAlien.recent = false;
}
public boolean drawMissile(ParallaxView view, Canvas canvas, Paint paint, int buggyXDisplacement, double buggyXDistance, Bitmap buggy, int jumpHeight, int screenHeight) {
wasHit = false;
checkFire();
// if buggy was hit by a missile
if (!AttackingAlien.recent && !view.waitForTimer && java.lang.Math.abs(((buggyXDisplacement + buggyXDistance) + buggy.getWidth() / 2) - (missileX + 10 + alien.getWidth() / 2)) < buggy.getWidth() / 2 && java.lang.Math.abs((ufoY + screenHeight / 100 * 25 + 75 + missileOffSetY) - ((screenHeight * 0.3) - jumpHeight + buggy.getHeight())) < 65) {
AttackingAlien.recent = true;
canvas.drawBitmap(view.explode, (float) (buggyXDisplacement + buggyXDistance), (float) (screenHeight * 0.5) - jumpHeight, paint);
ParallaxView.bombed--;
missileOffSetY = 0;
wasHit = true;
view.recent = true;
Handler handler = new Handler(Looper.getMainLooper());
handler.postDelayed(new Runnable() {
@Override
public void run() {
setRecent();
waitForTimer = false;
wasHit = false;
}
}, 7000);
waitForTimer = true;
} else {
// buggy was not hit so UFO fires more missiles
//TODO: check if the movements are realistic
if (!waitForTimer && !waitForUfoTimer && Background.checkpoint >= 'A') {
if (startMissile) {
startMissile = false;
missileYstart = ufoY;
}
canvas.drawText("●", missileX + alien.getWidth() / 2, missileYstart + screenHeight / 100 * 25 + alien.getHeight() + missileOffSetY, paint);
missileOffSetY = missileOffSetY + 4;
}
wasHit = false;
}
return wasHit;
}
}
</code></pre>
<p>The remainder of the code is available on request. </p>
| [] | [
{
"body": "<ol>\n<li><p>You should remove duplicated blocks.</p>\n\n<pre><code>int max2 = 20000;\nint min2 = 18000;\nint diff2 = max2 - min2;\nint result = rn2.nextInt(diff2 + 1);\nresult += min2;\n</code></pre>\n\n<p>is repeated many times with slight variation in values of min and max. you can extract it as a... | {
"AcceptedAnswerId": "197762",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-03T20:39:31.523",
"Id": "197751",
"Score": "1",
"Tags": [
"java",
"game",
"android"
],
"Title": "Improved Android mini game"
} | 197751 |
<p>Edit: This code was reworked and repostetd under a new question: <a href="https://codereview.stackexchange.com/questions/199706/generic-skip-list-implementation-in-c-version-3">Generic Skip list implementation in C++ Version 3</a></p>
<p>This is a follow up of:
<a href="https://codereview.stackexchange.com/questions/197309/non-generic-skip-list-implementation-in-c">Non generic Skip List implementation in C++</a></p>
<p>If you don't know what a Skiplist is: <a href="https://en.wikipedia.org/wiki/Skip_list" rel="nofollow noreferrer">https://en.wikipedia.org/wiki/Skip_list</a></p>
<p>I continued the work on the Skiplist. I tried to incorporate the improvements suggested. I still don't feel ready to add more stuff ( Iterator class, Template Skipnode). I think it's better to first present the progress so far.</p>
<p>A short summary of what has changed:</p>
<p><b>Documentation / Clean up the code</b>:</p>
<p>I added alot more comments and tried to make the code more readable in general. I hope the code is now easier to follow. I think one of the reasons not many people commented last time, was the missing explanations in the code.</p>
<p><b>Vector:</b></p>
<p>I removed the false micromanagement of vectors size.</p>
<p><b>Random Generator:</b></p>
<p>The random generator was reworked like suggested.</p>
<p><b>Rules of Five:</b></p>
<p>I implemented the missing functions Copy Constructor, Move Constructor, Copy Assignment and Move assignment.</p>
<p><b>Implementation of Head Element:</b></p>
<p>Head now doesn't hold key and value anymore, it only contains pointers.</p>
<p><b>Unit Tests:</b></p>
<p>I added Unit Tests in seperate cpp / h files to test the vector more systematically.</p>
<p><b>skiplist.h</b></p>
<pre><code>#ifndef SKIP_LIST_GUARD
#define SKIP_LIST_GUARD
#include <iostream>
#include <random>
#include <vector>
namespace skiplist {
class Skiplist {
public:
Skiplist() = default; // constructor
~Skiplist() noexcept; // destructor
Skiplist(const Skiplist& other); // copy constructor
Skiplist& operator=(const Skiplist& other); // copy assignment
Skiplist(Skiplist&& other); // move constructor
Skiplist& operator=(Skiplist&& other); // move assignment
void insert(int key, int value); // insert elements, double keys are not allowed
bool erase(int key); // search for an element and erase it from the skip list
int* find(int key); // find element by key and return the value
void clear() noexcept; // erase all elements
size_t size() const; // return count of nodes
int get_top_level() const { return top_level; } // maximum height the skiplist has reached
void print(std::ostream& os) const; // prints out all elements in list, replace if iterators implemented (for const auto & x : skiplist)
void debug_print(std::ostream& os) const; // show all the levels for debug only. can this be put into skiplist_unit_tests ?
private:
struct Skipnode; // forward declaration so Basenode can have Skiplist*
struct Basenode { // Empty node, mainly created to represent head element.
// Is there a way to get a empty head with no key / values without using this ?
Basenode(int in_level);
Basenode(const std::vector<Skipnode*>& in_next);
std::vector <Skipnode*> next;
};
struct Skipnode : Basenode { // derived so with Basenode* we can start the iteration of the node on head
Skipnode(int in_key, int in_value, int in_level);
Skipnode(int in_key, int in_value, const std::vector<Skipnode*>& in_next);
int key;
int value;
};
size_t top_level_of_new_node(); // helper function to calculate level of new node random
Basenode head{0}; // element before first element containg pointers to all the first elements of each level
size_t top_level = 0; // maximum level the nodes have reached so far
std::mt19937 random_engine = std::mt19937{ std::random_device{}() }; //random generator member
};
bool next_level(std::mt19937& eng); // flip coin helper function returning true or false random
}
#endif
</code></pre>
<p><b>skiplist.cpp</b></p>
<pre><code>#include "skiplist.h"
namespace skiplist {
Skiplist::Basenode::Basenode(int in_level)
:next{ in_level,nullptr }
{
}
Skiplist::Basenode::Basenode(const std::vector<Skipnode*>& in_next)
: next{ in_next }
{
}
Skiplist::Skipnode::Skipnode(int in_key, int in_value, int in_level)
:key{ in_key }, value{ in_value }, Basenode{in_level}
{
}
Skiplist::Skipnode::Skipnode(int in_key, int in_value, const std::vector<Skipnode*>& in_next)
: key{ in_key }, value{ in_value }, Basenode{in_next}
{
}
Skiplist::~Skiplist() noexcept // destructor
{
if (top_level == 0) return;
Skipnode* current_position = head.next[0]; //start on first element
while (current_position->next[0] != nullptr) {
Skipnode* lastpos = current_position;
current_position = current_position->next[0];
delete lastpos;
}
delete current_position; //delete last element
}
Skiplist::Skiplist(const Skiplist& other) // copy constructor
:head{other.head},top_level{other.top_level}, random_engine{other.random_engine }
// on the first level let the other Skiplist present its elements and make a deep copy of them
// now still the higher levels point to the other node so this is fixed in the second part
// then the next level pointers are installed linked to the elements of the new node
{
if (top_level == 0) return; // no elements are present so dont bother to allocate nodes
{
// installment of lowest level, each element is located here
Skipnode* other_node = other.head.next[0];
Basenode* current_position = &head;
while (other_node != nullptr) {
Skipnode* new_node = new Skipnode{ other_node->key,other_node->value,other_node->next };
current_position->next[0] = new_node;
current_position = current_position->next[0];
other_node = other_node->next[0];
}
current_position->next[0] = nullptr;
}
// installment of the other levels
for (size_t curr = 1; curr < top_level; ++curr) {
Basenode* current_position = &head; // the current position of the level[curr]
Skipnode* next_position = current_position->next[curr]; // next position after curr containing still pointers to the other skiplist
Basenode* lowest_position = &head; // lowest level position used to find the new pointers and attach them "behind" current
while (lowest_position != nullptr && next_position != nullptr) {
if (lowest_position->next[0]->key == next_position->key) { // check by unique key, address of next pos is still of the other skiplist
current_position->next[curr] = lowest_position->next[0]; // lowest is the valid address of new node
current_position = current_position->next[curr];
next_position = next_position->next[curr]; // go to next element of other node
if (next_position == nullptr) { // case end is reached
current_position->next[curr] = nullptr;
current_position = current_position->next[curr];
}
}
else { // forward position of lowest level until other key == next position key
lowest_position = lowest_position->next[0];
}
}
}
}
Skiplist& Skiplist::operator=(const Skiplist& other) // copy assignment
// copy assignmnt currently the same as copy constructor
// would it be better to reuse the already existing space?
// maybe override the values of already available nodes
{
if (&other == this) return *this;
head = other.head;
top_level = other.top_level;
random_engine = other.random_engine;;
if (top_level == 0) return *this; // no elements are present so dont bother to allocate nodes
{
// installment of lowest level, each element is located here
Skipnode* other_node = other.head.next[0];
Basenode* current_position = &head;
while (other_node != nullptr) {
Skipnode* new_node = new Skipnode{ other_node->key,other_node->value,other_node->next };
current_position->next[0] = new_node;
current_position = current_position->next[0];
other_node = other_node->next[0];
}
current_position->next[0] = nullptr;
}
// installment of the other levels
for (size_t curr = 1; curr < top_level; ++curr) {
Basenode* current_position = &head; // the current position of the level[curr]
Skipnode* next_position = current_position->next[curr]; // next position after curr containing still pointers to the other skiplist
Basenode* lowest_position = &head; // lowest level position used to find the new pointers and attach them "behind" current
while (lowest_position != nullptr && next_position != nullptr) {
if (lowest_position->next[0]->key == next_position->key) { // check by unique key, address of next pos is still of the other skiplist
current_position->next[curr] = lowest_position->next[0]; // lowest is the valid address of new node
current_position = current_position->next[curr];
next_position = next_position->next[curr]; // go to next element of other node
if (next_position == nullptr) { // case end is reached
current_position->next[curr] = nullptr;
current_position = current_position->next[curr];
}
}
else { // forward position of lowest level until other key == next position key
lowest_position = lowest_position->next[0];
}
}
}
return *this;
}
Skiplist::Skiplist(Skiplist&& other) // move constructor
:head{ other.head }, top_level{ other.top_level }, random_engine{ other.random_engine }
{
head.next = other.head.next; // point all other nodes to new location
other.head = Basenode{ 0 }; // empty other head so the connections to the nodes are gone
other.top_level = 0;
other.random_engine = std::mt19937{ std::random_device{}() };
}
Skiplist& Skiplist::operator=(Skiplist&& other) // move assignment
{
head = other.head;
top_level = other.top_level;
random_engine = other.random_engine;
head.next = other.head.next; // point all other nodes to new location
other.head = Basenode{ 0 }; // empty other head so the connections to the nodes are gone
other.top_level = 0;
other.random_engine = std::mt19937{ std::random_device{}() };
return *this;
}
size_t Skiplist::top_level_of_new_node()
// flips a "coin" true / false . As long as the result is true the level gets increased
// the chance to reach a higher level decreases evey time by roughly half
// e.g. level 2 = 50% 3 = 25% etc.
// This is to make sure that on higher levels there are less nodes then on the lower ones
// the count of nodes on each levels should be arround half of the count of nodes on the level before
// if calculated level is bigger than the max level it gets increased
{
size_t new_node_level = 0;
do {
++new_node_level;
if (new_node_level == (top_level + 1)) { //new node can maximum grow by one lvl;
++top_level;
head.next.resize(head.next.size() + 1, nullptr); // head.next size must be always = top size
break;
}
} while (next_level(random_engine)); //flip coin. every time it is true go to the next lvl
return new_node_level;
}
void Skiplist::insert(int key, int value)
// first key and value is inserted into a new insert_node.
// the level until were the node is present is calculated "random"
//
// Then the right position for the node is searched:
// The search starts on the highest level of the insert_node
// if next node on the level is not exist or the value of the key bigger
// check if node is high enough to be on this height
// if high enough install node between current and next
{
// make a new node which is present until the calculated_level
Skipnode* new_node = new Skipnode(key, value, top_level_of_new_node()); //create new node
size_t current_level = top_level; //start on highest lvl
Basenode* current_position = &head; //start on first element
bool node_added = false;
do {
const size_t curr = current_level - 1; // for readability
if (current_position->next[curr] == nullptr || current_position->next[curr]->key > key) {
if (new_node->next.size() >= current_level) { // is node on this level?
node_added = true;
new_node->next[curr] = current_position->next[curr]; // install new node before next node
current_position->next[curr] = new_node;
}
--current_level; // go to the next lower lvl
}
else {
current_position = current_position->next[curr]; // move to the next element on the level
}
} while (current_level > 0);
if (!node_added) // case new node could not be added if new key == key in table
delete new_node;
}
bool Skiplist::erase(int key)
// starts search on the highest lvl of the skiplist
// if a node with the erase key is found the algorith goes
// down until the lowest lvl.
// on the way down all links with the key in the list are removed
// on the lowest lvl the current node which contains the erase key is deleted
{
size_t current_level = top_level; //start on highest lvl
Basenode* current_position = &head; //start on head
while (current_level > 0) {
const size_t curr = current_level - 1; // for readability
const size_t top = top_level - 1; // for readability
if ((current_position->next[curr] == nullptr) || (current_position->next[curr]->key > key)) {
--current_level;
}
else if (current_position->next[curr]->key == key) { //key found on current lvl
--current_level; // go down first before link is deleted
if (current_level != 0)
current_position->next[curr] = current_position->next[curr]->next[curr]; // take out pointer of found element from list on current level
else { // first level of skip node is reached
Skipnode* delete_node = current_position->next[current_level]; // store position for delete
current_position->next[curr] = current_position->next[curr]->next[curr]; // take out pointer of list
delete delete_node; // delete current position found node
while (head.next[top_level - 1] == nullptr /*&& top_level > 1*/) { //no nodes on highest lvl
--top_level;
if (top_level == 0)
break;
}
return true;
}
}
else {
current_position = current_position->next[curr]; // iterate horizontal on current lvl
}
}
return false;
}
int* Skiplist::find(int key)
// find element by key and return pointer to value
// first it is iterated horizontal and vertical until the last level is reached
// on the last level if the keys match the val is returned
{
Basenode* current_position = &head; //start on head
size_t current_level = top_level; //start on highest lvl
while (current_level > 1) {
const size_t curr = current_level - 1; // for readability
if (current_position->next[curr] == nullptr || (current_position->next[curr]->key >= key)) {
--current_level; // traverse veertical
}
else {
current_position = current_position->next[curr]; // traverse horizontal
}
}
while (current_position->next[0] != nullptr) {
if (current_position->next[0]->key == key) { // element found
current_position = current_position->next[0];
return &static_cast<Skipnode*>(current_position)->value;
}
current_position = current_position->next[0];
}
return nullptr; //element was not found;
}
void Skiplist::clear() noexcept
{
if (top_level == 0) return;
Skipnode* current_position = head.next[0]; //start on first element
while (current_position->next[0] != nullptr) {
Skipnode* lastpos = current_position;
current_position = current_position->next[0];
delete lastpos;
}
delete current_position; //delete last element
top_level = 0;
head = Basenode{ 0 };
}
size_t Skiplist::size() const
// size of the skipnode is calculated on request
{
if (top_level == 0) return 0; //special case nothing is build yet
size_t size = 0;
const Basenode* current_position = &head;
if (current_position->next.empty())
return size;
while (current_position->next[0] != nullptr) {
++size;
current_position = current_position->next[0];
}
return size;
}
void Skiplist::print(std::ostream& os) const
//prints out all elements
{
if (top_level == 0)
return;
const Skipnode* current_position = head.next[0];
while (current_position != nullptr) {
os << current_position->key << "/" << current_position->value << " ";
current_position = current_position->next[0];
}
os << "\n";
}
void Skiplist::debug_print(std::ostream& os) const
//messy debug routine to print with all available layers
{
if (top_level == 0) {
os << "empty" << '\n';
return;
}
Basenode* current_position = const_cast<Basenode*>(&head);
size_t current_level = current_position->next.size() - 1;
current_position = current_position->next[current_level];
if (head.next[0] == nullptr)
return;
while (current_level >= 0) {
os << "lvl: " << current_level << "\t";
Basenode* lastpos = const_cast<Basenode*>(&head);
while (current_position != nullptr) {
if (current_level > 0) {
int void_count = 0;
while (lastpos != nullptr && static_cast<Skipnode*>(lastpos)->key != static_cast<Skipnode*>(current_position)->key) {
lastpos = lastpos->next[0];
++void_count;
}
for (int i = 0; i < void_count - 1; ++i)
os << "-/-- ";
}
if (current_position != &head)
os << static_cast<Skipnode*>(current_position)->key << "/" << static_cast<Skipnode*>(current_position)->value << " ";
current_position = static_cast<Skipnode*>(current_position->next[current_level]);
}
os << "\n";
if (current_level == 0)
break;
--current_level;
current_position = const_cast<Basenode*>(&head);
}
}
bool next_level(std::mt19937& eng)
{
static auto val = std::mt19937::result_type{ 0 };
static auto bit = std::mt19937::word_size;
if (bit >= std::mt19937::word_size)
val = eng();
return val & (std::mt19937::result_type{ 1 } << (bit++));
}
}
</code></pre>
<p><b>skiplist_unit_test.h</b></p>
<pre><code>#ifndef SKIPLIST_UNIT_TEST_GUARD_280620182216
#define SKIPLIST_UNIT_TEST_GUARD_280620182216
#include <iostream>
#include <vector>
#include <string>
#include <map>
#include <chrono>
#include "skiplist.h"
namespace skiplist::unit_test {
int get_random(int min, int max);
void insert_print(int key, int val, Skiplist& sk, const std::string& skiplist_name, std::ostream& os);
void erase_print(int key, Skiplist& sk, const std::string& skiplist_name, std::ostream& os);
void info_print(const Skiplist& a, const std::string& a_name, std::ostream& os);
void test_insert_and_erase(std::ostream& os);
void test_leakage_of_memory(std::ostream& os);
void test_find(std::ostream& os);
void test_copy_constructor(std::ostream& os);
void test_move_constructor(std::ostream& os);
void test_copy_assignment(std::ostream& os);
void test_move_assignment(std::ostream& os);
void test_performance_of_insert_delete(std::ostream& os, const int repeats, const int count_of_elements);
}
#endif
</code></pre>
<p><b>skiplist_unit_test</b></p>
<pre><code>#include "skiplist_unit_test.h"
namespace skiplist::unit_test{
int get_random(int min, int max)
{
static std::random_device rd;
static std::mt19937 mt(rd());
std::uniform_int_distribution<int> distribution(min, max);
return distribution(mt);
}
void insert_print(int key, int val, Skiplist& sk, const std::string& skiplist_name, std::ostream& os)
{
sk.insert(key, val);
os << "insert in " << skiplist_name << " key " << key << " and val " << val << '\n' << '\n';
}
void erase_print(int key, Skiplist& sk, const std::string& skiplist_name, std::ostream& os)
{
sk.erase(key);
os << "erase from " << skiplist_name << " key " << key << '\n' << '\n';
}
void info_print(const Skiplist& a, const std::string& a_name, std::ostream& os)
{
os << "Skiplist " << a_name << ":\n";
a.debug_print(os);
os << "top_lvl:" << a.get_top_level() << '\n';
os << "size:" << a.size() << '\n' << '\n';
}
void test_insert_and_erase(std::ostream& os)
{
os << "test_insert_and_erase START\n";
Skiplist skiplist;
std::vector<int> keys{ 1,6,2,7,3,8,4,9,5 };
for (const auto& x : keys) {
skiplist.insert(x, x + 10);
skiplist.print(os);
skiplist.debug_print(os);
os << '\n';
}
skiplist.debug_print(os);
os << "size:" << skiplist.size() << '\n';
if (skiplist.size() != keys.size())
std::cout << "Invalid Size!!!\n";
os << "top_level:" << skiplist.get_top_level() << '\n';
std::sort(keys.begin(), keys.end());
for (const auto& x : keys) {
os << '\n';
os << "delete " << x << '\n';
skiplist.erase(x);
skiplist.debug_print(os);
os << "size:" << skiplist.size() << '\n';
}
os << "test_insert_and_erase FINNISHED\n";
}
void test_leakage_of_memory(std::ostream& os)
// insert and erase repeatly into a skip list
// if no memory leak there shouldnt be more memory and more memory used
{
std::vector<int>keys;
constexpr int fill_size = 100000;;
constexpr int repeats = 10;
for (int i = 0; i < fill_size; ++i)
keys.push_back(i);
Skiplist skiplist;
for (int i = 0; i < repeats; ++i) {
for (const auto&x : keys)
skiplist.insert(x, x + 10);
for (const auto&x : keys)
skiplist.erase(x);
}
}
void test_find(std::ostream& os)
{
os << "test_find START\n";
Skiplist skiplist;
std::vector<int> keys{ 1,6,2,7,3,8,4,9,5 };
for (const auto& x : keys)
skiplist.insert(x, x + 10);
skiplist.debug_print(os);
std::sort(keys.begin(), keys.end());
for (const auto& x : keys) {
const int search_value = x + 10;
os << "searching with key " << x << " for value " << search_value << '\t';
int* value = skiplist.find(x);
if (value == nullptr) {
os << "TEST FAILED\n";
continue;
}
os << "found:" << *value << '\t';
if (*value == search_value)
os << "TEST PASSED\n";
else
os << "TEST FAILED\n";
}
const int invalid_key = keys.back() + 1;
os << "searching with key " << invalid_key << " not in skiplist" << '\t';
int* value = skiplist.find(invalid_key); // insert element which should not be found
if (value == nullptr) {
os << "not found" << '\t';
os << "TEST PASSED\n";
}
else {
os << "found:" << *value << '\t';
os << "TEST FAILED\n";
}
os << "test_find FINNISHED\n";
}
void test_copy_constructor(std::ostream& os)
{
os << "test_copy_constructor START\n";
Skiplist a;
for (int i = 2; i<10; ++i)
a.insert(i, i + 10);
info_print(a, "a", os);
Skiplist b{ a };
info_print(b, "b", os);
a.clear();
info_print(a, "a", os);
info_print(b, "b", os);
os << "test_copy_constructor FINISHED\n";
}
void test_move_constructor(std::ostream& os)
{
os << "test_move_constructor START\n";
Skiplist a;
for (int i = 2; i<10; ++i)
a.insert(i, i + 10);
info_print(a, "a", os);
Skiplist b{ std::move(a) };
info_print(a, "a", os);
info_print(b, "b", os);
for (int i = 12; i<15; ++i)
a.insert(i, i + 20);
info_print(a, "a", os);
info_print(b, "b", os);
os << "test_move_constructor FINISHED\n";
}
void test_copy_assignment(std::ostream& os)
{
os << "test_copy_assignment START\n";
Skiplist a;
for (int i = 2; i<10; ++i)
a.insert(i, i + 10);
info_print(a, "a", os);
Skiplist b;
b = a;
info_print(b, "b", os); // b should be the same like a
a.clear(); // clearing a should do nothing with b
info_print(a, "a", os);
info_print(b, "b", os);
os << "test_copy_constructor FINISHED\n";
}
void test_move_assignment(std::ostream& os)
{
os << "test_move_assignment START\n";
Skiplist a;
for (int i = 2; i<10; ++i) // fill first list
a.insert(i, i + 10);
info_print(a, "a", os);
Skiplist b;
for (int i = 12; i<15; ++i) // fill second list with other values
b.insert(i, i + 10);
info_print(b, "b", os);
b = std::move(a);
info_print(a, "a", os); // a should be empty
info_print(b, "b", os); // b should contain a's values, b's values get override
a.clear(); // clearing a should do nothing with b
info_print(a, "a", os);
info_print(b, "b", os);
os << "test_move_constructor FINISHED\n";
}
void test_performance_of_insert_delete(std::ostream& os,const int repeats, const int count_of_elements)
{
os << "test_performance_of_insert_delete START\n";
std::vector <int> rnd;
std::map <int, int > mp;
for (int i = 0; i < repeats; ++i) {
//fill vector with n unique random elements
for (int j = 0; j < count_of_elements; ++j) {
int in = 0;
while (true) {
in = get_random(1, std::numeric_limits<int>::max());
bool twice = false;
auto it = mp.find(in);
if (it == mp.end())
break;
}
rnd.push_back(in);
mp.insert(std::make_pair(in, i));
}
os << rnd.size() << "\n";
mp.clear();
os << '\n';
//fill map and skiplist and compar
// fill skiplist
auto begin_sk = std::chrono::system_clock::now();
Skiplist sk;
for (std::size_t i = 0; i < rnd.size(); ++i)
sk.insert(rnd[i], i);
auto end_sk = std::chrono::system_clock::now();
os << "skiplist filled. Time:" << std::chrono::duration_cast<std::chrono::milliseconds>(end_sk - begin_sk).count() << "\n";
// erase skiplist
auto begin_sk_d = std::chrono::system_clock::now();
for (std::size_t i = 0; i < rnd.size(); ++i)
sk.erase(rnd[i]);
auto end_sk_d = std::chrono::system_clock::now();
os << "skiplist deleted. Time:" << std::chrono::duration_cast<std::chrono::milliseconds>(end_sk_d - begin_sk_d).count() << "\n";
os << '\n';
// fill map
auto begin_mp = std::chrono::system_clock::now();
std::map<int, int> mp;
for (std::size_t i = 0; i < rnd.size(); ++i)
mp.insert(std::pair<int, int>(rnd[i], i));
auto end_mp = std::chrono::system_clock::now();
os << "map filled. Time:" << std::chrono::duration_cast<std::chrono::milliseconds>(end_mp - begin_mp).count() << "\n";
// erase map
auto begin_mp_d = std::chrono::system_clock::now();
for (std::size_t i = 0; i < rnd.size(); ++i)
mp.erase(rnd[i]);
auto end_mp_d = std::chrono::system_clock::now();
os << "map deleted. Time:" << std::chrono::duration_cast<std::chrono::milliseconds>(end_mp_d - begin_mp_d).count() << "\n";
os << '\n';
}
os << "test_performance_of_insert_delete FINISHED\n";
}
}
</code></pre>
<p><b>main.cpp</b></p>
<pre><code>#include <iostream>
#include <vector>
#include <string>
#include <fstream>
#include "skiplist_unit_test.h"
int get_random(int min, int max)
{
static std::random_device rd;
static std::mt19937 mt(rd());
std::uniform_int_distribution<int> distribution(min, max);
return distribution(mt);
}
int main()
try {
std::ofstream ofs{ "skiplist_unit_test_results.txt" };
skiplist::unit_test::test_insert_and_erase(ofs);
skiplist::unit_test::test_leakage_of_memory(ofs);
skiplist::unit_test::test_find(ofs);
skiplist::unit_test::test_copy_constructor(ofs);
skiplist::unit_test::test_move_constructor(ofs);
skiplist::unit_test::test_copy_assignment(ofs);
skiplist::unit_test::test_move_assignment(ofs);
skiplist::unit_test::test_performance_of_insert_delete(ofs, 3, 100'000);
}
catch (std::runtime_error& e) {
std::cerr << e.what() << "\n";
std::cin.get();
}
catch (...) {
std::cerr << "unknown error\n";
std::cin.get();
}
</code></pre>
<p>During making the changes / reworking the code. The following Questions came up:</p>
<p><b> Representation of the Skipnode-Pointers </b></p>
<p>Last time it was suggested to replace Vector with sth "faster" for representing the collection of pointers in the nodes. I just have no Idea what could be used.</p>
<p><b> Performance </b></p>
<p>Probaly related to the vector question is the performance Issue. If i run the test were i insert and delete compared to <code>std::map</code> the skiplist is still as slow as before. To give you some values:</p>
<pre><code>100000
skiplist filled.Time:2478
skiplist deleted.Time : 2671
map filled.Time : 800
map deleted.Time : 1676
200000
skiplist filled.Time : 5390
skiplist deleted.Time : 5411
map filled.Time : 1650
map deleted.Time : 3408
300000
skiplist filled.Time : 7774
skiplist deleted.Time : 7948
map filled.Time : 2380
map deleted.Time : 4970
</code></pre>
<p>So the skiplist is still 3 times slower than map. I get roughly the same results like with the mikromanagement in the vector i did in the last question. So there must be something which really eats alot of performance</p>
<p>EDIT: It was commented that map is superior to skiplist with insert / delete. So which container would be better to use for a compare. Is there a common Skiplist implementation in c++ to use?</p>
<p><b> Implementation of Copy Assignment</b></p>
<p>Currently the Copy constructor is implemented like the copy assignment. The code is repeditive. Is it a good idea in the move assignment to take old nodes if present and refill them with the new key / values?</p>
<p><b> Representation of the Headnode </b></p>
<p>The Head Element is now a Basenode for the Skipnodes. This is feels kinda ugly like a dirty hack to me. I even have to use at some places in the code statci_cast to cast to the key / values. I tryed to live without head but then the algorithms couldnt be implemented. Any suggestions are very welcome.</p>
<p><b> Unit Tests </b></p>
<p>I added the Unit Tests. Im not very expirience in writing Unit Tests. Currently each function tests a aspect of the skiplist and gives some report. Is this a good approach.</p>
<p><b> Test for leaking Memory </b></p>
<p>In the Unit Tests i tryed to test for leaking memory. Currently i allocate several times memory and deallocate it. During the run i look if the used memory increases manually in the debugger. Is this a good approach? I assume not.</p>
<p><b> Random Generator </b></p>
<p>Last time someone suggested to move Random Generator completely out of the class, and to put it in a separate class. I didn't understand how. Is the current implementation inside the class ok?</p>
<p><b> General </b></p>
<p>Beside these questions who burn me under the tip feel free to make any suggestions for improvements. </p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-03T21:01:20.927",
"Id": "381273",
"Score": "0",
"body": "If I remember correctly, most `std::map` implementations use a red-black binary search tree, not a skip list. I've not looked thoroughly at the details of your code, but that may... | [
{
"body": "<p>✘ Your move-assignment operator is not moving, but doing the same copy as the regular assignment.</p>\n\n<hr>\n\n<p>The various constructors that have a few initializers but no body can go inline in the class definition.</p>\n\n<hr>\n\n<p>BTW, destructors are <code>noexcept</code> by default.</p>\... | {
"AcceptedAnswerId": "198209",
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-03T20:44:14.420",
"Id": "197752",
"Score": "3",
"Tags": [
"c++",
"performance",
"collections",
"skip-list"
],
"Title": "Non generic Skip List implementation in C++ Version 2"
} | 197752 |
<p>I'm trying to develop some templates for common HTML + CSS tasks I've been dealing with. One of which is a general search results list either from client- or server-side. </p>
<p>So far I'm using the following reusable code which seems to be working fine without any noticeable bug: </p>
<pre><code><ul class="query-list">
<li>
<a href="dummy_page1.html">
<div class="image-container">
<img class="icon-img" src="img_100x100.png" >
</div>
<div class="text-container">
<div class="title-container">
<h3 title="dummy title">[Dummy Title] Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse quis accumsan felis. Maecenas vel libero mi. Suspendisse potenti. Sed tempus ex eu diam imperdiet mattis ac ut orci. Sed non lectus libero. Suspendisse vitae nunc a quam mattis congue id eget tortor. Vivamus id arcu eros. Duis eu risus semper, dapibus quam in, tristique magna. Duis semper tempus dolor eget elementum. Duis arcu ipsum, suscipit a egestas quis, lobortis sit amet purus.</h3>
</div>
<div class="notes-container">
<p>
<span>dummy notes 1</span>
<span>&bull; dummy notes 2</span>
<span>&bull; dummy notes 3</span>
</p>
</div>
<div class="notes-container">
<p>
<span>dummy notes 4</span>
<span>&bull; dummy notes 5</span>
<span>&bull; dummy notes 6</span>
</p>
</div>
</div>
</a>
</li>
</ul>
<style>
/* Query List */
ul.query-list {list-style-type: none; min-width: 340px;}
ul.query-list li {height: 5.7em; margin: 10px 0; font-size: 12px;}
ul.query-list li a {text-decoration: none; display: flex; height: 100%;}
ul.query-list li a:hover {background-color: #fafafa; opacity: 0.7;}
ul.query-list li a:hover .title-container {text-decoration: underline;}
ul.query-list .image-container {flex-shrink: 0; height: 100%; width: 5.7em; margin-right: 5px;}
ul.query-list .text-container {display: flex; flex-direction: column; height: 100%;}
ul.query-list .title-container {overflow: hidden; margin-bottom: 0.2em;}
ul.query-list .title-container .no-title {color: darkgray; font-weight: bold;}
ul.query-list .notes-container {flex-shrink: 0; flex-grow: 0; height: 1.1em; overflow: hidden;}
ul.query-list .notes-container p {color: darkgray; text-align: left;}
.query-list p, h3 {margin: 0; line-height: 1.1em; font-size: 12px; text-align: left; font-family: arial;}
.query-list span {white-space: nowrap}
/* General Definitions */
.icon-img {max-width: 100%; max-height: 100%; display: block;}
h3 {color: darkblue;}
</style>
</code></pre>
<p>Some main characteristics of this code are: </p>
<ul>
<li>the text content has a maximum of 5 lines (title + notes) independently of the amount of text content</li>
<li>independently of the number of title lines, the notes are always immediately bellow (no variable gap)</li>
<li>the maximum number of title lines automatically adjust according to the number of notes lines included or removed</li>
</ul>
<p><strong>Interested in:</strong> </p>
<ul>
<li>Is it possible to simplified it? There is a nest of <code><div></code>, <code><a></code> and <code>flexbox</code> that seems to me overly complicated for such a simple task ...</li>
<li>Any standard nomenclature or other best practices? </li>
<li>Any ideas to improve its design and appearance (without <code>JS</code>)? </li>
</ul>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-04T21:55:35.027",
"Id": "381464",
"Score": "0",
"body": "What is a query list? A list of search results?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-04T22:27:51.267",
"Id": "381483",
"Score": "0... | [
{
"body": "<p>If the results are ranked (typically by relevance), you should use an <code>ol</code> instead of a <code>ul</code>.</p>\n\n<p>It’s best practice to use sectioning content elements (<code>article</code>, <code>aside</code>, <code>nav</code>, <code>section</code>) if you use heading elements (<code>... | {
"AcceptedAnswerId": "197846",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-03T23:09:01.767",
"Id": "197759",
"Score": "3",
"Tags": [
"html",
"css"
],
"Title": "HTML+CSS Template: Search Results List"
} | 197759 |
<p>I need to review my code. I used prepared statements to select data from the database. Is there more sanitization needed or any other problem in the code? Rate it, please. Thanks. </p>
<pre><code><?php
session_start();
require_once './db_con.php';
require_once './funcs.php';
if ( $_SERVER['REQUEST_METHOD'] === 'POST') {
$email = trim(filter_input(INPUT_POST, 'email'));
$password = trim(filter_input(INPUT_POST, 'password'));
$errs = array();
if ( empty($email) ) {
$errs[] = "Please enter your E-mail.";
} elseif ( !filter_var($email, FILTER_VALIDATE_EMAIL) ) {
$errs[] = "Please enter a valid E-mail.";
}
if ( empty($password) ) {
$errs[] = "Please enter your password.";
} elseif (strlen($password) < 6) {
$errs[] = "Your password must have at least 6 characters.";
}
if ( !empty( $errs ) ) {
foreach ($errs as $err) {
echo $err.'</br >';
}
} else {
$stmt = $connection->prepare("SELECT `password` FROM `users` WHERE `email` = ?");
$stmt->bind_param("s", $email);
$stmt->execute();
$result = $stmt->get_result();
$rows_count = $result->num_rows;
if ( $rows_count === 1 ) {
$row = $result->fetch_row();
$hash = $row[0];
if ( password_verify($password, $hash) ) {
$_SESSION['email'] = $email;
header('Location: index.php');
} else {
echo "Password is wrong.";
}
} else {
echo "register.";
}
$stmt->close();
}
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<div id="wrapper">
<form action="#" method="POST">
<p><label>Enter Your E-mail: </label><input type="text"
name="email" value="" /></p>
<p><label>Enter Your Password: </label><input
type="password" name="password" value="" /></p>
<p><input type="submit" value="Log now" /></p>
</form>
</div>
</body>
</html>
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-05T15:39:59.437",
"Id": "381592",
"Score": "2",
"body": "There's not much to say about this basic code. It works, no major flaws. Perhaps there could be better error handling. You use this nice `$errs` array yet you don't check for dat... | [] | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-03T23:17:31.780",
"Id": "197760",
"Score": "1",
"Tags": [
"php",
"mysqli"
],
"Title": "Log in page using MYSQLi"
} | 197760 |
<p>In my JavaScript code, I have as below. very simply this is a for loop where I go through several dom elements, retrieve some values and set it. And, before doing it, I am also checking. Now, I feel like the code is not readable. To be honest, I can read it as I wrote it.</p>
<pre><code> for (var pos = startLoop, arrayPos = 0; arrayPos < (maxLocations); arrayPos++, pos++) {
xmlMSVal[arrayPos] && $('.someParent .nf-repeater-row:nth-child(' + pos + ') .bed1').val(xmlMSVal[arrayPos].textContent);
xmlPCVal[arrayPos] && $('.someParent .nf-repeater-row:nth-child(' + pos + ') .bed2').val(xmlLTVal[arrayPos].textContent);
xmlRITVal[arrayPos] && $('.someParentr .nf-repeater-row:nth-child(' + pos + ') .bed3').val(xmlPCVal[arrayPos].textContent);
}
</code></pre>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-03T23:35:29.310",
"Id": "197761",
"Score": "1",
"Tags": [
"javascript",
"eslint"
],
"Title": "Setting values inside of several input fields"
} | 197761 |
<p>I am currently reading the book <em>C++ Concurrency in Action</em> by Anthony Williams. In chapter 9, he implemented a lock-based work stealing queue and mentioned it is possible to implement a lock-free queue that allows the owner thread to push and pop at one end while other threads can steal entries from the other. So, I implemented it myself here. Basically, I have 3 methods: <code>push</code>, <code>try_pop_back</code>, and <code>try_steal_front</code>.</p>
<ol>
<li><code>push</code> will always add a new item to the <em>back</em> of the queue</li>
<li><code>try_pop_back</code> tries to pop an existing item from the <em>back</em> of the queue</li>
<li><code>try_steal_front</code> tries to steal from the <em>front</em> of the queue</li>
</ol>
<p>This queue is thread local, and <code>push</code>, <code>try_pop_back</code> will always be accessed by single thread, however, <code>try_steal_front</code> runs in multiple threads and will compete with <code>push</code> and <code>try_pop_back</code>. I wonder whether the code works good across all CPU architectures (e.g. Intel x86-64, AMD, ARM, etc.)</p>
<p>The code is also on <a href="https://github.com/LingyanYin/lockfree_work_stealing_queue" rel="nofollow noreferrer">GitHub</a>. I have a simple test case there which could run this queue under multiple threads.</p>
<pre><code>#include <atomic>
#include <array>
//#include "functionwrapper.h"
// push and pop are accessed by only one single thread
// thread local queue
// push/pop by this single thread could compelete with steal with multiple other threads
class LockFreeWorkStealingQueue {
private:
// using DataType = FunctionWrapper;
using DataType = int;
// change to be template argument in the future
static constexpr auto DEFAULT_COUNT = 2048u;
static constexpr auto MASK = DEFAULT_COUNT - 1u;
std::array<DataType, DEFAULT_COUNT> q;
std::atomic<unsigned int> lock_front{0};
std::atomic<unsigned int> lock_back{0};
public:
LockFreeWorkStealingQueue() {}
LockFreeWorkStealingQueue(const LockFreeWorkStealingQueue&) = delete;
LockFreeWorkStealingQueue& operator=(const LockFreeWorkStealingQueue&) = delete;
/**
* always add a new item to the back of the queue
* runs sequentially with try_pop_back
* runs parallel with multiple threads' try_steal_front
*/
void push(DataType data) {
auto bk = lock_back.load(std::memory_order_acquire);
// try resetting the lock_front and lock_back to prevent
// they being too large
if (bk == lock_front.load(std::memory_order_acquire)) {
lock_front.store(0, std::memory_order_release);
lock_back.store(0, std::memory_order_release);
}
q[bk & MASK] = std::move(data);
lock_back.fetch_add(1, std::memory_order_release);
}
/**
* tries to pop an existing item from the back of the queue
* runs sequentially with push
* runs parallel with multiple threads's try_steal_front
*/
bool try_pop_back(DataType& res) {
auto ft = lock_front.load(std::memory_order_acquire);
auto bk = lock_back.load(std::memory_order_acquire);
if (bk > ft) {
while(bk && !lock_back.compare_exchange_weak(bk, bk - 1, std::memory_order_release, std::memory_order_relaxed));
res = std::move(q[(bk - 1) & MASK]);
return true;
}
return false;
}
/**
* tries to steal from the front of the queue
* runs in multiple threads
*/
bool try_steal_front(DataType& res) {
auto ft = lock_front.load(std::memory_order_acquire);
auto bk = lock_back.load(std::memory_order_acquire);
// if there is only one item in the queue, try not steal
// if stealing, contention with try_pop_back, failed anyway
if (bk && ft < bk - 1) {
while(!lock_front.compare_exchange_weak(ft, ft + 1, std::memory_order_release, std::memory_order_relaxed));
// check again to see any changes by push or try_pop_back
if (ft < lock_back.load(std::memory_order_acquire)) {
res = std::move(q[ft & MASK]);
return true;
} else {
// nothing to steal, reset lock_front
lock_front.fetch_sub(1, std::memory_order_release);
}
}
return false;
}
};
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-04T18:50:07.353",
"Id": "381432",
"Score": "0",
"body": "I also add the github link and there is a simple test that runs this queue under multiple threads."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-04... | [
{
"body": "<p>I'm not qualified to talk about memory orders, so I'll skip that part (except to note that I've never met anyone else who is, either, which is why I recommend going <code>seq_cst</code> all the way). I'll just pretend all your orders are <code>seq_cst</code>.</p>\n\n<hr>\n\n<p>If I understand corr... | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-04T00:27:30.187",
"Id": "197764",
"Score": "5",
"Tags": [
"c++",
"c++11",
"multithreading",
"queue",
"lock-free"
],
"Title": "A simple lock-free queue for work stealing"
} | 197764 |
<p>I have an HTML file that contains a submit form, which asks the users the fill in their personal info:</p>
<p><a href="https://i.stack.imgur.com/Y2x09.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Y2x09.png" alt="enter image description here"></a></p>
<p>then it will post and store into the DB by method of PHP SQL:</p>
<pre><code> // Check input errors before inserting in database
if (empty($CName_err) && empty($Address_err) && empty($amount_err) && empty($Phone_err)) {
// Prepare an insert statement
$pdo = Database::connect();
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "INSERT INTO database (CName, Address, Phone, Amount ,Ticket, Purpose) VALUES (?, ?, ?, ? ,?, ?)";
$q = $pdo->prepare($sql);
$q->execute(array($CName, $Address, $Phone, $amount ,$Ticket ,$Purpose));
Database::disconnect();
</code></pre>
<p>Hence, any risks of an SQL injection attack in this case?</p>
<p>What should I do to improve my coding?</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-04T00:47:02.760",
"Id": "381286",
"Score": "0",
"body": "Welcome to Code Review! I hope you get great answers."
}
] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-04T00:29:31.317",
"Id": "197765",
"Score": "1",
"Tags": [
"php",
"sql",
"mysql",
"server",
"sql-injection"
],
"Title": "HTML file with a submit form"
} | 197765 |
<p>I made a bare-bones implementation of <code>printf</code> based on an exercise in Chapter 7, problem 5 of "Pointers on C" by Kenneth A. Reek. What criticism do you have of my writing style? </p>
<p>For instance, do you find I added far too many header files in code. Should I add <code>#ifndef</code> guards for the header files? Do you find any of the functions throughout the implementation too difficult too read? </p>
<p>For instance, the <code>myprintf</code> function is the most important function, as it takes advantage of all other functions throughout the program. Is the way <code>myprintf</code> is implemented with switch statements too messy?</p>
<pre><code>#include <stdio.h>
#include <stdarg.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <math.h>
#include <limits.h>
#include <float.h>
#include <assert.h>
#define MAX_LENGTH 1000
void reverse (char *s) {
char temp;
for ( int i = 0, j = strlen(s)-1; i < j; i++, j--)
{
temp = s[i];
s[i] = s[j];
s[j] = temp;
}
}
char * printd(long long int n)
{
static char d[1000];
static char abs[1000];
static char * abs_p = abs;
static int sign;
if ( n < 0 )
{
*d = ('-');
n = -n;
}
while ( lldiv(n,10).quot != 0)
{
*abs_p++ = (lldiv(n,10).rem+'0');
n = (lldiv(n,10).quot);
}
reverse(abs);
strcat(d,abs);
return d;
}
char * lltoa(long long int n)
{
static char s[MAX_LENGTH];
long long int i, sign;
if ((sign = n) < 0) /* record sign */
n = -n; /* make n positive by n =-n */
i = 0;
do /* generate digits in reverse order */
{
s[i++] = lldiv(n,10).rem + '0'; /* get next digit with n % 10 + '0'; */
} while (n = lldiv(n,10).quot, n > 0); /* delete it with while ( (n /= 10) > 0 )*/
if (sign < 0)
s[i++] = '-';
s[i] = '\0';
reverse(s);
return s;
}
char * lltoa2(long long int n)
{
char d[MAX_LENGTH];
char abs[MAX_LENGTH];
char * abs_p = abs;
int sign;
if ( n < 0 )
{
*d = ('-');
n = -n;
}
while (lldiv(n,10).quot != 0)
{
*abs_p++ = (lldiv(n,10).rem+'0');
n = (lldiv(n,10).quot);
}
*abs_p++ = (lldiv(n,10).rem+'0'); /* first digit after pos or neg sign must be included */
reverse(abs); /* contents of abs are originally in reverse order of input */
d[0] = '\0';
strcat(d,abs);
return &d[0];
}
double nround(double input, double power)
{
double marge = pow(10,power);
double up = input * marge;
double result = ((double)(llround(up)))/marge;
return result;
}
// ftoa rounds accurately up to 15 digits, guranteed
// ftoa can only deal with integral values with an absolute value less than or equal to LLONG_MAX
/* ftoa only works until 9.9999999999999999e15 rounded to
zero decimal places
*/
char * ftoa(const double input, const double power) // pow is the '*' in "%.*f"
{
const double in = nround(input,power);
static char a[MAX_LENGTH] = "\0";
int j = 0;
while (j < strlen(a) ) a[j++] = '\0';
long long int f_to_i = (long long int)(in);
strcat(a,lltoa(f_to_i)); strcat(a,".");
double integral = 0;
double fraction = 0;
(in >= 0) ? (fraction = modf(in,&integral)): (fraction = modf(-in,&integral)); /* stores fractional part of input */
char non_zero_mantissa[1000] = "\0"; /* stores non-zero digits in mantissa after leading zeros following decimal point */
strcat(non_zero_mantissa,lltoa(llround(fraction*pow(10,power))));
int i = strlen(non_zero_mantissa);
while ( i++ < power )
{
strcat(a,"0");
}
strcat(a,non_zero_mantissa);
return a;
#if 0
int c = 0;
while ( a[c] != '\0') putchar(a[c++]);
#endif
}
//#if 0
int myprintf(char const * s,...)
{
va_list var_arg;
char * s_p = (char *)(s-1);
va_start(var_arg,s);
int ROUND_TO = 0;
char rounding[1000];
while (*++s_p != '\0')
{
switch(*s_p)
{
case '%':
{
switch(*++s_p)
{
case 'f':
{
char const * f_p = ftoa(va_arg(var_arg,double),6);
while ( *f_p != '\0') putchar(*f_p++);
break;
}
case 'd':
{
char const * d_p = (char *)lltoa(va_arg(var_arg,long long int));
while ( *d_p != '\0') putchar(*d_p++);
break;
}
case 's':
{
char const * string_p = va_arg(var_arg,char *);
while ( *string_p != '\0') putchar(*string_p++);
break;
}
case 'c':
{
putchar((char)va_arg(var_arg,int));
break;
}
case '.':
{
if (isdigit(*(s_p+1))) //peek after '.' and see if there is a digit
{
ROUND_TO = 1;
int i = 0;
char * r_p = rounding;
while (isdigit(*++s_p)) { *r_p++ = *s_p; }
*r_p = '\0';
if ( *s_p == 'f' )
{
myprintf("%s",ftoa(va_arg(var_arg,double),atoi(rounding)));
++s_p;
}
else
{
putchar('%');
putchar(*s_p);
myprintf("%s",atoi(rounding));
}
}
else
{
putchar('%');
putchar(*s_p++);
}
}
default:
{
putchar(*s_p);
break;
}
}
break;
}
default:
{
putchar(*s_p);
break;
}
}
}
va_end(var_arg);
return 1;
}
//#endif
//#if 0
int main(void)
{
#if 0
ftoa(-3.9999,3);
putchar('\n');
ftoa(-1.5555,2);
putchar('\n');
ftoa(-3.39823929,5);
putchar('\n');
ftoa(-3.0000000000000099,15);
putchar('\n');
ftoa(-3.6666666666666666,15);
putchar('\n');
ftoa(-3.4545,3);
putchar('\n');
ftoa(-3.454599,5);
putchar('\n');
ftoa(-1.0000000000000009,15);
putchar('\n');
ftoa(3.9999,3);
putchar('\n');
ftoa(1.5555,2);
putchar('\n');
ftoa(3.39823929,5);
putchar('\n');
ftoa(3.0000000000000099,15);
putchar('\n');
ftoa(3.6666666666666666,15);
putchar('\n');
ftoa(3.4545,3);
putchar('\n');
ftoa(3.454599,5);
putchar('\n');
ftoa(1.0000000000000009,15);
putchar('\n');
ftoa(9.9999999999999999e15,14); //FAILS!!!
putchar('\n');
myprintf("Thatcher Swag\n%s\n%f\n%c\n%d\n","Swiss Cheese",3.45,'T',3535232523);
double a = 3.14, b = 325.3235, c = 790.866;
myprintf("My bank account amount: %f\n",c);
double light_speed = 3.0e8;
double planck_mass = 2.17647051*pow(10,-8);
myprintf("Speed of light: %f\n",light_speed*planck_mass);
printf("Speed of light: %f\n",light_speed*planck_mass); //TESTS PASS
myprintf("%f\n",planck_mass);
printf("%f\n",planck_mass); //TESTS_PASS
#endif
myprintf("%.5f\n",43.235278);
myprintf("%.5f\n",3.14159265);
myprintf("%.3f\n",4.9999);
myprintf("%.10f\n",1558.2392038592972022352698);
myprintf("%.15f\n",1.2392038592972022352698); //myprintf can only round a floating-point that has 15 digits, including before mantissa or less
myprintf("%f\n",323.3435);
myprintf("%s %c %.3f %d\n","Swiss",'A',123.3257,1325352);
myprintf("%s\n",lltoa2(32235235));
myprintf("%s\n",lltoa2(232362351));
myprintf("%s\n",lltoa2(LLONG_MAX));
myprintf("My parents gave me %d hot dogs for July 4\n",359);
}
//#endif
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-04T01:35:26.750",
"Id": "381287",
"Score": "2",
"body": "A good starting point is to look at the actual implementation of [GNU C library functions](https://www.gnu.org/software/libc/) (download the archive file). In this case, look und... | [
{
"body": "<p>There is so much going on here that needs improvement that the correctness of converting <code>double</code> to a <em>string</em> has not been assessed yet. I am doubtful that its correctly rounds edge cases. Example </p>\n\n<pre><code>myprintf(\"%f\\n\",0.00000049999999999999993); --> 0.0000... | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-04T01:15:10.830",
"Id": "197766",
"Score": "5",
"Tags": [
"c",
"reinventing-the-wheel",
"formatting"
],
"Title": "Bare-Bones implementation of printf"
} | 197766 |
<p>Below is LRU Cache class implementation. </p>
<pre><code># Design and implement a data structure for Least Recently Used (LRU) cache.
# It should support the following operations: get and put.
#
# get(key) - Get the value (will always be positive) of the key if the key exists in the cache,
# otherwise return -1.
# put(key, value) - Set or insert the value if the key is not already present.
# When the cache reached its capacity,
</code></pre>
<p>I've left out a lot of the details, but most of the methods you can just delegate to the internal ordered dict self.store. </p>
<p><a href="https://leetcode.com/problems/lru-cache/description/" rel="nofollow noreferrer">https://leetcode.com/problems/lru-cache/description/</a> </p>
<p>Could you do both operations in O(1) time complexity?</p>
<pre><code>class LRUCache(object):
def __init__(self, capacity):
"""
:type capacity: int
"""
self.capacity = capacity
self.dic = {}
self.history_dic = {}
self.key_dic = {}
self.current = 0
self.count = 0
def get(self, key):
"""
:type key: int
:rtype: int
"""
if not key in self.dic:return -1
self.update_history(key)
return self.dic[key]
def put(self, key, value):
"""
:type key: int
:type value: int
:rtype: void
"""
self.update_history(key)
if key in self.dic:
self.dic[key] = value
return
if len(self.dic)==self.capacity:
i = self.current
while not self.history_dic[i]:
i += 1
self.dic.pop(self.history_dic[i])
self.key_dic.pop(self.history_dic[i])
self.current = i+1
self.dic[key] = value
def update_history(self,key):
if key in self.key_dic:
self.history_dic[self.key_dic[key]] = None
self.history_dic[self.count] = key
self.key_dic[key] = self.count
self.count += 1
# Time: O(1), per operation.
# Space: O(k), k is the capacity of cache.
# put(key, value) - Set or insert the value if the key is not already present.
# When the cache reached its capacity,
# it should invalidate the least recently used item before inserting a new item.
#
# Follow up:
# Could you do both operations in O(1) time complexity?
#
# Example:
#
# LRUCache cache = new LRUCache( 2 /* capacity */ );
#
# cache.put(1, 1);
# cache.put(2, 2);
# cache.get(1); // returns 1
# cache.put(3, 3); // evicts key 2
# cache.get(2); // returns -1 (not found)
# cache.put(4, 4); // evicts key 1
# cache.get(1); // returns -1 (not found)
# cache.get(3); // returns 3
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-04T04:55:25.233",
"Id": "381294",
"Score": "2",
"body": "You could just use [@functools.lru_cache](https://docs.python.org/3/library/functools.html)"
}
] | [
{
"body": "<p>This cache feels like it could be used like a <code>dict</code> but is nowhere near it. Renaming <code>get</code> to <code>__getitem__</code> and <code>put</code> to <code>__setitem__</code> would provide a neater feeling here. Even better, since your main storage <em>is</em> a <code>dict</code>, ... | {
"AcceptedAnswerId": "197789",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-04T03:17:48.667",
"Id": "197768",
"Score": "2",
"Tags": [
"python",
"reinventing-the-wheel",
"cache"
],
"Title": "Least recent use cache in python"
} | 197768 |
<p>I built one JavaScript debounce function. I need a JavaScript expert's opinion if this is the correct way to do it, and if not, then what the flaw is in this current function.</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var debounce = function(inpFun, wait) {
var timeout;
return function () {
if(!timeout) {
inpFun.apply(this, arguments);
timeout = setTimeout(function() {
timeout = undefined;
}, wait);
}
else {
console.log("Debouncing");
}
}
};
var buttonClickFunction = debounce(function (event) {
console.log("Button Clicked");
console.log(event.target.id);
}, 2000);
document.querySelector("#button1").addEventListener("click", buttonClickFunction);</code></pre>
</div>
</div>
</p>
| [] | [
{
"body": "<h1>Event rate limiter</h1>\n<p>It is important to use the correct terms when defining functions. If you are unsure it is always better to look up the literature to ensure you are using the term correctly.</p>\n<h2>Debouncing</h2>\n<p>You have not implemented a de-bounce. De-bounce delays action on a... | {
"AcceptedAnswerId": "197802",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-04T05:53:11.727",
"Id": "197772",
"Score": "1",
"Tags": [
"javascript",
"functional-programming",
"event-handling",
"dom"
],
"Title": "JavaScript debounce function"
} | 197772 |
<p>Problem : A binary tree is given as an input, each node of binary tree contains one integer value. Find the maximum sum of collection of nodes such that following two conditions are met.</p>
<ul>
<li>if node's parent node is considered for sum, then node cannot be considered.</li>
<li>if node's either of child is considered for sum, then node cannot be considered.</li>
</ul>
<p>For example : </p>
<p>For a binary tree </p>
<pre><code> 15
20 25
5 15 5
</code></pre>
<p>The max sum we can get is considering <code>[20, 25]</code> which is <code>45</code>.</p>
<p>To implement this I used O(n^2) approach and code is here. </p>
<p>I am trying to optimize it and looking for feedback on improving algorithm, code efficiency and cleanliness</p>
<p><code>tree</code> is String representation of tree, given in BFS manner. <code>_</code> is present in place of null element. <code>_</code> is not given for the deepest level's element's null representation.</p>
<p>the above tree would be represented as <code>15 20 25 5 15 5 _</code></p>
<pre><code>static int findMaxSum(String tree) {
String[] tokens = tree.split(" ");
int max = 0;
for (int i = 0; i < tokens.length; i++) {
if (!isValidToken(tokens[i])) {
continue;
}
Set<Integer> set = new HashSet<>();
//wildcard entry
set.add(i);
int sum = Integer.parseInt(tokens[i]);
for (int j = 0; j < tokens.length; j++) {
if (isValidToken(tokens[j])) {
if(!set.contains(j) && !set.contains(getParentIndex(j))){
if (!set.contains(getLeftChildIndex(j)) && !set.contains(getRightChildIndex(j))) {
set.add(j);
sum += Integer.parseInt(tokens[j]);
}
}
}
}
max = Math.max(max,sum);
}
return max;
}
static boolean isValidToken(String token) {
return !"_".equals(token);
}
static int getLeftChildIndex(int parentIndex) {
return parentIndex * 2 + 1;
}
static int getRightChildIndex(int parentIndex) {
return parentIndex * 2 + 2;
}
static int getParentIndex(int childIndex) {
return (childIndex - 1)/2;
}
</code></pre>
<p>Note: this code works but it is not efficient. I am looking for ideas on how to improve it.</p>
| [] | [
{
"body": "<p>If I understand the rules correctly, it can me implemented in O(N) in the following way:</p>\n\n<ol>\n<li>Attach a second integer to each node</li>\n<li>non-leaf node = <code>0</code>, leaf node = node's main value.</li>\n<li>Do a depth-first walk.</li>\n<li>For every node that you visited all chi... | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-04T06:11:49.853",
"Id": "197773",
"Score": "3",
"Tags": [
"java",
"performance",
"algorithm",
"tree"
],
"Title": "Binary Tree max sum conditionally"
} | 197773 |
<p>I build a Tower of <a href="https://en.wikipedia.org/wiki/Tower_of_Hanoi" rel="noreferrer">Hanoi solver</a> which print the solution as an image </p>
<p>It works as expected but generating the image is relatively slow compared to the time to calculate the answer.</p>
<p>Here is the code:</p>
<pre><code>#!/usr/bin/env python
# -*- coding: utf-8 -*-
import argparse
from PIL import Image
def hanoi(disks, source, helper, target, steps):
if disks > 0:
hanoi(disks - 1, source, target, helper, steps)
target.append(source.pop())
steps.append([SOURCE[:], HELPER[:], TARGET[:]])
hanoi(disks - 1, helper, source, target, steps)
def save_image(name):
print('\nSaving image {}.png'.format(name))
data = []
peg = args.disks * 2
cells = peg * 3 + 40 # 40 is to put some spaces between pegs and the border
for step in steps:
for _ in range(5): # White space
data.append([1 for _ in range(cells)])
src = step[0]
hlp = step[1]
trg = step[2]
size = max(len(src), len(hlp), len(trg))
for _ in range(size - len(src)):
src.append(0)
for _ in range(size - len(hlp)):
hlp.append(0)
for _ in range(size - len(trg)):
trg.append(0)
src.reverse()
hlp.reverse()
trg.reverse()
for s, h, t in zip(src, hlp, trg):
blanksrc = peg - 2 * s
blankhlp = peg - 2 * h
blanktrg = peg - 2 * t
row = [1 for _ in range(10)]
row += [1 for _ in range(blanksrc // 2)]
row += [0 for _ in range(s * 2)]
row += [1 for _ in range(blanksrc // 2)]
row += [1 for _ in range(10)]
row += [1 for _ in range(blankhlp // 2)]
row += [0 for _ in range(h * 2)]
row += [1 for _ in range(blankhlp // 2)]
row += [1 for _ in range(10)]
row += [1 for _ in range(blanktrg // 2)]
row += [0 for _ in range(t * 2)]
row += [1 for _ in range(blanktrg // 2)]
row += [1 for _ in range(10)]
data.append(row)
for _ in range(5): # White space
data.append([1 for _ in range(cells)])
data.append([0 for _ in range(cells)]) # Black line to separate steps
da = [bit for row in data for bit in row]
image = Image.new('1', (cells, len(data)))
image.putdata(da)
image.save('{}.png'.format(name))
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('-d', '--disks', type=int, default=4,
help='Number of disks, default 4')
parser.add_argument('-f', '--filename', help='Filename', required=True)
args = parser.parse_args()
if not args.disks > 0:
raise ValueError('There must be at least one disk')
SOURCE = list(reversed(range(1, args.disks + 1)))
TARGET = []
HELPER = []
steps = [[SOURCE[:], HELPER[:], TARGET[:]]]
hanoi(args.disks, SOURCE, HELPER, TARGET, steps)
save_image(args.filename)
</code></pre>
<p>As I add more disks in the problem, compared to the computation of the answer, the time taken to generate the image is longer and longer.</p>
<p>How can I make it faster and why it is so slow?</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-04T07:37:25.423",
"Id": "381306",
"Score": "3",
"body": "I don't think the code is slow. It's just that there are \\$n^2\\$ steps"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-04T08:10:10.887",
"Id": ... | [
{
"body": "<p>Like I said before, the reason why this takes a lot of time is because the number of steps is proportional to the square of the number of disks.</p>\n\n<p>But there are some other improvements to be made to this code.</p>\n\n<h1><code>range</code></h1>\n\n<p><code>list(reversed(range(1, args.disks... | {
"AcceptedAnswerId": "197801",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-04T06:28:01.763",
"Id": "197774",
"Score": "11",
"Tags": [
"python",
"performance",
"beginner",
"image",
"tower-of-hanoi"
],
"Title": "Slow image generation"
} | 197774 |
<p>I'm trying to poll for newly created files.</p>
<p>Because the <code>FileSystemWatcher</code> class is known not to be reliable (<a href="https://stackoverflow.com/a/240008/588868">here</a>, <a href="https://stackoverflow.com/a/7191512/588868">here</a> and <a href="https://bytes.com/topic/net/answers/460919-filesystemwatcher-unreliable" rel="nofollow noreferrer">here</a>), and because it does not wait for the end of a complete file write, I created a new class to get files creation.</p>
<p>The specifications are:</p>
<ul>
<li>Files should be signaled only when the file write is complete (large files should be signaled at the end of the copy)</li>
<li>Files should be signaled only once</li>
<li>Existing files (when the program starts) should be signaled</li>
<li>The poller will live in a windows service. Thus it should support very long lifetime (several weeks)</li>
</ul>
<p>Here's what I have right now:</p>
<pre><code>public class FileSystemPoller
{
private readonly string _path;
private readonly CancellationToken _cancellationToken;
private readonly string _searchPattern;
private readonly SearchOption _searchOptions;
private readonly HashSet<string> _filesProcessed = new HashSet<string>();
private readonly TimeSpan _interval;
public FileSystemPoller(
string path,
CancellationToken cancellationToken,
string searchPattern = null,
SearchOption options = SearchOption.TopDirectoryOnly,
TimeSpan? interval = null
)
{
_path = path;
_cancellationToken = cancellationToken;
_searchPattern = searchPattern ?? "*";
_searchOptions = options;
_interval = interval.GetValueOrDefault(TimeSpan.FromSeconds(1));
}
private async Task PollForChanges(BlockingCollection<FileInfo> outQueue)
{
var di = new DirectoryInfo(_path);
var files = di.GetFiles(_searchPattern, _searchOptions);
foreach (var file in files)
{
if (!_filesProcessed.Contains(file.FullName) && !IsFileLocked(file))
{
Debug.WriteLine($"File created disk : {file.FullName}");
outQueue.Add(file);
_filesProcessed.Add(file.FullName);
}
}
foreach (var filePath in _filesProcessed)
{
if (!File.Exists(filePath))
{
_filesProcessed.Remove(filePath);
Debug.WriteLine($"Removed from disk : {filePath}");
}
}
Debug.WriteLine("Poll directory changes");
await Task.Delay(_interval).ConfigureAwait(false);
await PollForChanges(outQueue).ConfigureAwait(false);
}
public IEnumerable<FileInfo> GetCreatedFiles()
{
if (_cancellationToken.IsCancellationRequested) yield break;
using (var queue = new BlockingCollection<FileInfo>())
{
PollForChanges(queue);
if (!_cancellationToken.IsCancellationRequested)
{
foreach (var fileInfo in queue.GetConsumingEnumerable(_cancellationToken))
{
yield return fileInfo;
}
}
}
}
private static bool IsFileLocked(FileInfo file)
{
FileStream stream = null;
try
{
stream = file.Open(FileMode.Open,
FileAccess.ReadWrite, FileShare.None);
}
catch (IOException)
{
//the file is unavailable because it is:
//still being written to
//or being processed by another thread
//or does not exist (has already been processed)
Debug.WriteLine($"File present but locked : {file.FullName}");
return true;
}
finally
{
stream?.Close();
}
//file is not locked
return false;
}
}
</code></pre>
<p>This code seems to work, <em>but</em>:</p>
<ul>
<li>if any exception occurs in the <code>PollForChanges</code>, the whole process stops</li>
<li>I'm not sure if the regular scheduling of the method <code>PollForChanges</code>. Especially, I fear I eventually get trapped in a <code>StackOverflowException</code> (because the method is calling itself).</li>
<li>dealing with present files, signaled files, ... is a mess in this code. </li>
<li>Some refactors are suggested. Especially, calling an async method without waiting for it (like <a href="https://stackoverflow.com/questions/22629951/suppressing-warning-cs4014-because-this-call-is-not-awaited-execution-of-the">https://stackoverflow.com/questions/22629951/suppressing-warning-cs4014-because-this-call-is-not-awaited-execution-of-the</a>)</li>
</ul>
<p>Globally, what are possible improvements?</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-04T13:31:22.657",
"Id": "381371",
"Score": "0",
"body": "Please do not add, remove, or edit code in a question after you've received an answer. The site policy is explained in [What to do when someone answers](/help/someone-answers)."
... | [
{
"body": "<p>There is something wrong in the way you are using the cancellation token:</p>\n\n<p>In the code <code>GetConsumingEnumerable()</code> throws if the cancellation token is set:</p>\n\n<blockquote>\n<pre><code> foreach (var fileInfo in queue.GetConsumingEnumerable(_cancellationToken))\n ... | {
"AcceptedAnswerId": "197791",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-04T07:20:31.680",
"Id": "197777",
"Score": "3",
"Tags": [
"c#"
],
"Title": "Reliable replacement for FileSystemWatcher"
} | 197777 |
<p>Any suggestions to make this code better(efficient, style, etc.)? </p>
<p>I also want to know if there is a simpler way to check if a character is a vowel or not because I had to copy and paste "element == (vowel)" like 4 times.</p>
<pre><code>int isVowel(char element)
{
if(element == 'a'||element == 'e'||element == 'i'||element == 'o'||element == 'u')
{
return 0;
}else
{
return 1;
}
}
std::string LetterChanges(const std::string& str)
{
std::vector<char>cstr(str.c_str(),str.c_str()+str.size());
for(auto &element : cstr)
{
if((element >= 'A' && element < 'Z')||(element >='a' && element < 'z'))
{
element = element+1;
if(isVowel(element)==0)
{
element = std::toupper(element);
}
}
}
std::string ss(cstr.begin(),cstr.end());
return ss;
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-04T08:17:27.020",
"Id": "381313",
"Score": "0",
"body": "Does the code look like that in your code editor? It seems like the formatting was changed during pasting it here."
}
] | [
{
"body": "<h1><code>isVowel()</code></h1>\n\n<p>The first thing to say about <code>isVowel()</code> is that it should return <code>bool</code>, not <code>int</code>. And the logic should really be flipped so that it returns <code>true</code> or <code>1</code> if it's a vowel... not <code>false</code> or <code>... | {
"AcceptedAnswerId": "197849",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-04T08:01:30.647",
"Id": "197779",
"Score": "0",
"Tags": [
"c++"
],
"Title": "Replace every letter in the string with the letter following it in the alphabet and capitalize vowels"
} | 197779 |
<p>I have a situation where I need to use person's height in different units. Some parts of the system use Inches/Feet some Meters/Centimeters.</p>
<p>I was thinking of a Height value object which would encapsulate different measurement untis, and upon creation calculate and store all supported measurement units and provide accessors to get each.</p>
<p>I end up with this</p>
<pre><code>public class Height : IEquatable<Height>
{
private Height()
{ }
public double InMeters { get; private set; }
public double InFeet { get; private set; }
public double InInches { get; private set; }
public static Height FromCMeters(double heightInCms) => new Height
{
InMeters = (double) heightInCms / 100,
InFeet = heightInCms * 30.48,
InInches = heightInCms * 2.54
};
public static Height FromFoots(double feet) => new Height
{
InFeet = feet,
InMeters = (feet * 30.48) / 100,
InInches = feet * 12
};
public static Height FromInches(double inches) => new Height
{
InInches = inches,
InFeet = inches / 12,
InMeters = (inches * 2.54) / 100
};
public bool Equals(Height other)
{
if (ReferenceEquals(null, other)) return false;
if (ReferenceEquals(this, other)) return true;
return InMeters.Equals(other.InMeters);
}
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) return false;
if (ReferenceEquals(this, obj)) return true;
if (obj.GetType() != this.GetType()) return false;
return Equals((Height) obj);
}
public override int GetHashCode() => InMeters.GetHashCode();
}
</code></pre>
<p>I intentionally omitted addition/subsctraction to keep code small.
The usage of Height value object:</p>
<pre><code>var height = Height.FromCMeters(191);
// height.InMeters
// height.InInches
// height.InFeet
</code></pre>
<p>I have few doubts:</p>
<ul>
<li>If I need to support new unit of measure I would have to change the value object which I don't think is a good idea</li>
<li>I tend to keep my value objects very small, this one seems to be doing <em>too much</em> for a value object (all those conversion logics)</li>
<li>I think it keeps track of many values instead of a one, and it feels that all this conversion logic belongs to somewhere else</li>
</ul>
<p>This Height <strong>VO</strong> is mostly going to be used to represent height. All operations are going to be creating height from different units (m/cm/feet/inch) and pass it around. Whoever receives it is going to use it just to retrieve height value in the unit it needs.</p>
<p>This simple usage makes me think I don't really need more involved design, where I would have simply Height <strong>VO</strong> (with single metric) and let another component do the necessary conversion.</p>
<p>What do you think ?</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-04T10:35:12.887",
"Id": "381339",
"Score": "3",
"body": "If height is all you need, this approach seems ok. If you need to handle other measures as well, I'd suggest using a library that specifically handles that, e. g. [UnitsNet](http... | [
{
"body": "<p>Instead of carrying around the conversion from each unit to each other unit, it is a better idea to decide on one canonical unit (this can be meters or inches, it does not matter).</p>\n\n<p>Then to introduce a new unit, all you need to add is a <code>FromUnit</code> method and a <code>InUnit</cod... | {
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-04T08:37:37.393",
"Id": "197780",
"Score": "5",
"Tags": [
"c#",
"ddd"
],
"Title": "Value Object encapsulating different units of measure"
} | 197780 |
<p><strong>Requirements</strong></p>
<p>What I need: attach meta information to <em>methods</em>, such that</p>
<ol>
<li>it is 'easy' to retrieve all such methods for a given class instance</li>
<li>methods can still be called 'in a normal way', e.g. <code>obj.method()</code></li>
<li>meta-data is accessible from the decorated method, e.g. <code>obj.method.data</code></li>
<li>IDEs (PyCharm in particular) do not produce any warnings or errors (and, if possible, IDE support, e.g. auto-completion, should be able to handle the annotation)</li>
</ol>
<p>Additionally, I would like the code to be readable/intuitive (not necessarily the super classes, though), generally robust and 'bug-free'. I accept the limitation that my decorators need to be the most 'outer' decorator for the automatic collection to take place.</p>
<p>From my point of view, overcoming function/method transformation while still exposing an arbitrary object type (not a function type -- thinking of this, maybe subclassing a FunctionType might be another idea?) is the hardest challenge.</p>
<p>What do you think of the following three solutions? Is there something I did miss?</p>
<p><strong>Code</strong></p>
<pre><code>class MethodDecoratorWithIfInCall(object):
def __init__(self):
self._func = None
def __call__(self, *args, **kwargs):
if self._func is None:
assert len(args) == 1 and len(kwargs) == 0
self._func = args[0]
return self
else:
return self._func(*args, **kwargs)
def __get__(self, *args, **kwargs):
# update func reference to method object
self._func = self._func.__get__(*args, **kwargs)
return self
class MacroWithIfInCall(MethodDecoratorWithIfInCall):
def __init__(self, name):
super(MacroWithIfInCall, self).__init__()
self.name = name
class MethodDecoratorWithExplicitDecorate(object):
def __init__(self, *args, **kwargs):
# wildcard parameters to satisfy PyCharm
self._func = None
def __call__(self, *args, **kwargs):
return self._func(*args, **kwargs)
def __get__(self, *args, **kwargs):
# update func reference to method object
self._func = self._func.__get__(*args, **kwargs)
return self
def _decorate(self):
def _set_func(func):
self._func = func
return self
return _set_func
@classmethod
def decorate(cls, *args, **kwargs):
obj = cls(*args, **kwargs)
return obj._decorate()
class MacroWithExplicitDecorate(MethodDecoratorWithExplicitDecorate):
def __init__(self, name):
super(MacroWithExplicitDecorate, self).__init__()
self.name = name
class MacroWithoutSuperclass(object):
def __init__(self, func, name):
self.func = func
self.name = name
def __get__(self, *args, **kwargs):
# update func reference to method object
self.func = self.func.__get__(*args, **kwargs)
return self
def __call__(self, *args, **kwargs):
return self.func(*args, **kwargs)
@staticmethod
def decorate(name):
return lambda func: MacroWithoutSuperclass(func, name)
class Shell:
def __init__(self):
macros = [macro for macro in map(self.__getattribute__, dir(self))
if isinstance(macro, (MacroWithIfInCall, MacroWithExplicitDecorate, MacroWithoutSuperclass))]
for macro in macros:
print(macro.name, macro())
@MacroWithIfInCall(name="macro-with-if-in-call")
def macro_add_1(self):
return "called"
@MacroWithExplicitDecorate.decorate(name="macro-with-explicit-decorate")
def macro_add_2(self):
return "called"
@MacroWithoutSuperclass.decorate(name="macro-without-superclass")
def macro_add_3(self):
return "called"
if __name__ == '__main__':
shell = Shell()
</code></pre>
<p><strong>Output</strong></p>
<pre><code>macro-with-if-in-call called
macro-with-explicit-decorate called
macro-without-superclass called
</code></pre>
| [] | [
{
"body": "<p>From your three approaches, I think <code>MacroWithoutSuperclass</code> is probably the cleanest. I wanted to just comment a bit, but it turned out I had too much to say... Thus, here a few remarks followed by a maybe more intuitive solution as an inspiration (it's probably not perfect).</p>\n\n<h... | {
"AcceptedAnswerId": "198215",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-04T09:11:17.457",
"Id": "197783",
"Score": "3",
"Tags": [
"python",
"python-3.x",
"functional-programming",
"meta-programming"
],
"Title": "Decorate instance method with (arbitrary) meta data in python"
} | 197783 |
<p>I am creating an app (with react native) on where messages can be viewed. On the home screen you can see a badge with the unread/new messages. It shows the badge (after a short delay, you will see this in the code).</p>
<p>Although it works, I think there is room for improvement, so I hope one of you can take a look at the code and see where the improvements/performance increase can be made.</p>
<p>This is the code I have so far:</p>
<pre><code>export default class Home extends React.Component {
constructor(props) {
super(props)
this.announce = firebase.firestore().collection('announcements');
this.state = {
newAnnouncements: 0,
}
}
componentDidMount() {
let userId;
let countHasRead;
let countAnnounce;
firebase.auth().onAuthStateChanged((user) => {
if (user) {
userId = user.uid
}
});
setTimeout(() => {
this.announce
.get()
.then(snapshot => {
countAnnounce = snapshot.size;
});
this.announce
.where('hasread.userId', '==', userId)
.get()
.then(snapshot => {
countHasRead = snapshot.size;
})
.catch(err => {
console.log('Error getting documents', err);
});
setTimeout(() => {
this.setState({newAnnouncements: countAnnounce - countHasRead});
}, 1000);
}, 500);
}
}
</code></pre>
<p>I then use <code>this.state.newAnnouncements</code> in the badge.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-04T10:40:22.727",
"Id": "381340",
"Score": "1",
"body": "It is also unclear if this works as intended. \"Somehow this is not working the first time the app loads, but when I navigate to another screen and back to home, it shows the bad... | [] | {
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-04T10:22:19.560",
"Id": "197790",
"Score": "2",
"Tags": [
"javascript",
"react-native"
],
"Title": "Get count of unread messages from google firestore"
} | 197790 |
<p><strong>The problem</strong></p>
<p>You are given a list of \$ n \$ positive integers. Your task is to split the list into \$ k \$ subarrays so that the largest subarray sum is minimized.</p>
<p><strong>The input</strong></p>
<p>On the first line you have two integers <code>n</code> and <code>k</code>; the size of the list and the number of subarrays. On the second line you have <code>n</code> numbers: <code>x1, x2, ..., xN</code>.</p>
<p><strong>The limits</strong></p>
<p>\$ 1 \leq n \leq 10^5 \$</p>
<p>\$ 1 \leq k \leq n \$</p>
<p>\$ 1 \leq x \leq 10^9 \$</p>
<p><strong>An example</strong></p>
<p>Input</p>
<pre><code>5 3
2 4 7 3 5
</code></pre>
<p>Output: </p>
<pre><code>8 (the subarrays are [2,4], [7], [3,5])
</code></pre>
<p><strong>My solution</strong></p>
<p>Let's define a function <code>isPossible</code>, that returns true if it is possible to divide the list into \$ k \$ subarrays so that the maximum sum is the parameter <code>sum</code>. The function loops through the user-inputted array and pushes elements into a vector as long as the elements do not exceed the parameter <code>sum</code>. When the vector can't take the next element without exceeding <code>sum</code>, a new vector is created. All these created vectors are pushed into a vector and if the size of the vector holding all the vectors is less than or equal to \$ k \$, return <code>true</code>. Else return <code>false</code>.</p>
<p>The method <code>vectorsum</code> is a shortcut to getting the sum of the elements inside a vector.</p>
<p>After that I handle the input in <code>main()</code> and binary search the turning point of <code>isPossible</code>.</p>
<p><strong>What went wrong?</strong> </p>
<p>I can handle the small test cases easily, but with larger numbers I get a "time limit exceeded"-error. However the time limit is 1 second and I don't think the test even took so long, so I suspect there might be something off with my data types. Any other improvements are accepted, too!</p>
<pre><code>#include "stdafx.h"
#include <iostream>
#include <vector>
#include <numeric>
#include <math.h>
using namespace std;
int arraysize;
int numberofsubarrays;
long long usernumber;
vector<long long> userArray; //Used in main()
vector<vector<long long>> subarrays; //Used in isPossible()
int vectorsum(vector<long long> userVector) {
int ans = accumulate(userVector.begin(), userVector.end(), 0);
return ans;
}
bool isPossible(long long n) {
subarrays = {};
subarrays.push_back({});
for (auto u : userArray) {
subarrays.back().push_back(u);
if (vectorsum(subarrays.back()) <= n) {
continue;
}
else {
subarrays.back().pop_back();
subarrays.push_back({ u });
}
}
if ((long long)subarrays.size() > numberofsubarrays) {
return false;
}
else {
return true;
}
}
int main()
{
cin >> arraysize >> numberofsubarrays; //Input handling
for (int u = 0; u < arraysize; u++) {
cin >> usernumber;
userArray.push_back(usernumber);
}
long long left = 1;
long long middle;
long long right = pow(10, 10);
while (left + 1 != right) { //Binary search
middle = ceil((left + right) / 2);
/*cout << left << " " << middle << " " << right << endl;*/
if (isPossible(middle)) {
right = middle;
}
else {
left = middle;
}
}
cout << left + 1 << endl;
return 0;
}
</code></pre>
| [] | [
{
"body": "<p>Don't use <code>using namespace std;</code> Writing <code>std::</code> a few times isn't that bad, and it helps keep the std lib types identifiable in your code.</p>\n\n<hr>\n\n<p>Don't use globals so much. It is much better to limit the scope of variables to where they are needed and pass them ar... | {
"AcceptedAnswerId": "197805",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-04T11:31:47.187",
"Id": "197797",
"Score": "6",
"Tags": [
"c++",
"programming-challenge",
"time-limit-exceeded",
"binary-search",
"vectors"
],
"Title": "Binary searching the turning point of a function"
} | 197797 |
<p>I have a database with a number of stored procedures. These stored procedures provide the basic CRUD operations against the data. I'm trying to create a DAO layer with separate DAOs for each domain class (Album, Artist, Genre, Review, etc) which uses a common Base DAO.</p>
<p>Using the Album DAO as an example, this is what I have so far:</p>
<pre><code> public class AlbumDao
{
//Members
BaseDao baseDao = new BaseDao();
//Public Methods
public Album GetAlbumById(int id)
{
Album album;
//Get Album
List<Parameter> parameters = new List<Parameter>();
parameters.Add(new Parameter("@Id", SqlDbType.Int, id));
DataTable dataTable = baseDao.ExecuteQuery("GetAlbumById", parameters);
album = AlbumMapper(dataTable.Rows[0]);
//Return
return album;
}
public List<Album> GetAllAlbums()
{
return GetAlbumList("GetAlbums");
}
public List<Album> GetAllFiveStarAlbums()
{
List<Parameter> parameters = new List<Parameter>();
parameters.Add(new Parameter("@Rating", SqlDbType.Int, 5));
return GetAlbumList("GetAlbumsByRating", parameters);
}
public void InsertAlbum(Album newAlbum)
{
List<Parameter> parameters = new List<Parameter>();
parameters.Add(new Parameter("@Title", SqlDbType.VarChar, newAlbum.Title));
parameters.Add(new Parameter("@Composer", SqlDbType.VarChar, newAlbum.Composer));
parameters.Add(new Parameter("@ReleaseYear", SqlDbType.Int, newAlbum.ReleaseYear));
parameters.Add(new Parameter("@Rating", SqlDbType.Int, newAlbum.Rating));
parameters.Add(new Parameter("@IsFranchise", SqlDbType.Bit, newAlbum.IsFranchise));
baseDao.ExecuteNonQuery("AddAlbum", parameters);
}
//List Method
private List<Album> GetAlbumList(string procedureName, List<Parameter> parameters = null)
{
List<Album> albumList = new List<Album>();
try
{
DataTable dataTable = baseDao.ExecuteQuery(procedureName, parameters);
foreach (DataRow row in dataTable.Rows)
{
albumList.Add(AlbumMapper(row));
}
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
return albumList;
}
//Mappers
private Album AlbumMapper(DataRow dr)
{
Album album = new Album();
if (dr.Table.Columns.Contains("AlbumId"))
{
album.Id = Int32.Parse(dr["AlbumId"].ToString());
}
if (dr.Table.Columns.Contains("Title"))
{
album.Title = dr["Title"].ToString();
}
if (dr.Table.Columns.Contains("Composer"))
{
album.Composer = dr["Composer"].ToString();
}
if (dr.Table.Columns.Contains("ReleaseYear"))
{
album.ReleaseYear = Int32.Parse(dr["ReleaseYear"].ToString());
}
if (dr.Table.Columns.Contains("Rating"))
{
album.Rating = Int32.Parse(dr["Rating"].ToString());
}
if (dr.Table.Columns.Contains("isFranchase"))
{
album.IsFranchise = Boolean.Parse(dr["isFranchase"].ToString());
}
return album;
}
}
</code></pre>
<p>And this is the base DAO:</p>
<pre><code>public class BaseDao
{
string connectionString = "xxx";
SqlConnection connection;
SqlCommand command;
SqlDataAdapter adapter;
public DataTable ExecuteQuery(string procedureName, List<Parameter> parameters = null)
{
DataTable dataTable = new DataTable();
using (connection = new SqlConnection(connectionString))
{
//Create Command
command = new SqlCommand(procedureName, connection);
command.CommandType = CommandType.StoredProcedure;
//Add Parameters If Exist
if (parameters != null)
{
foreach (Parameter parameter in parameters)
{
command.Parameters.Add(parameter.Name, parameter.Type).Value = parameter.Value;
}
}
//Populate DataTable With Stored Procedure Results
try
{
adapter = new SqlDataAdapter(command);
adapter.Fill(dataTable);
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
//Return
return dataTable;
}
public void ExecuteNonQuery(string procedureName, List<Parameter> parameters = null)
{
using (connection = new SqlConnection(connectionString))
{
//Create Command
command = new SqlCommand(procedureName, connection);
command.CommandType = CommandType.StoredProcedure;
//Add Parameters If Exist
if (parameters != null)
{
foreach (Parameter parameter in parameters)
{
command.Parameters.Add(parameter.Name, parameter.Type).Value = parameter.Value;
}
}
//Execute
try
{
connection.Open();
command.ExecuteNonQuery();
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
}
}
</code></pre>
<p>Here is the Album class (just a simple class with constructors and properties):</p>
<pre><code> public class Album
{
//CONSTRUCTORS
public Album() { }
public Album(int id, string title, string composer, int releaseYear, int rating, bool isFranchise)
{
this.Id = id;
this.Title = title;
this.Composer = composer;
this.ReleaseYear = releaseYear;
this.Rating = rating;
this.IsFranchise = isFranchise;
}
public Album(string title, string composer, int releaseYear, int rating, bool isFranchise)
{
this.Title = title;
this.Composer = composer;
this.ReleaseYear = releaseYear;
this.Rating = rating;
this.IsFranchise = isFranchise;
}
//PROPERTIES
public int Id { get; set; }
public string Title { get; set; }
public string Composer { get; set; }
public int ReleaseYear { get; set; }
public int Rating { get; set; }
public bool IsFranchise { get; set; }
}
</code></pre>
<p>So for methods that return a single Album object such as <code>GetAlbumById</code>, I execute the query by passing in the SP name and its parameters to the base DAO, and then take the data from row 0.</p>
<p>For methods that return a list of Album objects such as <code>GetAllFiveStarAlbums</code>, I also call <code>ExecuteQuery</code> but from the <code>GetAlbumList</code> method that iterates through the DataTable and builds a list of Album objects.</p>
<p>In all cases, I use a mapper method to convert the DataTable row to an Album object. </p>
<p>You can imagine the DAOs for Artist, Review etc structured the same way. </p>
<p>I'm unsure if this is good design so I'd appreciate some feedback and advice?</p>
<p>Another thought that occurred to me is that the Album DAO could just have a single List method which takes the name of the stored procedure and SP parameters as parameters, but that would require passing that information from the BLL and I don't think the BLL should know about the names of database stored procedures. </p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-04T15:20:08.727",
"Id": "381395",
"Score": "0",
"body": "Please post the code for Album."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-04T15:29:13.920",
"Id": "381397",
"Score": "0",
"body": "... | [
{
"body": "<p>Why not save yourself all those ADO.NET and Datatable to custom class headaches and use an ORM like <a href=\"https://github.com/StackExchange/Dapper\" rel=\"nofollow noreferrer\">Dapper</a>? And then you simply have a bunch of Services, e.g. an <code>AlbumService</code> which has a <code>Get(int ... | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-04T11:41:33.557",
"Id": "197798",
"Score": "2",
"Tags": [
"c#",
".net",
"ado.net"
],
"Title": "ADO.NET DAO Layer Design With Base DAO"
} | 197798 |
<p>I often need to update properties using the <code>out</code> parameter of the standard <code>TryParse</code> methods. However, use of a property as <code>out</code> or <code>ref</code> parameter is not allowed. So, I wrote my own implementation of the <code>TryParse</code> method <code>MyTryParse</code> using the generic extension method, which is supposed to work for all standard value types.</p>
<p><strong>Codes:</strong></p>
<pre><code>class Program
{
static void Main(string[] args)
{
new Tester().TestIt();
Console.Read();
}
}
class Tester
{
public bool BooleanP { get; set; } = true;
public char CharP { get; set; } = 'A';
public int IntP { get; set; } = 123;
public double DoubleP { get; set; } = 3.14;
public DateTime DateTimeP { get; set; } = DateTime.Now;
public struct TestStruct
{
public int X { get; set; }
};
public TestStruct StructP { get; set; }
public void TestIt()
{
try
{
// bool.TryParse("TRUE", out BooleanP); // ERROR: A property or indexer may not be passed as out or ref parameter
// bool
BooleanP = BooleanP.MyTryParse("bad");
BooleanP.PPrint("\nBooleanP");
BooleanP = BooleanP.MyTryParse("FALSE");
BooleanP.PPrint("BooleanP");
// char
CharP = CharP.MyTryParse("xx");
CharP.PPrint("\nCharP");
CharP = CharP.MyTryParse("Y");
CharP.PPrint("CharP");
// int
IntP = IntP.MyTryParse("0.1");
IntP.PPrint("\nIntP");
IntP = IntP.MyTryParse("555");
IntP.PPrint("IntP");
// double
DoubleP = DoubleP.MyTryParse("3xxx");
DoubleP.PPrint("\nDoubleP");
DoubleP = DoubleP.MyTryParse("3.1415");
DoubleP.PPrint("DoubleP");
// DateTime
DateTimeP = DateTimeP.MyTryParse("20180707");
DateTimeP.PPrint("\nDateTimeP");
DateTimeP = DateTimeP.MyTryParse("2018.07.07");
DateTimeP.PPrint("DateTimeP");
// struct
Console.WriteLine();
StructP = StructP.MyTryParse("9", true);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}
public static class Extensions
{
private enum StandardTtype
{
Undefined,
Boolean,
Byte, SByte,
Char,
Int16, UInt16, Int32, UInt32, Int64, UInt64,
Single, Double, Decimal, DateTime
};
public static T MyTryParse<T>(this T value, string text, bool throwEx = false) where T : struct
{
object oVal = value;
string typeName = typeof(T).Name;
StandardTtype type = StandardTtype.Undefined;
Enum.TryParse(typeName, out type);
switch (type)
{
case StandardTtype.Boolean:
{
if (bool.TryParse(text, out bool outVal))
oVal = outVal;
else ThrowException();
}
break;
case StandardTtype.Byte:
{
if (byte.TryParse(text, out byte outVal))
oVal = outVal;
else ThrowException();
}
break;
case StandardTtype.SByte:
{
if (sbyte.TryParse(text, out sbyte outVal))
oVal = outVal;
else ThrowException();
}
break;
case StandardTtype.Char:
{
if (char.TryParse(text, out char outVal))
oVal = outVal;
else ThrowException();
}
break;
case StandardTtype.Int16:
{
if (short.TryParse(text, out short outVal))
oVal = outVal;
else ThrowException();
}
break;
case StandardTtype.UInt16:
{
if (ushort.TryParse(text, out ushort outVal))
oVal = outVal;
else ThrowException();
}
break;
case StandardTtype.Int32:
{
if (int.TryParse(text, out int outVal))
oVal = outVal;
else ThrowException();
}
break;
case StandardTtype.UInt32:
{
if (uint.TryParse(text, out uint outVal))
oVal = outVal;
else ThrowException();
}
break;
case StandardTtype.Int64:
{
if (long.TryParse(text, out long outVal))
oVal = outVal;
else ThrowException();
}
break;
case StandardTtype.UInt64:
{
if (ulong.TryParse(text, out ulong outVal))
oVal = outVal;
else ThrowException();
}
break;
case StandardTtype.Single:
{
if (float.TryParse(text, out float outVal))
oVal = outVal;
else ThrowException();
}
break;
case StandardTtype.Double:
{
if (double.TryParse(text, out double outVal))
oVal = outVal;
else ThrowException();
}
break;
case StandardTtype.Decimal:
{
if (decimal.TryParse(text, out decimal outVal))
oVal = outVal;
else ThrowException();
}
break;
case StandardTtype.DateTime:
{
if (DateTime.TryParse(text, out DateTime outVal))
oVal = outVal;
else ThrowException();
}
break;
case StandardTtype.Undefined:
default:
if (throwEx)
throw new Exception($"The type '{typeName}' is unhandled");
break;
}
try
{
value = (T)oVal;
}
catch (Exception ex)
{
if (throwEx)
throw new Exception($"Cannot convert '{oVal.ToString()}' into '{typeName}'", ex);
}
void ThrowException()
{
if (throwEx)
throw new Exception($"Cannot parse \"{text}\" into `{typeName}`");
}
return value;
}
public static void PPrint<T>(this T value, string name = "value")
{
Console.WriteLine(name + " = " + value );
}
}
</code></pre>
<p>The main purpose of this method is to work quietly (unless I tell to do otherwise) and update properties (or fields) if this is possible.</p>
<p><strong>Question:</strong> Is something in the <code>MyTryParse</code> method which can go wrong?</p>
<p>Any other suggestion for improving performance, style of readability would be very welcome.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-04T15:23:26.677",
"Id": "381396",
"Score": "3",
"body": "Could you post an example of your real problem and explain why this is a problem, I mean a case of: _I often need to update properties using the `out` parameter of the standard_ ... | [
{
"body": "<ul>\n<li>Trying to put all this type-specific code into a single 'generic' method requires runtime type checks and boxing/unboxing. You're paying for this at runtime, but what do you gain from it? Writing several type-specific methods seems more appropriate here. You would have to write multiple ove... | {
"AcceptedAnswerId": null,
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-04T12:27:14.293",
"Id": "197803",
"Score": "1",
"Tags": [
"c#",
"generics",
"extension-methods"
],
"Title": "Generic TryParse extension method for the standard value types"
} | 197803 |
<blockquote>
<p>A non-empty zero-indexed string S consisting of Q characters is given.
The period of this string is the smallest positive integer P such
that:</p>
<p>\$P ≤ Q/2\$ and \$S[K] = S[K+P]\$ for \$0 ≤ K < Q−P.\$ </p>
<p>So for example, for the integers 955,1651 and 102, convert the numbers
to binary and the function should return 4,5,-1 respectively.</p>
<p>The function returns -1 if there is no binary period for the given
integer.</p>
<p>The int n can be any value between 1 to 99999999</p>
</blockquote>
<p>Here is the original code given in the challenge. The Challenge states that by modifying at most 2 lines, in the function solution, the existing bug should be fixed.</p>
<p><a href="https://i.stack.imgur.com/Ufege.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Ufege.png" alt="enter image description here"></a></p>
<p>Here is my Solution, Can someone please review this?</p>
<pre><code>int solution(int n)
{
int d[30];
int l = 0;
int p;
//convert the integer to binary
while(n > 0)
{
d[l]= n %2 ;
n = n /2;
l++;
}
//compute the length of the resulting binary number
//and that is stored in the variable l
for(p = l/2; p >0; p--){
int ok = 1;
int i;
for(i = 0; i < (l - l/2); i++){
if(d[i] != d[i + p]){
ok = 0;
break;
}
}
if(ok){
return p;
}
}
return -1;
}
int main(int argc, char** argv) {
printf("%d\n",solution(102));
printf("%d\n",solution(955));
printf("%d\n",solution(1651));
return 0;
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-04T13:40:13.723",
"Id": "381373",
"Score": "0",
"body": "i think `for(i = 0; i < (l - l/2); i++){` should be `for(i = 0; i < l-p; i++){`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-04T13:59:11.840",
... | [
{
"body": "<p>I see some things that may help you improve your program. </p>\n\n<h2>Use the appropriate <code>#include</code>s</h2>\n\n<p>In order to compile and link, this code requires at least <code>#include <stdio.h></code>. For the program to be complete, all appropriate <code>#include</code>s shou... | {
"AcceptedAnswerId": "197822",
"CommentCount": "10",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-04T12:59:00.643",
"Id": "197807",
"Score": "10",
"Tags": [
"c"
],
"Title": "C code to calculate the binary period of an integer"
} | 197807 |
<p>This is essentially a best practices question about reading a file and making sure it follows a specific format. My current implementation works, but it's a <code>while</code> loop with a bunch of <code>if</code>/<code>else</code> statements. I think it wouldn't be too readable for other developers.</p>
<pre><code>/**
* Request the server to add the theatre details found in the file indicated by the path.
* The details include the theatre ID (unique across all theatres), the seating dimension, and
* the floor area (square metres). All theatres have as many seats in a row as they do rows, and the number of
* rows is indicated by the seating dimension.
* <p>
* <p>The file format is, each line consists of
* "THEATRE" "\t" theatre ID; "\t" seating dimension; "\t" floor area;
* <p>
* <p>If there is no file associated with the path, or the file format is incorrect, then
* the request fails.
*
* @param path The path indicating the file to use for the initialisation.
* @return An empty string if the initialisation is successful, otherwise a
* message explaining what went wrong beginning with ERROR (e.g. "ERROR incorrect format").
*/
public String initialise(String path)
{
//IO
File theatreFile = new File(path);
Scanner fileScanner = null;
try
{
fileScanner = new Scanner(theatreFile);
}
catch (FileNotFoundException e)
{
return ResponseMessages.FILE_NOT_FOUND_ERR_MSG.getDescription();
}
String currentID = null;
int numRows;
int floorSpace;
/*Loop through input file tokens, check if format is correct and if so, create a theatre object
that corresponds with the given data. */
while(fileScanner.hasNext())
{
if(fileScanner.hasNext(THEATRE_NAME_MARKER))
{
fileScanner.next();
if(fileScanner.hasNext(THEATRE_CODE_MARKER))
{
currentID = fileScanner.next();
if (getTheatreIDs().contains(currentID))
{
return ResponseMessages.DUPLICATE_CODE_ERR_MSG.getDescription();
}
if (fileScanner.hasNextInt())
{
numRows = fileScanner.nextInt();
if (fileScanner.hasNextInt())
{
floorSpace = fileScanner.nextInt();
}
else
{
return ResponseMessages.FILE_FORMAT_ERR_MSG.getDescription();
}
}
else
{
return ResponseMessages.FILE_FORMAT_ERR_MSG.getDescription();
}
}
else
{
return ResponseMessages.FILE_FORMAT_ERR_MSG.getDescription();
}
}
else
{
return ResponseMessages.FILE_FORMAT_ERR_MSG.getDescription();
}
Theatre newTheatre = new Theatre(currentID, numRows, floorSpace);
theatres.add(newTheatre);
}
fileScanner.close();
return ResponseMessages.FILE_FOUND_SUCCESS_MSG.getDescription();
}
</code></pre>
<p>Additionally, here's an example of what an input file may look like:</p>
<pre><code>THEATRE T2 10 400
THEATRE T1 7 200
THEATRE T3 12 600
THEATRE 215 21 1200
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-04T13:43:24.913",
"Id": "381377",
"Score": "0",
"body": "Invert the if conditions. You then don't need the 'else' as te main body returns. So you don't keep stepping into deeper levels"
},
{
"ContentLicense": "CC BY-SA 4.0",
... | [
{
"body": "<ul>\n<li><p>Always close resources in a <code>try-with-resources</code> or <code>try-finally</code> block. Otherwise if something bad happens before you manually close it, the resource will remain open.</p></li>\n<li><p>All three variables can be defined inside your loop.</p></li>\n<li><p>It would b... | {
"AcceptedAnswerId": "197858",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-04T13:25:20.397",
"Id": "197809",
"Score": "1",
"Tags": [
"java",
"file",
"io"
],
"Title": "Method that reads an input file of a particular format and creates objects corresponding to the file"
} | 197809 |
<p>I have a form, I need to send untraslated values, but as well, I need to get translated ones from Vue to write them down in page.</p>
<p>For now, I ended up creating a 'shadow' property and changing it via the <code>watch</code> function. Note that I'm referencing the SELECT via the custom <code>ref</code> prop and <code>Vue.$refs</code>. So:</p>
<pre><code><select name="screw[type]" ref="screw_type_select" v-model="form.screw.type">
<option value="My value" data-value="<?php _e('My value', 'context'); ?>"><?php _e('My value', 'context'); ?></option>
//[...]
</code></pre>
<p>Then in Vue:</p>
<pre><code>var vueapp = new Vue({
el: '#form'
,data:{
form:{
,screw:{
type: "Svasata Piana"
,type_t: "Svasata Piana"
}
}
}// data
,watch:{
'form.screw.type':function(){
var select = this.$refs.screw_type_select;
this.form.screw.type_t = select.options[select.selectedIndex].getAttribute('data-value')
}
}
});
</code></pre>
<p>Then again in html:</p>
<pre><code>{{ form.screw.type_t }} // instead of {{ form.screw.type }}
</code></pre>
<p>So the form will send value, but the user will see data-value intead (which is translated).</p>
<p>What do you think of this way?</p>
| [] | [
{
"body": "<p>This is not the Vue-way to do it. Vue does not recommend the use of <code>$refs</code>. And in this case, you can also avoid it.</p>\n\n<p>Your current code is:</p>\n\n<pre><code><select name=\"screw[type]\" ref=\"screw_type_select\" v-model=\"form.screw.type\">\n <option value=\"My val... | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-04T14:25:46.157",
"Id": "197812",
"Score": "3",
"Tags": [
"javascript",
"i18n",
"vue.js"
],
"Title": "Using something other than form field's value in Vue"
} | 197812 |
<p>This is my attempt at a C++ version of Java's <code>LinkedHashMap</code>. Any criticism is welcome.</p>
<p>I implemented important methods. Big thing still to do would be an iterator. First I wanted to get feedback on this thus far:</p>
<pre><code>#include <unordered_map>
#include <list>
#include <utility>
#include <algorithm>
#include <set>
using namespace std;
template <class K, class V>
class linked_hash_map {
private:
typedef typename list<K>::iterator list_iterator;
unordered_map< K, pair<V, list_iterator > > hash;
list<K> ls;
public:
int size() { return hash.size(); }
bool empty() { return hash.empty(); }
void insert(pair<K,V> kv) {
if (hash.count(kv.first) == 1) {
auto p = hash[kv.first];
hash[kv.first] = make_pair(kv.second, p.second);
} else {
ls.push_back(kv.first);
auto it = ls.end(); --it;
hash.insert( make_pair(kv.first, make_pair(kv.second, it)));
}
}
void erase(K key) {
if (hash.count(key) == 1) {
auto p = hash[key];
hash.erase(key);
ls.erase(p.second);
}
}
void eraseEldest() {
if(!hash.empty()) {
K key = ls.front();
ls.pop_front();
hash.erase(key);
}
}
void eraseNewest() {
if(!hash.empty()) {
K key = ls.back();
ls.pop_back();
hash.erase(key);
}
}
V at(K key) {
auto p = hash.at(key);
return p.first;
}
V operator[](K key) {
auto p = hash[key];
return p.first;
}
list<K>& keyList() {
return ls;
}
};
</code></pre>
| [] | [
{
"body": "<pre><code>#include <algorithm>\n#include <set>\n</code></pre>\n\n<p>I don't see anything from <code><algorithm></code> or <code><set></code> in the code.</p>\n\n<pre><code>using namespace std;\n</code></pre>\n\n<p>Never do this. Just never do this. But <em>especially</em> nev... | {
"AcceptedAnswerId": "197881",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-04T15:10:31.777",
"Id": "197814",
"Score": "4",
"Tags": [
"c++"
],
"Title": "A C++ implementation of LinkedHashMap"
} | 197814 |
<p>I have incremented an integer in the function <code>nextpalin()</code> and converted it into a <code>std::string</code> for finding whether it's a palindrome or not. </p>
<p>If it is a palindrome I return it. The code is giving TLE on SPOJ but working fine on other online IDEs; how to make this code more efficient?</p>
<pre><code>#include <iostream>
#include <string.h>
using namespace std;
int nextpalin (int num){
while (num++) {
string str = to_string (num); /// int to string conversion
int l = str.length()-1;
int s = 0;
while( s<l ){
if (str[s]!=str[l]) break;
else {
s++;
l--;
}
if (s>=l) return num;}
}
}
int main () {
int t;
cin >> t;
while (t--){
int num;
cin >> num;
if (num==0) cout << "1" << endl;
else {
if (num<9) cout << num+1 << endl;
else cout << nextpalin( num) << endl;}
}
}
</code></pre>
| [] | [
{
"body": "<p>For starter, since you are doing C++, use C++ headers instead of C ones. And also <a href=\"https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice\">don't get into the habit of <code>using namespace std</code></a>. You're typing 20 characters anyway to help ... | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-04T15:15:41.780",
"Id": "197816",
"Score": "7",
"Tags": [
"c++",
"programming-challenge",
"time-limit-exceeded",
"palindrome"
],
"Title": "The Next Palindromic number"
} | 197816 |
<p>I wrote this code to make sure account numbers (accounting), which are numbers, are stored as text in the range. Replacing <code>r.value</code> by <code>r.text</code> does not seem to work on whole ranges, so I need to loop. Any better idea?</p>
<pre><code>Sub num2text(r As Range, Optional keepFormat As Boolean)
'change numbers to text, optionally leaving the numberFormat unchanged
Dim oldFormat
Dim c As Range
For Each c In r
If IsNumeric(c) Then
If keepFormat Then oldFormat = c.NumberFormat 'save num fmt
c.NumberFormat = "@"
c.Value = c.Text
If keepFormat Then c.NumberFormat = oldFormat 'restore num fmt
End If
Next c
End Sub
Sub num2text_test()
num2text Range("b10:b100")
End Sub
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-04T17:03:44.570",
"Id": "381417",
"Score": "0",
"body": "Is appending a `'` an option to retain formatting?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-04T18:19:19.803",
"Id": "381428",
"Score":... | [
{
"body": "<p>I updated the code to include @TinMan's remarks.<br>\nI also added a safety net by intersecting the range in parameter with the <code>UsedRange</code> to avoid scanning 1 million empty cells if a full column is provided as a parameter. </p>\n\n<p>The most effective change is probably using <code>... | {
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-04T15:57:30.723",
"Id": "197821",
"Score": "1",
"Tags": [
"vba",
"excel"
],
"Title": "Store account numbers as text"
} | 197821 |
<blockquote>
<p>Given a string s consisting of lowercase Latin Letters, find the
first non repeating character in s.</p>
<p><strong>Input:</strong></p>
<p>The first line contains T denoting the number of testcases. Then
follows description of testcases. Each case begins with a single
integer N denoting the length of string. The next line contains the
string s.</p>
<p><strong>Output:</strong> </p>
<p>For each testcase, print the first non repeating character present in
string. Print -1 if there is no non repeating character. </p>
<p><strong>Constraints:</strong></p>
<pre><code>1<=T<=50
1<=N<=100
</code></pre>
<p><strong>Example:</strong></p>
<p><strong>Input :</strong></p>
<pre><code>3
5
hello
12
zxvczbtxyzvy
6
xxyyzz
</code></pre>
<p><strong>Output :</strong> </p>
<pre><code>h
c
-1
</code></pre>
</blockquote>
<p>My approach:</p>
<pre><code>/*package whatever //do not write package name here */
import java.io.InputStreamReader;
import java.io.IOException;
import java.io.BufferedReader;
import java.util.*;
class GFG {
private static int firstNonRepNum (String str, int size)
{
Hashtable <Character, Integer> count = new Hashtable<>();
int occurs;
for (char ch: str.toCharArray())
{
if (!count.containsKey(ch))
{
count.put(ch,1);
}
else
{
occurs = count.get(ch);
count.put(ch, occurs+1);
}
}
for (char ch: str.toCharArray())
{
int val = count.get(ch);
if (val == 1)
{
return ch;
}
}
return -1;
}
public static void main (String[] args) throws IOException{
//code
//BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
//String line = br.readLine();
Scanner sc = new Scanner(System.in);
int numTests = sc.nextInt();
String line2;
int size;
String str;
for (int i = 0; i < numTests; i++)
{
size = sc.nextInt();
str = sc.next();
if (firstNonRepNum(str,size) == -1)
{
System.out.println("-1");
}
else
{
System.out.println((char)firstNonRepNum(str, size));
}
}
}
}
</code></pre>
<p>I have the following questions with regards to the above code:</p>
<ol>
<li><p>How can I further improve my approach?</p></li>
<li><p>Is there a better way to solve this question?</p></li>
<li><p>Are there any grave code violations that I have committed?</p></li>
<li><p>Can space and time complexity be further improved?</p></li>
</ol>
<p><a href="https://practice.geeksforgeeks.org/problems/non-repeating-character/0" rel="nofollow noreferrer">Reference</a></p>
| [] | [
{
"body": "<p>Your algorithm is correct. There is no way to reduce time or space complexity, so I will give some less important suggestions.</p>\n\n<ol>\n<li><p>because you know that there will only be latin letters, we can use an array instead of a hashtable and avoid the overhead. You can decide for yourself ... | {
"AcceptedAnswerId": "197852",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-04T16:39:34.377",
"Id": "197823",
"Score": "3",
"Tags": [
"java",
"beginner",
"programming-challenge",
"interview-questions",
"complexity"
],
"Title": "Non repeating character in Java"
} | 197823 |
<p>I'm trying to develop some templates for common PHP tasks I've been dealing with. One of which is a general image file upload handler.</p>
<p>So far I'm using the following reusable code which seems to be working fine without any noticeable bug:</p>
<pre><code><?php
if ( !isset($_POST['submit']) ) {
goto page_content;}
if ( $_FILES['file_upload']['error']===4 ) {
echo 'No file uploaded';
goto page_content;}
if ( $_FILES['file_upload']['error']===1 || $_FILES['file_upload']['error']===2 ) {
echo 'File exceeds maximum size limit';
goto page_content;}
if ( $_FILES['file_upload']['error']!==0 ) {
echo 'Failed to upload the file';
goto page_content;}
if ( !is_uploaded_file($_FILES['file_upload']['tmp_name']) ) {
echo 'Failed to upload the file';
goto page_content;}
require_once('imageResize.php');
$err = imageResize($_FILES['file_upload']['tmp_name'], 'random.png' );
if ( $err !== 0 ) {
echo 'Invalid image format';
goto page_content;}
echo 'Image uploaded successfully';
page_content:
?>
<form action="filename.php" method="POST" enctype="multipart/form-data">
<input type="hidden" name="MAX_FILE_SIZE" value="1000000">
<input type="file" name="file_upload" accept="image/*">
<input type="submit" name="submit">
</form>
</code></pre>
<p>Additional file <code>imageResize.php</code>: </p>
<pre><code><?php
// image resize
function imageResize($source, $target){
$size = getimagesize($source);
if ($size === false) {return 1;} // invalid image format
$sourceImg = @imagecreatefromstring(@file_get_contents($source));
if ($sourceImg === false) {return 2;} //invalid image format
$width = imagesx($sourceImg);
$height = imagesy($sourceImg);
$sidelenght = min($width,$height);
$targetImg = imagecreatetruecolor(100, 100);
imagecopyresampled($targetImg, $sourceImg, 0, 0, ($width-$sidelenght)/2, ($height-$sidelenght)/2, 100, 100, $sidelenght, $sidelenght);
imagedestroy($sourceImg);
imagepng($targetImg, $target);
imagedestroy($targetImg);
return 0;
}
?>
</code></pre>
<p>Some main characteristics of this code are:</p>
<ul>
<li>provides messages for the most common errors that can happened during the upload process</li>
<li>it allows the client to upload an image file up to 1Mb size</li>
<li>resizes all images to a standard 100x100 px size</li>
<li>save all images to a standard PNG format</li>
</ul>
<p><strong>Questions</strong></p>
<ol>
<li>Is this code safe? Or are there any vulnerability that could be exploited by an malicious client? In this case, how can I solve it? </li>
<li>To avoid several nested <code>if-then-else</code> conditions (which can become hard to read), I'm currently using <code>goto</code> (which can become a bad control structure practice). Is there a better alternative?</li>
</ol>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-04T17:30:37.253",
"Id": "381425",
"Score": "0",
"body": "Following others suggestion, this is a repost from [StackOverflow](https://stackoverflow.com/questions/51177466/php-template-file-upload-handler)"
}
] | [
{
"body": "<blockquote>\n <p><strong>DO NOT use GOTO</strong>. They have been <a href=\"https://en.wikipedia.org/wiki/Goto#Criticism\" rel=\"nofollow noreferrer\">criticised since 1960s</a>.</p>\n</blockquote>\n\n<ol>\n<li>Your indentation is broken for the first snippet. It is also inconsistent with your seco... | {
"AcceptedAnswerId": "197841",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-04T17:29:32.467",
"Id": "197826",
"Score": "2",
"Tags": [
"php",
"image",
"form",
"http",
"network-file-transfer"
],
"Title": "PHP Template: Image file upload handler"
} | 197826 |
<p>I wrote a basic C++ template to manage shared resources like textures and shaders in a 3D engine. The idea is that the cache itself holds weak references to the resources (through <code>std::weak_ptr</code>) and turns it into strong references (through <code>std::shared_ptr</code>) when the resource is fetched from the cache or constructed if it's not present. As soon as all strong references go out of scope, the given object gets deleted and removed from the cache by a custom deleter. Suggestions/improvements are welcome:</p>
<pre><code>#ifndef PTRCACHE_H
#define PTRCACHE_H
#include <memory>
#include <map>
#include <functional>
#include <mutex>
namespace MyEngine
{
template<typename Key, typename Val, typename ... Args>
class PtrCache
{
public:
PtrCache(const std::function<Val*(Args...)>& creator) :
_creator(creator),
_mutex(std::make_unique<std::mutex>())
{}
PtrCache(const PtrCache& other) = delete;
PtrCache& operator=(const PtrCache& other) = delete;
PtrCache(PtrCache&& other) :
_cache(std::move(other._cache)),
_creator(std::move(other._creator)),
_mutex(std::move(other._mutex))
{}
PtrCache& operator=(PtrCache&& other)
{
if (this != &other) {
_cache = std::move(other._cache);
_creator = std::move(other._creator);
_mutex = std::move(other._mutex);
}
return *this;
}
/**
* Returns true if ret was taken from the cache, false otherwise.
*/
bool getOrCreate(const Key& key, std::shared_ptr<Val>& ret, Args... args)
{
std::lock_guard<std::mutex> lock(*_mutex);
auto it = _cache.find(key);
if (it != _cache.end()) {
ret = std::shared_ptr<Val>(it->second); // Construct from weak_ptr
return true;
}
ret = std::shared_ptr<Val>(_creator(args...), [this, key](Val* ptr) { // Construct from creator and pass custom deleter which removes the element from the cache.
std::lock_guard<std::mutex> lock(*_mutex);
_cache.erase(key);
delete ptr;
});
_cache[key] = ret;
return false;
}
inline void clear()
{
std::lock_guard<std::mutex> lock(*_mutex);
_cache.clear();
}
inline size_t size()
{
std::lock_guard<std::mutex> lock(*_mutex);
return _cache.size();
}
private:
std::map<Key, std::weak_ptr<Val>> _cache;
std::function<Val*(Args...)> _creator;
std::unique_ptr<std::mutex> _mutex;
};
}
#endif
</code></pre>
<p>Basic usage example:</p>
<pre><code>PtrCache<std::string, GLTexture, const std::string&> texture_cache([] (const std::string& path) {
auto tex = SOIL_load_OGL_texture(path.c_str(), SOIL_LOAD_AUTO, SOIL_CREATE_NEW_ID, SOIL_FLAG_MIPMAPS | SOIL_FLAG_TEXTURE_REPEATS | SOIL_FLAG_COMPRESS_TO_DXT);
if (tex) {
return new GLTexture(tex, GL_TEXTURE_2D);
}
else {
throw std::exception((std::string("Could not create texture ") + path).c_str());
return nullptr;
}
});
std::shared_ptr<GLTexture> my_texture;
std::string path = "my_texture.png";
texture_cache.getOrCreate(path, my_texture, path);
</code></pre>
<p>The only caveat I see is that the user of this class has to ensure that the lifetime of the cache goes beyond the lifetime of any contained managed object. Otherwise, the custom deleter would obviously cause undefined behaviour.</p>
| [] | [
{
"body": "<p>The basic idea of your cache, as I understand it, is that it is a map of weak pointers connected to shared pointers with custom deleters that remove them from the map. As you noticed yourself, that's a risky pattern, because if any resources outlive the cache, you get UB.</p>\n\n<p>Is it really ne... | {
"AcceptedAnswerId": "197872",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-04T20:13:27.160",
"Id": "197834",
"Score": "2",
"Tags": [
"c++",
"template",
"cache"
],
"Title": "C++ Software cache for shared resources"
} | 197834 |
<p>I have made a helper <code>struct</code> in Swift that creates circular icons from a PNG image (a white icon on transparent background) and a background <code>UIColor</code>. These variables are user-definable in my app, and the created icons are used in notifications and Spotlight, for example.</p>
<p>The PNG images are named <code>iconA.png</code>, <code>iconB.png</code> etc. and are all a standard 100-points square. The default image is a fully transparent one called <code>iconEmpty.png</code>. I wanted to provide a <code>CGSize</code> argument so that I could use this method for other purposes as well, should the need arise.</p>
<p>It works as expected, but I am wondering how it might be improved or made more efficient, as I am not very experienced with drawing contexts.</p>
<pre><code>import UIKit
struct IconMaker {
func makeIcon(with color: UIColor, size: CGSize, icon: UIImage = UIImage(named: "iconEmpty.png")!) -> UIImage {
// Make solid color background
let rect = CGRect(x: 0, y: 0, width: size.width, height: size.height)
UIGraphicsBeginImageContextWithOptions(size, false, UIScreen.main.scale)
color.setFill()
UIRectFill(rect)
let backgroundImage: UIImage = UIGraphicsGetImageFromCurrentImageContext()!
UIGraphicsEndImageContext()
// Add other image (which has transparency)
UIGraphicsBeginImageContextWithOptions(size, false, UIScreen.main.scale)
backgroundImage.draw(in: rect, blendMode: .normal, alpha: 1)
icon.draw(in: rect, blendMode: .normal, alpha: 1)
let newImage: UIImage = UIGraphicsGetImageFromCurrentImageContext()!
UIGraphicsEndImageContext()
// Circular mask
let cornerRadius = newImage.size.height/2
UIGraphicsBeginImageContextWithOptions(size, false, UIScreen.main.scale)
let bounds = CGRect(origin: CGPoint.zero, size: size)
UIBezierPath(roundedRect: bounds, cornerRadius: cornerRadius).addClip()
newImage.draw(in: bounds)
let finalImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return finalImage!
}
}
</code></pre>
| [] | [
{
"body": "<pre><code>let rect = CGRect(x: 0, y: 0, width: size.width, height: size.height)\n</code></pre>\n\n<p>can be simplified to</p>\n\n<pre><code>let rect = CGRect(origin: .zero, size: size)\n</code></pre>\n\n<p>The explicit type annotation in</p>\n\n<pre><code>let backgroundImage: UIImage = UIGraphicsGet... | {
"AcceptedAnswerId": "197984",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-04T20:48:10.003",
"Id": "197836",
"Score": "4",
"Tags": [
"image",
"swift",
"uikit"
],
"Title": "A helper class for creating icons from a PNG image and colour in Swift"
} | 197836 |
<p>I will start by saying this implementation was based on the approach taken with B-Trees in the book:</p>
<p><em>Introduction to Algorithms, 3rd Edition - Cormen, 2011</em></p>
<p>The implementation stores all the b-tree nodes in a binary file, and constantly writes and reads from the said file in order to add new ones and to update the nodes information.</p>
<p>The file created is organized and treated like an array, the tree keeps track of the numbers of nodes it has and where each one is, so, when a new key/item is added a new position in the file/array is given/added.</p>
<p>To access directly to the node in the file fseek() is used to "jump" directly to the node location, witch gives the file "the array like properties".</p>
<p>Note: the print method prints the tree starting from the root and to do so it requieres a queue, that i will also provide for testing purposes.</p>
<p>This implementation lacks the delete method and other small but usefull methods, like get min/max item, etc... because before i tackle those i want to know if the current ones are good.</p>
<p>Methods Implementaded:</p>
<ul>
<li>Crete B-Tree</li>
<li>Insertion</li>
<li>Search</li>
<li>Print tree</li>
</ul>
<p>The code is highly commented, so will abstain from explainning how the algorithm of the functions works, but if requested, i will update the post.</p>
<p>From the tests i ran the implementation worked as expected, but i must say i didnt do an extensive testing.</p>
<p>I am sorry if the question got "too big", the essential code to be reviewed is the <strong>btree.c</strong> one</p>
<p><strong>btree.c</strong></p>
<pre><code>#include "btree.h"
//#############################################################################
// HELPER METHODS
//#############################################################################
btNode disk_read(int disk, int order, FILE *fp){
btNode read_node;
// calculate the nº of bytes a node has
int size_of_btNode = (sizeof(int) * 3) + (sizeof(element) * order-1) + (sizeof(int) * order);
int offset = size_of_btNode * disk; // calculate the position of the node in the file
fseek(fp, offset, SEEK_SET); // set the file pointer there
fread(&read_node.numKeys, sizeof(read_node.numKeys), 1, fp); // read the information from the file
fread(&read_node.isLeaf, sizeof(read_node.isLeaf), 1, fp);
fread(&read_node.pos_in_disk, sizeof(read_node.pos_in_disk), 1, fp);
read_node.keys = malloc(sizeof(element) * order-1);
fread(read_node.keys, sizeof(element), order-1, fp);
read_node.kids = malloc(sizeof(int) * order);
fread(read_node.kids, sizeof(int), order, fp);
return read_node;
}
void disk_write(btNode node, int order, FILE *fp){
// calculate the nº of bytes a node has
int size_of_btNode = (sizeof(int) * 3) + (sizeof(element) * order-1) + (sizeof(int) * order);
int offset = size_of_btNode * node.pos_in_disk; // calculate the position of the node in the file
fseek(fp, offset, SEEK_SET); // set the file pointer there
fwrite(&node.numKeys, sizeof(node.numKeys), 1, fp); // write the information to the file
fwrite(&node.isLeaf, sizeof(node.isLeaf), 1, fp);
fwrite(&node.pos_in_disk, sizeof(node.pos_in_disk), 1, fp);
fwrite(node.keys, sizeof(element), order-1, fp);
fwrite(node.kids, sizeof(int), order, fp);
}
btNode new_node(int order, int is_leaf) {
btNode n;
n.numKeys = 0; // set nº of keys to 0
n.isLeaf = is_leaf;
n.keys = malloc((order-1) * sizeof(element)); // allocate space for the array of keys
for(int i=0; i < order-1; i++){ // initialize the keys in the array
n.keys[i].key = -1;
n.keys[i].data = -1;
}
n.kids = malloc((order) * sizeof(int)); // allocate space for the array of keys
for(int i=0; i < order; i++){ // initialize the kids in the array
n.kids[i] = -1;
}
return n;
}
void bt_split_child(btNode x, int pos, bTree *tree, FILE *fp, int split_root){
btNode y = disk_read(x.kids[pos], tree->order, fp); // node to split (pos-th child)
if(split_root == 1){ // special case when splitting the root of the tree
tree->node_count++; // increment nº of total nodes
y.pos_in_disk = tree->node_count; // attribute a new location in the file
}
btNode z = new_node(tree->order, y.isLeaf); // new (pos+1)-th child
tree->node_count++; // increment nº of total nodes
z.pos_in_disk = tree->node_count; // attribute a new location in the file
int t = (tree->order / 2); // calculate minimum ramification degree
if(tree->order % 2 == 0){
t--;
}
z.numKeys = t; // nº of keys the new node will receive
if(tree->order % 2 != 0){
t--;
}
for(int j = 0; j <= t && (j+t+1)<= y.numKeys-1; j++){ // move elements to new node
z.keys[j] = y.keys[j+t+1];
y.keys[j+t+1].key = -1; // erase the element from the previous node
y.keys[j+t+1].data = -1;
}
if(y.isLeaf == 0){ // if y is not a leaf
for(int j = 0; j <= t; j++){ // move children as well
z.kids[j] = y.kids[j+t+1];
y.kids[j+t+1] = -1; // erase the element from the previous node
}
}
y.numKeys = t; // update the nº of keys the node has after split
if(split_root == 1){ // special case when splitting the root of the tree
x.kids[pos] = y.pos_in_disk;
x.kids[pos+1] = z.pos_in_disk;
}else{
int j, i, r;
for(j = 0; j < tree->order;j++){ // make room for x`s new child
if(x.kids[j] == y.pos_in_disk){
for(i = j+1; i < tree->order;i+=2){
if(i+1 < tree->order)
x.kids[i+1] = x.kids[i];
}
r = j;
}
}
x.kids[r+1] = z.pos_in_disk;
}
for(int j = pos; j < tree->order-2; j+=2){ // make room for the element
x.keys[j+1] = x.keys[j]; // that will be promoted
}
x.keys[pos] = y.keys[t]; // promote element
y.keys[t].key = -1; // erase the updated element from the previous node
y.keys[t].data = -1;
x.numKeys++; // increment the nº of keys the root node has
disk_write(x, tree->order, fp); // update the information in the file
disk_write(y, tree->order, fp); // update the information in the file
disk_write(z, tree->order, fp); // update the information in the file
}
btNode bt_insert_nonfull(btNode node, element key, bTree *tree, FILE *fp){
int pos = node.numKeys;
if(node.isLeaf == 1){ // if in a leaf insert the new element
int i = pos-1;
while(i >= 0 && key.key < node.keys[i].key){ // find the correct position
node.keys[i+1] = node.keys[i];
node.keys[i].key = -1;
node.keys[i].data = -1;
i--;
}
if(i+1 != pos){
node.keys[i+1] = key;
}else{
node.keys[pos] = key;
}
node.numKeys++;
disk_write(node, tree->order, fp);
return node;
}else{ // otherwise, descend to the appropriate child
int n_pd = node.pos_in_disk;
int i = pos-1;
while (key.key < node.keys[i].key && i >= 0) { // get the correct child of the node
i--;
pos--;
}
btNode x = disk_read(node.kids[pos], tree->order, fp); // get the child node
if(x.numKeys == tree->order-1){ // is this child full?
bt_split_child(node, pos, tree, fp, 0); // split the child
btNode x1 = disk_read(n_pd, tree->order, fp); // get the updated node
if(key.key > x1.keys[pos].key) // adjust the position if needed
pos++;
}
btNode x1 = disk_read(n_pd, tree->order, fp); // get the updated node
btNode x2 = disk_read(x1.kids[pos], tree->order, fp); // get the child node
bt_insert_nonfull(x2, key, tree, fp);
}
}
//#############################################################################
// METHODS
//#############################################################################
bTree *btCreate(int order){
bTree *tree; // creates the "header" of the B-Tree
if((tree = malloc(sizeof(bTree))) == NULL) // allocate space for the new tree
return NULL;
btNode root = new_node(order, true); // creates the root of the new B-Tree
root.pos_in_disk = 0; // give the root a position in the file
tree->order = order; // give the tree it`s order
tree->root = root; // give the tree it`s root
tree->node_count = 0; // set the tree`s node count to 0
return tree;
}
void btInsert(bTree *tree, element key, FILE *fp){
if(tree->node_count > 0)
tree->root = disk_read(0, tree->order, fp); // update the root of the tree
btNode root = tree->root;
if(root.numKeys == tree->order-1){ // if the root is full
btNode s = new_node(tree->order, 0); // create a new root node
s.kids[0] = root.pos_in_disk; // root becomes the first child
bt_split_child(s, 0, tree, fp, 1); // split the root
s = disk_read(0, tree->order, fp); // get the new root
tree->root = s; // make it the new root after the split
bt_insert_nonfull(s, key, tree, fp); // now insert the new element
}else{
tree->root = bt_insert_nonfull(root, key, tree, fp); // insert the new element in a non-full node
}
}
int btSearch(btNode node, int order, element key, FILE *fp){
int pos = 0;
while(pos < node.numKeys && key.key > node.keys[pos].key){ // find the correct position
pos++;
}
if(pos <= node.numKeys && key.key == node.keys[pos].key){ // is the item one of the key`s of this node?
return node.pos_in_disk;
}else if(node.isLeaf == 1){ // if a leaf was hit and no item was found
return -1;
}else{
btNode x = disk_read(node.kids[pos], order, fp); // go deeper in the tree
return btSearch(x, order, key, fp);
}
}
void print_node_keys(btNode node, int order){
printf("[");
for(int i = 0; i < order-1; i++){
if(node.keys[i].key != -1)
printf("key: %d, ", node.keys[i].key);
}
printf("] ");
}
void btPrintTree(bTree *tree, queue *q,FILE *fp){
btNode end = { .numKeys = -1}; // marker to know when a level of the tree ends
insert(q, tree->root); // insert the root in the queue
int item_count= 1; // real item/node counter
while(!isEmpty(q)){
btNode current = removeData(q); // remove the first item in the queue and return that node
if(current.numKeys == -1){ // was a marker found?
printf("\n");
insert(q, end);
if(item_count == 0) // to avoid and endless loop of markers
break; // when the tree is already printed
}else{
item_count--;
print_node_keys(current, tree->order);
if(current.pos_in_disk == 0) // special case for the root
insert(q, end);
for(int i = 0; i < tree->order; i++){ // insert all the kids os the next node in the queue
if(current.kids[i] != -1){
btNode x = disk_read(current.kids[i], tree->order, fp); // get the kid
insert(q, x);
item_count++;
}
}
}
}
}
</code></pre>
<p><strong>btree.h</strong></p>
<pre><code>#ifndef BTREE_H
# define BTREE_H
#include <stdio.h>
#include <malloc.h>
#include "queue.h"
//#############################################################################
// STRUCTS
//#############################################################################
typedef struct element{
int key; // the key of the element
int data; // that data that each element contains
}element;
typedef struct btNode{
int numKeys; // nº of keys the node has
int isLeaf; // is this a leaf node? 1 = true, 0 = false
int pos_in_disk; // position of the node in the file
element *keys; // holds the keys of the node
int *kids; // holds the children of the node
}btNode;
typedef struct bTree {
int order; // order of the B-Tree
btNode root; // root of the B-Tree
int node_count; // total nº of nodes the tree has
} bTree;
typedef struct queue queue;
//#############################################################################
// METHODS
//#############################################################################
// create a new empty tree
bTree *btCreate(int order);
// return nonzero if key is present in tree
int btSearch(btNode node, int order, element key, FILE *fp);
// insert a new element into a tree
void btInsert(bTree *tree, element key, FILE *fp);
// print all keys of the tree from the root
void btPrintTree(bTree *tree, queue *q,FILE *fp);
// read and returns a node from the file
btNode disk_read(int disk, int order, FILE *fp);
#endif
</code></pre>
<p><strong>queue.c</strong></p>
<pre><code>#include "queue.h"
queue *createQueue(int size) {
queue *q;
if((q = malloc(sizeof(queue))) == NULL)
return NULL;
if((q->list = malloc(sizeof(btNode) * size)) == NULL)
return NULL;
q->size = size;
q->front = 0;
q->rear = -1;
q->itemCount = 0;
return q;
}
btNode peek(queue *q) {
return q->list[q->front];
}
bool isEmpty(queue *q) {
return q->itemCount == 0;
}
bool isFull(queue *q) {
return q->itemCount == q->size;
}
int size(queue *q) {
return q->itemCount;
}
void insert(queue *q ,btNode data) {
if(!isFull(q)) {
if(q->rear == q->size-1) {
q->rear = -1;
}
q->list[++q->rear] = data;
q->itemCount++;
}
}
btNode removeData(queue *q) {
btNode data = q->list[q->front++];
if(q->front == q->size) {
q->front = 0;
}
q->itemCount--;
return data;
}
</code></pre>
<p><strong>queue.h</strong></p>
<pre><code>#ifndef QUEUE_H
# define QUEUE_H
#include "btree.h"
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <stdbool.h>
//#############################################################################
// STRUCTS USED
//#############################################################################
typedef struct element element;
typedef struct btNode btNode;
typedef struct bTree bTree;
typedef struct queue{
int size;
int front;
int rear;
int itemCount;
btNode *list;
}queue;
//#############################################################################
// METHODS
//#############################################################################
queue *createQueue(int size);
btNode peek(queue *q);
bool isEmpty(queue *q);
bool isFull(queue *q);
int size(queue *q);
void insert(queue *q ,btNode data);
btNode removeData(queue *q);
#endif
</code></pre>
<p>Small testing program:</p>
<p><strong>test.c</strong></p>
<pre><code>#include "btree.h"
#include "queue.h"
int main(){
element n1 = {.key = 20};
element n2 = {.key = 30};
element n3 = {.key = 10};
element n4 = {.key = 40};
element n5 = {.key = 15};
element n6 = {.key = 17};
element n7 = {.key = 18};
element n8 = {.key = 50};
element n9 = {.key = 60};
element n10 = {.key = 70};
FILE *fp;
fp = fopen("file.bin", "wb+");
bTree *tree = btCreate(4);
btInsert(tree, n2, fp);
btInsert(tree, n1, fp);
btInsert(tree, n3, fp);
btInsert(tree, n4, fp);
btInsert(tree, n5, fp);
btInsert(tree, n6, fp);
btInsert(tree, n7, fp);
btInsert(tree, n8, fp);
btInsert(tree, n9, fp);
btInsert(tree, n10, fp);
queue *q = createQueue(15);
btPrintTree(tree, q, fp);
int pos = btSearch(tree->root, tree->order, n10, fp);
if(pos != -1) {
btNode x = disk_read(pos, tree->order, fp);
printf("node has: %d keys", x.numKeys);
}else
printf("item doesnt exist!");
return 0;
}
</code></pre>
| [] | [
{
"body": "<p><strong>Reading and Writing from the disk</strong></p>\n\n<p>You have the same code in <code>disk_read</code> and <code>disk_write</code> to calculate <code>size_of_btNode</code>. This can be moved into a helper function to avoid the code duplication. In this calculation you use <code>sizeof(int... | {
"AcceptedAnswerId": "197850",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-04T23:16:51.840",
"Id": "197844",
"Score": "4",
"Tags": [
"c",
"tree",
"file"
],
"Title": "B-Tree implementation in secondary-memory/disk-memory"
} | 197844 |
<p>I'm designing an <code>isIn</code> method that takes a <code>value:any</code> and checks whether it exists in an array. It's working, but I'm wondering whether I missed any edge cases:</p>
<pre><code>/**
* Checks if given value is in the target array of allowed values.
*
* @param value The value being checked.
* @param target The target value to perform the check against.
* @return True if the value is in the target array, false otherwise.
*/
export function isIn(value: any, target: any[]): boolean {
if (!isArray(value)) {
return !isArray(target) || target.indexOf(value)>-1;
}
else {
return (JSON.stringify(target)).indexOf(JSON.stringify(value)) != -1;
}
}
describe("isIn", () => {
it(`should return true when the value is in the array`, () => {
expect(isIn(2, [2])).to.be.true;
expect(isIn('a', ['a', 'b'])).to.be.true;
expect(isIn('a', ['a'])).to.be.true;
expect(isIn([2,3], [[2,3]])).to.be.true;
});
it(`should return false when the value is not in the array`, () => {
expect(isIn('a', ['b'])).to.be.false;
expect(isIn([2,4], [[2,3]])).to.be.false;
});
});
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-08T00:18:30.750",
"Id": "381897",
"Score": "2",
"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... | [
{
"body": "<h2>Objects</h2>\n\n<p>One edge case you didn't test is <code>isIn({property: 'value'}, [{property: 'value'}])</code>. I don't know what you want it to do here, but currently it will return <code>false</code>.</p>\n\n<p>You also did not test what happens when no values are passed in, or just a value.... | {
"AcceptedAnswerId": "198003",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-05T04:25:41.497",
"Id": "197851",
"Score": "1",
"Tags": [
"array",
"typescript"
],
"Title": "Checking whether an array contains a value or another array"
} | 197851 |
<p>This MIPS Assembly program will make you access the elements in the 4x4 matrix in either row or column-major order i.e. accessing all elements row by row or column by column.</p>
<p>Output is posted below as well.</p>
<p>Data section has variables declared, Text section has the main function.</p>
<p>This took me several days to put together since I just started this from scratch.
I'll appreciate any feedback.
I also hope this helps out those who are looking to to some matrix calculations and such. </p>
<pre><code># Data Section
.data
.globl array
.align 4
array: .float 1.00, 2.00, 3.00, 4.00, 5.00, 6.00, 7.00, 8.00, 9.00, 10.00, 11.00, 12.00, 13.00, 14.00, 15.00, 16.00
matrix_size: .word 4
float_size: .word 4
lb_: .asciiz "Print in row or column-major order\n" #uncomment a line in ADDING OFFSET section to change which to print (can't print both at the same time!)
j_: .asciiz "j: "
k_: .asciiz " k: "
bar_: .asciiz " | "
colon: .asciiz ": "
lineBrk: .asciiz "\n"
# MIPS Printing Syntax
# li $v0 n # n = 1:(print_integer), 2:(print_float), 4:(print_str)
# la $a0 text_ # text_ should be defined in the .data section above beforehand
# syscall
# Text Section
.text
.globl main
main:
#Print title
li $v0 4
la $a0 lb_
syscall
la $a1 array
move $s7 $a1 # base address of array
lw $s1 matrix_size # $s1 = matrix_size
lw $s2 float_size # $s2 = float_size
li $t5 0 # j counter
jloop:
li $t6 0 # k counter
# j kloop
kloop:
#Print j and k value
#j: t5
#k: t6
li $v0 4 # "j"
la $a0 j_
syscall
li $v0 1
move $a0 $t5
syscall # value_j
li $v0 4 # "k"
la $a0 k_
syscall
li $v0 1
move $a0 $t6
syscall # value_k
li $v0 4 # " | "
la $a0 bar_
syscall
## Caculate column major offset
# $s0 = offset result
# $s1 = matrix_size: 4
# $s2 = float_size: 4
# $s7 = base address stored
# $t5 = j
# $t6 = k
# offset = 4*(4*k + j) = float_size * (matrix_size*k + j)
mul $s0 $s1 $t6 # s0 = 4*k
add $s0 $s0 $t5 # s0 = s0 + j
mul $s0 $s0 $s2 # s0 = 4*s0, offset stored in s0
# print( offset: )
li $v0 1
move $a0 $s0
syscall
li $v0 4
la $a0 colon
syscall
#### ADDING OFFSET ####
# This will increase the memory address. It's like increasing the index for accessing next element.
# addi $a1 $a1 4 #row major -> new_addr += 4 (cumulatively increase the address to access the array by 4)
add $a1 $s7 $s0 #column major -> new addr = base_addr + offset
# print( element\n )
lwc1 $f12 0($a1)
li $v0 2
syscall
li $v0 4
la $a0 lineBrk
syscall
# k_counter++
addi $t6 $t6 1
bne $t6 $s1 kloop
# j_counter++
addi $t5 $t5 1
bne $t5 $s1 jloop
#Done, terminate program
li $v0, 10
syscall
.end main
</code></pre>
<p>Output: #0,16,32.. etc. are the offset added to the base address</p>
<h1>it is in multiple of 4 since floats are 4 bytes</h1>
<p><a href="https://i.stack.imgur.com/g9SyH.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/g9SyH.png" alt="enter image description here"></a></p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-05T06:43:53.527",
"Id": "381514",
"Score": "0",
"body": "I know the mods are going to yell at me again, but since I (still) don't speak MIPS, I can only ask questions, not make recommendations. So: Why does it look like you are declari... | [] | {
"AcceptedAnswerId": null,
"CommentCount": "11",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-05T05:54:13.290",
"Id": "197857",
"Score": "1",
"Tags": [
"matrix",
"assembly"
],
"Title": "MIPS Assembly Program to access elements in the 4x4 matrix, row or column-major oder"
} | 197857 |
<p>I wrote this code to count the number of amino acids that appear in a proteome. However, I was recently told by someone I could improve it quite a lot to make it more readable and efficient by using dictionaries.</p>
<p><strong>This is the code:</strong></p>
<pre><code>import Bio
from Bio import SeqIO
from Bio import AlignIO
import itertools
import numpy as np
import glob
import pandas as pd
import csv
import re
from collections import defaultdict
import time
#Packages being imported
GAP = 0
SEQCOUNTERPERALIGNMENT = 0
AMINOACIDSPERSTRAIN = 0
NONE = 0
G = 0
A = 0
L = 0
M = 0
F = 0
W = 0
K = 0
Q = 0
E = 0
S = 0
P = 0
V = 0
I = 0
C = 0
Y = 0
H = 0
R = 0
N = 0
D = 0
T = 0
#These variables are all used for counting amino acid proportions later on, here I am establishing them as zero,
#This is a list of all amino acids, these will evenetually become percentages, but are being created here for use later on
current_time = time.strftime("%d.%m.%y %H:%M", time.localtime())
output_name = 'test#%s.txt' % current_time
file = open(output_name, "w+")
#this opens a results file for writing, with a time stamp
files = glob.glob('*.faa')
#this collects all the files ending in .faa, within the current directory as a list
for x in files:
#for each file
SEQCOUNTERPERALIGNMENT = 0
#the sequence counter is reset
FILE = x
#we are establishing the file variable within the loop from x
for record in SeqIO.parse (FILE, "fasta"):
#using the parse function of biopyton, we read the fasta file
sequence=record.seq
#the sequence is established from each record of the fasta file
for character in sequence:
#for each variable within the record
if character in ['G', 'A', 'L', 'M', 'F', 'W', 'K', 'Q', 'E', 'S', 'P', 'V', 'I', 'C', 'Y', 'H', 'R', 'N', 'D', 'T']:
#if the variable is one of the 20 amino acids, we increase the count by 1, if not we either describe it as a gap or increase none by 1, none can be used to check if there is any issue with the code
SEQCOUNTERPERALIGNMENT = SEQCOUNTERPERALIGNMENT + 1
AMINOACIDSPERSTRAIN = AMINOACIDSPERSTRAIN + 1
if character in 'G':
G = G + 1
elif character in 'A':
A = A + 1
elif character in 'L':
L = L + 1
elif character in 'M':
M = M + 1
elif character in 'F':
F = F + 1
elif character in 'W':
W = W + 1
elif character in 'K':
K = K + 1
elif character in 'Q':
Q = Q + 1
elif character in 'E':
E = E + 1
elif character in 'S':
S = S + 1
elif character in 'P':
P = P + 1
elif character in 'V':
V = V + 1
elif character in 'I':
I = I + 1
elif character in 'C':
C = C + 1
elif character in 'H':
H = H + 1
elif character in 'R':
R = R + 1
elif character in 'N':
N = N + 1
elif character in 'D':
D = D + 1
elif character in 'T':
T = T + 1
elif character in 'Y':
Y = Y + 1
elif character in '-':
GAP = GAP + 1
else:
NONE = NONE + 1
pG = 100.* G / AMINOACIDSPERSTRAIN
pA = 100.* A / AMINOACIDSPERSTRAIN
pL = 100.* L / AMINOACIDSPERSTRAIN
pM = 100.* M / AMINOACIDSPERSTRAIN
pF = 100.* F / AMINOACIDSPERSTRAIN
pW = 100.* W / AMINOACIDSPERSTRAIN
pK = 100.* K / AMINOACIDSPERSTRAIN
pQ = 100.* Q / AMINOACIDSPERSTRAIN
pE = 100.* E / AMINOACIDSPERSTRAIN
pS = 100.* S / AMINOACIDSPERSTRAIN
pP = 100.* P / AMINOACIDSPERSTRAIN
pV = 100.* V / AMINOACIDSPERSTRAIN
pI = 100.* I / AMINOACIDSPERSTRAIN
pC = 100.* C / AMINOACIDSPERSTRAIN
pH = 100.* H / AMINOACIDSPERSTRAIN
pR = 100.* R / AMINOACIDSPERSTRAIN
pN = 100.* N / AMINOACIDSPERSTRAIN
pD = 100.* D / AMINOACIDSPERSTRAIN
pT = 100.* T / AMINOACIDSPERSTRAIN
pY = 100.* Y / AMINOACIDSPERSTRAIN
Speciesname = record.description.split('[', 1)[1].split(']', 1)[0]
file.write ('\nG,' + str(pG) + ',' + str(FILE) + ',' + str(Speciesname))
file.write ('\nA,' + str(pA) + ',' + str(FILE) + ',' + str(Speciesname))
file.write ('\nL,' + str(pL) + ',' + str(FILE) + ',' + str(Speciesname))
file.write ('\nM,' + str(pM) + ',' + str(FILE) + ',' + str(Speciesname))
file.write ('\nF,' + str(pF) + ',' + str(FILE) + ',' + str(Speciesname))
file.write ('\nW,' + str(pW) + ',' + str(FILE) + ',' + str(Speciesname))
file.write ('\nK,' + str(pK) + ',' + str(FILE) + ',' + str(Speciesname))
file.write ('\nQ,' + str(pQ) + ',' + str(FILE) + ',' + str(Speciesname))
file.write ('\nE,' + str(pE) + ',' + str(FILE) + ',' + str(Speciesname))
file.write ('\nS,' + str(pS) + ',' + str(FILE) + ',' + str(Speciesname))
file.write ('\nP,' + str(pP) + ',' + str(FILE) + ',' + str(Speciesname))
file.write ('\nV,' + str(pV) + ',' + str(FILE) + ',' + str(Speciesname))
file.write ('\nI,' + str(pI) + ',' + str(FILE) + ',' + str(Speciesname))
file.write ('\nC,' + str(pC) + ',' + str(FILE) + ',' + str(Speciesname))
file.write ('\nH,' + str(pH) + ',' + str(FILE) + ',' + str(Speciesname))
file.write ('\nN,' + str(pN) + ',' + str(FILE) + ',' + str(Speciesname))
file.write ('\nR,' + str(pR) + ',' + str(FILE) + ',' + str(Speciesname))
file.write ('\nD,' + str(pD) + ',' + str(FILE) + ',' + str(Speciesname))
file.write ('\nT,' + str(pT) + ',' + str(FILE) + ',' + str(Speciesname))
file.write ('\nY,' + str(pY) + ',' + str(FILE) + ',' + str(Speciesname))
#writes the seperate amino acid proportions to the file
AMINOACIDSPERSTRAIN = 0
GAP = 0
NONE = 0
G = 0
A = 0
L = 0
M = 0
F = 0
W = 0
K = 0
Q = 0
E = 0
S = 0
P = 0
V = 0
I = 0
C = 0
Y = 0
H = 0
R = 0
N = 0
D = 0
T = 0
#this resets the variables for the next loop over the next file
</code></pre>
<p>The python script establishes a bunch of variables at the beginning to be zero, and then on a loop searches the file for certain characters, it then uses the count of the characters, to calculate the percentage of each of these characters, over the whole file, and then write it to a next text file. After this is complete, it then resets the variables to 0, and then does it again on the loop. </p>
<p>Ideally, I'd like to use dictionaries to streamline this code. but I'm not sure where to start.</p>
<p><strong>Example input (a snippet from a .faa file)</strong>:</p>
<pre><code>>WP_013179448.1 DNA-directed RNA polymerase [Methanococcus voltae]
MYKILTIEDTIRIPPKMFGNPLKDNVQKVLMEKYEGILDKDLGFILAIEDIDQISEGDIIYGDGAAYHDTTFNILTYEPE
VHEMIEGEIVDIVEFGAFIRLGPLDGLIHISQVMDDYVAFDPQREAIIGKETGKVLEKGDKVRARIVAVSLKEDRKRGSK
IALTMRQPALGKLEWLEDEKLETMENAEF
>WP_013179449.1 DNA-directed RNA polymerase subunit E'' [Methanococcus voltae]
MARKGLKACTKCNYITHDDFCPICQHETSENIRGLLIILDPVNSEVAKIAQKDIKGKYALSVK
>WP_013179451.1 30S ribosomal protein S24e [Methanococcus voltae]
MDIKVVSEKNNPLLGRKEVKFALKYEGATPAVKDVKMKLVAILNANKELLVIDELAQEFGKMEANGYAKIYESEEAMNSI
EKKSIIEKNKIVEEAEEAQE
>WP_013179452.1 30S ribosomal protein S27ae [Methanococcus voltae]
MAQKTKKSDYYKIDGDKVERLKKSCPKCGEGVFMAEHLNRFACGKCGYMEYKKNEKAEKEE
>WP_013179453.1 hypothetical protein [Methanococcus voltae]
MNELNELKNPDKIDGKNNNTKNNNNNNNKDSNTENSITEIIKADNETQDNLSDLCVLEDIKTLKSKYKVYKTSKYLTKKD
INNIIEKDYDEIIMPQSIYKLLNEKNKSSMEKLRLCGIIVKTTDNVGRPKKITKYDKDKIKELLVDGKSVRKTAEIMDMK
KTTVWENIKDCMNEIKIEKFRKMIYEYKELLIMQERYGSYVESLFLELDIYINNEDMENALEILNKIIIYVKSEDKKD
>WP_013179454.1 integrase [Methanococcus voltae]
MKNKRINNNQKSKWETMRTDVINTQRNQNINSKNKQYRVKKHYCKEWLTKEELKVFIETIEYSEHKLFFKMLYGMALRVS
ELLKIKVQDLQLKEGVCKLWDTKTDYFQVCLIPDWLINDIKEYIALKSLDSSQELFKFNNRKYVWELAKKYSKMAELDKD
ISTHTFRRSRALHLLNDGVPLEKVSKYLRHKSIGTTMSYIRITVVDLKQELDKIDDWYEL
>WP_013179455.1 hypothetical protein [Methanococcus voltae]
MNTQNAIKKTLKTSKVNKNISNVIIGYSAILLDTYSNNKNLLLVKYDKLFKGFLNSSSITEKQYNKLYDTVLNSLF
>WP_013179456.1 hypothetical protein [Methanococcus voltae]
MVVKLVKISNGGYVSSLELKRINDIILSQLTNEFTIKDIVNMYSNKYDDCNNNAIAQKTRRLLNNHIESGVFTVRNALKN
KKIYKFKDVFVPASAGDTNTSLLFYSTSMKNSNHIEKQKKNNNKYNTNVNKPTITPDQIRVMAGIVNNPQIKSLKKERFK
SILHLNCKHMLNEEDRTELLENFKEYIIKASSQNLVLERTRYHKNKPKYITFPYLTRFTNSKQLKRQLAQYNCIFEQKAI
KYNRGVHLTLTTDPKLFRNIYEANKHFSKAFNRFMSFLSKRNKDVNGKSRRPVYLAAYEYTKSGLCHAHILIFGKKYLLD
QRVITQEWSRCGQGQIAHIYSIRRDGINWIYGRARPEEIQTGEYKNANEYLKKYLVKSLYSELDGSMYWAMNKRFFTFSK
SLKPAMMKRPKPEKYYKFVGIWTDEEFTDEINQAFKTGIPYDEIKKIHWKNLNNGLSCG
>WP_013179457.1 hypothetical protein [Methanococcus voltae]
MVRGRYPVFSGFKKFNKINLGKEKRNEGVYKYYNQDKTLLYVGVSNEVKLRLLSAYYGRSDYAVLENKKKLRQNIAYYKV
KYCGLDQARKIEHRIKKQCKYNLN
>WP_013179458.1 hypothetical protein [Methanococcus voltae]
MVLNLEDLDKLDSIFSDGGIDKIENKTKNYNNDSDSFNVLDALKEVNKIFENWRSIRGIPKAQNIQPLKEYQVSKEKQTE
VKKDSNEITNVSNTNNINKNISAQDIYDNFLQALEFFKSSYGDMPVSEMVSTLKENKEDILSVINLSMGDVNGA
>WP_013179459.1 hypothetical protein [Methanococcus voltae]
MGRKPLDPKAIKKKLEEHEAGTIKLPYSTLQRYKNTLDKQDLKEKDEEYKQNIDLDDELNNIDLNSEYVNYYDIIDFKNP
FSMCVFGIKRQGKTTLLKHMAYSNQKDVLIYDLVHNFNNFGKRCYQAKETQFPDSALEFQRFYSSIYNKLNKNRENPILL
LIDECDKIAPNNSRMPGGLAELNDLHRHAKFNTSFVCVARRPATLNTNLKEIADYIIFFKLTGKNDKSFLNDLHKDLYNA
VESLNAEEHEFIIYDMPMSKIYKSKLDLNINFKK
>WP_013179460.1 hypothetical protein [Methanococcus voltae]
MTKTINGINFKAMGIVTISKVVGEQVLTPIIGNGTVKSGLPKILGAVLLAGTKNTYAKYAGTGLAVDGIEDILMGSGILS
KLGAVAGAKTTAGTGNTNNIDIM
>WP_013179461.1 hypothetical protein [Methanococcus voltae]
MAVVKPGNGDPSVLGLNDFEFNAKGDTIKAGRWTDIYKFTVPVQEQVAIGSDDNGNVGILYGIIKDNSETPAEVSGVIRI
SRRPARENVSDRQLEVRTEMIKDTMTDRLKAYFLPVKRNKRIGENSKLVIEFMPDTDFVLGDSVLQIPITRW
</code></pre>
<p><strong>Example output</strong></p>
<pre><code>G,6.2152758802848975,GCF_000006175.1_ASM617v2_protein.faa,Methanococcus voltae
A,5.358317495592757,GCF_000006175.1_ASM617v2_protein.faa,Methanococcus voltae
L,9.04238847295845,GCF_000006175.1_ASM617v2_protein.faa,Methanococcus voltae
M,2.5514448269790093,GCF_000006175.1_ASM617v2_protein.faa,Methanococcus voltae
F,3.7227292323199204,GCF_000006175.1_ASM617v2_protein.faa,Methanococcus voltae
W,0.5889817901403234,GCF_000006175.1_ASM617v2_protein.faa,Methanococcus voltae
K,9.248430899887264,GCF_000006175.1_ASM617v2_protein.faa,Methanococcus voltae
Q,2.067103444227877,GCF_000006175.1_ASM617v2_protein.faa,Methanococcus voltae
E,7.731246192364286,GCF_000006175.1_ASM617v2_protein.faa,Methanococcus voltae
S,6.133911385564481,GCF_000006175.1_ASM617v2_protein.faa,Methanococcus voltae
P,3.1477129897808624,GCF_000006175.1_ASM617v2_protein.faa,Methanococcus voltae
V,6.35290736389157,GCF_000006175.1_ASM617v2_protein.faa,Methanococcus voltae
I,9.564983312182612,GCF_000006175.1_ASM617v2_protein.faa,Methanococcus voltae
C,1.347169345420616,GCF_000006175.1_ASM617v2_protein.faa,Methanococcus voltae
H,1.4429041862234933,GCF_000006175.1_ASM617v2_protein.faa,Methanococcus voltae
N,7.343449247378424,GCF_000006175.1_ASM617v2_protein.faa,Methanococcus voltae
R,2.929526608416165,GCF_000006175.1_ASM617v2_protein.faa,Methanococcus voltae
D,5.753603212480747,GCF_000006175.1_ASM617v2_protein.faa,Methanococcus voltae
T,5.148429483092579,GCF_000006175.1_ASM617v2_protein.faa,Methanococcus voltae
Y,4.309484630813666,GCF_000006175.1_ASM617v2_protein.faa,Methanococcus voltae
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-05T09:18:27.707",
"Id": "381536",
"Score": "0",
"body": "Can your provide a sample `faa` file and the output?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-05T09:30:39.243",
"Id": "381539",
"Score... | [
{
"body": "<ol>\n<li><p>Add functions</p>\n\n<p>Everything is currently in the global namespace, you can add a few functions to split up the code and make it more readable. </p>\n\n<p>You could use a <code>count_occurence</code> function and a <code>write_output</code> function.</p></li>\n<li><p>Avoid working w... | {
"AcceptedAnswerId": "197866",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-05T08:18:09.620",
"Id": "197861",
"Score": "6",
"Tags": [
"python",
"python-3.x",
"bioinformatics"
],
"Title": "Counting the occurrences of certain amino-acids in a file"
} | 197861 |
<p>I am working on a bit of a multiple part project, the goal of the project is to have a spreadsheet full of order data (order number, customer data, products ordered, prices etc) merged so that the duplicate information is grouped up.</p>
<p><img src="https://i.gyazo.com/3034782c17256afac40f6a31cd469dc1.png" alt="Order data"></p>
<p>The above is an example of what the data looks like when it comes in. </p>
<p>I then got it to unmerge so that it looks a little cleaner. </p>
<p><img src="https://i.gyazo.com/5b6c69b85c5d07f87f2c8633c78678b6.png" alt="Unmerged data"></p>
<p>The code used for these two steps was created with much help from this community and looks like this:</p>
<pre><code>Option Explicit
Sub MergeCells()
Dim i As Long, c As Long, col As Variant
Application.DisplayAlerts = False
'Application.ScreenUpdating = false
col = Array("A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "AA", "AB", "AC", "AD", "AE", "AF", "AG", "AH", "AI", "AJ", "AK")
For c = LBound(col) To UBound(col)
For i = Cells(Rows.Count, col(c)).End(xlUp).Row - 1 To 2 Step -1
If Cells(i, col(c)).Value = Cells(i, col(c)).Offset(1, 0).Value And Not IsEmpty(Cells(i, col(c))) Then
Cells(i, col(c)).Resize(2, 1).Merge
Cells(i, col(c)).HorizontalAlignment = xlCenter
Cells(i, col(c)).VerticalAlignment = xlCenter
End If
Next i
Next c
Application.DisplayAlerts = True
'Application.ScreenUpdating = True
End Sub
</code></pre>
<p>Then this:</p>
<pre><code>Sub fixMergedCells(sh As Worksheet)
'replace merged cells by Center Acroos Selection
'high perf version using a hack: https://stackoverflow.com/a/9452164/78522
Dim c As Range, used As Range
Dim m As Range, i As Long
Dim constFla: constFla = Array(xlConstants, xlFormulas)
Set used = sh.UsedRange
For i = 0 To 1 '1 run for constants, 1 for formulas
Err.Clear
On Error Resume Next
Set m = Intersect(used.Cells.SpecialCells(constFla(i)), used.Cells.SpecialCells(xlBlanks))
On Error GoTo 0
If Not m Is Nothing Then
For Each c In m.Cells
If c.MergeCells Then
With c.MergeArea
'Debug.Print .Address
.UnMerge
.HorizontalAlignment = xlCenterAcrossSelection
End With
End If
Next c
End If
Next i
End Sub
</code></pre>
<p>And finally:</p>
<pre><code>Sub fixMergedCells(Optional sh As Variant)
If IsMissing(sh) Then Set sh = ActiveSheet
sh.Cells.UnMerge
End Sub
</code></pre>
<p>I am currently working on two final steps, one to make sure that the data that got merged and then split will appear for each relevant line. Then I want to highlight each row that contains an order number so that we can see clearly where one order starts and another ends.</p>
<p>My last step of the plan is to combine all of the codes into one macro, as I want it to be easy for someone to use. </p>
<p>Thanks for reading, I just wanted to share what I've gotten so far and see what y'all think of my plan :)</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-05T10:57:19.173",
"Id": "381553",
"Score": "2",
"body": "Welcome to Code Review SE! This looks like a good first question. Next time you ask a question, it would be a good idea to link to the raw images (i.e. those with an image extens... | [
{
"body": "<p>Welcome to Code Review! You've made a very good start at learning VBA and how to put together clean code. Many helpful folks will give you supportive comments and I'll jump in with mine...</p>\n\n<p>Starting with your <code>MergeCells</code> routine:</p>\n\n<ol>\n<li>The name <code>MergeCells</cod... | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-05T09:04:13.713",
"Id": "197863",
"Score": "1",
"Tags": [
"vba"
],
"Title": "Order Spreadsheet code cleaning project"
} | 197863 |
<p>I have defined a userdata in Lua (Lua version is 5.1) as shown below-</p>
<pre><code>#include <lua.h>
#include <lauxlib.h>
#include <stdio.h>
typedef struct FloatArray {
int size;
float values[1];
} FloatArray;
static int new_array(lua_State *L) {
int n = luaL_checkint(L, 1);
size_t nbytes = sizeof(FloatArray) + (n - 1) * sizeof(float);
FloatArray *a = (FloatArray *)lua_newuserdata(L, nbytes);
a->size = n;
return 1;
}
</code></pre>
<p>I can create a new array of given size by using following Lua code-</p>
<pre><code>a = array.new(10)
</code></pre>
<p>Now, I am extending the above function for converting any given 1-d table to <code>array</code>. Please see the code snippet below-</p>
<pre><code>static int new_array_from_table(lua_State *L) {
luaL_argcheck(L, lua_type(L, -1) == LUA_TTABLE, 1, "'1-d array' expected");
// get the length of input table
int n = lua_objlen(L, -1);
int index;
float values[n];
// fetch data and use it to fill the array
for (index = 1; index <= n; index++) {
lua_rawgeti(L, -1, index);
values[index - 1] = (float)lua_tonumber(L, -1);
lua_pop(L, 1);
}
// create new userdata
size_t nbytes = sizeof(FloatArray) + (n - 1) * sizeof(float);
FloatArray *a = (FloatArray *)lua_newuserdata(L, nbytes);
a->size = n;
// fill the userdata
for (index = 0; index < n; index++)
a->values[index] = values[index];
return 1;
}
</code></pre>
<p>The above code works. However, as you can notice that fetching the table data and filling the userdata are done separately.</p>
<p><strong>I wish to have a better implementation, in which we first create new userdata and then we fill the userdata from fetched data at one step.</strong></p>
<p>In other words, I am looking for a way to do the following-</p>
<pre><code>// get the length of input table
int n = lua_objlen(L, -1);
// create new userdata
size_t nbytes = sizeof(FloatArray) + (n - 1) * sizeof(float);
FloatArray *a = (FloatArray *)lua_newuserdata(L, nbytes);
a->size = n;
// fetch data and use it to fill the array
int index;
for (index = 1; index <= n; index++) {
lua_rawgeti(L, -1, index);
a->values[index] = (float)lua_tonumber(L, -1);
lua_pop(L, 1);
}
</code></pre>
<p><em>I noticed that after creating new userdata, the data is being converted to 0</em>. Any workaround, please?</p>
| [] | [
{
"body": "<p>You have a duplication of the allocation and init part in the 2 functions, instead you can create a helper that will create the usertable, return a pointer to it and leave it on top of the stack:</p>\n\n<pre><code>static FloatArray *create_array(lua_State *L, int n) {\n size_t nbytes = sizeof(Flo... | {
"AcceptedAnswerId": "197879",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-05T10:15:54.563",
"Id": "197867",
"Score": "2",
"Tags": [
"lua",
"lua-table"
],
"Title": "Faster way of converting a 1-d table to predefined userdata in Lua"
} | 197867 |
<p>The following code is part of my practice in implementing algorithms in Haskell. I'm aware that bubble sort is a bad choice for sorting sequences in real applications.</p>
<pre><code>import Test.QuickCheck
import Data.List (sort)
-- Going from left to right, swaps two adjacent elements if they are not in order.
-- After the first go, the largest element in the list has bubbled up to the end
-- of the list. In the next go, we start swapping from the first element to the
-- penultimate element and so forth.
bubbleSort :: Ord a => [a] -> [a]
bubbleSort xs = go xs (length xs -1)
where go xs limit | limit > 0 = let swapped = swapTill xs limit in
go swapped (limit -1)
| otherwise = xs
-- Swaps adjacent elements in a list if they are not in order, until a limit.
-- After this, the largest elements, from limit to (length xs),
-- are sorted at the list's end.
swapTill :: (Ord a, Num p) => [a] -> p -> [a]
swapTill xs limit = go xs 0
where go xs count | count < limit = swap xs
| otherwise = xs
where swap [x] = [x]
swap (x:y:xs) | x < y = x : (go (y:xs) (count +1))
| otherwise = y : (go (x:xs) (count +1))
-- Tests
bubbleSortWorks :: [Int] -> Bool
bubbleSortWorks xs = bubbleSort xs == sort xs
runQuickCheck = quickCheck bubbleSortWorks
</code></pre>
<p>I'd very much appreciate hints on how to make this implementation shorter (maybe using a fold) and/or more readable.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-11T17:25:46.377",
"Id": "382403",
"Score": "0",
"body": "Please see *[What to do when someone answers](https://codereview.stackexchange.com/help/someone-answers)*. I have rolled back Rev 5 → 4."
},
{
"ContentLicense": "CC BY-SA... | [
{
"body": "<p>Here's your shortening including a fold.</p>\n\n<pre><code>bubbleSort :: Ord a => [a] -> [a]\nbubbleSort xs = foldr swapTill xs [1..length xs-1]\n\nswapTill :: Ord a => Int -> [a] -> [a]\nswapTill 0 = id\nswapTill count = \\(x:y:xs) -> min x y : swapTill (count-1) (max x y:xs)\n<... | {
"AcceptedAnswerId": "198081",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-05T10:30:18.370",
"Id": "197868",
"Score": "6",
"Tags": [
"algorithm",
"haskell",
"sorting",
"reinventing-the-wheel"
],
"Title": "Bubble sort in Haskell"
} | 197868 |
<p>For an external application I need to send a command as a string, like this: </p>
<p><code>["START", "1", "2", "3", "4", "STOP"]</code></p>
<p>Note the double quotes!</p>
<p>I create this command with the following function:</p>
<pre><code>def create_command(amount):
command = ["START"]
list = create_list(amount)
command += list
command += ["STOP"]
command = str(command )
command = command.replace("\'", "\"")
return command
</code></pre>
<p>And I create a list from a given number with the following function:</p>
<pre><code>def create_list(data):
list = []
data = str(data)
for letter in data:
list.append(letter)
return list
</code></pre>
<p>Is the a way to make both functions more pythonic and not so straightforward? I don't really like them now, they look a bit clumpsy and I think there must be a better way do the thing.</p>
| [] | [
{
"body": "<p><code>create_list</code> is building a list of all the items in the <code>str</code>ing form of <code>data</code>. And so you can change it to:</p>\n\n<pre><code>def create_list(data):\n return list(str(data))\n</code></pre>\n\n<p>I find it easier to read <code>create_command</code> if you merg... | {
"AcceptedAnswerId": "197878",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-05T12:05:23.823",
"Id": "197874",
"Score": "11",
"Tags": [
"python",
"python-2.x"
],
"Title": "Convert list to a string with double quotes"
} | 197874 |
<p>I would like to ask you for review of my application’s Status viewing logic implementation.<br/>
At first I have to close to you somewhat of my domain problem space.
I’m building social application. Part of my application are user’s statuses. User should add private status.<br/>
Similarly, user should add public status. Private status is visible only to the Followers (It’s like on Instagram, user can follow other user to eg. get notification about followed user activities), and Public is visible to every user. Status owner can check information about who previewed his status.</p>
<p>When it comes to domain objects (I mean real world objects by this), I have following objects:</p>
<p>UserProfile (represents user. My approach is to not confusing actors with inner system objects. I mean, we have to consider two systems.</p>
<p>First is outer system, which is everything, that interacts with our system and second is inner system, generally system we are implementing. What is more we should have unambiguous terms in our namespace, so user is someone who interacts with our system by eg. asking it to send message and UserProfile is something which represents user in our system eg. Storing user’s data. Sorry for my bloated explanation. So that’s why I don’t have class user)</p>
<p>Status</p>
<p>Now we go to some of concrete implementation.</p>
<p>My approach is to delegate logic of giving preview of status to significant user in different class than Status.
Status class has only flag, which indicates whether status is public or not.</p>
<pre><code>class Status {
private boolean privy;
boolean isPublic() {
return !privy;
}
static Status ofInaccessible() {
return InaccessibleStatus.create();
}
}
</code></pre>
<p>I also thought to use in some degree Null Object pattern for status, which can be accessed by user. I said in some degree, because the main goal is to return some text informing about blocked content ( I know I could return 404 status instead but...)</p>
<pre><code>class InaccessibleStatus extends Status {
// Overriding methods omitted
}
</code></pre>
<p>Here we have UserProfile class, which status viewing logic is delegated to StatusPreviewer class:</p>
<pre><code>class UserProfile {
private final StatusPreviewer statusPreviewer;
private UserProfile(...) {
this.statusPreviewer = StatusPreviewer.create(this);
}
// Cheking if user is on followers list - omitted method definition
boolean isFollowing( UserProfile UserProfile );
Status preview( Status status ) {
return statusPreviewer.preview( status )
}
}
</code></pre>
<p>And now the time for status view logic has come. I thought for a while about encapsulating logic of status view inside Status. Mhmm.. Can Status know who can read him? Rather not. So I came up with specialized class StatusPreviewer which is only responsible for giving access to status, by returning Status or InaccessibleStatus object.</p>
<p>So here is my StatusPreviewer class:</p>
<pre><code>class StatusPreviewer {
private UserProfile previewedBy;
private StatusPreviewer( UserProfile previewedBy ) {
this.previewedBy = previewedBy;
}
preview( Status status ) {
if (status.isPublic() || previewedBy.isFollowing( status.getOwner())) {
status.addViewer( userProfile );
return status;
}
else return Status.ofInaccessible();
}
}
</code></pre>
<p>Of course, I won’t use domain object directly within presentation layer. StatusPreviewer is some kind of indirect object used by UserProfile as containment(composition). Someone could think that StatusPreviewer is also UserProfile, so it should be subclass of UserProfile. But the point is, that I don’t need all of even part of UserProfile interface, so StatusPreviewer is different type.</p>
<p>I always try to write readable, easy to maintain code, that benefit from SOLID principles, but I am still learning.</p>
<p>Thanks in advance for any review from more experienced users or even someone with better, fresh insight.</p>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-05T12:09:07.007",
"Id": "197875",
"Score": "1",
"Tags": [
"java",
"object-oriented"
],
"Title": "Status view logic - is my approach good?"
} | 197875 |
<p>I found this question in O'Reilly Data Structure and Algorithm in Javascript:</p>
<blockquote>
<p>According to legend, the first-century Jewish historian Flavius
Josephus was about to be captured along with a band of 40 compatriots
by Roman soldiers during the Jewish-Roman War. The Jewish soldiers
decided that they preferred suicide to being captured and devised a
plan for their demise. They were to form a circle and kill every third
soldier until they were all dead. Josephus and one other decided they
wanted no part of this and quickly calculated where they needed to
place themselves so they would be the last survivors.</p>
<p>Write a program that allows you to place n people in a circle and
specify that every mth person will be killed. The program should
determine the number of the last two people left in the circle. Use a
circularly linked list to solve the problem.</p>
</blockquote>
<p>This is my solution:</p>
<pre><code>function Node(element) {
this.element = element;
this.next = null;
}
function LList() {
this.head = new Node("head");
this.head.next = this.head;
this.find = find;
this.insert = insert;
this.display = display;
this.findPrevious = findPrevious;
this.remove = remove;
this.advance = advance;
this.count = count;
}
function remove(item) {
var prevNode = this.findPrevious(item);
if (!(prevNode.next == this.head)) {
prevNode.next = prevNode.next.next;
}
}
function findPrevious(item) {
var currNode = this.head;
while (!(currNode.next == this.head) &&
(currNode.next.element != item)) {
currNode = currNode.next;
}
return currNode;
}
function display() {
var currNode = this.head;
while (!(currNode.next == this.head)) {
print(currNode.next.element);
currNode = currNode.next;
}
}
function count() {
var currNode = this.head;
var count = 0;
while (!(currNode.next == this.head)) {
count++
currNode = currNode.next;
}
return count;
}
function find(item) {
var currNode = this.head;
while (currNode.element != item) {
currNode = currNode.next;
}
return currNode;
}
function insert(newElement, item) {
var newNode = new Node(newElement);
var current = this.find(item);
newNode.next = current.next;
current.next = newNode;
}
function advance(item, n) {
var currNode = this.find(item);
for (let i = n; i > 0; i--) {
currNode = currNode.next;
}
return currNode;
}
function survivor(number, position) {
//40 compatriots
//kill every third soldier. advance by 3
//last two survivors
//place n people in a circle
var compatroits = new LList();
var currNode = compatroits.head;
for (let i = 1; i <= number; i++) {
compatroits.insert(i, currNode.element);
currNode = currNode.next;
}
//kill every mth person in the circle
//start from head
var currItem = compatroits.head.element;
while (compatroits.count() > 2) {
//advance mth person
var killNode = compatroits.advance(currItem, position);
//set new start point to m.next node
currItem = killNode.next.element;
//remove mth person
compatroits.remove(killNode.element);
}
//determine the last two people in the circle
return compatroits.display();
}
</code></pre>
<p>Does anyone have a more efficient way to solve this problem?</p>
| [] | [
{
"body": "<h1>The Ouroboros</h1>\n\n<p>Your code is way too complex for the task </p>\n\n<p>The most obvious improvement is to remove the functions <code>find</code>, <code>findPreviouse</code>, and <code>count</code></p>\n\n<h2>Why</h2>\n\n<ul>\n<li>Rather than hold the data each list item has, hold the curre... | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-05T13:39:19.087",
"Id": "197883",
"Score": "4",
"Tags": [
"javascript",
"linked-list",
"circular-list"
],
"Title": "JavaScript circular linked list compatriot game"
} | 197883 |
<p>I wrote a program in Python that scans all files in a directory, makes dictionaries with stuff like date of creation and a hash of the contents of a file. Then i scan another directory which is just a copy of the original dir, but with some files added, deleted and changed. My program reports these changes.</p>
<pre><code>import os
import stat
import hashlib
import json
class DirInfo:
def __init__(self):
self._dirInfo = {}
def probe(self, dirname):
fname = os.path.join(dirname, "data.txt")
blocksize = 512000000
for file in os.listdir(dirname):
if file != "data.txt":
fileWithPath = os.path.join(dirname, file)
fileInfo = {}
fileInfo['name'] = file
if os.path.isfile(fileWithPath):
sbuf = os.fstat(os.open(fileWithPath, os.O_RDONLY))
fileInfo['type'] = stat.S_IFMT(sbuf.st_mode)
fileInfo['mode'] = stat.S_IMODE(sbuf.st_mode)
fileInfo['mtime'] = sbuf.st_mtime
fileInfo['size'] = sbuf.st_size
hasher = hashlib.sha256()
with open(fileWithPath, 'rb') as x:
for chunk in iter(lambda: x.read(blocksize), b""):
hasher.update(chunk)
fileInfo['sha256'] = hasher.hexdigest()
if os.path.islink(fileWithPath):
fileInfo['symlink'] = os.readlink(fileWithPath)
self._dirInfo[file] = fileInfo
del fileInfo
DirInfo.save(self._dirInfo, fname)
pass
def compare(self, other):
pad = "D:\\Testmapje met random files\\data.txt"
pad2 = "D:\\Testmapje met random files 2\\data.txt"
dct = DirInfo.load(self, pad)
dct2 = DirInfo.load(other, pad2)
assert isinstance(other, DirInfo)
for key in dct:
if key not in dct2:
print (key, "is verwijderd")
for key in dct2:
fileHuidig = key
if key not in dct:
print (key, "is toegevoegd")
else:
allKeysPerFileMeasurement1 = (dct.get(key))
allKeysPerFileMeasurement2 = (dct2.get(key))
for key in allKeysPerFileMeasurement2:
Measurement1Value = (allKeysPerFileMeasurement1.get(key))
Measurement2Value = (allKeysPerFileMeasurement2.get(key))
if Measurement1Value != Measurement2Value:
print("In bestand:", fileHuidig, "was", key, Measurement1Value, "nu is", key, Measurement2Value)
return []
def save(self, fname):
json.dump(self, open(fname, 'w'))
pass
def load(self, fname):
return json.load(open(fname, 'r'))
if __name__ == '__main__':
dirname = "D:\\Testmapje met random files"
dirnameanders = "D:\\Testmapje met random files 2"
dirInfo1 = DirInfo()
dirInfo1.probe(dirname)
# change some files
dirInfo2 = DirInfo()
dirInfo2.probe(dirnameanders)
for err in dirInfo1.compare(dirInfo2):
print(err)
</code></pre>
<p>My program gives the following output:</p>
<pre class="lang-none prettyprint-override"><code>LinkNaarTestFolder2 is verwijderd (deleted)
In bestand: Lief dagboek.txt was mtime 1530555920.17531 nu is mtime 1530723663.3718975
In bestand: Lief dagboek.txt was size 30 nu is size 22
In bestand: Lief dagboek.txt was sha256 c33b32ad0a34316c970febc149199ca59946e75753ddc6438f09d1204835d0e4 nu is sha256 4728379b3f491004319de08ca6161d0b47d3f7921d79d7a9b95e1ca2c458ed48
In bestand: LinkNaarTestFolder was symlink C:\Test voor python nu is symlink C:\Users\Kevin\Documents\Battlefield 3
lol.txt is toegevoegd (is added)
</code></pre>
<p>Any ways to make my code shorter?</p>
| [] | [
{
"body": "<p>There is no reason here for this to be a class. You don't even use any class features and even have to work around it being a class by doing e.g. <code>DirInfo.save(self._dirInfo, fname)</code> instead of being able to do <code>self.save(fname)</code>.</p>\n\n<p>I would also add more functions, fo... | {
"AcceptedAnswerId": "197893",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-05T14:47:52.633",
"Id": "197887",
"Score": "6",
"Tags": [
"python",
"beginner",
"json",
"file-system"
],
"Title": "Scan similar files in different directories and report differences"
} | 197887 |
<p>I wrote a function in JavaScript that expects an array of integers (negative or positive) and determines if that array has an increasing sequence. </p>
<p>For the sake of better time performance I made the function <code>return</code> out of the loop with <code>false</code> as soon as <code>i+1</code> - <code>i</code> did not equal <code>1</code> or <code>-1</code>. I used <code>continue</code> to do this. Here is the function:</p>
<pre><code>const increasingSequence = (arr) => {
for (let i = 0; i < arr.length - 1; i ++) {
if (arr[i+1] - arr[i] === 1 || arr[i+1] - arr[i] === -1) {
continue;
} else {
return false;
}
}
return true;
}
</code></pre>
<p>Seems to be producing the desired output:</p>
<pre><code>var arr1 = [1, 2, 3, 4];
var arr2 = [1, 2, 4, 5];
var arr3 = [-4, -3, -2, -1];
var arr4 = [-4, -3, -1, 0];
increasingSequence(arr1); // true
increasingSequence(arr2); // false
increasingSequence(arr3); // true
increasingSequence(arr4); // false
</code></pre>
<p>This is actually a helper function to a bigger problem I'm trying to solve, so time complexity is important. Feedback about improving time complexity or any missing edge cases would be greatly appreciated.</p>
| [] | [
{
"body": "<p>Your code has a bug because it will accept decreasing sequences as <code>true</code> as well, for example, <code>increasingSequence([4,3,2,1]);</code> will be true.</p>\n\n<p>Having said that, you could do the tests a whole lot simpler by using a search:</p>\n\n<pre><code> const increasingSequenc... | {
"AcceptedAnswerId": "197890",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-05T15:17:09.527",
"Id": "197889",
"Score": "2",
"Tags": [
"javascript",
"beginner",
"algorithm",
"array",
"complexity"
],
"Title": "Determine if Array has an Increasing Sequence"
} | 197889 |
<p>I wrote a little wrapper for Google Static Maps API so that I do not pull down from Google Maps if I have already retrieved the address. The below code works, but I wrote it in a quick fashion - not really paying attention to the best practices of golang.</p>
<p>Several questions I have about this code:<br>
- How can I improve the <code>v := url.Values{}</code> section?<br>
- Is there a better method to the <code>for i := 0; i < 30; i++</code> loop?</p>
<pre><code>package main
import (
"crypto/md5"
"encoding/hex"
"errors"
"fmt"
"io/ioutil"
"net/http"
"net/url"
"os"
)
var apiKey = os.Getenv("API_KEY")
// loadMap generates a new map or returns a cached one
func loadMap(address string, title string) ([]byte, error) {
mapHost := "http://maps.googleapis.com/maps/api/staticmap"
v := url.Values{}
v.Add("center", address)
v.Add("zoom", "15")
v.Add("scale", "2")
v.Add("size", "400x350")
v.Add("markers", address)
v.Add("sensor", "false")
v.Add("key", apiKey)
mapURL := mapHost + "?" + v.Encode()
filename := title + ".png"
for i := 0; i < 30; i++ {
body, err := ioutil.ReadFile(filename)
if err == nil {
return body, nil
}
if i == 0 {
fmt.Println("Getting map for " + address + " and saving it to " + filename)
fmt.Println("Map URL: " + mapURL)
httpClientGetMap, _ := http.Get(mapURL)
body, _ := ioutil.ReadAll(httpClientGetMap.Body)
ioutil.WriteFile(filename, []byte(body), 0600)
}
i++
}
return nil, errors.New("Failed to get an image")
}
// viewHandler returns the map image
func viewHandler(w http.ResponseWriter, r *http.Request) {
address := r.URL.Query().Get("address")
md5 := md5.Sum([]byte(address))
title := hex.EncodeToString(md5[:])
p, err := loadMap(address, title)
if err != nil {
fmt.Println(err)
w.WriteHeader(http.StatusGatewayTimeout)
return
}
w.Header().Set("content-type", "image/png")
w.Write(p)
}
func main() {
http.HandleFunc("/getmap", viewHandler)
http.ListenAndServe(":8080", nil)
}
</code></pre>
| [] | [
{
"body": "<h2>Improve the for loop</h2>\n\n<p>The <code>loadMap</code> method is really hard to read, and is not verry efficient: </p>\n\n<p>Currently, if a file doesn't exists, here are the steps followed by the method: </p>\n\n<ul>\n<li>try to read the content of a file to see if it exists</li>\n<li>send a r... | {
"AcceptedAnswerId": "197959",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-05T16:30:37.393",
"Id": "197896",
"Score": "3",
"Tags": [
"go"
],
"Title": "Utility to cache Google Maps"
} | 197896 |
<p>I wrote my first series of test for this simple function:</p>
<pre><code>def map_directory(self, path='', method='recursive'):
"""
scan the given path
method -> recursive (all levels) or single (first level only)
:param method: string
:param path: string
:return: generator
"""
if not path:
path = self.path
if method == 'recursive':
f = self.scan_tree
elif method == 'single':
f = os.scandir
else:
raise BullShitError('please enter a valid scanning method : {} is BS'
.format(method))
return f(path)
def scan_tree(self, path=''):
"""
recursively yield DirEntry objects for given directory.
:return: generator
"""
if not path:
path = self.path
for entry in (d for d in os.scandir(path) if FileSystemManager.is_readable(d.path) is True):
try:
if entry.is_dir(follow_symlinks=False):
yield entry
yield from self.scan_tree(entry.path)
else:
yield entry
except PermissionError:
logger.warning('this entry raised an error : {}'.format(entry.path))
continue
</code></pre>
<p><strong>Tests :</strong></p>
<pre><code>import os
from django.test import TestCase
from packages.system.filesystem import FileSystemManager
from packages.system.local_dirs import user_home
class FileSystemManagerTests(TestCase):
@classmethod
def setUpClass(cls):
cls.test_dir = os.path.join(user_home, 'test/a/b/c')
os.makedirs(cls.test_dir, 0o755, exist_ok=True)
cls.fl = FileSystemManager(cls.test_dir)
@classmethod
def tearDownClass(cls):
pass
def test_map_directory_returns_only_direntry_objects(self):
"""
map_directory() returns only DirEntry objects in the returned generator
"""
mapping = self.fl.map_directory()
for obj in mapping:
self.assertIsInstance(obj, os.DirEntry)
def test_map_directory_returns_generator(self):
"""
map_directory() returns a generator
"""
from typing import Generator
self.assertIsInstance(self.fl.map_directory(), Generator)
def test_map_directory_recursive_method(self):
"""
map_directory() recursive returns a, b, c
"""
mapping = self.fl.map_directory(os.path.join(user_home, 'test'))
self.assertEqual(len(tuple(mapping)), 3)
def test_map_directory_single_method(self):
"""
map_directory() single method returns a
"""
mapping = self.fl.map_directory(os.path.join(user_home, 'test'),
method='single')
self.assertEqual(len(tuple(mapping)), 1)
</code></pre>
<p>I then have 3 main questions:</p>
<ol>
<li>Is this "over tested"?</li>
<li>Does testing for only the length of the generator suffice for a proper test?</li>
<li>Should I ignore this function which is straightforward enough and center the focus of my tests on the <code>self.scan_tree</code> method?</li>
</ol>
<p>Any other comments are welcomed, thanks.</p>
| [] | [
{
"body": "<h2>General</h2>\n\n<ol>\n<li><p>You use what seems to be a non-standard docstring style. That's fine, but it's actually quite close to the RST / <a href=\"http://www.sphinx-doc.org/en/master/\" rel=\"nofollow noreferrer\">Sphinx</a> syntax. An overview of the various styles can be found <a href=\"ht... | {
"AcceptedAnswerId": "198009",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-05T18:04:17.843",
"Id": "197903",
"Score": "2",
"Tags": [
"python",
"python-3.x",
"unit-testing",
"django"
],
"Title": "Unit tests for os.scandir/scantree a directory"
} | 197903 |
<p>Over the last few days I created this Pig Latin Translator just for fun. I would really appreciate it if anybody could give suggestions of how to improve the code and make the program more efficient.</p>
<p><a href="https://github.com/AgnikBanerjeeGithub/Pig-Latin-Translator" rel="noreferrer">Here</a> is the GitHub link for the project.</p>
<p>For anybody who doesn't know the Pig Latin, feel free to look at the README, which explains what Pig Latin is, and the rules of the language. The code is in <a href="https://github.com/AgnikBanerjeeGithub/Pig-Latin-Translator/blob/master/PigLatin.java" rel="noreferrer">PigLatin.java</a>.</p>
<pre><code> /* -------------------- Program Information --------------------
Name Of Program: PigLatin.java
Date of Creation: 7/3/2018
Name of Author(s): Agnik Banerjee
Version of Java: 1.8.0_171
Created with: IntelliJ IDEA 2017.3.5 Community Edition
-------------------- Program Information -------------------- */
import java.util.Scanner;
public class PigLatin {
private static Scanner scan = new Scanner(System.in);
public static void main(String[] args) {
System.out.print("Enter one or more words that you would like to translate to Pig Latin: ");
final String userInput = scan.nextLine();
scan.close();
String[] word = userInput.split(" "); // Splits the string into an array of words
String output = "";
for (int i = 0; i < word.length; i++) {
String pigLatinWord = translateWord(word[i]); // Translates each word individually
output += pigLatinWord + " "; // Joins the translated word back into the output
}
System.out.println("Original Word(s): " + userInput);
System.out.println("Translation: " + output + "\n");
}
public static String translateWord(String word) {
String lowerCaseWord = word.toLowerCase();
int pos = -1; // Position of first vowel
char ch;
// This for loop finds the index of the first vowel in the word
for (int i = 0; i < lowerCaseWord.length(); i++) {
ch = lowerCaseWord.charAt(i);
if (isVowel(ch)) {
pos = i;
break;
}
}
if (pos == 0) {
// Translating word if the first character is a vowel (Rule 3)
return lowerCaseWord + "yay"; // Adding "yay" to the end of string (can also be "way" or just "ay")
} else {
// Translating word if the first character(s) are consonants (Rule 1 and 2)
String a = lowerCaseWord.substring(pos); // Extracting all characters in the word beginning from the 1st vowel
String b = lowerCaseWord.substring(0, pos); // Extracting all characters located before the first vowel
return a + b + "ay"; // Adding "ay" at the end of the extracted words after joining them.
}
}
// This method checks if the character passed is a vowel (the letter "y" is counted as a vowel in this context)
public static Boolean isVowel(char ch) {
if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u' || ch == 'y') {
return true;
}
return false;
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-06T06:57:22.377",
"Id": "381695",
"Score": "0",
"body": "IntelliJ should have already suggested you change string concatenation in a loop to `StringBuilder`, and simply the `if` condition in the method `isVowel`. Most of the time, you ... | [
{
"body": "<p>I would suggest the following points to make this programme more object-oriented:</p>\n\n<p><strong>Try using a collection object provided by Java instead of using array</strong></p>\n\n<pre><code>String[] word = userInput.split(\" \");\n</code></pre>\n\n<p>could be</p>\n\n<pre><code>List<Strin... | {
"AcceptedAnswerId": "198426",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-05T18:34:34.130",
"Id": "197904",
"Score": "7",
"Tags": [
"java",
"pig-latin"
],
"Title": "Java Pig Latin Translator"
} | 197904 |
<p>Which is good to use and why?</p>
<pre><code>if ($a == 3) {
//do something
}
</code></pre>
<p>Or </p>
<pre><code> if (3 == $a) {
//do something
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-05T20:24:04.683",
"Id": "381638",
"Score": "0",
"body": "Id say this isn't a question for code review, as there isn't any code to review !"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-05T20:58:28.170",
... | [
{
"body": "<p>Neither and both. </p>\n\n<p>The 'both'</p>\n\n<p><code>x == $assignedVariable</code> is a method of defensive programming which is aimed at preventing accidental assignment if someone was to use <code>$x = 3</code> by mistake. Whether this offers value is debatable; modern systems exist which cat... | {
"AcceptedAnswerId": "197911",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-05T19:19:59.730",
"Id": "197906",
"Score": "-5",
"Tags": [
"php"
],
"Title": "Best practice if statment"
} | 197906 |
<p>I am trying to write a Linked List implementation that can insert and delete at either head or tail in constant time. </p>
<p>I think I have it working, but I was curious what improvements I could make to this code? </p>
<p>Additionally, is there a way to delete from the tail in constant time without having a doubly linked list?</p>
<pre><code>public class LinkedList {
private ListNode head;
private ListNode tail;
private int size;
public LinkedList() {
head = null;
tail = null;
size = 0;
}
public void insert(int index, int data) {
if (index > size) { throw new System.ArgumentException("Index is larger than size of list"); }
if (index == 0) {
ListNode node = new ListNode(data, head, null);
if (head == null) {
tail = node;
}
else {
head.Prev = node;
}
head = node;
}
else if ( index == size) {
ListNode node = new ListNode(data, tail.Prev, tail);
tail.Next = node;
tail = node;
}
else {
ListNode currNode = _find(index);
ListNode node = new ListNode(data, currNode, currNode.Prev);
currNode.Prev.Next = node;
currNode.Prev = node;
}
size++;
}
public void delete(int index) {
if (index > size - 1) { throw new System.ArgumentException("Index is larger than size of list"); }
if (index == 0) {
head = head.Next;
head.Prev = null;
}
else if (index == size - 1) {
tail = tail.Prev;
tail.Next = null;
}
else {
ListNode node = _find(index);
node.Prev.Next = node.Next;
node.Next.Prev = node.Prev;
}
size--;
}
private ListNode _find(int index) {
ListNode currNode = head;
for (int i=0; i<index; i++) {
currNode = currNode.Next;
}
return currNode;
}
public int this[int key] {
get { return _find(key).Data; }
set { _find(key).Data = value; }
}
public int getSize() {
return size;
}
}
internal class ListNode {
private int data;
private ListNode next;
private ListNode prev;
public ListNode(int data, ListNode link, ListNode prev) {
this.data = data;
this.next = link;
this.prev = prev;
}
public int Data { get => data; set => data = value; }
public ListNode Next { get => next; set => next = value; }
internal ListNode Prev { get => prev; set => prev = value; }
}
</code></pre>
<p>Unit Test Code</p>
<pre><code>using Fundamentals;
using NUnit.Framework;
namespace UnitTests {
[TestFixture]
public class LinkedListUnitTests {
LinkedList LList;
[SetUp]
public void init() {
LList = new LinkedList();
}
[Test]
public void canAccessSizeOfLinkedList() {
Assert.That(LList.getSize(), Is.EqualTo(0));
}
[Test]
public void canInsertAtBeginningOfLinkedList() {
LList.insert(0, 1);
Assert.That(LList[0], Is.EqualTo(1));
}
[Test]
public void canInsertAtEndOfLinkedList() {
LList.insert(0, 1);
LList.insert(1, 2);
Assert.That(LList[LList.getSize() - 1], Is.EqualTo(2));
}
[Test]
public void canInsertIntoMiddleOfLinkedList() {
LList.insert(0, 1);
LList.insert(1, 3);
LList.insert(1, 2);
Assert.That(LList[1], Is.EqualTo(2));
}
[Test]
public void canAccessWithBrackets() {
LList.insert(0, 1);
LList.insert(1, 2);
LList.insert(2, 3);
Assert.That(LList[1], Is.EqualTo(2));
}
[Test]
public void canSetWithBrackets() {
LList.insert(0, 1);
LList.insert(1, 2);
LList.insert(2, 4);
LList[2] = 3;
Assert.That(LList[2], Is.EqualTo(3));
}
[Test]
public void canDeleteFromEndOfLinkedList() {
LList.insert(0, 1);
LList.insert(1, 2);
LList.insert(2, 3);
LList.delete(2);
Assert.That(LList.getSize(), Is.EqualTo(2));
//TODO check that the end was actually deleted
}
[Test]
public void canDeleteFromBeginningofLinkedList() {
LList.insert(0, 1);
LList.insert(1, 2);
LList.insert(2, 3);
LList.delete(0);
Assert.That(LList.getSize(), Is.EqualTo(2));
Assert.That(LList[0], Is.EqualTo(2));
}
[Test]
public void canDeleteFromMiddleOfLinkedList() {
LList.insert(0, 1);
LList.insert(1, 2);
LList.insert(2, 3);
LList.delete(1);
Assert.That(LList.getSize(), Is.EqualTo(2));
Assert.That(LList[1], Is.EqualTo(3));
}
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-05T20:42:08.883",
"Id": "381639",
"Score": "7",
"body": "To delete from one of the ends of a linked list in constant time, you need to be able to find the next or previous node in constant time. This isn't possible in a singly linked l... | [
{
"body": "<h1>Properties</h1>\n\n<p>The properties in <code>ListNode</code> can be simplified to:</p>\n\n<pre><code>public int Data { get; set; }\npublic ListNode Next { get; set; }\ninternal ListNode Prev { get; set; }\n</code></pre>\n\n<p>Similarly, <code>size</code> and <code>getSize</code> in <code>LinkedL... | {
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-05T20:09:40.050",
"Id": "197909",
"Score": "2",
"Tags": [
"c#",
"linked-list"
],
"Title": "Insert and Delete at Head and Tail of Linked List in constant time"
} | 197909 |
<p>This code allows you monitor the progress of the Powershell Jobs you just started. One of the key features is the ability to stop the other Jobs when 1 is failed.</p>
<p>For example, if you are running some Jobs with a runtime of around 60 seconds, the results needs to be combined to be of any use, Job 2 failed at 20 seconds. With this command your script will return in around 21 seconds instead of 60.</p>
<p>I wrote this code in response to a question on <a href="https://stackoverflow.com/questions/51191280/powershell-scripts-wanting-to-update-global-variables-in-multiple-instances/51194222#51194222">Stack Overflow</a>. It did resemble some of my existing code. The code is altered to be more complete and generic.</p>
<p>To point something out that I would like some recommendations on is a clean method for updating <code>ProgressBars</code> in nested functions. Right now I am using the 'AllScope' option on a variable and this does not look as neat as I hoped it to be.</p>
<p>This is also available on <a href="https://gist.github.com/SteloNLD/20a2404ac557fe27d58c472201beeca0" rel="nofollow noreferrer">GitHub</a>.</p>
<pre><code>Function Watch-Job {
[CmdletBinding()]
[OutputType([System.Management.Automation.Job[]])]
Param(
# Powershell Job(s) to Watch,
# normally the result of the Start/Get-Job command or -AsJob parameter.
[Parameter(
Mandatory=$true,
ValueFromPipeline=$true
)]
[Alias("Jobs")]
[ValidateNotNull()]
[System.Management.Automation.Job[]]$Job,
# When Multiple Jobs are provided in the $Job Parameter and a single Job fails
# This wil wil stop the remaining Jobs that are still running.
[Switch]$StopJobOnError,
# This wil remove the Job when it is finished (Failed, Stopped, Completed, ...)
[Switch]$RemoveJob
)
# Setup ProgessBar
if (-Not $JobStartCount) {
#Create variable for the current scope (function) that is also avaiable to any child scopes (functions).
$VariableJobStartCount = @{
Name = "JobStartCount"
Option = "AllScope"
Value = ($Job | Measure-Object | Select-Object -ExpandProperty Count)
}; New-Variable @VariableJobStartCount
Write-Progress -PercentComplete 0 -Activity "Watch-Job" -Status "$JobStartCount/$JobStartCount Jobs Left" #-CurrentOperation "Waiting for a Job to Finisch"
}
# Wait for a single job to finisch (Failed, Stopped, Completed, ...)
$Job | Wait-Job -Any | ForEach-Object {
if ($_.State -eq 'Failed') {
# Show a warning the current 'Failed' Job
Write-Warning "Job $($_.Name) returned with state $($_.State)"
# Stop all other Jobs.
if ($StopJobOnError) {
Write-Warning "A Job has failed, forcibly stopping other Jobs"
$Job | Stop-Job
}
}
Else {
# Show information about the current Job
Write-Verbose "Job $($_.Name) retuned with state $($_.State)"
}
# Remove the JobData for the Current Job
if ($RemoveJob) { $_ | Remove-Job}
# Wait for further Jobs to complete
$RemainingJobs = $Job | Where-Object Id -ne $_.Id
If ($RemainingJobs) {
Write-Progress -PercentComplete (100-($RemainingJobs.Count)/$JobStartCount*100) -Activity "Watch-Job" -Status "$($RemainingJobs.Count)/$JobStartCount Jobs Left"
Watch-Job -Job $RemainingJobs -StopJobOnError:$StopJobOnError -RemoveJob:$RemoveJob | Out-Null
}
Else {
Write-Progress -Activity "Watch-Job" -Completed
}
}
Return $Job
}
</code></pre>
<p>Code for testing this function:</p>
<pre><code># ------------------------------------------------
# Example Script
# ------------------------------------------------
Clear-Host
$ErrorActionPreference = "Stop" # Recommended, if something happens, TERMINATE!
$VerbosePreference = "Continue" # Only for this example, use -Verbose!
# DateTime this script started, used to calculate script run time
$ScriptStartDateTime = Get-Date
Write-Verbose "Script Started at $ScriptStartDateTime"
# A place to store the Jobs
$Jobs = @()
# Create a few (15) dummy Jobs
(1..15) | ForEach-Object {
# Create a Job that should fail in between the other Jobs
If ($_ -eq 10) {
$Jobs += Start-Job -Name "Job$($_)" -ScriptBlock {
Start-Sleep -Seconds 7
throw "build failed somehow"
Start-Sleep -Seconds 13
}
}
Else {
# Create an example job that has a long running time
$Jobs += Start-Job -Name "Job$($_)" -ArgumentList @($_) -ScriptBlock {
param($i)
Start-Sleep -Seconds ($i*2)
}
}
}
# Wait for Jobs to complete.
Watch-Job -Job $Jobs -StopJobOnError -RemoveJob -Verbose
# Output Script Runtime to the Verbose Output.
$RunTime = (Get-date) - $ScriptStartDateTime
Write-Verbose "Script Stopped at $(Get-Date)"
Write-Verbose "Total RunTime in Secconds: $($RunTime.TotalSeconds)"
</code></pre>
<p>Example Output:</p>
<pre class="lang-none prettyprint-override"><code>VERBOSE: Script Started at 07/05/2018 22:21:45
VERBOSE: Job Job1 retuned with state Completed
VERBOSE: Job Job2 retuned with state Completed
VERBOSE: Job Job3 retuned with state Completed
WARNING: Job Job10 returned with state Failed
WARNING: A Job has failed, forcibly stopping other Jobs
VERBOSE: Job Job4 retuned with state Stopped
VERBOSE: Job Job5 retuned with state Stopped
VERBOSE: Job Job6 retuned with state Stopped
VERBOSE: Job Job7 retuned with state Stopped
VERBOSE: Job Job8 retuned with state Stopped
VERBOSE: Job Job9 retuned with state Stopped
VERBOSE: Job Job11 retuned with state Stopped
VERBOSE: Job Job12 retuned with state Stopped
VERBOSE: Job Job13 retuned with state Stopped
VERBOSE: Job Job14 retuned with state Stopped
VERBOSE: Job Job15 retuned with state Stopped
Id Name PSJobTypeName State HasMoreData Location Command
-- ---- ------------- ----- ----------- -------- -------
753 Job1 BackgroundJob Completed False localhost ...
755 Job2 BackgroundJob Completed False localhost ...
757 Job3 BackgroundJob Completed False localhost ...
759 Job4 BackgroundJob Stopped False localhost ...
761 Job5 BackgroundJob Stopped False localhost ...
763 Job6 BackgroundJob Stopped False localhost ...
765 Job7 BackgroundJob Stopped False localhost ...
767 Job8 BackgroundJob Stopped False localhost ...
769 Job9 BackgroundJob Stopped False localhost ...
771 Job10 BackgroundJob Failed False localhost ...
773 Job11 BackgroundJob Stopped False localhost ...
775 Job12 BackgroundJob Stopped False localhost ...
777 Job13 BackgroundJob Stopped False localhost ...
779 Job14 BackgroundJob Stopped False localhost ...
781 Job15 BackgroundJob Stopped False localhost ...
VERBOSE: Script Stopped at 07/05/2018 22:21:54
VERBOSE: Total RunTime in Secconds: 8.2599559
</code></pre>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-05T20:49:04.857",
"Id": "197910",
"Score": "4",
"Tags": [
"powershell",
"scope"
],
"Title": "See the Progress of the Powershell Jobs you are running"
} | 197910 |
<p>I just implemented binary search tree as described in Cormen's algorithm book. I'm not interested in correctness or performance of the implementation. I'm looking for reviews, comments on code style and suggestions on what can be done to improve readability of the code and make it more concise, or any general issues you noticed.</p>
<p>To make things easy, I assume that duplicate values won't be inserted.</p>
<p>The code is a bit long but most methods are symmetric and some lines are just comments. Feel free to review as much as you want. Partial reviews are welcome.</p>
<pre><code>class BinarySearchTree:
"""
BinarySearchTree implementation from Cormen's Introduction to
Algorithm book
The implementation assumes that there is no duplicates in the tree.
"""
class Node:
def __init__(self, value, parent=None):
self.value = value
self.parent = parent
self.left = None
self.right = None
def __init__(self, iterable=None):
self._root = None
if iterable is not None:
for element in iterable:
self.insert(element)
def __contains__(self, item):
return self._search(self._root, item) is not None
def __len__(self):
return self._count(self._root)
def _count(self, node):
"""
Returns the size of subtree rooted on given node
Returns 0 if root is None
"""
if node is None:
return 0
return 1 + self._count(node.left) + self._count(node.right)
def search(self, value):
"""
Finds and returns the given value.
Returns None if not found in BST.
"""
node = self._search(self._root, value)
if node is None:
return None
return node.value
def _search(self, node, value):
"""
Searches node with specified value under subtree
rooted on given node, Returns None if value is not found
"""
if node is None:
return None
if node.value == value:
return node
if value < node.value:
return self._search(node.left, value)
else:
return self._search(node.right, value)
def insert(self, element):
"""Inserts given element to BST."""
if self._root is None:
self._root = self.Node(element)
return
self._insert(self._root, element)
def _insert(self, node, element):
"""
Insert given value to subtree rooted on given node.
It is assumed that root is not None
"""
if element <= node.value:
if node.left is None:
node.left = self.Node(element, node)
else:
self._insert(node.left, element)
else:
if node.right is None:
node.right = self.Node(element, node)
else:
self._insert(node.right, element)
def remove(self, element):
"""
Removes the given element from BST.
Throws ValueError if element is not in the BST
"""
node = self._search(self._root, element)
if node is None:
raise ValueError("Given element is not found in BST")
parent = node.parent
if node.left is None and node.right is None: # leaf node
if parent is not None:
if parent.left is node:
parent.left = None
else:
parent.right = None
else:
self._root = None
elif node.left is None:
if parent is None:
self._root = node.right
elif parent.left is node:
parent.left = node.right
else:
parent.right = node.right
node.right.parent = parent
elif node.right is None:
if parent is None:
self._root = node.left
elif parent.left is node:
parent.left = node.left
else:
parent.right = node.left
node.left.parent = parent
else:
if parent is None:
successor_node = self._maximum(node)
successor_node.parent.right = None
successor_node.parent = None
successor_node.left = node.left
successor_node.right = node.right
self._root = successor_node
elif parent.left is node:
successor_node = self._maximum(node)
successor_node.parent.right = None
successor_node.parent = parent
successor_node.left = node.left
successor_node.right = node.right
else:
predecessor_node = self._minimum(node)
predecessor_node.parent.left = None
predecessor_node.parent = parent
predecessor_node.left = node.left
predecessor_node.right = node.right
def maximum(self):
"""
Returns the maximum element in BST
Throws ValueError if BST is empty
"""
if self._root is None:
raise ValueError("BST is empty")
return self._maximum(self._root).value
def _maximum(self, node):
"""Returns the maximum node of subtree rooted on given node."""
while node.right is not None:
node = node.right
return node
def minimum(self):
"""
Returns the minimum element in BST
Throws ValueError if BST is empty
"""
if self._root is None:
raise ValueError("BST is empty")
return self._minimum(self._root).value
def _minimum(self, node):
"""Returns the minimum node of subtree rooted on given node."""
while node.left is not None:
node = node.left
return node
def successor(self, element):
"""
Returns successor of given element in BST.
If given element is not in the BST, throws ValueError
"""
node = self._search(self._root, element)
if node is None:
raise ValueError("Given element is not found in BST")
successor_node = self._successor(node)
if successor_node is None:
return None
return successor_node.value
def _successor(self, node):
"""Returns successor node of given node."""
if node.right is None:
if node.parent is None:
return None
else:
parent = node.parent
while parent is not None and parent.right is node:
node = parent
parent = parent.parent
if parent is None:
return None
else:
return parent
else:
node = node.right
return self._minimum(node)
def predecessor(self, element):
"""
Returns precedessor of given element in BST.
If given element is not in the BST, throws ValueError
"""
node = self._search(self._root, element)
if node is None:
raise ValueError("Given element is not found in BST")
predecessor_node = self._predecessor(node)
if predecessor_node is None:
return None
return predecessor_node.value
def _predecessor(self, node):
"""Returns predecessor node of given node."""
if node.left is None:
if node.parent is None:
return None
else:
parent = node.parent
while parent is not None and parent.left is node:
node = parent
parent = parent.parent
if parent is None:
return None
else:
return parent
else:
node = node.left
return self._maximum(node)
</code></pre>
<p>I also uploaded it on <a href="https://gist.github.com/Shathra/dd34223e5a4d9cfa085ce147d23bada4" rel="nofollow noreferrer">GitHub</a> with a test file.</p>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-05T21:51:38.023",
"Id": "197915",
"Score": "3",
"Tags": [
"python",
"python-3.x",
"tree"
],
"Title": "Binary Search Tree in Python 3"
} | 197915 |
<p>I want to parse a CSV file and store the data using the istream <code>>></code> operator but I am running into big performance issues.</p>
<p>Here is the current version:</p>
<pre><code>#include <vector>
#include <sstream>
#include <fstream>
#include <string>
#include <iostream>
template <class T>
class CSV
{
std::vector<std::vector<T>> _data;
size_t _width;
size_t _height;
public:
CSV(const std::string& filepath)
{
std::ifstream file(filepath);
if (!file)
throw std::exception();
for (std::string line; std::getline(file, line);)
{
std::stringstream ss1(line);
std::vector<T> row;
for (std::string field; std::getline(ss1, field, ',');)
{
std::stringstream ss2(field);
T item;
ss2 >> item;
row.push_back(item);
}
_data.push_back(row);
}
_height = _data.size();
if (!_height)
throw std::exception();
_width = _data[0].size();
for (auto& row : _data)
if (row.size() != _width)
throw std::exception();
}
size_t Width(void)
{
return _width;
}
size_t Height(void)
{
return _height;
}
const std::vector<std::vector<T>> &Data(void)
{
return _data;
}
};
</code></pre>
<p>It works but it's slow because I start by making a <strong>copy</strong> of each line in the file. I then make a <strong>copy</strong> of that line inside of a <code>stringstream</code>. I then parse each field in that line and make a <strong>copy</strong> of it. I then make a <strong>copy</strong> of that inside another <code>stringstream</code>, and finally I extract the data from the <code>stringstream</code>.</p>
<p>Basically there is too much copying, but I honestly don't know how to avoid it with <code>stringstream</code>s. I know there are other ways to parse things that are not <code>stringstream</code>s but then I miss out on using the <code>>></code> operator and the point of making a templated CSV parser.</p>
<hr>
<p>For an idea of its speed I have an 80MB file and it takes 11 seconds to parse using <code>CSV<int></code>. I also have <code>-03</code> turned on and am using clang++.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-06T15:17:06.117",
"Id": "381759",
"Score": "0",
"body": "Are you sure its text copying that is your problem. I would bet its more likely to be memory management of the vector. Do you have a link to your 80 MB file."
}
] | [
{
"body": "<pre><code>#include <iostream>\n</code></pre>\n\n<p>You don't seem to need this include.</p>\n\n<pre><code>size_t _width;\nsize_t _height;\n</code></pre>\n\n<p>These should both be <code>std::size_t</code>.</p>\n\n<pre><code>CSV(const std::string& filepath)\n</code></pre>\n\n<p>Single argum... | {
"AcceptedAnswerId": "197921",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-05T23:03:09.820",
"Id": "197918",
"Score": "8",
"Tags": [
"c++",
"parsing",
"template"
],
"Title": "Templated CSV file parser"
} | 197918 |
<p>Any improvements that I can make with this code?
Also, is there another way to convert a vector to a string variable without using a for ranged-based loop? From the posts I've seen for converting, I only saw printing the vector instead of returning a string.</p>
<pre><code>#include <string>
#include <vector>
#include <sstream>
#include <algorithm>
#include <iterator>
using namespace std;
std::string AlphabetSoup(string str) {
std::vector<char>letters;
istringstream iss(str);
copy(istream_iterator<char>(iss),
istream_iterator<char>(),
back_inserter(letters));
std::sort(letters.begin(),letters.end());
//Regrouping the characters into a string
std::string orderedString;
for(auto element : letters)
{
orderedString += element;
}
return orderedString;
}
</code></pre>
| [] | [
{
"body": "<h2> <a href=\"https://stackoverflow.com/a/1453605/5416291\">Don't use <code>using namespace std</code></a></h2>\n\n<p>You don't need a stringstream or an istringstream or a vector for this. <code>std::sort</code> can be performed on a string directly. An std::string_view can be used to avoid copying... | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-06T01:23:06.480",
"Id": "197922",
"Score": "4",
"Tags": [
"c++",
"strings",
"sorting"
],
"Title": "Sort string's characters into alphabetic order"
} | 197922 |
<p>I want to design Chinese mapping number routing. How can I improve this code in the method <code>mapRouting</code>?</p>
<p>I want to use reflect auto get method name by providing a value without <code>if</code> <code>else</code>, but I have no idea how to do it.</p>
<pre><code>public class FwMappingChi {
public static Map<String, String> mapRouting(String mapName){
if(mapName == "ACTION") {
return ACTION;
}
else if(mapName == "ENVIRONMENT") {
return ENVIRONMENT;
}
else if(mapName == "RULE_TYPE") {
return RULE_TYPE;
}
return null;
}
@SuppressWarnings("serial")
private static final Map<String, String> ACTION = new HashMap<String, String>(){
{
put("0", "新增");
put("1", "刪除");
}
};
@SuppressWarnings("serial")
private static final Map<String, String> ENVIRONMENT = new HashMap<String, String>(){
{
put("0", "正式環境");
put("1", "長期UAT");
put("2", "測試需求");
}
};
@SuppressWarnings("serial")
private static final Map<String, String> RULE_TYPE = new HashMap<String, String>(){
{
put("0", "系統間連接");
put("1", "系統間連接");
put("2", "人員維護用");
put("3", "提供服務用");
put("4", "User對外連接");
}
};
}
</code></pre>
<p>example:</p>
<pre><code>List<Map<String, Object>> exportDatas = fwApplyListDetailMapper.getExportQuery(idsArr);
List<List<String>> pdfValues = new ArrayList<>();
for (int i = 0; i < exportDatas.size(); i++) {
List<String> record = new ArrayList<>();
Map<String, Object> map = exportDatas.get(i);
for (String index : headerIndex) {
Object value = map.get(index);
if(FwMappingChi.mapRouting(index) != null) {
record.add(FwMappingChi.mapRouting(index).get(String.valueOf(value)));
}
}
pdfValues.add(record);
record = null;
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-06T04:49:54.650",
"Id": "381684",
"Score": "0",
"body": "Please provide examples of how these maps are used."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-06T05:01:05.347",
"Id": "381685",
"Score"... | [
{
"body": "<p>You could simply put your maps in a map, as the mapRouting function is nothing but a simple lookup.</p>\n\n<p>Prepare somewhere</p>\n\n<pre><code>private static final Map<String, Map<String, String>> MASTER = new HashMap<>() {\n {\n put(\"ACTION\", ACTION);\n put(\"... | {
"AcceptedAnswerId": "197933",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-06T04:42:18.327",
"Id": "197930",
"Score": "2",
"Tags": [
"java",
"hash-map"
],
"Title": "Chinese mapping number routing"
} | 197930 |
<p>Here is how to transform a Zorglub (it is an API that I can not modify):</p>
<pre><code>Zorglub transformedZorglub = zorglub.transform()
</code></pre>
<p>I am given a <code>java.util.List<Zorglub></code> and I must transform them all, then afterwards I will perform more operations on the transformed Zorglubs. After transformation I never use the originals anymore. This question is only about the transformation part. I wrote this:</p>
<pre><code>List<Zorglub> transformedZorglubs = new ArrayList<Zorglub>(zorglubs.size())
zorglubs.each {
transformedZorglubs.add(
it.transform()
)
}
zorglubs = transformedZorglubs
</code></pre>
<p>Is there something smarter or more elegant to do?</p>
<p>In particular, something that would avoid creating a new list and using twice as much memory, while avoiding bugs that often arise when modifying a list while iterating over it?</p>
| [] | [
{
"body": "<p><code>zorglubs = zorglubs.collect{it.transform()}</code> will a bit more elegantly but actually <code>collect</code> returns new array.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-21T20:05:36.460",... | {
"AcceptedAnswerId": "200045",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-06T06:39:10.193",
"Id": "197934",
"Score": "1",
"Tags": [
"groovy"
],
"Title": "Replace each element in a list"
} | 197934 |
<p>I <a href="https://codereview.stackexchange.com/q/197886/52915">was asked</a> to give more context. So here we go.</p>
<p>We want to create some HTML in code behind to add an "add" and a "refresh" button to a grid view header column. Approach #1 does this using string concatination to produce the necessary HTML, whereas approach #2 uses .NET objects to create exactly the same HTML.</p>
<p>This time I'm posting the complete classes:</p>
<p>Approach #1</p>
<pre><code>class AddBtnTemplate : ITemplate {
StatRefTimeGrid Parent;
public AddBtnTemplate(StatRefTimeGrid parent) {
Parent = parent;
}
public void InstantiateIn(Control container) {
GridViewHeaderTemplateContainer ctr = (GridViewHeaderTemplateContainer)container;
string html = "<div style='width:150px'>";
if (Parent.MayEdit)
html += string.Format("<img alt='{0}' title='{0}' src='Img/add18d.png' style='cursor: pointer' onclick='StatRefTimeGrid.addRow()' />", Texts.CompValue.AddRefTime[Parent.Parent.State.LangIdx]);
if (ctr.Grid.VisibleRowCount > 1)
html += string.Format("<img alt='{0}' title='{0}' src='Img/refresh18d.png' style='cursor: pointer' onclick='StatRefTimeGrid.refresh()' />", Texts.CompValue.RefreshRefTimeGrid[Parent.Parent.State.LangIdx]);
html += "</div>";
ctr.Controls.Add(new LiteralControl(html));
}
}
</code></pre>
<p>Approach #2</p>
<pre><code>private class AddBtnTemplate : ITemplate {
private readonly StatRefTimeGrid mParent;
public AddBtnTemplate(StatRefTimeGrid parent) {
mParent = parent;
}
public void InstantiateIn(Control container) {
GridViewHeaderTemplateContainer templateContainer = (GridViewHeaderTemplateContainer)container;
HtmlGenericControl div = new HtmlGenericControl("div") {
Style = {[HtmlTextWriterStyle.Width] = "150px"},
};
if (mParent.MayEdit) {
AddNewImage(div, Texts.CompValue.AddRefTime[mParent.Parent.State.LangIdx], "~/Img/add18d.png", "StatRefTimeGrid.addRow()");
}
if (templateContainer.Grid.VisibleRowCount > 1) {
AddNewImage(div, Texts.CompValue.RefreshRefTimeGrid[mParent.Parent.State.LangIdx], "~/Img/refresh18d.png", "StatRefTimeGrid.refresh()");
}
templateContainer.Controls.Add(div);
}
private void AddNewImage(HtmlGenericControl div, string altText, string imageUrl, string onClick) {
div.Controls.Add(new Image {
AlternateText = altText,
ToolTip = altText,
ImageUrl = imageUrl,
Attributes = {
["onclick"] = onClick,
},
Style = {
[HtmlTextWriterStyle.Cursor] = "pointer",
[HtmlTextWriterStyle.Position] = "relative",
[HtmlTextWriterStyle.Top] = "3px",
},
});
}
}
</code></pre>
<p>I'm looking for arguments for or against either solution. What do you think?</p>
| [] | [
{
"body": "<p>Second approach is better, according to the rule: do not repeat the code!</p>\n\n<p>Don't use '+=' to join string, in your case better to use StringBuilder:</p>\n\n<pre><code>var sb = new StringBuilder();\nsb.Append();\n...\nsb.Appden();\n...\nreturn sb.ToString();\n</code></pre>\n\n<p>I think thi... | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-06T07:20:15.800",
"Id": "197936",
"Score": "7",
"Tags": [
"c#",
"comparative-review",
"asp.net"
],
"Title": "ASP.NET HTML code generation, two approaches"
} | 197936 |
<p><strong>Following task:</strong></p>
<p>Customer-data, given in a JSON-file, have to be completed with additional address-data. Given in a second JSON-file. </p>
<p>Then these data-stock has to be saved into a MongoDB-database.</p>
<p><strong>Schema of the customer-JSON:</strong></p>
<pre><code>[
{
"id": "1",
"first_name": "Ario",
"last_name": "Noteyoung",
"email": "anoteyoung0@nhs.uk",
"gender": "Male",
"ip_address": "99.5.160.227",
"ssn": "509-86-9654",
"credit_card": "5602256742685208",
"bitcoin": "179BsXQkUuC6NKYNsQkdmKQKbMBPmJtEHB",
"street_address": "0227 Kropf Court"
},
{
"id": "2",
"first_name": "Minni",
"last_name": "Endon",
"email": "mendon1@netvibes.com",
"gender": "Female",
"ip_address": "213.62.229.103",
"ssn": "765-11-9543",
"credit_card": "67613037902735554",
"bitcoin": "135wbMcR98R6hqqWgEJXHZHcanQKGRPwE1",
"street_address": "90 Sutteridge Way"
},
...
]
</code></pre>
<p><strong>Schema of the addresses-JSON:</strong></p>
<pre><code>[
{
"country": "United States",
"city": "New Orleans",
"state": "Louisiana",
"phone": "504-981-8641"
},
{
"country": "United States",
"city": "New York City",
"state": "New York",
"phone": "212-312-1945"
},
...
]
</code></pre>
<p><strong>Desired result:</strong></p>
<pre><code>[
{
"_id" : ObjectId("5b3f16f5743a6704739bf436"),
"id" : "1",
"first_name" : "Ario",
"last_name" : "Noteyoung",
"email" : "anoteyoung0@nhs.uk",
"gender" : "Male",
"ip_address" : "99.5.160.227",
"ssn" : "509-86-9654",
"credit_card" : "5602256742685208",
"bitcoin" : "179BsXQkUuC6NKYNsQkdmKQKbMBPmJtEHB",
"street_address" : "0227 Kropf Court",
"country" : "United States",
"city" : "New Orleans",
"state" : "Louisiana",
"phone" : "504-981-8641"
},
...
]
</code></pre>
<p><strong>My solution:</strong></p>
<pre><code>const mongodb = require("mongodb");
const filePathCustomer = "./customers.json";
const filePathAddresses = "./addresses.json";
const MongoClient = mongodb.MongoClient;
completeCustomers = (filePathCustomers, filePathAddresses) => {
const customers = require(filePathCustomers);
const addresses = require(filePathAddresses);
return (updatedCustomers = customers.map((customer, index) => {
const updatedCustomer = Object.assign(customer, addresses[index]);
return updatedCustomer;
}));
};
MongoClient.connect(
"mongodb://localhost:27017/bitcoinExchange",
(error, client) => {
if (error) {
throw new Error("Connecting to MongoDb has failed.");
}
const db = client.db();
let execCompleteCustomer = new Promise(resolve => {
resolve(completeCustomers(filePathCustomer, filePathAddresses));
});
execCompleteCustomer
.then(customer => {
db.collection("customers").insertMany(customer, (error, result) => {
if (error) {
db.close();
throw new Error("Writing to database has failed");
}
console.log(
"Count of customer documents inserted:",
result.insertedCount
);
return true;
});
})
.then(result => {
if (result) db.close();
})
.catch(() => {
db.close();
throw new Error("The merging of the customer-data has failed.");
});
}
);
</code></pre>
<p><strong>What would you have done different and why?</strong></p>
<p><strong>Is my error-handling done in a good way and fashion? How could it be improved?</strong></p>
<p>What bothers me a bit are this multiple occurences of db.close().</p>
<p><strong>Is there a way in Node to avoid these redundancy?</strong></p>
<p>Something like finally in Java.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-06T08:22:56.447",
"Id": "381701",
"Score": "0",
"body": "How do you know which address to couple with which customer? They don't share an identifier and relying on the order in a JSON smells like a bad idea."
},
{
"ContentLicen... | [
{
"body": "<h2>Just a few things</h2>\n\n<ol>\n<li>To start out, the return statement in your function <code>completeCustomers</code> should/could be changed.</li>\n</ol>\n\n<p>The way the function is defined should also be changed. But we'll get to that in a second.</p>\n\n<pre><code>return (updatedCustomers =... | {
"AcceptedAnswerId": "198067",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-06T07:45:55.363",
"Id": "197938",
"Score": "0",
"Tags": [
"javascript",
"node.js",
"mongodb"
],
"Title": "Node.js Data-Completion script"
} | 197938 |
<p>Here is my code to find the details of the domain. The domain can be feed as following:</p>
<pre><code>bash script.sh domain1.com domain2.com
bash script.sh domains.txt <-- not completed
</code></pre>
<p>The output should be in following format:</p>
<pre><code>IP Address: 192.168.101.2
Server Name: servername.com
NS1: ns1.ournameserver.com
NS2: ns2.ournameserver.com
NS3: ns3.ournameserver.com
Datacenter: datacenter-name
Region: datacenter-13
Server Role: cPanel Web Server
Env: Production
Owner: xxxxxxxxxxx
Status: Active
IP Address: 192.168.101.2
Server Name: servername
NS1: ns1.ournameserver.com
NS2: ns2.ournameserver.com
NS3: ns3.ournameserver.com
Datacenter: datacenter-name
Region: datacenter-13
Server Role: cPanel Web Server
Env: Production
Owner: xxxxxxxxxxx
Status: Suspended
</code></pre>
<p>If it is in cloudflare:</p>
<pre><code>Domain name: test.com
IP Address: 192.168.101.1
Server ID: N/A
Server Name: N/A
NS1: LYNDA.CLOUDFLARE.COM
NS2: DYN.CLOUDFLARE.COM
Datacenter: OVH
Region: HETZ-C3
Server Role: cPanel Web Server
Env: Production
Owner: xxxxxxxxxxx
</code></pre>
<p>Now it is only giving result in normal format, it also needs to be in JSON format</p>
<p>script.sh</p>
<pre><code>#!bin/bash
HIP="$@"
check ()
{
regexp="^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$"
nameserver=('@ns1.ournameserver.com' '@ns2.ournameserver.com' '@ns3.ournameserver.com')
for j in ${nameserver[@]}
do
IPADD=`dig $j $i +noall +answer | grep "A" | awk '{print $5}'`
if [[ $IPADD =~ $regexp ]]
then
echo "IP Address = " $IPADD
ServerName=`nslookup $IPADD | grep -o -P '(?<=\=).*(?=.)'`
echo "ServerName = " $ServerName
DATA=`whois $IPADD | egrep 'org-name|OrgName' | awk '{print $2.$3}'`
echo "Data Center = " $DATA
break
fi
done
}
check2 ()
{
Pinging=`ping $i -c 1 | grep 'from' | cut -d$' ' -f4-5| tr '\(|\)' ' '`
IPADD=`awk '{print $2}' <<< $Pinging`
echo "IP Address = " $IPADD
ServerName=`awk '{print $1}' <<< $Pinging`
echo "Server Name = " $ServerName
}
for i in ${HIP[@]}
do
echo "Domain Name = " $i;
nsserver=`nslookup -type=ns $i | grep 'nameserver' | grep -o -P '(?<=ns.).*(?=.)' | head -n 1`
if [[ $nsserver == 'cloudflare.com' ]]
then
check
if ! [[ $IPADD =~ $regexp ]]
then
echo "This Domain does not belong to this server."
fi
else
check2
fi
whois $i | grep "Registrant Name"
nslookup -type=ns $i | grep nameserver | awk '{print $2,$3,$4}'
var=`curl -sL $i | grep '<title>' | tr -d ' ' | grep -o -P '(?<=Account).*(?=ed)'`
if [[ $var == 'Suspend' ]]
then
echo "Status = Account Suspended"
else
var=`curl -I $i 2>/dev/null | head -n 1 | cut -d$' ' -f2-3`
echo "Status = " $var
fi
printf '%*s' 100 | tr ' ' '#'
echo ''
done
</code></pre>
| [] | [
{
"body": "<p>Shellcheck reports quite a few issues you might want to correct:</p>\n<pre class=\"lang-none prettyprint-override\"><code>shellcheck -f gcc 197939.sh\n197939.sh:2:5: warning: Assigning an array to a string! Assign as array, or use * instead of @ to concatenate. [SC2124]\n197939.sh:5:24: note: Bac... | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-06T07:52:50.977",
"Id": "197939",
"Score": "4",
"Tags": [
"bash"
],
"Title": "Finding domain details with bash"
} | 197939 |
<p>I am new to jquery and implemented following function in a js file in case of error-</p>
<pre><code>function before_submit_check_if_has_blank_field() {
$("[type=submit]").click(function(e) {
var of_key_field = $('.key_field')
var of_val_field = $('.val_field')
var should_run = 1
if (of_key_field.length === 1) {
$('.key_field:not(:first)').filter(function() {
if (this.value === "") {
alert('Please Fill In Or Remove The Blank Fields First')
e.preventDefault();
should_run = 0
}
});
} else {
$('.key_field').filter(function() {
if (this.value === "") {
alert('Please Fill In Or Remove The Blank Fields First')
e.preventDefault();
should_run = 0
}
});
}
if (should_run != 0) {
if (of_val_field.length === 1) {
$('.val_field:not(:first)').filter(function() {
if (this.value === "") {
alert('Please Fill In Or Remove The Blank Fields First')
e.preventDefault();
should_run = 0
}
});
} else {
$('.val_field').filter(function() {
if (this.value === "") {
alert('Please Fill In Or Remove The Blank Fields First')
e.preventDefault();
should_run = 0
}
});
}
}
update_config_field_from_key_value_field()
});
}
</code></pre>
<p>The above code snippet is a part of my jquery where I am displaying a layout to the user with some fields and once those fields are empty then I am showing alert message while saving the form.</p>
<p>In above function I am repeating following lines of alert message which must be replaced by standard one-</p>
<blockquote>
<pre><code>if (this.value === "") {
alert('Please Fill In Or Remove The Blank Fields First')
e.preventDefault();
should_run = 0
}
</code></pre>
</blockquote>
<p>Can anyone please review my code and refactor it?</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-06T09:10:21.770",
"Id": "381706",
"Score": "0",
"body": "Hey, welcome to Code Review! Your current title says what you want out of a review, but since we all want to improve our code here one way or another, you should edit it to descr... | [
{
"body": "<p>What I would do is to create an object error = { errorCode: false} and every time you run throw check you assign to errorCode true if the conditions are not met.</p>\n\n<p>Then at the end you just check if error.errorCode is true and display the error message.</p>\n",
"comments": [],
"meta... | {
"AcceptedAnswerId": "197978",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-06T08:53:47.813",
"Id": "197941",
"Score": "0",
"Tags": [
"javascript",
"beginner",
"jquery",
"validation",
"form"
],
"Title": "jQuery function to display an alert when submitting blank fields"
} | 197941 |
<p>I am new to java, and to programming as a whole. trying to become a self taught programmer. i read books and solve exercise. the issue i face is lack of feedback. any comments on this piece of code is appreciated :</p>
<pre><code>/*
* Quadratic.java
* ------------------
* calculates the solutions of a quadratic equation (a*x^2 + b*x + c).
* this program calculates only real solutions. constant a is assembly nonzero.
*/
// to use input and output tools
import java.util.Scanner;
public class Quadratic {
/**
* prompt user to enter a-b-c values, computes solutions, display result
*/
public static void main(String [] args) {
// create scanner object to read values from user
Scanner input = new Scanner(System.in);
// prompt user to enter quadratic equation constants values (a,b,c)
System.out.println("Enter coefficients for the quadratic equation:");
// enter constant 'a' value
System.out.println("a: ");
double a = input.nextDouble();
// enter constant 'b' value
System.out.println("b: ");
double b = input.nextDouble();
// enter constant 'c' value
System.out.println("c: ");
double c = input.nextDouble();
// calculate quadratic equation solution
quadraticEquationSolver(a,b,c);
}
/**
* calculates quadratic equation solutions and print it to screen
* this method calculates only real solutions, in cases where that is not
* the case, a message to that effect is displayed on screen.
*/
private void quadraticEquationSolver(double a, double b, double c) {
// calculate square delta. delta = b^2 - 4*a*c
double deltaSquare = Math.pow(b, 2) - (4 * a *c);
// check if deltaSquare is a negative or a non-negative
if(deltaSquare < 0) {
// the equation has no real solutions
System.out.println("The equation has no real solutions");
return;
}else {
// calculate delat = sqrt (squareDelta)
double delta = Math.sqrt(deltaSquare);
// calculate first solution
double x1 = (-b + delta) / (2 * a);
// calculate second solution
double x2 = (-b - delta) / (2 * a);
// display result, each solution on different line
System.out.println("The first solution is " + x1);
System.out.println("The second solution is " + x2);
// in case solutions are equal, point it out
if (x1 == x2) System.out.println("both solutions are equal");
}
}
}
</code></pre>
<p>comments? is it too much? or just not the right way or words?
return statement used in method quadraticEquationSolver, inside if statement then clause? is it ok? bad? any other alternative?
if else statement, it could have been a cascaded if else statement like:</p>
<pre><code>if(deltaSquare < 0) {
// the equation has no real solutions
System.out.println("The equation has no real solutions");
return;
}else if (deltaSquare == 0){
// solutions are equal
double solution = (-b ) / (2 * a);
// display solution
System.out.println("The first solution = The second solution = " + solution);
} else {
// calculate delat = sqrt (squareDelta)
double delta = Math.sqrt(deltaSquare);
// calculate first solution
double x1 = (-b + delta) / (2 * a);
// calculate second solution
double x2 = (-b - delta) / (2 * a);
// display result, each solution on different line
System.out.println("The first solution is " + x1);
System.out.println("The second solution is " + x2);
}
</code></pre>
<p>which approach is better, the detailed cascading if statement ? or the brief more general simple if else statement? , in terms of good software engineering.</p>
<p>method return: here i faced two challenges. 1) in then clause of if else statement, method should not return any value. how to handle a situation where in its most cases the method should return a value but in one or two case, it does not return anything? 2) in other cases the solution involves two values which is not possible for a method to return two values. i got around this situation by declaring a non return method which just communicates the results to the user directly. is it too bad to do that? or is it common ?</p>
<p>lastly, any comments you have to improve? from any point of view</p>
| [] | [
{
"body": "<h1>Code Conventions</h1>\n\n<p>I recommend checking out the <a href=\"http://www.oracle.com/technetwork/java/codeconventions-150003.pdf\" rel=\"nofollow noreferrer\">Java Code Conventions</a> for some style tips and also about comments. You can stick with that, but the more modern <a href=\"https://... | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-06T09:45:24.100",
"Id": "197943",
"Score": "3",
"Tags": [
"java",
"beginner"
],
"Title": "Console program to solve quadratic equation"
} | 197943 |
<p>I have written the following program: Math Quiz. It is a programming exercise number 5 chapter 6 from the book "Art and Science of Java". </p>
<p>The program seems to be working. However, I would be grateful for any suggestions on any areas that I can improve on (any bad habits etc.).</p>
<p>I am also intrested if there are any more efficient or elegant ways of randomly choosing two numbers which meet the criteria listed beneath. </p>
<p>The program should meet these requirements:</p>
<p>• It should ask a series of five questions - arithmetic problems - coded as a named constant. </p>
<p>• Each question should consist of a single addition or subtraction problem involving just two numbers.</p>
<p>• The problem — addition or subtraction — should be chosen randomly for each question.</p>
<p>• None of the numbers involved, including the answer, should be less than 0
or greater than 20 - within these constraints, the program should choose the
numbers randomly.</p>
<p>• The program should give the student three chances to answer each question. If the student gives the correct answer, the program should indicate that fact in some properly congratulatory way.</p>
<p>• If the student does not get the answer in three tries, the program should give the answer and go on to another problem.</p>
<pre><code>/*
* File: MathQuiz.java
* ---------------------
*/
import acm.program.*;
import acm.util.*;
public class MathQuiz extends ConsoleProgram {
private static final int NUMBER_OF_QUESTIONS = 5;
public void run() {
println("Welcome to MathQuiz");
// Starts a function which will ask questions
for (int i=0; i < NUMBER_OF_QUESTIONS; i++) {
// Draws a random number between 0 and 20
int x = getRandomX();
// Draws a random sign - plus or minus with a probability of 50 per cent
String sign = getPlusOrMinus();
// Initializes a second variable which will be used for second random number
int y = 0;
// Initializes a variable where the good answer to the arithmetic problem will be kept
int goodanswer = 0;
// Draws a second random number between 0 and 20-x (method getRandomYPlus) if the drawn sign is + or between 0 and x (method getRandomYMinus) if the drawn sign is -
// I have created two methods because that numbers have to be such so that the answer will not be greater than 20 or less than zero
if (sign == "+") {
y = getRandomYPlus(x);
goodanswer = x + y;
} else {
y = getRandomYMinus(x);
goodanswer = x-y;
}
// Poses an arithmetic problem with the two random numbers and a random sign
int answer = readInt("What is " + x + sign + y + "? ");
// Initializes a variable which will count the number of answers
int count = 0;
// Students gets three chances to give a correct answer
while (answer != goodanswer && count !=3) {
answer = readInt("That`s incorrect - try a different answer: ");
count ++;
}
if (answer == goodanswer) {
println("You got it!");
// After three wrong answers program gives a correct answer and moves to another problem
} else {
println ("No, the answer is " + goodanswer + ".");
}
}
}
// Method which draws a random number between 0 and 20
private int getRandomX() {
int x = 0;
x = rgen.nextInt(0,20);
return x;
}
// Method which draws a random sign - plus or minus - with a probability of 50 per cent
private String getPlusOrMinus() {
String sign = null;
sign = rgen.nextBoolean() ? "+" : "-";
return sign;
}
// Draws a second random number between 0 and 20-x (method getRandomYPlus) if the drawn sign is + or between 0 and x (method getRandomYMinus) if the drawn sign is -
// I have created two methods because that numbers have to be such so that the answer will not be greater than 20 or less than zero
private int getRandomYPlus(int x) {
int y = 0;
y = rgen.nextInt(0,20-x);
return y;
}
private int getRandomYMinus(int x) {
int y = 0;
y = rgen.nextInt(0,x);
return y;
}
// Creates an instance variable for random number generator
private RandomGenerator rgen = new RandomGenerator();
}
</code></pre>
| [] | [
{
"body": "<p>The biggest problem is that you have hard-coded the maximum number size (20) at multiple places. Just like the number of rounds this should be a constant.</p>\n\n<hr>\n\n<p>You should void importing using a wild card. Always import only the specific classes you want to use. Otherwise you'll be hav... | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-06T09:48:59.903",
"Id": "197944",
"Score": "3",
"Tags": [
"java",
"beginner",
"quiz"
],
"Title": "Math Quiz program - programming excercise number 5 chapter 6 from \"Art and Science of Java\""
} | 197944 |
<p>Given this piece of code, what is a better way to write it (cleaner).
It is taken for granted that <code>data</code> will not be null, nor its length will be 0, so this check is skipped.</p>
<pre><code>private byte[] process(byte[] bytes) {
int from = 0;
if (bytes[0] == '\n') {
from = 1;
} else if (bytes[0] == '\r' && bytes[1] == '\n') {
from = 2;
}
return Arrays.copyOfRange(bytes, from, bytes.length);
}
</code></pre>
<p>I thought about converting it to <code>String</code>, then applying a regex (<code>^[\r\n]</code>), but that means some encoding has to be used for the conversion and then I would have to convert it back to <code>byte[]</code>, which does not comply with my needs.
Is there any clearer way to write this?</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-06T11:03:59.487",
"Id": "381713",
"Score": "1",
"body": "To whoever down-voted and close-voted this question, I don't see how the author is asking for help fixing broken code."
}
] | [
{
"body": "<p>I don't think you can make this specifically better.</p>\n\n<p>What you could do is make the function more generic, but that depends on what your data contains beyond the first two bytes. For example, you could simply skip any and all line feeds and carriage returns at the beginning:</p>\n\n<pre><... | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-06T11:00:01.763",
"Id": "197950",
"Score": "3",
"Tags": [
"java",
"array"
],
"Title": "Removing leading new line from byte[]"
} | 197950 |
<p>I'm learning Golang and have been trying to get 100% on the following Hackerrank practice challenge: <a href="https://www.hackerrank.com/challenges/climbing-the-leaderboard/problem" rel="noreferrer">Climbing the Leaderboard</a></p>
<p>The code passes ~8 of 11 tests. The Hackerrank tests are time-bound and my code is not efficient enough to past the most intensive tests.</p>
<p>I'm removing duplicates from the scores using a map. Then work through each of Alice's scores to find the index of each one by doing a binary search. Given that Alice's scored are sorted, I re-use the index for the next search.</p>
<p>Any ideas?</p>
<pre><code>package main
import (
"fmt"
)
func main() {
// example 1
scores := []int32{100, 100, 50, 40, 40, 20, 10}
alice := []int32{5, 25, 50, 120}
r := climbingLeaderboard(scores, alice)
for a, v := range r {
fmt.Printf("Position: %d alice[a]: %d\n", v, alice[a])
}
fmt.Printf("\n")
}
func removeDuplicates(a []int32) []int32 {
r := []int32{}
seen := map[int32]int32{}
for _, val := range a {
if _, ok := seen[val]; !ok {
r = append(r, val)
seen[val] = val
}
}
return r
}
func getMidPoint(start, end int) int {
i := end - start
if i%2 == 0 {
return i/2 + start
}
return (i+1)/2 + start
}
// 100 100 50 40 40 20 10
// 100 50 40 20 10
// 0 1 2 3 4
func binarySearch(scores []int32, v int32, i int) int {
var mid int
start := 0
end := i
for true {
if end-start == 1 {
//fmt.Printf("1 - v: %d start: %d end %d\n", v, start, end)
if v < scores[end] {
return end + 2
} else if v < scores[start] {
return start + 2
}
return 1
}
if end == 0 {
return 1
}
mid = getMidPoint(start, end)
if v > scores[mid] {
end = mid
} else if v < scores[mid] {
start = mid
} else {
// v == scores[mid]
//fmt.Printf("2 - v: %d start: %d end %d\n", v, start, end)
return mid + 1
}
}
return end
}
// attempt 3 - binary search
func climbingLeaderboard(originalScores []int32, alice []int32) []int32 {
r := make([]int32, len(alice))
//create scores and remove dups
scores := removeDuplicates(originalScores)
i := len(scores)
for a, v := range alice {
// fmt.Printf("1 - i: %d a: %d alice[a]: %d\n", i, a, alice[a])
i = binarySearch(scores, v, i-1)
r[a] = int32(i)
}
return r
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-06T14:42:35.533",
"Id": "381745",
"Score": "0",
"body": "Do you get \"Runtime Error :(\" or \"Time limit exceeded\" as feedback on hackerrank? It seems like the provided parsing code is broken, which fires a `panic` on test cases 6, 8 ... | [
{
"body": "<p>As @hoffmale correctly pointed out, the Hackerrank code to read in the input files on the larger tests was causing a problem. More specifically it didn't have enough memory to read in the array. So I increased the size of the reader and the writer (just in case). I also made a change to my binary... | {
"AcceptedAnswerId": null,
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-06T11:50:40.263",
"Id": "197955",
"Score": "5",
"Tags": [
"time-limit-exceeded",
"go",
"binary-search"
],
"Title": "Inefficient binary search? Hackerrank - Climbing the Leaderboard"
} | 197955 |
<p>I combined the ideas from <a href="https://codereview.stackexchange.com/q/127925/153110">this answer</a> and a comment to <a href="https://stackoverflow.com/q/2157149/1557062">this question</a> to create a new instance of a type extracted from a type list. The index of the desired type within the type list is provided at run time, only.</p>
<pre><code>#include <iostream>
#include <memory>
class Base
{
public:
virtual void foo() = 0;
};
class A : public Base
{
public:
void foo() override
{
std::cout << "A" << std::endl;
}
};
class B : public Base
{
public:
void foo() override
{
std::cout << "B" << std::endl;
}
};
template <class... Types>
class type_list {};
using list_t = type_list<A,B>;
template <class... Types>
static constexpr std::size_t length = sizeof...(Types);
template <std::size_t idx, class... Types>
class extract
{
static_assert(idx < sizeof...(Types), "index out of bounds");
template <std::size_t i, std::size_t n, class... Rest>
struct extract_impl;
template <std::size_t i, std::size_t n, class T, class... Rest>
struct extract_impl<i, n, T, Rest...>
{
using type = typename extract_impl<i + 1, n, Rest...>::type;
};
template <std::size_t n, class T, class... Rest>
struct extract_impl<n, n, T, Rest...>
{
using type = T;
};
public:
using type = typename extract_impl<0, idx, Types...>::type;
};
template <std::size_t idx, class TypeList>
struct type_list_extract;
template <std::size_t idx, template <class...> class TypeList, class... Types>
struct type_list_extract<idx, TypeList<Types...>>
{
using type = typename extract<idx, Types...>::type;
};
template <std::size_t idx, class TypeList>
using type_list_extract_t = typename type_list_extract<idx, TypeList>::type;
template<std::size_t idx, bool done = false, class... Types>
struct action_wrapper
{
static std::unique_ptr<Base> get_instance_by_id(std::size_t id)
{
if (id == idx)
{
using type = type_list_extract_t<idx, Types...>;
return std::make_unique<type>();
}
static constexpr auto cont = length<Types...> < idx + 1;
return action_wrapper<idx + 1, cont, Types...>::get_instance_by_id(id);
}
};
template<std::size_t idx, class... Types>
struct action_wrapper<idx, true, Types...>
{
static std::unique_ptr<Base> get_instance_by_id(std::size_t id)
{
return nullptr;
}
};
static std::unique_ptr<Base> get_instance_by_id(std::size_t id)
{
return action_wrapper<0, false, list_t>::get_instance_by_id(id);
}
int main()
{
std::unique_ptr<Base> ptr = get_instance_by_id(1);
if (ptr)
{
ptr->foo();
}
}
</code></pre>
| [] | [
{
"body": "<p><a href=\"https://stackoverflow.com/questions/213907/c-stdendl-vs-n\">Prefer using <code>\\n</code> over <code>std::endl</code></a></p>\n\n<hr>\n\n<p>Other than that, it looks like your code is rather clean and up-to-date style-wise. I might suggest that the <code>get_instance_by_id</code> return... | {
"AcceptedAnswerId": "198000",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-06T12:34:20.270",
"Id": "197960",
"Score": "2",
"Tags": [
"c++",
"template-meta-programming",
"variadic"
],
"Title": "Extract from typelist by runtime value"
} | 197960 |
<p>This is my code:</p>
<pre><code>n = int(raw_input())
seq = raw_input().split()
def minimize_list(lst):
new_lst = []
k = len(lst)
for i in range(k-1):
new_lst.append(lst[i+1]-lst[i])
return new_lst
for i in range(len(seq)):
seq[i] = int(seq[i])
final_list = []
for num in seq:
final_list.append(num)
while len(final_list) != 1:
final_list = minimize_list(final_list)
print (final_list[0])%(1000000000+7)
</code></pre>
<p>It takes a number and a sequence of numbers. (The first number is the number of numbers in the sequence). It then calculates a shorter sequence with the difference of adjacent numbers until there is just 1 number. Unfortunately, The time complexity is not good enough. I have to make it better to meet the time limit which is 1 second.</p>
<p>Any idea?</p>
<p>Note: I cannot see the input. I can just pass my code to a server which has 10 examples and runs my code on them. The server then tells me that this code has exceeded the time limit for some examples.</p>
<p>Update: I want to print (final_list[0])%(1000000000+7)</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-06T14:28:40.440",
"Id": "381736",
"Score": "0",
"body": "Do you have any example input and output? This usually makes these problems way easier to understand."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07... | [
{
"body": "<p>One easy way is to use <a href=\"http://www.numpy.org/\" rel=\"nofollow noreferrer\"><code>numpy</code></a>, which is implemented in C (if it is available on the machine your online judge is running on). It provides fast ways to do numerical calculations. In this case, you can use <a href=\"https:... | {
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-06T14:01:49.107",
"Id": "197964",
"Score": "1",
"Tags": [
"python",
"python-2.x",
"time-limit-exceeded"
],
"Title": "Minimize array and output the remainder with respect to 1 second time limit"
} | 197964 |
<p>Ongoing development of game. The player is controlled by mouse click to move upward. The goal is to avoid meteors for as long as possible. I would be grateful if someone could critique my code. </p>
<p>Verison 1 can be found <a href="https://codereview.stackexchange.com/questions/197603/flappy-bird-style-game-in-space-setting">here</a>. Since then I have:</p>
<ul>
<li>Added intro menu screen </li>
<li>Added game loop to contain main game logic</li>
<li>Added health to game, game over screen when health == 0 </li>
<li>Removed unnecessary and redundant comments</li>
<li>Implemented recommendations found in original post</li>
</ul>
<p>Still working on:</p>
<ul>
<li>Adding rotation to meteors</li>
<li>Display health with health bar</li>
<li>Buttons in intro menu </li>
</ul>
<pre><code># All images found @ http://kenney.nl/assets/space-shooter-extension, http://kenney.nl/assets/space-shooter-redux, and https://www.goldstar.com/events/los-angeles-ca/the-sirens-of-titan-tickets
import pygame
import random
pygame.init()
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
def game_intro():
intro = False
intro_background = pygame.image.load("assets/title_screen.png")
# Get dimensions of background
width = background.get_width()
height = background.get_height()
HW, HH = width/2, height/2
screen = pygame.display.set_mode((width,height))
intro_background = intro_background.convert()
while not intro:
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
if event.type == pygame.MOUSEBUTTONDOWN:
game_loop(background)
screen.blit(intro_background, (0,0))
message_display("Click to take Constant home")
pygame.display.update()
clock.tick(15)
pygame.quit()
def game_loop(background):
done = False
x = 0
health = 5
while not done:
dt = clock.tick(30)
# Main event Loop
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
if event.type == pygame.MOUSEBUTTONDOWN:
player.ignite()
#-----Game Logic
# Draw background and move to the left
rel_x = x % width
screen.blit(background, (rel_x - width, 0))
if rel_x < width:
screen.blit(background, (rel_x, 0))
x -= 2
# Check to see if player has collided with meteor
meteor_hit_list = pygame.sprite.spritecollide(player, meteor_group,
True)
# Event if player collides with meteor
for item in meteor_hit_list:
health -= 1
print("Shuttle hit", health)
if health == 0:
game_over()
create_meteor()
distance(screen)
all_sprites_group.draw(screen)
meteor_group.update()
player.update(dt/1000)
pygame.display.flip()
pygame.quit()
def game_over():
exit = False
screen = pygame.display.set_mode((850,526))
while not exit:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
if event.type == pygame.MOUSEBUTTONDOWN:
game_intro()
screen.fill(BLACK)
message_display("GAME OVER! Click to restart")
pygame.display.update()
pygame.display.flip()
clock.tick(30)
pygame.quit()
def create_meteor():
meteor = Meteor(width, height)
meteor_group.add(meteor)
all_sprites_group.add(meteor)
def message_display(text):
font = pygame.font.SysFont("transistor", 25, True, False)
travel_text = font.render(text, True, WHITE)
screen.blit(travel_text, (HW-150, HH))
def distance(screen):
"""Show how far the rocketship has travelled."""
# Get time since init was called
time = pygame.time.get_ticks()
# Convert milliseconds to seconds, 1 second = 1 km
travel_distance = round(time/1000, 2)
message_display("You have travelled " + str(travel_distance) + " lightyears")
class Player(pygame.sprite.Sprite):
def __init__(self,PLAYER_SURFACE, HW, HH):
super().__init__()
self.image = PLAYER_SURFACE
self.rect = pygame.rect.Rect(((HW - (PLAYER_SURFACE.get_width())), HH),
self.image.get_size())
# Gravity
self.dy = 0
def ignite(self):
self.dy = -400
def update(self, dt):
# Apply gravity
self.dy = min(400, self.dy + 40)
self.rect.y += self.dy * dt
# What happens if go to border of screen
if self.rect.top <= 0: # Top
self.rect.y = 0
self.dy = -4
elif self.rect.bottom >= height: # Bottom
self.rect.y = 526-self.rect.height
class Meteor(pygame.sprite.Sprite):
def __init__(self, width, height):
super().__init__()
self.image = random.choice(METEOR_IMAGES)
self.rect = self.image.get_rect()
# Random starting location
self.rect.x = random.randrange(width, (width + 300))
self.rect.y = random.randrange(0, height)
# Random movement to the left
self.change_x = random.randrange(-10,-5)
self.change_y = random.randrange(-4,3)
def reset_pos(self, screen):
self.image = random.choice(METEOR_IMAGES)
self.rect = self.image.get_rect()
self.rect.x = random.randrange(width, (width + 100))
self.rect.y = random.randrange(0, height)
# Random movement to the left
self.change_x = random.randrange(-10,-5)
self.change_y = random.randrange(-4,3)
def update(self):
# Move meteor
self.rect.x += self.change_x
self.rect.y += self.change_y
# Reset if falls off screen
if self.rect.right < 0:
self.reset_pos(screen)
if self.rect.top > height:
self.reset_pos(screen)
if self.rect.bottom < 0:
self.reset_pos(screen)
clock = pygame.time.Clock()
background = pygame.image.load("assets/background.png")
# Get dimensions of background
width = background.get_width()
height = background.get_height()
HW, HH = width/2, height/2
screen = pygame.display.set_mode((width,height))
background = background.convert()
PLAYER_SURFACE = pygame.image.load("assets/player.png").convert_alpha()
METEOR_IMAGES = []
METEOR_LIST = [
"assets/meteors/meteor1.png"...
]
for image in METEOR_LIST:
METEOR_IMAGES.append(pygame.image.load(image).convert_alpha())
pygame.display.set_caption("Return from Titan")
all_sprites_group = pygame.sprite.Group()
meteor_group = pygame.sprite.Group()
# Create spaceship
player = Player(PLAYER_SURFACE, HW, HH)
all_sprites_group.add(player)
# Create meteor sprites on the screen
for i in range(4):
create_meteor()
game_intro()
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-06T16:41:29.057",
"Id": "381776",
"Score": "0",
"body": "Thanks for the recommendation. I wasn't aware of the connection between stack exchange and stack overflow, so I used a guest username not knowing it would get linked to my accoun... | [] | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-06T14:50:05.613",
"Id": "197971",
"Score": "4",
"Tags": [
"python",
"pygame"
],
"Title": "Mouse Click Controlled Meteor Avoidance Game"
} | 197971 |
<p>We have a requirement to check the size of some of our website home pages, in MB. This is to ensure that they are not growing too large, and that large images haven't been uploaded. I couldn't find much info on this, but have come up with following which is working as required. </p>
<p>The code is designed to either run locally on my machine, or by leveraging our Selenium grid. It simply loads home page, and from the browser Performance log, we strip out the Network.dataReceived (bytes) information and sum it. </p>
<p>Finally, we have set levels which the site should fall within.</p>
<pre><code>#!/usr/bin/python
""" This script will simply check the download page size (bytes) of a Home page."""
import argparse
import re
import sys
from selenium import webdriver
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities
parser = argparse.ArgumentParser(description="This script will measure size of a home page.")
parser.add_argument('--site', default='somewebsite.com', required=True)
parser.add_argument('--local', action='store_true', default=False)
parser.add_argument('--datacentre', choices=['dc1', 'dc2'])
args = parser.parse_args()
logging_prefs = {'performance' : 'INFO'}
if args.local:
caps = DesiredCapabilities.CHROME.copy()
caps['loggingPrefs'] = logging_prefs
driver = webdriver.Chrome(desired_capabilities=caps)
else:
profile = webdriver.FirefoxProfile()
profile.set_preference('plugin.state.flash', 0)
profile.set_preference("webdriver_enable_native_events", False)
profile.update_preferences()
caps = DesiredCapabilities.FIREFOX.copy()
caps['loggingPrefs'], caps['acceptSslCerts'] = logging_prefs, False
if args.datacentre == 'dc1':
driver = webdriver.Remote(
command_executor='http://selenium/hub',
desired_capabilities=caps,
browser_profile=profile)
elif args.datacentre == 'dc2':
driver = webdriver.Remote(
command_executor='http://selenium/hub',
desired_capabilities=caps,
browser_profile=profile)
driver.implicitly_wait(30)
driver.set_page_load_timeout(30)
url = "http://" + args.site + "/"
driver.get(url)
total_bytes = []
try:
for entry in driver.get_log('performance'):
if "Network.dataReceived" in str(entry):
r = re.search(r'encodedDataLength\":(.*?),', str(entry))
total_bytes.append(int(r.group(1)))
except Exception:
print 'error'
driver.close()
sys.exit(3)
if total_bytes is not None:
mb = round((float(sum(total_bytes) / 1000) / 1000), 2)
if args.local:
from datetime import datetime
d = (datetime.today()).strftime("%d-%m-%y-%H-%M")
filename = 'results_{}.txt'.format(str(d))
with open(filename, 'a') as f:
f.write("{}, {}\n".format(args.site, mb))
try:
if mb < 2.0:
print "OK. Total Network Data Received size for {}: {}MB".format(args.site, str(mb))
sys.exit(0)
elif mb >= 2.0 and mb < 4.0:
print "Warning. Total Network Data Received size for {}: {}MB".format(args.site, str(mb))
sys.exit(1)
elif mb > 4.0:
print "CRITICAL. Total Network Data Received size for {}: {}MB".format(args.site, str(mb))
sys.exit(1)
except Exception:
print "UNKNOWN. Something went wrong."
sys.exit(3)
finally:
driver.close()
</code></pre>
| [] | [
{
"body": "<ol>\n<li><p>You're using the wrong shebang. According to <a href=\"https://stackoverflow.com/a/19305076\">this StackOverflow answer</a>:</p>\n\n<blockquote>\n <p><strong>Correct</strong> usage for Python 3 scripts is:</p>\n\n<pre><code>#!/usr/bin/env python3\n</code></pre>\n \n <p>This defaults t... | {
"AcceptedAnswerId": "198073",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-06T15:30:35.813",
"Id": "197972",
"Score": "3",
"Tags": [
"python",
"http",
"networking",
"selenium"
],
"Title": "Measure website home page total network size in bytes"
} | 197972 |
<p>I developed a Spring RESTful service that uses a JWT for authorization.
To the validity of this JWT, i used two different implementations.</p>
<ol>
<li>Create a filter to intercept every request and validate request, if invalid then reject it.</li>
<li>Create a annotation to be used in controller methods, this approach is explained below.</li>
</ol>
<p>The JWT contains user id which is used to identify authenticated user, but if i used a filter, i have to decode this JWT again in controller method, because of this problem i used second implementation.</p>
<p>The question is about annotation approach.</p>
<ul>
<li>Is this a good implementation to JWT validation ?</li>
<li>How can i improve this code ?</li>
</ul>
<p>Here's the code,</p>
<p><strong>Annotation</strong></p>
<pre><code>@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Authorize {
String[] value();
}
</code></pre>
<p><strong>Implementation of the annotation</strong></p>
<pre><code>public class MethodAccessResolver implements HandlerMethodArgumentResolver {
@Override
public boolean supportsParameter(MethodParameter parameter) {
return (parameter.getMethodAnnotation(Authorize.class) != null) && (parameter.getParameterName().equals("jwt"));
}
@Override
public Object resolveArgument(
MethodParameter parameter,
ModelAndViewContainer mavContainer,
NativeWebRequest webRequest,
WebDataBinderFactory binderFactory
) throws Exception {
String[] allowedUsers = parameter.getMethodAnnotation(Authorize.class).value();
JwtProperties jwt = JwtUtil.validate(webRequest.getHeader("Authorization"));
String currentUser = jwt.getScope().get(0);
int no = 0;
for (String allowedUser : allowedUsers) {
if (!allowedUser.equals(currentUser)) {
no++;
}
}
if (no == allowedUsers.length) {
throw new UnauthorizedAccessException("Un-authorized access", 0xd1561);
} else {
return jwt;
}
}
}
</code></pre>
<p><strong>Controller method - where the annotation is used</strong></p>
<pre><code>@GetMapping(
path = "/api/event/post",
produces = MediaType.APPLICATION_JSON_VALUE
)
@Authorize(value = {UserSupport.USER, UserSupport.ADMIN, UserSupport.END_USER})
public ResponseEntity<?> getLiveLocations(
HttpServletRequest request,
JwtProperties jwt
) throws
MongoException,
ParseException,
JwtException,
UnsupportedEncodingException,
ResourceNotFoundException,
UnauthorizedAccessException {
//do something
}
</code></pre>
<p>An <code>Exception</code> is thrown if token is invalid or the user role contains in token is not allowed to access particular URL.</p>
<p>If token is validated then user details will be injected to method parameter <code>JwtProperties jwt</code>.</p>
| [] | [
{
"body": "<ul>\n<li><p>I'd prefer the filter, just because then you don't have to worry about a missed annotation leaving your API wide open. I never found decoding JWTs to be expensive, and I suspect you're performing premature optimization.</p></li>\n<li><p><code>value</code> isn't especially descriptive. Pe... | {
"AcceptedAnswerId": "197976",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-06T15:42:37.977",
"Id": "197973",
"Score": "2",
"Tags": [
"java",
"spring",
"jwt"
],
"Title": "Create annotation to validate JWT in Spring controller instead of filter"
} | 197973 |
<p>This is an implementation of the <a href="https://en.wikipedia.org/wiki/Karatsuba_algorithm" rel="nofollow noreferrer">Karatsuba algorithm</a> for multiplication:</p>
<pre><code>use std::cmp::max;
/// Multiplies two numbers using the Karatsuba algorithm
fn karatsuba(a: isize, b: isize) -> isize {
// Single digit multiplication: no need for Karatsuba
if a < 10 && b < 10 {
a * b
} else {
let nr_of_digits = max(get_nr_of_digits(a), get_nr_of_digits(b));
let half_nr_of_digits = nr_of_digits / 2;
let (p, q) = split_at(half_nr_of_digits, a);
let (r, s) = split_at(half_nr_of_digits, b);
let u = karatsuba(p, r);
let w = karatsuba(q, s);
let v = karatsuba(p + q, r + s);
// Since we used integer division for half_nr_of_digits,
// half_nr_of_digits * 2 is not always equal to nr_of_digits.
// For example when nr_of_digits is 9.
let raised_u = u * 10_isize.pow(half_nr_of_digits * 2);
let raised_v_w_u = (v - w - u) * 10_isize.pow(half_nr_of_digits);
// That's the product of a and b
raised_u + raised_v_w_u + w
}
}
/// Gets the number of digits in a number. For example:
/// get_nr_of_digits(12345) == 5
fn get_nr_of_digits(x: isize) -> u32 {
let mut nr_of_digits = 1;
let mut copy = x;
while copy > 9 {
copy /= 10;
nr_of_digits += 1;
}
nr_of_digits
}
/// Splits a number at a position. For example:
/// split_at(2, 1234) == (12, 34)
fn split_at(pos: u32, x: isize) -> (isize, isize) {
let power = 10_isize.pow(pos);
let high = x / power;
let low = x % power;
(high, low)
}
#[test]
fn split_at_works() {
assert_eq!(split_at(2, 1234), (12, 34));
assert_eq!(split_at(1, 67), (6, 7));
assert_eq!(split_at(2, 67), (0, 67));
assert_eq!(split_at(2, 674), (6,74));
assert_eq!(split_at(2, 67461), (674, 61));
assert_eq!(split_at(3, 674610), (674, 610));
}
#[test]
fn karatsuba_works() {
// Positive numbers
assert_eq!(karatsuba(12, 34), 12 * 34);
assert_eq!(karatsuba(3, 4), 3 * 4);
assert_eq!(karatsuba(5678, 4321), 5678 * 4321);
assert_eq!(karatsuba(678, 4321), 678 * 4321);
assert_eq!(karatsuba(67, 65432), 67 * 65432);
assert_eq!(karatsuba(671, 654), 671 * 654);
assert_eq!(karatsuba(6781001, 6542001), 6781001 * 6542001);
assert_eq!(karatsuba(671, 654), 671 * 654);
assert_eq!(karatsuba(67, 654321), 67 * 654321);
assert_eq!(karatsuba(678032, 432132012), 678032 * 432132012);
// Negative numbers
assert_eq!(karatsuba(-678, 432), -678 * 432);
assert_eq!(karatsuba(678032, -232132012), 678032 * -232132012);
assert_eq!(karatsuba(571, -654), 571 * -654);
}
#[test]
fn get_nr_of_digits_works() {
assert_eq!(get_nr_of_digits(0), 1);
assert_eq!(get_nr_of_digits(10), 2);
assert_eq!(get_nr_of_digits(12345), 5);
assert_eq!(get_nr_of_digits(87654321), 8);
}
</code></pre>
<p>I'd love to know how to make this faster and rustier.</p>
| [] | [
{
"body": "<p>I can only think of two good reasons for using base 10:</p>\n\n<ol>\n<li>The purpose of the code is to teach, and the person (could be yourself) or people being taught are more comfortable with base 10 than base 2.</li>\n<li>The underlying representation of the integers is in base 10.</li>\n</ol>\... | {
"AcceptedAnswerId": "198423",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-06T15:47:03.133",
"Id": "197974",
"Score": "4",
"Tags": [
"algorithm",
"rust"
],
"Title": "Karatsuba multiplication in Rust"
} | 197974 |
<p>I have found that my code causes my Excel to 'not respond' when it gets to this for loop, <code>For thisRow = 2 To lastWSrow(outWS)</code>. I'm guessing this is because I am writing cell by cell and the data is too much for excel to handle.</p>
<p>My code essentially does 55 of vlookups on sheet2. It would be similar to doing <code>vlookup(c2&y2,Sheet1!I:J,2,false)</code> but manually it takes long to do.</p>
<p>Could anyone look at this loop and help me optimize this area? I have left only the part needed adjustment. I have put comments on each line to provide description.</p>
<p><code>outws = sheet2</code></p>
<pre><code>For thisRow = 2 To lastWSrow(outWS) '2 to last row of sheet2
For thisCol = 1 To UBound(mappings, 1)
'create unique key
thisScen = outWS.Cells(thisRow, posIDcol).Value & "|" & mappings(thisCol, 1)
'search
thisDataRow = findInArrCol(thisScen, 1, scenData)
'write to sheet2
If thisDataRow = 0 Then
If outWS.Cells(thisRow, posUnitsCol).Value <> 0 Then 'missing scenario
outWS.Cells(thisRow, mappings(thisCol, 3)).Value = "No data"
outWS.Cells(thisRow, mappings(thisCol, 3)).Value = 0
End If
Else
If mappings(thisCol, 1) = "irpv01|PV01_Swap_1M" Then
outWS.Cells(thisRow, PV01_1MCol).Value = outWS.Cells(thisRow, PV01_1MCol).Value + scenData(thisDataRow, 2) * scenData(thisDataRow, 3) 'since map PV01_0D to PV01_1m already, sum PV01_1M to that column in database.
Else
outWS.Cells(thisRow, mappings(thisCol, 3)).Value = scenData(thisDataRow, 2) * scenData(thisDataRow, 3) 'need to scale by position units to get correct risk
End If
End If
Next thisCol
Next thisRow
</code></pre>
<p><strong>findInArrCol</strong></p>
<pre><code>Public Function findInArrCol(matchVal As Variant, matchCol As Long, sortedArr() As Variant, Optional nearest As String) As Long
Dim low As Long, mid As Long, high As Long
findInArrCol = 0
low = 1
high = UBound(sortedArr, 1)
Do While low <= high
mid = (low + high) / 2
If sortedArr(mid, matchCol) = matchVal Then
findInArrCol = mid
Exit Function
ElseIf sortedArr(mid, matchCol) < matchVal Then
low = mid + 1
Else
high = mid - 1
End If
Loop
If findInArrCol = 0 Then
If nearest = "lessThan" Then
findInArrCol = WorksheetFunction.Max(high, 1)
End If
If nearest = "greaterThan" Then
findInArrCol = WorksheetFunction.Min(low, UBound(sortedArr, 1))
End If
End If
End Function
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-06T16:33:07.723",
"Id": "381772",
"Score": "7",
"body": "@Close-Voters: Excel going \"Not Responding\" isn't broken code, it's a single-threaded host application busy running VBA code, period."
},
{
"ContentLicense": "CC BY-SA ... | [
{
"body": "<pre><code>Application.Calculation = xlCalculationManual\nApplication.ScreenUpdating = False\n</code></pre>\n\n<p>' Place actual code between the above and below </p>\n\n<pre><code>Application.Calculation = xlCalculationAutomatic\nApplication.ScreenUpdating = True \n</code></pre>\n\n<p>The abo... | {
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-06T15:55:59.417",
"Id": "197975",
"Score": "0",
"Tags": [
"vba",
"excel",
"time-limit-exceeded"
],
"Title": "Writing many cells to sheet causes Excel to not respond, replacing vlookups"
} | 197975 |
<p>I'm trying to read a file containing over 10.000 lines and each line contains an ID for an individual and a very long string composed of more than 1 million characters (numbers as example: <code>2200500200...205</code> until 1 million characters long). </p>
<p>I need to go through this long string and retrieve a subset based on flag information formed by 0 or 1s coming from a string called <code>flagArray01String</code> in the sample code, so I'm checking one string of the same length and printing the subset in a file. </p>
<p>I'm in doubt if I should convert the long strings (string from file and string composed of flags) to char and perform the loop after that. I'm looking forward to receiving any comments that could help me obtaining a better performance. </p>
<p>Should I load all the strings in memory for some individuals? Are there any other performance tricks?</p>
<hr>
<p>Example of a sample file:</p>
<pre><code>ID1 2020205000200200202020
ID2 2020205000200200202020
ID3 2020205000200200202020
...
ID10000 2020205000200200202020
</code></pre>
<p>Example of flag:
flag = <code>1000001111111111111100</code>, where all the positions with 1´s should be retrieved and printed in a separated file.</p>
<hr>
<pre><code>if (IN_file.is_open())
{
getline(IN_file, headerFileOriginal);
while (IN_file >> idOriginal >> longString)
{
sizeTemp = longString.size();
if (sizeTemp > 0)
numbIdsOriginal++;
for (int p = 0; p < flagArray01String.size(); p++)
{
if ((flagArray01String[p] == '1'))
{
subsetString = subsetString + longString[p];
}
}
OUT_FILE << idOriginal << '\t' << subsetString << endl;
subsetString = "";
}
}
else
{
myfileLog << "Problems to open file " << IN_file_StringName << endl;
cout << "Problems to open file " << IN_file_StringName << endl;
}
IN_file.close();
OUT_FILE.flush();
OUT_FILE.close();
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-06T17:49:16.413",
"Id": "381782",
"Score": "1",
"body": "Welcome to Code Review. Please don't forget to delete your [original question](https://stackoverflow.com/questions/51214564/performance-problems-reading-and-writing-subset-from-a... | [
{
"body": "<p>I see some things 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-prac... | {
"AcceptedAnswerId": "197990",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-06T17:44:50.730",
"Id": "197982",
"Score": "5",
"Tags": [
"c++",
"performance",
"file"
],
"Title": "Producing excerpts from a file at specified positions within long lines (>1 M characters)"
} | 197982 |
<p>I am currently a student and I have an assignment in my OOP C++ course where I need to create a snake game using these specific requirements. I added some features into snake to fit these requirements</p>
<ol>
<li>Must use classes, objects, and functions</li>
<li>Must use inheritance or polymorphism </li>
<li>Must use vectors, arrays and or structs</li>
<li>enumerators or lists</li>
</ol>
<p>Any feed back would be greatly appriciated! My main goal is making it more coherent and efficient / shortening code!</p>
<pre><code>#include <iostream>
#include <conio.h>
#include <windows.h>
#include <iomanip>
#include <string>
#include <vector>
#include <stdlib.h>
#include <time.h>
#define KEY_UP 72
#define KEY_DOWN 80
#define KEY_LEFT 75
#define KEY_RIGHT 77
using namespace std;
class gameInfo {
public:
vector<int> score = { 60, 40, 20 };
vector<int> snakeBodyX;
vector<int> snakeBodyY;
bool isAlive = true, playerWon = false;
int playFieldWidth = 30;
int playFieldHeight = 20;
int x = playFieldWidth / 2, y = playFieldHeight / 2;
int foodPosX = rand() % (playFieldWidth - 4) + 2;
int foodPosY = rand() % (playFieldHeight - 4) + 2;
int min = 0, row, col, currentScore = 0, currentBest = 0, gamesPlayed = 0;
int tillHighScore = score[2];
void updateCurrentBest() {
if (currentScore > currentBest) currentBest = currentScore;
}
void updateTillHighScore() {
for (int i = 0; i < 3; i++) {
if (currentScore < score[i]) tillHighScore = score[i] - currentScore;
else if (currentScore >= score[0]) tillHighScore = 0;
}
}
void updateScoreBoard() {
for (int tracker = 0; tracker < score.size(); tracker++) {
if (currentScore > score[tracker]) {
score.insert(score.begin() + tracker, currentScore);
score.erase(score.begin()+score.size());
return;
}
}
}
};
class snakeInteractions : public gameInfo {
public:
void getSnakeBody() {
snakeBodyX.insert(snakeBodyX.begin(), x);
snakeBodyY.insert(snakeBodyY.begin(), y);
}
void resetSnakeBody() {
for (int erase = 0; erase < snakeBodyX.size(); erase++) {
snakeBodyX.erase(snakeBodyX.begin() + erase);
snakeBodyY.erase(snakeBodyY.begin() + erase);
}
}
void updateFoodPOS() { // randomly places food between 2 and (dimension - 2) - aka doesn't touch walls because I suck at this game and keep dying
bool isUnique = false;
while (!isUnique) {
foodPosX = rand() % (playFieldWidth - 4) + 2;
foodPosY = rand() % (playFieldHeight - 4) + 2;
for (int i = 0; i < snakeBodyX.size(); i++) {
if (foodPosY == snakeBodyY[i] && foodPosX == snakeBodyX[i]) break;
else isUnique = true;
}
}
}
void getSnakeCondition() { // just checks for if the snake has eatten a piece of food or died by crashing into itself or a wall.
if (foodPosX == x && foodPosY == y) {
currentScore += 10;
updateTillHighScore();
updateFoodPOS();
}
if (x == 0 || x == playFieldWidth - 1 || y == 0 || y == playFieldHeight - 1) {
isAlive = false;
}
for (int i = 1; i <= currentScore / 10; i++) {
if (snakeBodyX[i] == x && snakeBodyY[i] == y) {
isAlive = false;
}
}
}
};
class playSnake : public snakeInteractions {
public:
enum directions { UP, DOWN, LEFT, RIGHT };
directions dir;
void getKeyStroke() {
if (_kbhit()) {
switch (_getch()) {
case 'a': case 'A': case KEY_LEFT:
if (dir != RIGHT) dir = LEFT;
break;
case 'd': case 'D': case KEY_RIGHT:
if (dir != LEFT) dir = RIGHT;
break;
case 'w': case 'W': case KEY_UP:
if (dir != DOWN) dir = UP;
break;
case 's': case 'S': case KEY_DOWN:
if (dir != UP) dir = DOWN;
break;
}
}
}
void setPlayField() {
system("cls");
for (row = 0; row < playFieldHeight; row++) {
for (col = 0; col < playFieldWidth; col++) {
if (row == 0 || row == playFieldHeight - 1) cout << "*";
else if (col == 0 || col == playFieldWidth - 1) cout << "*";
else if (row == y && col == x) cout << "X";
else if (row == foodPosY && col == foodPosX) cout << "O";
else {
bool showSpace = true; // is there a better way of doing this? This feels sloppy
for (int body = 1; body < (currentScore+10)/10; body++) {
if (snakeBodyX[body] == col && snakeBodyY[body] == row) {
cout << "X";
showSpace = false;
}
}
if (showSpace) {
cout << " ";
}
}
}
setScoreBoard(row);
cout << endl;
}
}
void setScoreBoard(int row) { // is there a more efficient way of doing this? I couldn't think of one.
if (row == 1) cout << setw(22) << "Current Score:" << setw(13) << currentScore;
if (row == 2) cout << setw(26) << "Until High Score: " << setw(9) << tillHighScore;
if (row == 5) cout << setw(35) << "Top Scores ";
if (row == 6) cout << setw(35) << "===========================";
if (row == 7) cout << setw(17) << "1st Place" << setw(18) << score[0];
if (row == 8) cout << setw(17) << "2nd Place" << setw(18) << score[1];
if (row == 9) cout << setw(17) << "3rd Place" << setw(18) << score[2];
if (row == 12) cout << setw(35) << "Current Session ";
if (row == 13) cout << setw(35) << "===========================";
if (row == 14) cout << setw(21) << "Games Played:" << setw(14) << gamesPlayed;
if (row == 15) cout << setw(21) << "Current Best:" << setw(14) << currentBest;
}
void getSnakeMovement() {
if (dir == LEFT) x--;
else if (dir == RIGHT) x++;
else if (dir == UP) y--;
else if (dir == DOWN) y++;
else return;
}
void playAgain() { // is there a better way of doing this?
x = playFieldWidth / 2;
y = playFieldHeight / 2;
gamesPlayed++;
resetSnakeBody();
updateFoodPOS();
updateCurrentBest();
updateScoreBoard();
currentScore = 0;
isAlive = true;
playGame();
}
void playGame() {
while (isAlive) {
setPlayField();
getKeyStroke();
getSnakeMovement();
getSnakeBody();
getSnakeCondition();
if (!isAlive) playAgain(); // currently not a boolean, just takes true for testing reasons
Sleep(100);
}
}
};
int main() { // was always taught it was a good practice from my professor to keep main as minimal and clean as possible.
srand(time(NULL));
playSnake play;
play.playGame();
system("PAUSE");
}
</code></pre>
| [] | [
{
"body": "<p>Well, you follow the letter of the law for the first two requirements, as you are using a single god-object containing everything, and it's defined over multiple classes, which are only ever used to inherit for building the full class.<br>\nThat's probably not what your teacher wanted, but who kno... | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-06T18:49:23.933",
"Id": "197985",
"Score": "3",
"Tags": [
"c++",
"object-oriented",
"homework",
"vectors",
"snake-game"
],
"Title": "Snake Game in C++ using OOP"
} | 197985 |
<p>While working through some coding puzzles to brush up on Clojure, I encountered the need to use A* on some search problems. I tried to implement it from first principles/memory and that didn't go well, so I looked for existing implementations and found two (Joy of Clojure and <a href="http://clj-me.cgrand.net/2010/09/04/a-in-clojure/" rel="noreferrer">cgrand's</a>) but they were a little difficult to follow (for me) so I attempted to create my own. In the end it actually looks pretty close to cgrand's implementation.</p>
<p>I think this works as expected (using an example from <a href="https://www.youtube.com/watch?v=sAoBeujec74" rel="noreferrer">here</a> to verify), but just wanted to post to see if anybody can point out any glaring omissions / oversights. I've implemented this before in Python but it turned out to be quite different without using mutation. </p>
<p>The only issue I see is that I generate neighbors before testing whether I've already seen the node, so there is some inefficiency there. I couldn't figure out a good way to avoid this since my neighbor generation / filtering occurs in one step during the recursive call, whereas in languages allowing mutability you would process each child separately and you can test if it exists in the visited set each time.</p>
<pre><code>(defn a-star-search
[start neighbor-func goal? remain-cost path-cost]
(loop [q (conj (sorted-set) [0 start])
cost-so-far {start 0}
came-from {start nil}]
(if-let [[node-cost node :as node-state] (first q)]
(if (goal? node)
(reverse (take-while (complement nil?) (iterate came-from node)))
(let [neighbors (neighbor-func node)
prev-node (came-from node)
prev-cost (cost-so-far node)
cheaper (remove #(< (cost-so-far % Double/POSITIVE_INFINITY)
(+ prev-cost (path-cost node %)))
neighbors)
new-nodes (map #(vector (+ prev-cost
(path-cost node %)
(remain-cost %)) %)
cheaper)]
(recur (into (disj q node-state) new-nodes)
(->> cheaper
(map #(vector % (+ prev-cost (path-cost node %))))
(into cost-so-far))
(into came-from (map (juxt identity (fn [_] node)) cheaper)))))
"no more neigbors")))
(def graph {:s {:a 1 :b 4}
:a {:b 2 :c 5 :g 12}
:b {:c 2}
:c {:g 3}})
(def h-vals {:s 7 :a 6 :b 2 :c 1 :g 0})
(a-star-search :s
#(-> % graph keys)
#(= :g %)
h-vals
(fn [from to] (get-in graph [from to])))
</code></pre>
| [] | [
{
"body": "<p>I'm not going to be able to do a very thorough review. The code doesn't have anything outright wrong with it, and I'll admit, I've never been able to implement a decent A* implementation. It's just not something that's ever clicked for me very well (cue a new project to fix that).</p>\n\n<p>That s... | {
"AcceptedAnswerId": "197997",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-06T19:30:54.783",
"Id": "197987",
"Score": "5",
"Tags": [
"clojure",
"a-star"
],
"Title": "A* in Clojure - trickier than I expected"
} | 197987 |
<p>A coding challenge on a website says to determine if an array would have an increasing sequence if one element were removed from that array.</p>
<p>Here is the function: </p>
<pre><code>const almostIncreasingSequence = sequence => {
const increasingSequence = arr => {
for (let i = 0; i < arr.length; i++) {
if (arr[i - 1] >= arr[i]) {
return false;
}
}
return true;
};
for (let i = 0; i < sequence.length; i++) {
const left = sequence.slice(0, i);
const right = sequence.slice(i + 1);
const newArr = left.concat(right);
if (increasingSequence(newArr)) {
return true;
}
}
return false;
};
</code></pre>
<p>The function produces the exact same output as all of the visible tests on the site: </p>
<pre><code>var toTest = [
[1, 3, 2, 1],
[1, 3, 2],
[1, 2, 1, 2],
[1, 4, 10, 4, 2],
[10, 1, 2, 3, 4, 5],
[1, 1, 1, 2, 3],
[0, -2, 5, 6],
[1, 2, 3, 4, 5, 3, 5, 6],
[40, 50, 60, 10, 20, 30],
[1, 1],
[1, 2, 5, 3, 5],
[1, 2, 5, 5, 5],
[10, 1, 2, 3, 4, 5, 6, 1],
[1, 2, 3, 4, 3, 6],
[1, 2, 3, 4, 99, 5, 6],
[123, -17, -5, 1, 2, 3, 12, 43, 45],
[3, 5, 67, 98, 3]
];
for (let i = 0; i < toTest.length; i++) {
console.log(almostIncreasingSequence(toTest[i]));
}
</code></pre>
<p>Outputs: </p>
<pre><code>false
true
false
false
true
false
true
false
false
true
true
false
false
true
true
true
true
</code></pre>
<p>But then a hidden error triggers upon submission telling me that the execution time is longer than the maximum of 4 seconds. How can I improve the time complexity of this algorithm?</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-06T21:39:50.477",
"Id": "381824",
"Score": "1",
"body": "Not an answer, because my answer is not to use **this algorithm**. This algorithm is O(n2) [almost, the early returns in the function help], but the problem can be solved O(n). I... | [
{
"body": "<p>Your code has complexity \\$ O(N^2) \\$ (with \\$ N \\$ being the array length), and also creates up to \\$ N \\$ temporary arrays.</p>\n\n<p>Also note that your <code>increasingSequence</code> function accesses <code>arr[-1]</code>, the\nloop should start with <code>let i = 1</code>.</p>\n\n<p>As... | {
"AcceptedAnswerId": "197998",
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-06T19:43:05.660",
"Id": "197988",
"Score": "1",
"Tags": [
"javascript",
"beginner",
"algorithm",
"array",
"ecmascript-6"
],
"Title": "JavaScript Determine if Array has Almost Increasing Sequence"
} | 197988 |
<p>I am new to C#. I just created a method where I can convert a string with the format HH:MM AM/PM to minutes. I was wondering if there is a better or more effective way to achieve the same result.</p>
<pre><code>static void Main(string[] args)
{
string time1 = "11:15 AM";
string time2 = "11:15 PM";
calculateTimeInMinutes(time1);
calculateTimeInMinutes(time2);
void calculateTimeInMinutes(string currentTime)
{
if (currentTime.Contains("PM"))
{
int hours = Convert.ToInt32(currentTime.Substring(0, 2));
int HoursInminutes = (12 + (hours % 60)) * 60;
string minutesInString = currentTime.Split(':')[1];
int minutes = Convert.ToInt32(minutesInString.Remove(2));
int totalMinutes = HoursInminutes + minutes;
Console.WriteLine(totalMinutes);
}
else
{
int hours = Convert.ToInt32(currentTime.Substring(0, 2));
int HoursInminutes = (hours % 60) * 60;
string minutesInString = currentTime.Split(':')[1];
int minutes = Convert.ToInt32(minutesInString.Remove(2));
int totalMinutes = HoursInminutes + minutes;
Console.WriteLine(totalMinutes);
}
}
Console.ReadKey();
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-07T07:56:30.290",
"Id": "381851",
"Score": "2",
"body": "Could you explain the `hours % 60` part? This baffles me completely: for any time between `00:00` and `23:59` it will do nothing."
},
{
"ContentLicense": "CC BY-SA 4.0",
... | [
{
"body": "<p>The code is easy to understand, and it seems to produce the correct result.</p>\n\n<hr>\n\n<p>A couple of things:</p>\n\n<p><strong>1)</strong>\nThe code for \"AM\" and \"PM\" are almost identical with the difference of <code>12</code> (the PM-addend). You should not repeat yourself. </p>\n\n<p><s... | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-07T03:09:32.760",
"Id": "198002",
"Score": "4",
"Tags": [
"c#",
"beginner",
"datetime",
"unit-conversion"
],
"Title": "Convert a string in time format to minutes"
} | 198002 |
<p>This Program is a tool that allows me to import data from files that may not be easy to read just by opening; such as .db files which are wayyyyy to hard to understand just by opening the file in something like notepad and viewing the contents (this is meant for small files).</p>
<pre><code>from tkinter import *
from tkinter import ttk
import tkinter as tk
import sqlite3
class SqliteGui:
def __init__(self, master):
self.master = master
master.title(string = 'Advanced Data Import tool')
#placement
w = 515
h = 350
ws = master.winfo_screenwidth()
hs = master.winfo_screenheight()
x = (ws/2) - (w/2)
y = (hs/2) - (h/2)
master.geometry('%dx%d+%d+%d' % (w,h,x , y))
#creation of widgets
#entrys
self.pathentry = ttk.Entry(master )
self.pathentry.grid(row = 1 , column = 0 ,columnspan = 6, sticky = 'we')
self.catentry = ttk.Entry(master )
self.catentry.grid(row = 2 , column = 1 , sticky = 'we')
self.tableentry = ttk.Entry(master )
self.tableentry.grid(row = 2 , column = 4 , sticky = 'we')
#buttons
self.submitbutton = ttk.Button(master, text = 'Submit',command = sqlite_file_searcher)
self.submitbutton.grid(row = 2 , column = 5 , sticky = 'we')
self.clearbutton = ttk.Button(master, text = 'Clear' , command = sqlclearlistbox).grid(row = 6 , column = 1, sticky = 'we')
self.backbutton = ttk.Button(master , text = 'Back <--' , command = backwards).grid(row = 7 , column = 1, sticky = 'we')
#labels
self.pathlabel = tk.Label(master, text = 'File Name(sqlite db)' , fg = 'Green').grid(row = 0 , sticky = 'we' , column = 0)
self.select = tk.Label (master , text = 'SELECT' , fg = 'green').grid(row = 2 , sticky = 'we' , column = 0)
self.fromlabel = tk.Label(master , text = 'FROM' , fg = 'green').grid(row = 2 , sticky = 'we' , column =3 )
self.credit = tk.Label(master, text = 'Created By: Ronald Colyar' , fg= 'green').grid(row = 6 , column = 0 , sticky = 'we' )
#listbox
self.listbox = tk.Listbox(master , bd = 0)
self.listbox.grid(row = 5 , column = 0 , sticky = 'we' , columnspan = 6 , padx = 4 , pady = 4 )
#message
self.status = tk.Message(master , text = "Status: Good" , fg = 'Green')
self.status.grid(row = 7 , column = 0, sticky = 'we')
self.titlebar = tk.Menu(master)
self.help = tk.Menu(master , tearoff = False)
self.help.add_command(label = 'Help' , command =help_mthd )
self.titlebar.add_cascade(label = 'Help Options' ,menu = self.help)
master.config(menu = self.titlebar)
def statusUpdate(self, msg ,color):
self.status.config(text = msg)
self.status.config(fg = color)
class MainPage:
def __init__(self , master) :
self.master = master
master.title(string = 'Data Import tool')
#configuration of window
master.grid_rowconfigure(0,weight=1)
master.grid_rowconfigure(1,weight=1)
master.grid_rowconfigure(2,weight=1)
master.grid_rowconfigure(3,weight=1)
master.grid_columnconfigure(0,weight=1)
#placement
w = 505
h = 237
ws = master.winfo_screenwidth()
hs = master.winfo_screenheight()
x = (ws/2) - (w/2)
y = (hs/2) - (h/2)
master.geometry('%dx%d+%d+%d' % (w,h,x , y))
#creation of widgets
self.pathlabel = tk.Label(master, text = 'Path To File(.csv, .txt ,default iterable files)' , fg = 'Green').grid(row = 0 , sticky = 'we' , column = 0)
self.pathentry = ttk.Entry(master )
self.pathentry.grid(row = 1 , column = 0 , sticky = 'we' , pady = 4 , padx = 4)
self.submitbutton = ttk.Button(master, text = 'Submit' , command = defaultfilesearcher)
self.submitbutton.grid(row = 1 , column = 1 , sticky = 'we')
self.listbox = tk.Listbox(master , bd = 0)
self.listbox.grid(row = 2 , column = 0 , sticky = 'we' , columnspan = 2 , padx = 4 , pady = 4 )
self.credit = tk.Label(master, text = 'Created By: Ronald Colyar' , fg= 'green').grid(row = 3 , column = 0 , sticky = 'we' )
self.clearbutton = ttk.Button(master , text = 'Clear' ,command = mainclearlistbox).grid(row = 3 , column = 1 , sticky = 'we')
self.statusmessage = tk.Label(master, text = 'Status: Good' , fg = 'Green')
self.statusmessage.grid(row = 0 , column = 1 ,sticky = 'we')
#menus
self.titlebar = tk.Menu(master)
self.advanced = tk.Menu(master , tearoff = False )
self.advanced.add_command(label = 'Advanced Sqlite' , command = Sqlite_main)
#config
self.titlebar.add_cascade(label = 'sqlite' , menu = self.advanced)
master.config(menu = self.titlebar)
def statusUpdate(self,msg , color):
self.statusmessage.config(text =msg , fg = color)
def backwards():
second_window.withdraw()
Main_window.deiconify()
def defaultfilesearcher():
Path = str(Main_Object.pathentry.get())
#row identifier
Number_of_row = 0
#checking if error occurs
try:
open(Path, 'r')
errorcheck = False
except FileNotFoundError:
errorcheck = True
#if a error doesnt occur
if errorcheck == False:
Main_Object.statusUpdate('Status: Good' , 'green')
with open(Path , 'r') as f :
contents = f.readlines()
for i in contents:
Number_of_row +=1
#inserting the data
Main_Object.listbox.insert('end' , '#'+str(Number_of_row)+': '+str(i) )
else:
Main_Object.statusUpdate('File Not Found Try again' , 'red')
def sqlite_file_searcher():
global sqlite_obj
#db file
conn = sqlite3.connect(str(sqlite_obj.pathentry.get()))
c = conn.cursor()
#checking for an error
try:
results = c.execute("SELECT " + str(sqlite_obj.catentry.get()) +" FROM " + str(sqlite_obj.tableentry.get() ))
checkresults = True
except sqlite3.OperationalError:
checkresults = False
#the handling of the error check
if checkresults == True:
for i in results:
sqlite_obj.listbox.insert(0, i)
sqlite_obj.statusUpdate("Status: Good" , 'Green')
else:
#updating user if error occur
sqlite_obj.statusUpdate('Status :Error: Please Check Entered Information, View the help tab for assistance' , 'Red')
conn.close()
def help_mthd():
help_win = tk.Tk()
message = tk.Message(help_win , text= 'Welcome to the help window , 1. For the formatted database(sqlite) , you are selecting from a certain table inside of the .db file , if the table doesnt exist or the thing you are searching for doesnt exist, you will get an error verify that your information is correct if you are having a problem , 2..db File must be in same folder as the file searcher executable')
message.grid(row = 0 , column = 0 , sticky = 'we')
def Main():
global Main_window, Main_Object
Main_window = tk.Tk()
Main_Object = MainPage(Main_window)
Main_window.mainloop()
def Sqlite_main():
global Main_window, sqlite_obj ,second_window
Main_window.withdraw()
second_window = tk.Tk()
sqlite_obj = SqliteGui(second_window)
def sqlclearlistbox():
sqlite_obj.listbox.delete(0 , 'end')
def mainclearlistbox():
Main_Object.listbox.delete(0 , 'end')
if __name__ == "__main__" :
Main()
</code></pre>
<p><a href="https://i.stack.imgur.com/xlTDe.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/xlTDe.png" alt="enter image description here"></a><a href="https://i.stack.imgur.com/hnELG.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/hnELG.png" alt="enter image description here"></a><a href="https://i.stack.imgur.com/ZPhxA.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ZPhxA.png" alt="enter image description here"></a></p>
| [] | [
{
"body": "<h2>Use classe more</h2>\n\n<p>Classes make it much easier to organize GUI code. It's good that you've created a couple of classes, though about a third of your code lives outside of a class. I would recommend using classes for almost all code except the last couple of lines.</p>\n\n<h2>Use pep8 guid... | {
"AcceptedAnswerId": "198023",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-07T10:44:32.487",
"Id": "198011",
"Score": "2",
"Tags": [
"python",
"tkinter",
"sqlite"
],
"Title": "Iterable and .db file searcher that imports data"
} | 198011 |
<p>This project is intended to function as a basic web server with a command-line interface for easy use. It's written in Python 3, with the help of the <code>cmd</code> module for the CLI itself and the <code>_thread</code> module (I know, I know) to run the listening/responding process without interfering with the CLI.</p>
<p>I am wondering (with the exception of <code>_thread</code>, which I do intend to fix very soon) how well it conforms to best practices and how readable it is. Performance is not a big issue.</p>
<pre><code>import socket
import cmd
import os.path
import _thread # TODO: Switch from _thread to threading
import json
version = "0.3.0"
settings = {}
serverSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
serverSocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
def loadSettings():
global settings
with open('.linprconfig', 'r') as configFile:
settings = json.load(configFile)
def makeErrorResponse(errorNumber):
with open("htdocs/error/default.html") as defaultErrorTemplateFile:
defaultErrorTemplate = defaultErrorTemplateFile.readlines()
formattedErrorTemplate = ""
for line in defaultErrorTemplate:
formattedErrorTemplate += (line.replace("{}", str(errorNumber)))
return "HTTP/1.0 " + str(errorNumber) + "\n\n", formattedErrorTemplate,
def makeResponse(filename):
if filename == "/": filename = "/index.html"
try:
with open(os.path.join(settings["general"]["contentRoot"], filename[1:])) as requestedFile: # slice removes leading /
try:
return 'HTTP/1.0 200 OK\n\n', requestedFile.read(),
except UnicodeDecodeError: # it's not a text-based file
requestedFile = open(os.path.join(settings["general"]["contentRoot"], filename[1:]), 'rb') # reopen as binary
return 'HTTP/1.0 200 OK\n\n', requestedFile.read(),
except (FileNotFoundError, IsADirectoryError):
return makeErrorResponse(404)
def listen():
try:
while True:
clientConnection, clientAddress = serverSocket.accept()
# Get the client request and split it up
request = clientConnection.recv(1024).decode()
try:
headers = request.split('\n')
# Parse the request
command = headers[0]
if command.strip(" ") == "": continue
responseHeaders = makeResponse(command.split()[1])[0]
responseContent = makeResponse(command.split()[1])[1]
clientConnection.sendall(responseHeaders.encode())
try:
clientConnection.sendall(responseContent.encode())
except AttributeError: # it's a bytes object, so no .encode() method
clientConnection.sendall(responseContent)
clientConnection.close()
except Exception as e:
print("Error caught and 500 returned: "+ str(e))
responseHeaders = makeErrorResponse(500)[0]
responseContent = makeErrorResponse(500)[1]
clientConnection.sendall(responseHeaders.encode())
try:
clientConnection.sendall(responseContent.encode())
except AttributeError: # it's a bytes object, so no .encode() method
clientConnection.sendall(responseContent)
clientConnection.close()
except (KeyboardInterrupt, EOFError, SystemExit):
pass # this hides ugly messages on exit
class CommandLine(cmd.Cmd):
def preloop(self):
self.host = None
self.port = None
self.prompt = "LINPR " + version + " >"
def do_startup(self, s):
s = s.split(" ")
try:
self.host = s[0]
self.port = s[1]
except IndexError:
self.host = "0.0.0.0"
self.port = 80
serverSocket.bind((self.host, int(self.port)))
def help_startup(self):
print("Bind to a user-specified host and port. "
"When host and port are unsupplied, use the defaults 0.0.0.0 and 80.")
def do_listen(self, s):
print("Listening on port " + str(self.port))
serverSocket.listen(1)
_thread.start_new_thread(listen, ())
def help_listen(self):
print("Listen for any incoming connections and automatically respond to them with the requested resource.")
def do_exit(self, s):
print("Exiting...")
try:
serverSocket.close()
except NameError: # server_socket hasn't been created yet
pass
return True
def help_exit(self):
print("Exits LINPR and shuts down the server.")
def emptyline(self):
pass
loadSettings()
interpreter = CommandLine()
try:
interpreter.cmdloop(intro="Welcome to LINPR " + version + ". Type 'help' for help, or 'help cmd' for info on the 'cmd' command.")
except (KeyboardInterrupt, EOFError, SystemExit):
print("\n\nUse 'exit' to exit.")
CommandLine.do_exit(interpreter, "")
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-09T11:39:27.550",
"Id": "382055",
"Score": "0",
"body": "@Daniel Sorry, I didn't copy the full thing. I'll fix that now."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-09T12:31:13.917",
"Id": "382061",... | [
{
"body": "<h3>Direction and Architecture</h3>\n\n<p>If applicable to your use case, I'd first see if the functionality and performance of the existing module <a href=\"https://docs.python.org/3/library/http.server.html\" rel=\"nofollow noreferrer\">http.server</a> is sufficient, and if yes - would just use it.... | {
"AcceptedAnswerId": "198148",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-07T13:41:46.407",
"Id": "198016",
"Score": "3",
"Tags": [
"python",
"python-3.x",
"multithreading",
"reinventing-the-wheel",
"server"
],
"Title": "Basic web server in Python 3"
} | 198016 |
<p>This program in essence is extremely simple, however, it can be written in many different ways. I'm a beginner at C and I've written it in 5 different variations (mostly differing in the use of <code>getchar</code> over <code>scanf</code>, <code>while</code> over <code>do while</code> loops..). </p>
<p>Apart from readability and/or maintainability, is there any difference between these 5 code blocks (such as perhaps performance or efficiency, if we disregard the use of <code>getchar</code> over <code>scanf</code>)?</p>
<pre><code>unsigned char d;
</code></pre>
<ol>
<li><pre><code>while (1)
while(scanf("%c", &d), d != '\n') {
printf("%d\n", d * d);
}
</code></pre></li>
<li><pre><code>do {
scanf(" %c", &d);
printf("%d\n", d * d);
} while (1);
</code></pre></li>
<li><pre><code>while (1)
while((d = getchar()) != '\n') { //could also be written as while(d = getchar(), d != '\n')
printf("%d\n", d * d);
}
</code></pre></li>
<li><pre><code>while ((d = getchar())) {
if(d == '\n')
continue;
printf("%d\n", d * d);
}
</code></pre></li>
<li><pre><code>do {
d = getchar();
if(d == '\n')
continue;
printf("%d\n", d * d);
} while (1);
</code></pre></li>
</ol>
| [] | [
{
"body": "<blockquote>\n<pre><code>while (1)\n while(scanf(\"%c\", &d), d != '\\n') {\n printf(\"%d\\n\", d * d);\n }\n</code></pre>\n</blockquote>\n\n<p>It's better to consistently add braces around the body of statements like <code>while</code> and <code>if</code>.\nA common mistake is to wr... | {
"AcceptedAnswerId": "198024",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-07T14:53:09.213",
"Id": "198020",
"Score": "1",
"Tags": [
"c",
"comparative-review",
"io"
],
"Title": "Given a series of characters from stdin, print their squared integer ASCII counterparts"
} | 198020 |
<p>For my Pacman game i need to implement a pathfinding algorithm. I decide to do it with the Lee Algorithm, because in my opinion it's easier to understand than e.g. A* Star algorithm.<br>
I tried to implement it as explained on Wikipedia(<a href="https://en.wikipedia.org/wiki/Lee_algorithm" rel="nofollow noreferrer">https://en.wikipedia.org/wiki/Lee_algorithm</a>)</p>
<p>My output looks like this, O stands for Obstacle and 0 are the path:</p>
<pre><code>Path exists
Shortest Path:
5 4
4 4
3 4
3 3
3 2
2 2
2 1
2 0
1 0
0 0
0 O 1 1 1 1 1
0 1 1 O 1 1 1
0 0 0 O 1 1 1
1 O 0 0 0 1 1
1 O 1 O 0 1 1
1 1 1 O 0 1 1
1 1 1 1 1 1 1
</code></pre>
<p>Node.java </p>
<pre><code>class Node {
private int x;
private int y;
private int value;
public Node(int x, int y) {
this.x = x;
this.y = y;
}
public Node(int x, int y, int value) {
this.x = x;
this.y = y;
this.value = value;
}
public int getX() {
return this.x;
}
public int getY() {
return this.y;
}
public int getValue() {
return this.value;
}
public void setValue(int value) {
this.value = value;
}
public boolean equals(Node n) {
if (this.x == n.x && this.y == n.y) {
return true;
}
return false;
}
public String toString() {
return this.x + " " + this.y;
}
}
</code></pre>
<p>LeeAlgorithm.java </p>
<pre><code>import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
public class LeeAlgorithm {
private final int matrixWidth = 7, matrixHeight = 7;
private int matrix[][] = new int[matrixWidth][matrixHeight];
private boolean matrixVisited[][] = new boolean[matrixWidth][matrixHeight];
private ArrayList<Node> nodeList = new ArrayList<Node>();
private final int MAXITERATIONS = 1000;
private final int OBSTACLE = -1;
/*
find the shortest path between start and goal
*/
public LeeAlgorithm() {
matrix[4][1]=OBSTACLE; matrixVisited[4][1]=true;
matrix[3][1]=OBSTACLE; matrixVisited[3][1]=true;
matrix[2][3]=OBSTACLE; matrixVisited[2][3]=true;
matrix[4][3]=OBSTACLE; matrixVisited[4][3]=true;
matrix[5][3]=OBSTACLE; matrixVisited[5][3]=true;
//matrix[1][0]=OBSTACLE; matrixVisited[1][0]=true; no path
matrix[0][1]=OBSTACLE; matrixVisited[0][1]=true;
}
private ArrayList<Node> findPath(Node start, Node goal) {
if (nodeList.isEmpty()) {
nodeList.add(start);
matrixVisited[start.getX()][start.getY()] = true;
}
for (int i = 1; i < MAXITERATIONS; i++) {
nodeList = markNeighbors(nodeList, i);
if (matrix[goal.getX()][goal.getY()] != 0) {
System.out.println("Path exists");
break;
}
if (i == MAXITERATIONS - 1) {
System.out.println("No Path exists");
System.exit(0);
}
}
ArrayList<Node> pathList = backtraceFromGoal(goal, start);
return pathList;
}
/*
First step
mark all unlabeled neighbors of points which are marked with i, with i+1
*/
private ArrayList<Node> markNeighbors(ArrayList<Node> neighborList, int iteration) {
ArrayList<Node> neighbors = new ArrayList<Node>();
for (Node node : neighborList) {
if (node.getY() + 1 < matrix.length && matrixVisited[node.getX()][node.getY() + 1] == false) {
Node node1 = new Node(node.getX(), node.getY() + 1);
neighbors.add(node1);
matrix[node.getX()][node.getY() + 1] = iteration;
matrixVisited[node.getX()][node.getY() + 1] = true;
}
if (node.getY() >= 1 && matrixVisited[node.getX()][node.getY() - 1] == false) {
Node node2 = new Node(node.getX(), node.getY() - 1);
neighbors.add(node2);
matrix[node.getX()][node.getY() - 1] = iteration;
matrixVisited[node.getX()][node.getY() - 1] = true;
}
if (node.getX() + 1 < matrix.length && matrixVisited[node.getX() + 1][node.getY()] == false) {
Node node3 = new Node(node.getX() + 1, node.getY());
neighbors.add(node3);
matrix[node.getX() + 1][node.getY()] = iteration;
matrixVisited[node.getX() + 1][node.getY()] = true;
}
if (node.getX() >= 1 && matrixVisited[node.getX() - 1][node.getY()] == false) {
Node node4 = new Node(node.getX()-1, node.getY() );
neighbors.add(node4);
matrix[node.getX() - 1][node.getY()] = iteration;
matrixVisited[node.getX() - 1][node.getY()] = true;
}
}
return neighbors;
}
/*
Second step
from goal Node go to next node that has a lower mark than the current node
add this node to path until start Node is reached
*/
private ArrayList<Node> backtraceFromGoal(Node fromGoal, Node toStart) {
ArrayList<Node> pathList = new ArrayList<Node>();
pathList.add(fromGoal);
Node currentNode = null;
while (!pathList.get(pathList.size() - 1).equals(toStart)) {
currentNode = pathList.get(pathList.size() - 1);
Node n = getNeighbor(currentNode);
pathList.add(n);
n = currentNode;
}
return pathList;
}
/*
get Neighbor of node with smallest matrix value, todo shuffle
*/
private Node getNeighbor(Node node) {
ArrayList<Node> possibleNeighbors = new ArrayList<Node>();
if (node.getY() + 1 < matrix.length && matrixVisited[node.getX()][node.getY() + 1] == true &&
matrix[node.getX()][node.getY() + 1]!=OBSTACLE) {
Node n = new Node(node.getX(), node.getY() + 1, matrix[node.getX()][node.getY() + 1]);
possibleNeighbors.add(n);
}
if (node.getY() >= 1 && matrixVisited[node.getX()][node.getY() - 1] == true &&
matrix[node.getX()][node.getY() -1 ]!=OBSTACLE) {
Node n = new Node(node.getX(), node.getY() - 1, matrix[node.getX()][node.getY() - 1]);
possibleNeighbors.add(n);
}
if (node.getX() + 1 < matrix.length && matrixVisited[node.getX() + 1][node.getY()] == true &&
matrix[node.getX() + 1][node.getY()]!=OBSTACLE) {
Node n = new Node(node.getX() + 1, node.getY(), matrix[node.getX() + 1][node.getY()]);
possibleNeighbors.add(n);
}
if (node.getX() >= 1 && matrixVisited[node.getX() - 1][node.getY()] == true &&
matrix[node.getX() - 1][node.getY()]!=OBSTACLE) {
Node n = new Node(node.getX() - 1, node.getY(), matrix[node.getX() - 1][node.getY()]);
possibleNeighbors.add(n);
}
Collections.sort(possibleNeighbors, new Comparator<Node>() {
@Override
public int compare(Node first, Node second) {
return first.getValue() - second.getValue();
}
});
Node n = possibleNeighbors.remove(0);
return n;
}
private void printSolution(ArrayList<Node> output) {
System.out.println("Shortest Path:");
for (Node n : output) {
int x=n.getX();
int y=n.getY();
System.out.println(n.toString());
matrix[x][y]=0;
}
System.out.println("");
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix.length; j++) {
if(matrix[i][j]!=0 && matrix[i][j]!=OBSTACLE) {
matrix[i][j]=1;
}
if(matrixVisited[i][j]==false) {
matrix[i][j]=1;
}
if(matrix[i][j]==OBSTACLE) {
System.out.print("O ");
}
else {
System.out.print(matrix[i][j]+" ");
}
}
System.out.println("");
}
}
public static void main(String[] args) {
LeeAlgorithm l = new LeeAlgorithm();
ArrayList<Node> output = l.findPath(new Node(0, 0), new Node(5, 4));
l.printSolution(output);
}
}
</code></pre>
<p>Any Suggestions and improvements would be appreciated.</p>
| [] | [
{
"body": "<ul>\n<li><p>A standard trick to avoid testing for <code>node.getY() + 1 < matrix.length</code> etc is to add a border to your matrix, and initialize all nodes on the border to visited. The test reduces to just <code>matrixVisited[node.getX()][node.getY() + 1] == false</code>. This can also be sho... | {
"AcceptedAnswerId": "198025",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-07T15:40:27.603",
"Id": "198022",
"Score": "2",
"Tags": [
"java",
"algorithm",
"game",
"pathfinding"
],
"Title": "Java Pathfinding Lee Algorithm"
} | 198022 |
<p>I am trying to find the year most people are alive, given a list of births and deaths. I am not sure my approach is optimal or if am calculating the time complexity correctly</p>
<p>Break down:
I sort the dates
O(n log n)
I walk the dates in order
O(b + n log n)</p>
<p>Hashing the births, because they pivot the shifts between the number of living from those already dead. Since a birth year will be the year in which most people lived. </p>
<p>I am also pushing the deaths into a common array. </p>
<p>I then loop over the deaths
O(n^2 + n log n)</p>
<p>grabbing the count of those deceased and subtracting that from those still alive, and resting the array with those still alive on every iteration. </p>
<p>finally, I loop over the hash results to get the highest result.
with a final time complexity after dropping all constants</p>
<p>O(n+m) or O(n^2)</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>const people = [{ birth: 1720, death: 1860 },{ birth: 1720, death: 1860 },{ birth:1803, death: 1809},{ birth: 1730, death: 1810 },{ birth: 1920, death: 1950 },{ birth: 1930, death: 1940 },{ birth: 1940, death: 1990 }, { birth: 1970, death: 2010 }]
function yearMaxAlive(people) {
people.sort((a, b) => a.birth - b.birth)
let high = {
year: 0,
count: 0
},
alive = 0,
survivors = [];
for (let [year, count] of Object.entries(people.reduce((deaths => (ledger, year) => {
if (ledger[year.birth]) {
alive++
ledger[year.birth].alive = alive
} else if (!ledger[year.birth]) {
if (deaths.length > 0) {
let deleted = deaths.filter((a, i, aa) => {
if (a <= year.birth) {
return true
} else {
survivors.push(a)
return false
}
})
deaths = survivors
survivors = []
alive = alive - deleted.length
alive++
ledger[year.birth] = {
alive: alive,
deaths: deaths
}
} else {
alive++
ledger[year.birth] = {
alive: alive,
deaths: deaths
}
}
}
deaths.push(year.death)
return ledger
})([]), {}))) {
if (high.count < count.alive) {
high = {
year: year,
count: count.alive
}
}
}
return high
}
console.log(yearMaxAlive(people))</code></pre>
</div>
</div>
</p>
| [] | [
{
"body": "<p>The optimal algorithm is about O(n) to generate the count changes per year (and optionally get the first and last year), and about O(m) for enumerating them to find the first year with highest count (where m is preferably the number of years from the first to last year). </p>\n\n<p><div class=\"sn... | {
"AcceptedAnswerId": "198042",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-07T17:28:31.810",
"Id": "198026",
"Score": "1",
"Tags": [
"javascript",
"performance",
"algorithm",
"complexity"
],
"Title": "Year with the most living (given a list of births and deaths)"
} | 198026 |
<p>One of the things I was recently investigating was the ability to generate "gauge" charts—that is, a chart which shows where a value stands within a range of values.</p>
<p>As an example, if we know that, in general, the minimum air pressure is about 45 kPa, and the max is about 150 kPa, then we can generate a "gauge" that shows how far along that trend our current pressure, say 101.325 kPa, is. We might end up with one of the following (depending on whether we want horizontal or arc).</p>
<p><a href="https://i.stack.imgur.com/SBJdG.png" rel="noreferrer"><img src="https://i.stack.imgur.com/SBJdG.png" alt="Arc Gauge"></a>
<a href="https://i.stack.imgur.com/KOPO4.png" rel="noreferrer"><img src="https://i.stack.imgur.com/KOPO4.png" alt="Linear Gauge"></a></p>
<p>So basically, we can generate one of two graphs, where the value fills the left portion, and indicates, visually, how it stacks up to the range.</p>
<p>The code for each is below, both are mostly identical but have a few small differences.</p>
<h1>ArcGauge.fs:</h1>
<pre><code>module EBrown.Graphing.ArcGauge
open System.Drawing
open System.Drawing.Drawing2D
type Configuration =
{ Height : int
Width : int
Padding : Rectangle
GaugeWidth : int
Font : Font option
EmptyGaugeColor : Color option
FillGaugeColor : Color option
FontColor : Color option
OutlineColor : Color option
BackgroundColor : Color option
OutlineThickness : float32 option }
let generate<'a> configuration (toFloat : 'a -> float32) (formatter : 'a -> string) (max : 'a) (min : 'a) (value : 'a) =
use defaultFont = new Font("Arial", 12.f, FontStyle.Regular)
let font = configuration.Font |> Option.defaultValue defaultFont
let imageWidth = configuration.Width - configuration.Padding.Top - configuration.Padding.Bottom
let imageHeight = configuration.Height - configuration.Padding.Left - configuration.Padding.Right
let gaugeSweep = 180.0f
let angle = gaugeSweep * (((value |> toFloat) - (min |> toFloat)) / ((max |> toFloat) - (min |> toFloat)))
let gaugeWidth = configuration.GaugeWidth
let startAngle = 180.0f + (180.0f - gaugeSweep) / 2.0f
let image = new Bitmap(imageWidth + configuration.Padding.Left + configuration.Padding.Right, imageHeight + configuration.Padding.Top + configuration.Padding.Bottom)
use g = Graphics.FromImage(image)
g.SmoothingMode <- SmoothingMode.AntiAlias
g.InterpolationMode <- InterpolationMode.HighQualityBicubic
use backgroundBrush = new SolidBrush(configuration.BackgroundColor |> Option.defaultValue Color.White)
use emptyFillBrush = new SolidBrush(configuration.EmptyGaugeColor |> Option.defaultValue (Color.FromArgb(255, 192, 192, 192)))
use gaugeFillBrush = new SolidBrush(configuration.FillGaugeColor |> Option.defaultValue (Color.FromArgb(255, 192, 64, 64)))
use externalPen = new Pen(configuration.OutlineColor |> Option.defaultValue (Color.FromArgb(255, 96, 96, 96)), configuration.OutlineThickness |> Option.defaultValue 1.5f)
use fontBrush = new SolidBrush(configuration.FontColor |> Option.defaultValue Color.Black)
g.FillRectangle(backgroundBrush, Rectangle(0, 0, imageWidth + configuration.Padding.Left + configuration.Padding.Right, imageHeight + configuration.Padding.Top + configuration.Padding.Bottom))
use path = new GraphicsPath()
path.AddArc(Rectangle(configuration.Padding.Left, configuration.Padding.Top, imageWidth, imageWidth), startAngle, angle)
path.Reverse()
path.AddArc(Rectangle(configuration.Padding.Left + gaugeWidth, configuration.Padding.Top + gaugeWidth, imageWidth - gaugeWidth * 2, imageWidth - gaugeWidth * 2), startAngle, angle)
path.CloseFigure()
use externalPath = new GraphicsPath()
externalPath.AddArc(Rectangle(configuration.Padding.Left, configuration.Padding.Top, imageWidth, imageWidth), startAngle, gaugeSweep)
externalPath.Reverse()
externalPath.AddArc(Rectangle(configuration.Padding.Left + gaugeWidth, configuration.Padding.Top + gaugeWidth, imageWidth - gaugeWidth * 2, imageWidth - gaugeWidth * 2), startAngle, gaugeSweep)
externalPath.CloseFigure()
g.FillPath(emptyFillBrush, externalPath)
g.FillPath(gaugeFillBrush, path)
g.DrawPath(externalPen, externalPath)
let drawLabel = General.drawLabelCentered g (Rectangle(0, 0, image.Width, image.Height)) font fontBrush
let gaugeLabelOffsetX = (configuration.Padding.Left |> float32) + (gaugeWidth / 2 |> float32)
let imageMidX = (imageWidth |> float32) * 0.5f + (configuration.Padding.Left |> float32)
drawLabel (value |> formatter) (PointF(imageMidX, (imageWidth |> float32) * 0.5f + (configuration.Padding.Top |> float32) - 10.f))
drawLabel (min |> formatter) (PointF(gaugeLabelOffsetX, (imageWidth |> float32) * 0.5f + 5.f + (configuration.Padding.Top |> float32)))
drawLabel (max |> formatter) (PointF((image.Width |> float32) - gaugeLabelOffsetX, (imageWidth |> float32) * 0.5f + 5.f + (configuration.Padding.Top |> float32)))
image
</code></pre>
<h1>LinearGauge.fs:</h1>
<pre><code>module EBrown.Graphing.LinearGauge
open System.Drawing
open System.Drawing.Drawing2D
type Configuration =
{ Height : int
Width : int
Padding : Rectangle
GaugeWidth : int
Font : Font option
EmptyGaugeColor : Color option
FillGaugeColor : Color option
FontColor : Color option
OutlineColor : Color option
BackgroundColor : Color option
OutlineThickness : float32 option }
let generate<'a> configuration (toFloat : 'a -> float32) (formatter : 'a -> string) (max : 'a) (min : 'a) (value : 'a) =
use defaultFont = new Font("Arial", 12.f, FontStyle.Regular)
let font = configuration.Font |> Option.defaultValue defaultFont
let imageWidth = configuration.Width - configuration.Padding.Top - configuration.Padding.Bottom
let imageHeight = configuration.Height - configuration.Padding.Left - configuration.Padding.Right
let length = ((imageWidth |> float32) * (((value |> toFloat) - (min |> toFloat)) / ((max |> toFloat) - (min |> toFloat)))) |> int
let gaugeWidth = configuration.GaugeWidth
let image = new Bitmap(imageWidth + configuration.Padding.Left + configuration.Padding.Right, imageHeight + configuration.Padding.Top + configuration.Padding.Bottom)
use g = Graphics.FromImage(image)
g.SmoothingMode <- SmoothingMode.AntiAlias
g.InterpolationMode <- InterpolationMode.HighQualityBicubic
use backgroundBrush = new SolidBrush(configuration.BackgroundColor |> Option.defaultValue Color.White)
use emptyFillBrush = new SolidBrush(configuration.EmptyGaugeColor |> Option.defaultValue (Color.FromArgb(255, 192, 192, 192)))
use gaugeFillBrush = new SolidBrush(configuration.FillGaugeColor |> Option.defaultValue (Color.FromArgb(255, 192, 64, 64)))
use externalPen = new Pen(configuration.OutlineColor |> Option.defaultValue (Color.FromArgb(255, 96, 96, 96)), configuration.OutlineThickness |> Option.defaultValue 1.5f)
use fontBrush = new SolidBrush(configuration.FontColor |> Option.defaultValue Color.Black)
g.FillRectangle(backgroundBrush, Rectangle(0, 0, imageWidth + configuration.Padding.Left + configuration.Padding.Right, imageHeight + configuration.Padding.Top + configuration.Padding.Bottom))
let filledGauge = Rectangle(configuration.Padding.Left, configuration.Padding.Top, length, gaugeWidth)
let externalGauge = Rectangle(configuration.Padding.Left, configuration.Padding.Top, imageWidth, gaugeWidth)
g.FillRectangle(emptyFillBrush, externalGauge)
g.FillRectangle(gaugeFillBrush, filledGauge)
g.DrawRectangle(externalPen, externalGauge)
let drawLabel = General.drawLabel g (Rectangle(0, 0, image.Width, image.Height)) font fontBrush
let drawLabelCentered = General.drawLabelCentered g (Rectangle(0, 0, image.Width, image.Height)) font fontBrush
let gaugeLabelOffsetX = (configuration.Padding.Left |> float32)
let imageMidX = (imageWidth |> float32) * 0.5f + (configuration.Padding.Left |> float32)
drawLabelCentered (value |> formatter) (PointF(imageMidX, (configuration.Padding.Top |> float32) + (gaugeWidth |> float32) + 5.f))
drawLabel (min |> formatter) (PointF(gaugeLabelOffsetX, (configuration.Padding.Top |> float32) + (gaugeWidth |> float32) + 5.f))
drawLabel (max |> formatter) (PointF((image.Width |> float32) - gaugeLabelOffsetX - g.MeasureString(max |> formatter, font).Width, (configuration.Padding.Top |> float32) + (gaugeWidth |> float32) + 5.f))
image
</code></pre>
<p>You'll notice that both make references to a <code>General</code> module, which is pretty simple:</p>
<h1>General.fs:</h1>
<pre><code>module EBrown.Graphing.General
open System.Drawing
let drawLabelCentered (g : Graphics) (bounds : Rectangle) font brush str (ptLoc : PointF) =
let measurements = g.MeasureString(str, font)
g.DrawString(
str,
font,
brush,
PointF(
min (max (ptLoc.X - measurements.Width * 0.5f) (bounds.Left |> float32)) ((bounds.Right |> float32) - measurements.Width),
max (min (ptLoc.Y) ((bounds.Bottom |> float32) - measurements.Height)) ((bounds.Top |> float32))))
let drawLabel (g : Graphics) (bounds : Rectangle) font brush str (ptLoc : PointF) =
let measurements = g.MeasureString(str, font)
g.DrawString(
str,
font,
brush,
PointF(
min (max (ptLoc.X) (bounds.Left |> float32)) ((bounds.Right |> float32) - measurements.Width),
max (min (ptLoc.Y) ((bounds.Bottom |> float32) - measurements.Height)) (bounds.Top |> float32)))
</code></pre>
<p>As a test, I have the following F# script:</p>
<pre><code>// Learn more about F# at http://fsharp.org
// See the 'F# Tutorial' project for more help.
#load "General.fs"
#load "ArcGauge.fs"
#load "LinearGauge.fs"
open EBrown.Graphing
// Define your library scripting code here
open System.Drawing
open System.Drawing.Imaging
open System.Diagnostics
let values = (150., 45., 101.325)
let g1() =
let savePath = @"C:\Users\ebrown\Desktop\TestGauge.png"
let padding = Rectangle.FromLTRB(10, 10, 10, 30)
let config =
{ ArcGauge.Configuration.Height = 200
ArcGauge.Configuration.Width = 400
ArcGauge.Configuration.Padding = padding
ArcGauge.Configuration.Font = None
ArcGauge.Configuration.GaugeWidth = 64
ArcGauge.Configuration.EmptyGaugeColor = Color.FromArgb(255, 192, 192, 192) |> Some
ArcGauge.Configuration.FillGaugeColor = Color.FromArgb(255, 96, 16, 16) |> Some
ArcGauge.Configuration.FontColor = Color.FromArgb(255, 32, 0, 0) |> Some
ArcGauge.Configuration.OutlineColor = Color.FromArgb(255, 64, 64, 64) |> Some
ArcGauge.Configuration.BackgroundColor = Color.White |> Some
ArcGauge.Configuration.OutlineThickness = 1.25f |> Some }
let image = values|||> ArcGauge.generate config float32 (fun f -> f.ToString("0 KPa"))
image.Save(savePath, ImageFormat.Png)
Process.Start savePath |> ignore
let g2() =
let savePath = @"C:\Users\ebrown\Desktop\TestGauge2.png"
let padding = Rectangle.FromLTRB(10, 10, 10, 30)
let config =
{ LinearGauge.Configuration.Height = 50
LinearGauge.Configuration.Width = 400
LinearGauge.Configuration.Padding = padding
LinearGauge.Configuration.Font = None
LinearGauge.Configuration.GaugeWidth = 32
LinearGauge.Configuration.EmptyGaugeColor = Color.FromArgb(255, 192, 192, 192) |> Some
LinearGauge.Configuration.FillGaugeColor = Color.FromArgb(255, 96, 16, 16) |> Some
LinearGauge.Configuration.FontColor = Color.FromArgb(255, 32, 0, 0) |> Some
LinearGauge.Configuration.OutlineColor = Color.FromArgb(255, 64, 64, 64) |> Some
LinearGauge.Configuration.BackgroundColor = Color.White |> Some
LinearGauge.Configuration.OutlineThickness = 1.25f |> Some }
let image = values|||> LinearGauge.generate config float32 (fun f -> f.ToString("0 KPa"))
image.Save(savePath, ImageFormat.Png)
Process.Start savePath |> ignore
//() |> g1
//() |> g2
</code></pre>
<p>Lastly, you can <a href="https://github.com/EBrown8534/EBrown.Graphing" rel="noreferrer">find this on GitHub</a>.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-07T20:33:46.627",
"Id": "382087",
"Score": "0",
"body": "In both ArcGauge.fs and LinearGauge.fs, I'm getting the error below. I would have thought an open statement would fix it, but `open EBrown.Graphing.General` does not compile. The... | [
{
"body": "<p>Your two <code>Configuration</code> types are the same. Could they be merged into one type in a shared module? Then some code to get <code>imageWidth</code>, <code>imageHeight</code> could be shared, maybe as a member of the <code>Configuration</code> record.</p>\n\n<p>This line seems redundant:</... | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-07T17:53:46.950",
"Id": "198027",
"Score": "10",
"Tags": [
".net",
"generics",
"f#",
"graphics",
"data-visualization"
],
"Title": "Generating image gauges from a value, min and max"
} | 198027 |
<p>I have to implement a relatively basic order system in Java for part of the process of a job interview. At the moment I have working code that allows for the creation, and updating of orders for an imaginary company that manufactures bricks.</p>
<p>Before I submit the codebase to the company I am interviewing for I want my code to be reviewed so that I can improve any issues that exists within my program. I have tried to be as professional as possible with my development; obeying Java conventions and best practices, utilising JUnit testing to ensure my code works, keeping in mind SOLID principles and attempting to use them within my code to the best of my ability. </p>
<p>This is the first time I have attempted to produce professional-level (for a graduate with no experience) code, so I would love for someone to be able to review my program and tell me where I can improve.</p>
<p>I obviously don't want to post the entire program within this thread, so I'll post a few of the bigger classes. If you'd like to see the entire program, please just ask and I'd be happy to send it to you.</p>
<p>OrderSystem.java</p>
<pre><code>package core;
import java.util.ArrayList;
import java.util.Scanner;
/*
* Design principles ideas to implement
* - Reduce responsibility of this class, move excess functionality into different classes
* -> Order builder class, instead of building orders within this class
* -> Printer class?
* -> Reference number generator class?
*/
public class OrderSystem {
/*
* The amount of orders that have been created by the system in this session.
*/
private int ordersCreated = 0;
/*
* The order db that stores the information of all created orders.
*/
private static OrderDB db;
public OrderSystem()
{
db = new OrderDB();
}
/*
* Utilises OrderBuilder class to construct a BrickOrder object
* using the number of bricks on the order, as a parameter.
*
* Reference number is generated and is unique to the order that
* has been created. Reference number is returned by the method
* after the BrickOrder object has been created and added into
* the database of orders.
*/
public String createOrder(int numBricks)
{
OrderBuilder builder = new OrderBuilder();
BrickOrder o = builder.constructOrder(ordersCreated, numBricks);
incOrdersCreated(); //To keep refNum unique to each order.
db.addOrder(o);
System.out.println("Order ref " + o.getReferenceNumber() + " for " + o.getNumberOfBricks() + " bricks, created and added to DB.");
return o.getReferenceNumber();
}
public String updateOrder(String refNum, int newNumBricks)
{
ArrayList<BrickOrder> orderList = db.getOrderList();
for(BrickOrder o : orderList)
{
if(refNum.equals(o.getReferenceNumber()))
{
o.setNumberOfBricks(newNumBricks);
System.out.println("Order " + refNum + " details updated to " + newNumBricks + " bricks.");
return o.getReferenceNumber();
}
}
return "No order with reference number " + refNum + " in database.";
}
/*
* Return a specific order from the database using a reference number
*/
public BrickOrder getOrder(String refNum)
{
return db.getOrder(refNum);
}
/*
* Return all of the orders in the database in the form of an ArrayList
*/
public ArrayList<BrickOrder> getOrders()
{
return db.getOrderList();
}
/*
* Print the details of all orders present in the database to the console.
*/
public void printAllOrders()
{
ArrayList<BrickOrder> orderList = db.getOrderList();
Printer pr = new Printer();
pr.printOrderList(orderList);
}
/*
* Remove a specific order from the database using a reference number.
*/
public void removeOrder(String refNum)
{
db.removeOrder(refNum);
}
/*
* Return the number of orders created in this session.
*/
public int getOrdersCreated()
{
return ordersCreated;
}
/*
* Increments the value of ordersCreated
*/
private void incOrdersCreated()
{
ordersCreated++;
}
/*
* Returns a reference to the db.
*/
public OrderDB getDb()
{
return db;
}
}
</code></pre>
<p>OrderSystemTest.java</p>
<pre><code>package test;
import static org.junit.Assert.*;
import java.util.ArrayList;
import org.junit.Before;
import org.junit.Test;
import core.BrickOrder;
import core.OrderSystem;
public class OrderSystemTest {
private OrderSystem sys;
@Before
public void setup()
{
sys = new OrderSystem();
sys.getDb().clearDb();
}
/* A reference number must be returned after a new order
* has been created.
*/
@Test
public void testCreateOrderReturnsReference()
{
assertEquals(sys.createOrder(20), "BRICK1");
}
/*
* A reference number returned by a created order must be unique
* to the order that has just been created.
*/
@Test
public void testCreateOrderReturnsUniqueReference()
{
sys.createOrder(1);
sys.createOrder(1);
sys.createOrder(1); //Create three orders
BrickOrder o = sys.getOrder("BRICK1"); //Get details of first order
assertFalse(o.getReferenceNumber().equals("BRICK2"));
assertFalse(o.getReferenceNumber().equals("BRICK3")); //Check ref number is unique
o = sys.getOrder("BRICK2"); //Get details of second order
assertFalse(o.getReferenceNumber().equals("BRICK1"));
assertFalse(o.getReferenceNumber().equals("BRICK3")); //Check ref number is unique
o = sys.getOrder("BRICK3"); //Get details of third order
assertFalse(o.getReferenceNumber().equals("BRICK2"));
assertFalse(o.getReferenceNumber().equals("BRICK1")); //Check ref number is unique
}
/*
* Reference numbers of created orders must follow the correct
* trend of increasing reference numbers.
*/
@Test
public void testCreateOrderSetsCorrectReference()
{
sys.createOrder(1);
sys.createOrder(1);
sys.createOrder(1);
sys.createOrder(1);
sys.createOrder(1);
sys.createOrder(1);
assertEquals(sys.createOrder(5), "BRICK7");
}
/*
* Created orders must set the number of bricks within the order object.
*/
@Test
public void testCreateOrderSetsNumberOfBricks()
{
sys.createOrder(15);
BrickOrder o = sys.getOrder("BRICK1");
assertEquals(o.getNumberOfBricks(), 15);
}
/*
* If a user tries to attempt to retrieve an order that doesn't
* exist or uses an invalid reference number, null is returned.
*/
@Test
public void testReturnOfInvalidOrderReturnsNothing()
{
assertTrue(sys.getOrder("ROCK1") == null);
}
/*
* When a specific reference number is used to retrieve
* an order from the database, the correct details of
* the order must be returned.
*/
@Test
public void testOrderDetailsReturnedCorrectly()
{
sys.createOrder(50);
sys.createOrder(43);
sys.createOrder(112);
BrickOrder o = sys.getOrder("BRICK2");
assertEquals(o.getReferenceNumber(), "BRICK2");
assertEquals(o.getNumberOfBricks(), 43);
}
/*
* When a "get orders" request is submitted, all of the active orders
* are returned in the form of an ArrayList. Each order's specific
* details are then accessible via the ArrayList get() method.
*/
@Test
public void testFullOrderListReturnedCorrectly()
{
sys.createOrder(10);
sys.createOrder(100);
sys.createOrder(1000); //Create three orders
ArrayList<BrickOrder> orderList = sys.getOrders(); //Return full order list
BrickOrder o = orderList.get(0);
assertEquals(o.getReferenceNumber(), "BRICK1");
assertEquals(o.getNumberOfBricks(), 10);
o = orderList.get(1);
assertEquals(o.getReferenceNumber(), "BRICK2");
assertEquals(o.getNumberOfBricks(), 100);
o = orderList.get(2);
assertEquals(o.getReferenceNumber(), "BRICK3");
assertEquals(o.getNumberOfBricks(), 1000);
}
/*
* The number of orders created in this session is recorded in
* the "createdOrders" variable. Correct function of this variable
* is crucial for correct reference number generation This variable
* is incremented by 1 each time the createOrder() method is called.
* This number does not decrease when orders are removed from the database.
*/
@Test
public void testOrdersCreatedIncrementsCorrectly()
{
assertEquals(sys.getOrdersCreated(), 0);
sys.createOrder(1);
sys.createOrder(1);
sys.createOrder(1);
assertEquals(sys.getOrdersCreated(), 3);
sys.removeOrder("BRICK2");
sys.removeOrder("BRICK3");
assertEquals(sys.getOrdersCreated(), 3);
sys.createOrder(1);
assertEquals(sys.getOrdersCreated(), 4);
}
/*
* After an order is successfully updated, the reference
* number from the order must be returned.
*/
@Test
public void testUpdateOrderReturnsCorrectReferenceNumber()
{
sys.createOrder(5);
assertEquals(sys.updateOrder("BRICK1", 10), "BRICK1");
}
@Test
public void testUpdateOrderUpdatesOrderDetailsCorrectly()
{
sys.createOrder(5); //Create initial order
sys.updateOrder("BRICK1", 100); //Update order with matching reference number
BrickOrder o = sys.getOrder("BRICK1"); //Pull order information from db
assertEquals(o.getNumberOfBricks(), 100); //Ensure order details have been updated.
}
@Test
public void testUpdateOrderHandlesInvalidReferenceNumber()
{
sys.createOrder(5); //Create initial order
assertEquals(sys.updateOrder("ROCK1", 100), "No order with reference number ROCK1 in database."); //Update order with matching reference number
}
}
</code></pre>
<p>OrderDB.java</p>
<pre><code>package core;
import java.util.ArrayList;
/*
* OrderDB class stores all of the orders created by OrderSystem
* within an ArrayList<BrickOrder> variable. The stored ArrayList
* can be returned to OrderSystem at any time for updating and
* information extraction.
*/
public class OrderDB {
private ArrayList<BrickOrder> database;
public OrderDB()
{
database = new ArrayList<BrickOrder>();
}
/*
* Returns the order that corresponds to the reference number passed.
*
* Correct order is found by iterating through DB entries and
* comparing refNum to reference number stored in orders. Once
* match is found, the order is returned.
*/
public BrickOrder getOrder(String refNum)
{
for(BrickOrder o : database)
{
if(refNum.equals(o.getReferenceNumber()))
return o;
}
return null;
}
/*
* Adds a passed order into the db arraylist.
*/
public void addOrder(BrickOrder o)
{
database.add(o);
}
/*
* Removes an order that matches the passed reference number
* from the order db.
*/
public void removeOrder(String refNum)
{
try
{
int index = -1;
for(BrickOrder o : database) //Iterate through the whole database
{
if(refNum.equals(o.getReferenceNumber()))
index = database.indexOf(o); //Save index of matched order - Prevents concurrency exception
}
database.remove(index);
System.out.println("Order with reference number " + refNum + " removed.");
}
catch(IndexOutOfBoundsException e) //Catch exception when no matching order found
{
System.out.println("No order with reference number: " + refNum + ".");
}
}
public ArrayList<BrickOrder> getOrderList()
{
return database;
}
public void clearDb()
{
database.clear();
System.out.println("DB cleared");
}
}
</code></pre>
<p>OrderDBTest.java</p>
<pre><code>package test;
import static org.junit.Assert.*;
import org.junit.Before;
import org.junit.Test;
import core.BrickOrder;
import core.OrderDB;
import core.OrderSystem;
public class OrderDBTest {
private OrderSystem sys;
@Before
public void setup()
{
System.out.println("\nSetup");
sys = new OrderSystem();
sys.getDb().clearDb();
}
@Test
public void testOrderDatabaseAddsOrdersCorrectly()
{
System.out.println("testOrderDatabaseAddsOrders");
sys.getDb().clearDb();
sys.createOrder(25);
assertEquals(sys.getDb().getOrderList().size(), 1);
sys.createOrder(30);
assertEquals(sys.getDb().getOrderList().size(), 2);
sys.createOrder(35);
assertEquals(sys.getDb().getOrderList().size(), 3);
}
@Test
public void testOrderDatabaseRemovesOrdersCorrectly()
{
System.out.println("testOrderDatabaseRemovesOrdersCorrectly");
sys.createOrder(25);
assertEquals(sys.getDb().getOrderList().size(), 1);
sys.removeOrder("BRICK1");
assertEquals(sys.getDb().getOrderList().size(), 0);
}
@Test
public void testOrderDatabaseReturnsOrdersCorrectly()
{
System.out.println("testOrderDatabaseReturnsOrdersCorrectly");
sys.createOrder(25);
BrickOrder o = sys.getOrder("BRICK1");
assertEquals(o.getNumberOfBricks(), 25);
}
}
</code></pre>
<p>BrickOrder.java</p>
<pre><code>package core;
/*
* Implementation of BrickOrder class, implements Order interface.
*
* BrickOrder class allows storage of reference number and number
* of brings per each order. One BrickOrder class is instantiated
* for each order.
*/
public class BrickOrder implements Order{
private String referenceNumber;
private int numberOfBricks;
public BrickOrder(String refNum, int brickNum)
{
setReferenceNumber(refNum);
setNumberOfBricks(brickNum);
}
public String getReferenceNumber()
{
return referenceNumber;
}
public int getNumberOfBricks()
{
return numberOfBricks;
}
public void setReferenceNumber(String refNum)
{
referenceNumber = refNum;
}
public void setNumberOfBricks(int brickNum)
{
numberOfBricks = brickNum;
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-07T19:03:43.477",
"Id": "381888",
"Score": "0",
"body": "I've embedded the code in the thread."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-07T19:49:30.433",
"Id": "381889",
"Score": "0",
"bo... | [
{
"body": "<h3>Encapsulation and protecting your data</h3>\n\n<p><code>OrderDB</code> is not encapsulated well.\nThe <code>getOrderList</code> method exposes the internal data structure of the class.\nThis is especially bad because users of <code>OrderSystem</code> have access to it too, through the <code>getOr... | {
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-07T18:15:58.963",
"Id": "198028",
"Score": "5",
"Tags": [
"java",
"interview-questions"
],
"Title": "Implementing an order system for a job interview"
} | 198028 |
<p>The code below is a quick, working example of a compound interest table I wrote. My concern is mainly about separating the application data/logic from the UI code. I didn't use any frameworks on purpose, just because this is an exercise.</p>
<p><strong>Here's the code</strong> </p>
<p><div class="snippet" data-lang="js" data-hide="true" data-console="true" data-babel="false">
<div class="snippet-code snippet-currently-hidden">
<pre class="snippet-code-js lang-js prettyprint-override"><code>(function() {
"use strict";
function clearContents(tag) {
while (tag.firstChild) {
tag.removeChild(tag.firstChild);
}
}
function addValueToRow(rowTag, value) {
var newValue = document.createElement("td");
newValue.appendChild(document.createTextNode(value));
rowTag.appendChild(newValue);
}
function formatMoney(value) {
return value.toFixed(2).toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}
function main() {
var inputBoxes = document.getElementsByTagName("input");
var table = document.getElementById("results");
var monthlyContributionInput = document.getElementById("monthly-contribution");
var numberOfYearsInput = document.getElementById("year-count");
var annualInterestRateInput = document.getElementById("annual-interest-rate");
var updateTable = function(event) {
var rowcount = Number(numberOfYearsInput.value);
var monthlyContribution = Number(monthlyContributionInput.value);
var annualInterestRate = Number(annualInterestRateInput.value) / 100.0;
var interestFactor = 1 + annualInterestRate / 12.0;
var balance = 0;
var totalDeposit = 0;
var monthCount = 0;
var yearInterest = 0;
var perviousYearInterest = 0;
clearContents(table);
for (var row = 1; row <= rowcount; row += 1) {
var newRow = document.createElement("tr");
monthCount = 12 * row;
totalDeposit = 12.0 * monthlyContribution * row;
balance = monthlyContribution * (
(Math.pow(interestFactor, monthCount + 1) - 1) /
(interestFactor - 1) - 1);
perviousYearInterest = yearInterest;
yearInterest = balance - totalDeposit;
addValueToRow(newRow, "" + row);
addValueToRow(newRow, formatMoney(monthlyContribution * 12.0));
addValueToRow(newRow, formatMoney(yearInterest - perviousYearInterest));
addValueToRow(newRow, formatMoney(totalDeposit));
addValueToRow(newRow, formatMoney(balance - totalDeposit));
addValueToRow(newRow, formatMoney(balance));
table.appendChild(newRow);
}
};
for (var i = 0; i < inputBoxes.length; i += 1) {
inputBoxes[i].oninput = updateTable;
}
}
window.addEventListener("load", main, false);
})();</code></pre>
<pre class="snippet-code-css lang-css prettyprint-override"><code>:root {
--system-font-stack: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Oxygen-Sans, Ubuntu, Cantarell, "Helvetica Neue", sans-serif;
}
body {
font-family: var(--system-font-stack);
margin: 0;
padding: 1.5rem;
}
#user-inputs>div {
display: flex;
flex-direction: column;
margin-bottom: 0.75rem;
}
#user-inputs label {
margin-bottom: 0.25rem;
}
#user-inputs input {
width: 15rem;
}
#interest-table,
#interest-table thead,
#interest-table tr {
width: 100%;
}
#interest-table>thead>tr>td {
font-weight: bold;
}
#interest-table td {
font-size: 12px;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>
<head>
<title>Compound Interest Calculator</title>
</head>
<body>
<h1>Compound Interest Calculactor</h1>
<div id="user-inputs">
<div>
<label for="monthly-contribution">Monthly Contribution</label>
<input type="text" id="monthly-contribution" />
</div>
<div>
<label for="annual-interest-rate">Annual Interest Rate (%)</label>
<input type="text" id="annual-interest-rate" />
</div>
<div>
<label for="year-count">Number of Years</label>
<input type="text" id="year-count" />
</div>
<table id="interest-table">
<thead>
<tr>
<td>Year</td>
<td>Year Deposit</td>
<td>Year Interest</td>
<td>Total Deposit</td>
<td>Total Interest</td>
<td>Balance</td>
</tr>
</thead>
<tbody id="results">
</tbody>
</table>
<script src="_scripts/compound-interest.js"></script>
</body>
</html></code></pre>
</div>
</div>
</p>
| [] | [
{
"body": "<h2>A few notes:</h2>\n\n<ul>\n<li>The function <code>clearContents(tag)</code> can be simplified to <code>tag.innerHTML = ''</code></li>\n<li>You probably shouldn't be naming your function <code>main</code>, as it doesn't describe what it does.</li>\n<li>You should use <strong><code>const</code></st... | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-07T18:40:55.697",
"Id": "198030",
"Score": "6",
"Tags": [
"javascript",
"calculator"
],
"Title": "Compound Interest Calculator in HTML/JS"
} | 198030 |
<p>Among the mod-tools there is a few that are intended to just help get a bird's eye perspective on what happens on the site. These tools generally consist of tables. Tables over tables.</p>
<p>Stuff that would make an executive business analyst happy.</p>
<p>One of these tools reports some quite useful numbers as both absolute numbers and percentages. These percentages are pretty useful, but each of them is in a separate column.</p>
<p>The table columns <em>basically</em> follow this schema:</p>
<ul>
<li>User</li>
<li>Metric A</li>
<li>Metric B</li>
<li>...</li>
<li>Metric F</li>
<li>Metric A%</li>
<li>Metric B%</li>
<li>...</li>
<li>Metric F%</li>
<li>Metric G</li>
<li>Metric H</li>
<li>...</li>
</ul>
<p>Not every metric has a corresponding percentage report. None of the percentage reports comes before its corresponding metric. Unfortunately there's a rather large number of these metrics, which results in the table exceeding the horizontal space available on my screen most of the time.</p>
<p>That's not useful, and neither is the separation between the Metrics and their percentage report. So I wrote the following user-script to collapse the percentage reports into the same column as the absolute numbers.</p>
<pre><code>// ==UserScript==
// @name Advanced Review Stats TableCollapser
// @namespace http://github.com/Vogel612
// @version 1.0
// @description Collapse review-stats columns
// @updateURL https://raw.githubusercontent.com/Vogel612/mini-se-userscripts/master/advanced-review-stats-collapser.user.js
// @downloadURL https://raw.githubusercontent.com/Vogel612/mini-se-userscripts/master/advanced-review-stats-collapser.user.js
// @author Vogel612
// @match *://*.stackexchange.com/admin/review/breakdown*
// @match *://*.stackoverflow.com/admin/review/breakdown*
// @match *://*.superuser.com/admin/review/breakdown*
// @match *://*.serverfault.com/admin/review/breakdown*
// @match *://*.askubuntu.com/admin/review/breakdown*
// @match *://*.stackapps.com/admin/review/breakdown*
// @match *://*.mathoverflow.net/admin/review/breakdown*
// @grant none
// ==/UserScript==
(function() {
'use strict';
let statsTable = document.querySelectorAll("#content .mainbar-full table")[0];
let headers = Array.from(statsTable.getElementsByTagName("th"));
let percentageHeaders = filterHeaders(headers);
let collapsings = buildCollapseSpecs(headers, percentageHeaders);
collapseTable(statsTable, collapsings);
function filterHeaders(headers) {
let percentageHeaders = [];
for (let head of headers) {
if (head.innerHTML.endsWith("%")) {
percentageHeaders.push(head);
}
}
return percentageHeaders;
}
function buildCollapseSpecs(headers, percentageHeaders) {
let collapsings = [];
for (let percentage of percentageHeaders) {
let h = percentage.innerHTML;
// drop trailing %
let header = h.substr(0, h.length - 1);
let from = headers.indexOf(percentage);
// find matching non-percentage header
var to = -1;
for (let tableHead of headers) {
if (tableHead.innerHTML === header) {
to = headers.indexOf(tableHead);
break;
}
}
// we can't collapse upwards
if (to !== -1 && to <= from) {
collapsings.push({from: from, to: to});
}
}
return collapsings;
}
function collapseTable(table, collapsings) {
// sort collapsings by from descending to allow us to drop the column we're done with
collapsings.sort((a,b) => { return b.from - a.from });
// collapse the columns
for (let collapse of collapsings) {
for (let row of table.getElementsByTagName("tr")) {
collapseRow(row, collapse);
}
}
}
function collapseRow(row, collapseSpec) {
let from = row.children[collapseSpec.from];
let percentageValue = from.innerHTML.trim();
if (from.tagName === "TH") {
row.children[collapseSpec.to].innerHTML += " (%)";
} else {
row.children[collapseSpec.to].innerHTML += " (" + percentageValue + ")";
}
row.removeChild(from);
}
})();
</code></pre>
<p>How could this script be more extensible and maintainable?</p>
| [] | [
{
"body": "<h3>Algorithm</h3>\n\n<p>The algorithm to build the collapse-specs is inefficient:</p>\n\n<ol>\n<li>It makes a pass over all headers to find the percentage headers</li>\n<li>Then for each percentage header:\n\n<ol>\n<li>It finds the index using <code>Array.indexOf</code>, which is \\$O(n)\\$</li>\n<l... | {
"AcceptedAnswerId": "198038",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-07T19:14:24.293",
"Id": "198031",
"Score": "6",
"Tags": [
"javascript",
"stackexchange",
"userscript"
],
"Title": "Condensing a Table"
} | 198031 |
<p>I have this recursive generator that fetches 100 messages from an API and gets the next 100 until there are no more messages to get:</p>
<pre><code>async* fetchAllMessages(channel: Channel & TextBasedChannelFields, startingMessageId?: Snowflake) {
const results = await channel.fetchMessages(this.buildQueryLogOptions(startingMessageId));
const finalMessageIdFromBatch = results.lastKey();
if (!results) {
return;
}
if (!finalMessageIdFromBatch) {
return;
}
yield results;
yield* this.fetchAllMessages(channel, finalMessageIdFromBatch);
}
</code></pre>
<p>and I consume the generator like so:</p>
<pre><code>Async.parallelLimit(allTextChannels.map(channel => async function(callback) {
const messageGenerator = await this.fetchAllMessages(channel, undefined);
for ( ; ; ) {
const generatorResult = await messageGenerator.next();
if (generatorResult.done) {
break;
}
await this.logMessagesForChannelAndUser(channel, this.client.user.id, generatorResult.value);
}
console.log('finished channel: ', this.getNameForChannel(channel));
callback(undefined, true);
}.bind(this), 4, () => console.log('done'));
</code></pre>
<p>This works great for a majority of channels, but the recursive generator is really slamming the call stack for huge channels; node process is crashing with ELIFECYCLE 3221225725 (call stack overflow). I really like the recursive generator pattern because of its simplicity, but should I abandon it in this case? Or is there a better pattern out there for 'pausing' after a certain number of iterations and picking it back up with a new instantiation?</p>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-07T20:13:18.647",
"Id": "198034",
"Score": "1",
"Tags": [
"javascript",
"recursion",
"node.js",
"generator"
],
"Title": "Recursive Generator Exceeds Call Stack"
} | 198034 |
<p>My goal is to write very little code and I want a custom iterator that only changes the behavior of the dereference <code>operator*</code> but copies the rest of the behavior from the underlying container iterator.</p>
<p>The following code works <strong>but is it correct</strong>?</p>
<pre><code>#include <iostream>
#include <unordered_map>
using namespace std;
template <typename K, typename V>
class KeyValueStore
{
using base_iterator = typename unordered_map<K, V>::iterator;
public:
struct iterator : public base_iterator
{
iterator(base_iterator it) : base_iterator(it)
{ }
// The custom behavior for the dereference operator.
V& operator*()
{
return base_iterator::operator*().second;
}
};
V& get(const K& key)
{
return store.at(key);
}
void put(K key, V value)
{
store[key] = value;
}
iterator begin() { return iterator {store.begin()}; }
iterator end() { return iterator {store.end()}; }
private:
unordered_map<K, V> store;
};
int main()
{
KeyValueStore<string, int> store;
store.put("aa", 5);
store.put("vf", 4);
for (auto item : store)
cout << item << endl;
return 0;
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-07T20:40:16.390",
"Id": "381891",
"Score": "1",
"body": "Neither the title nor the description actually seem to have anything to do with what the code concretely does. Do you want to have the key-value scheme reviewed, or is this a gen... | [
{
"body": "<h1><a href=\"https://stackoverflow.com/questions/1452721\">Don’t</a> write <code>using namespace std;</code>.</h1>\n\n<hr>\n\n<p><a href=\"https://stackoverflow.com/questions/213907/c-stdendl-vs-n\">Prefer using <code>\\n</code> over <code>std::endl</code></a></p>\n\n<hr>\n\n<p>some of the functions... | {
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-07T20:25:29.157",
"Id": "198035",
"Score": "2",
"Tags": [
"c++",
"iterator"
],
"Title": "Implementing a custom iterator by inheriting from an existing iterator class and overriding operator*"
} | 198035 |
<p>I have been working on a small project intended for helping beginner Python programmers getting an idea of what a real project could be like (as opposed to programming exercises and such). </p>
<p>This application can create rudimentary user accounts and allow login with password verification. It doesn't do anything beyond that. The user data is stored in a JSON file. </p>
<p>I've written it to be as simple to understand as possible (without commenting each line), and have attempted to keep it to one instruction per line, whenever possible, so please keep that in mind when reviewing, that is done on purpose, I know the code could be made shorter by combining multiple instructions.</p>
<p>I'm interested in all improvements, but in particular, improvements to make the code easier to understand. </p>
<hr>
<p>Saved user records look like this in JSON file:</p>
<pre><code>[
{
"username": "test1",
"password": "$2b$12$2ksuZeBJsvvEhoTWIdbSReGp753Tb1/cNvlVC2gmjOHRkDeoenl2K",
"created": "2018-07-07 00:16:28.293901",
"active": true
},
{
"username": "test2",
"password": "$2b$12$n80DfPOxo4gIu504o/Yn6.CZCd1aa6s7YDhaFVB7ZJFJpogqIjRc6",
"created": "2018-07-07 00:28:07.315781",
"active": true
}
...
]
</code></pre>
<hr>
<h3>application.py</h3>
<p>This is the launching point, nothing to it, but included for completeness.</p>
<pre><code>from user_interface import *
if __name__ == '__main__':
main_menu()
</code></pre>
<hr>
<h3>encryption.py</h3>
<p>This is where I handle encrypting and checking passwords using <code>bcrypt</code>.</p>
<pre><code>import bcrypt
def encrypt_password(password: str) -> str:
"""
Encrypt a password with a randomly generated salt then a hash.
Cost rounds added to slow down the process in case of rainbow table/brute force attack.
:param password: The password to encrypt in clear text.
:return: The encrypted password as a unicode string.
"""
encoded_password = password.encode('utf8')
cost_rounds = 12
random_salt = bcrypt.gensalt(cost_rounds)
hashed_password = bcrypt.hashpw(encoded_password, random_salt).decode('utf8', 'strict')
return hashed_password
def check_password(password: str, password_hash: str) -> bool:
"""
Check a password against its encrypted hash for a match.
:param password: the password to check in clear text. (Unicode)
:param password_hash: The encrypted hash to check against. (Unicode)
:return: Whether the password and the hash match
"""
encoded_password = password.encode('utf8')
encoded_password_hash = password_hash.encode('utf8')
password_matches = bcrypt.checkpw(encoded_password, encoded_password_hash)
return password_matches
if __name__ == '__main__':
test_password = 'Password1'
hashed_test_password = encrypt_password(test_password)
print(f'hashed_password: {hashed_test_password}')
password_matches_hash = check_password(test_password, hashed_test_password)
print(f'password matches hash? {password_matches_hash}')
</code></pre>
<hr>
<h3>json_handling.py</h3>
<p>This module handles file operations, specifically on JSON files.</p>
<pre><code>import json
from pathlib import Path
from typing import List, Union
def create_file_if_not_exists(file_path: str) -> None:
"""
Checks if a file exists at the given path, and creates it if it doesn't.
:param file_path: the path of the file to check/create, which can be relative or absolute.
:return: None
"""
Path(file_path).touch()
def get_json_file_contents(file_path: str) -> Union[List, None]:
"""
Reads and return the contents of a JSON file.
:param file_path: The path where the JSON file is located.
:return: The contents of the file, or None if there if the file is empty or not found.
"""
try:
json_file = open(file_path)
except IOError:
return None
try:
file_contents = json.load(json_file)
except ValueError:
file_contents = None
json_file.close()
return file_contents
</code></pre>
<hr>
<h3>user_storage.py</h3>
<p>This module is responsible for various tasks specifically related to handling creating and retrieving user data from the JSON file.</p>
<pre><code>import datetime
from typing import Dict
from encryption import *
from json_handling import *
DEFAULT_FILE_PATH = 'data/users.json'
def prepare_new_user_data(username: str, password: str) -> Dict:
"""
Return user data ready for storage.
:param username: The username for this user.
:param password: The password for this user, in clear text.
:return: A Dict containing user data ready to store, including encrypted password.
"""
new_user = {
'username': username,
'password': encrypt_password(password),
'created': str(datetime.datetime.now()),
'active': True
}
return new_user
def check_if_user_already_exists(username: str, json_file_path: str=DEFAULT_FILE_PATH) -> bool:
"""
Queries a JSON file and returns whether it already exists.
:param username: The username to check for duplication.
:param json_file_path: The path where the JSON file is located.
:return: Whether the username already exists.
"""
all_users = get_json_file_contents(json_file_path)
if not all_users:
return False
for user in all_users:
if user['username'] == username:
return True
return False
def add_user(username: str, password: str, json_file_path: str=DEFAULT_FILE_PATH) -> None:
"""
Adds a user to a JSON file, unless it is a duplicate, in which case it raises a ValueError.
:param username: The username of the user to add.
:param password: The password of the user to add, in clear text.
:param json_file_path: The path where the JSON file to add the user to is located.
:return: None
"""
create_file_if_not_exists(json_file_path)
is_duplicate_user = check_if_user_already_exists(username, json_file_path)
if is_duplicate_user:
raise ValueError(f'Username "{username}" already exists.')
new_user = prepare_new_user_data(username, password)
all_users = get_json_file_contents(json_file_path)
if not all_users:
all_users = []
all_users.append(new_user)
with open(json_file_path, 'w') as users_file:
json.dump(all_users, users_file, indent=2)
def retrieve_user(username: str, json_filepath: str=DEFAULT_FILE_PATH) -> Union[Dict, None]:
"""
Returns a single user record from the target JSON file.
:param username: the username to search for.
:param json_filepath: The path where the JSON file to retrieve the user from is located.
:return: The user record as a Dict, or None if it is not found.
"""
all_users = get_json_file_contents(json_filepath)
for user in all_users:
if user['username'] == username:
return user
return None
def authenticate_username_and_password(username: str, password: str) -> bool:
"""
Verify that the provided username and password match what is stored in the user data,
for authentication purposes.
:param username: The user's username.
:param password: The user's password, in clear text.
:return: Whether the authentication was successful.
"""
user = retrieve_user(username)
password_hash = user['password']
if not user:
return False
if not check_password(password, password_hash):
return False
return True
if __name__ == '__main__':
test_username = 'test1'
test_password = 'Password1'
print(prepare_new_user_data(test_username, test_password))
test_file_path = 'data/test_database.json'
create_file_if_not_exists(test_file_path)
add_user(test_username, test_password, test_file_path)
print(get_json_file_contents(test_file_path))
</code></pre>
<hr>
<h3>user_interface.py</h3>
<p>This module handles interaction between the application and the user, which is done right now through the console. </p>
<pre><code>import getpass
import re
from user_storage import *
def main_menu() -> None:
"""
Displays the main menu of the application.
:return: None
"""
menu = '\n'.join([
'Select an option by entering its number and pressing Enter.',
'1. Create a user account',
'2. Log in to existing account',
'---'
])
print(menu)
valid_selections = [1, 2]
input_is_valid = False
selection = None
while not input_is_valid:
try:
selection = int(input('Selection: '))
if selection in valid_selections:
input_is_valid = True
else:
print('The number you entered is not a valid selection.')
except ValueError:
print('The value you entered is not a number.')
handle_main_menu_selection(selection)
def handle_main_menu_selection(selection: int) -> None:
"""
Calls the function related to the selection the user made.
:param selection: The user's selection.
:return: None
"""
if selection == 1:
create_new_user_menu()
elif selection == 2:
user_login_menu()
else:
raise ValueError(f'Selection {selection} is invalid.')
def create_new_user_menu() -> None:
"""
Displays the account creation menu, including asking the user for username and password.
:return: None
"""
menu = '\n'.join([
'---',
'Account creation',
'Username must...',
'\t- be at least 3 characters long',
'\t- contain only letters, numbers, and underscores',
'Password must...',
'\t- be at least 8 characters long',
'---'
])
print(menu)
user_added_successfully = False
username = ''
while not user_added_successfully:
try:
username = get_username_input()
password = get_password_input()
user_added_successfully = try_adding_user(username, password)
if not user_added_successfully:
print(f'Username "{username}" already exists.')
except ValueError as error:
print(str(error))
def try_adding_user(username: str, password: str) -> bool:
"""
Attempts to add a user to the user database file.
:param username: The username provided by the user.
:param password: The password provided to the user, in clear text.
:return: Whether the user was added successfully.
"""
try:
add_user(username, password)
return True
except ValueError:
return False
def user_login_menu() -> None:
menu = '\n'.join([
'---',
'User login',
'---'
])
print(menu)
login_successful = False
while not login_successful:
username = get_username_input()
password = get_password_input()
login_successful = authenticate_username_and_password(username, password)
if not login_successful:
print('Incorrect username or password.')
print('Login successful.')
def get_username_input() -> str:
"""
Request username input from the user.
:return: The username entered by the user.
"""
minimum_length = 3
username = input('Enter username: ')
if len(username) < minimum_length:
raise ValueError('Username must be at least 3 characters.')
# match upper & lower case letters, numbers, and underscores
pattern = re.compile('^([a-zA-Z0-9_]+)$')
if not pattern.match(username):
raise ValueError('Username must consist of only letters, numbers, and underscores.')
return username
def get_password_input() -> str:
"""
Request password input from the user.
:return: The password entered by the user.
"""
minimum_length = 8
password = getpass.getpass('Enter password: ')
if len(password) < minimum_length:
raise ValueError('Password must be at least 8 characters.')
return password
if __name__ == '__main__':
main_menu()
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-08T05:56:54.507",
"Id": "381907",
"Score": "7",
"body": "(Not enough for an answer) Encrypt != Hash. I think it's important for anyone working with passwords to understand that as early as possible in the process."
},
{
"Conten... | [
{
"body": "<h3>Avoid wildcard imports</h3>\n\n<p><code>from ... import *</code> is not recommended.\nEspecially when there are imports from multiple packages,\nit makes it difficult to know where some symbol comes from.\nIf you find it tedious to spell out the package names when using functions,\nconsider impor... | {
"AcceptedAnswerId": "198043",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-07T21:49:09.280",
"Id": "198040",
"Score": "18",
"Tags": [
"python",
"beginner",
"python-3.x",
"json"
],
"Title": "User login database intended for beginners"
} | 198040 |
<p>First time posting here, let me apologize ahead of time if this is not the correct format.. Anyway, I am new to programming and I am working on a school assignment to design a vehicle inventory system in Python (assignment details below). The code seems to be working as it should. I am questioning the 'update vehicle' function I defined outside of the class, whether it would make more sense to change to a class method. Or any other feedback anyone has. Thanks.
Create a final program that meets the requirements outlined below.</p>
<p>Assignment:
Create an automobile class that will be used by a dealership as a vehicle inventory program. The following attributes should be present in your automobile class:</p>
<ul>
<li>private string make</li>
<li>private string model</li>
<li>private string color</li>
<li>private int year</li>
<li>private int mileage</li>
</ul>
<p>Your program should have appropriate methods such as:</p>
<ul>
<li>constructor</li>
<li>add a new vehicle</li>
<li>remove a vehicle</li>
<li>update vehicle attributes</li>
</ul>
<p>At the end of your program, it should allow the user to output all vehicle inventory to a text file.</p>
<pre><code>class Automobile:
def __init__(self):
self.make = " "
self.model = " "
self.color = " "
self.year = 0
self.mileage = 0
def add_vehicle(self):
self.year = int(input("Enter year: "))
self.make = input("Enter make: ")
self.model = input("Enter model: ")
self.color = input("Enter color: ")
self.mileage = int(input("Enter mileage: "))
def __str__(self):
return('%d %s %s Color: %s Mileage: %d' %
(self.year, self.make, self.model, self. color,
self.mileage))
vehicle_list = []
def edit(vehicle_list):
pos = int(input('Enter the position of the vehicle to edit: '))
new_vehicle = car.add_vehicle()
new_vehicle = car.__str__()
vehicle_list[pos-1] = new_vehicle
print('Vehicle was updated')
user=True
while user:
print ("""
1.Add a Vehicle
2.Delete a Vehicle
3.View Inventory
4.Update Inventory
5.Export Inventory
6.Quit
""")
ans=input("What would you like to do? ")
if ans=="1":
car = Automobile()
car.add_vehicle()
vehicle_list.append(car.__str__())
elif ans=="2":
for i in vehicle_list:
vehicle_list.pop(int(input('Enter position of vehicle to remove: ')))
print('Successfully removed vehicle')
elif ans=="3":
print(vehicle_list)
elif ans=="4":
edit(vehicle_list)
elif ans=='5':
f = open('vehicle_inv.txt', 'w')
f.write(str(vehicle_list))
f.close()
else:
print('try again')
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-07T22:43:26.703",
"Id": "381894",
"Score": "0",
"body": "Welcome to Code Review! I hope you get great answers."
}
] | [
{
"body": "<ol>\n<li>The assignment mentions <em>private</em> fields. In Python those are created (<a href=\"https://stackoverflow.com/a/2064212/96588\">faked</a>, really) by prefixing the field with two underscores, as in <code>__make</code>.</li>\n<li>Interactive command line programs are a scourge, because t... | {
"AcceptedAnswerId": "198044",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-07T21:58:00.440",
"Id": "198041",
"Score": "2",
"Tags": [
"python",
"python-3.x",
"homework"
],
"Title": "Vehicle inventory program"
} | 198041 |
<p>I have a background in Linguistics and my journey as an aspiring developer has just begun. </p>
<p>I was hoping you could give me a feedback on the solution I have come up with for <a href="https://projecteuler.net/problem=2" rel="nofollow noreferrer">the second challenge of Project Euler</a>, and maybe explain me why many of the other solutions I have come across were wrapped inside a single function.</p>
<blockquote>
<p>Each new term in the Fibonacci sequence is generated by adding the
previous two terms. By starting with 1 and 2, the first 10 terms will
be:</p>
<p>1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...</p>
<p>By considering the terms in the Fibonacci sequence whose values do not
exceed four million, find the sum of the even-valued terms.</p>
</blockquote>
<pre><code>let fibSequence = [0, 1];
let result = 0;
function fibonacci(array) {
return array[array.length - 1] + array[array.length - 2];
}
while(fibSequence[fibSequence.length - 1] < 4e+6) {
fibSequence.push(fibonacci(fibSequence));
}
fibSequence.forEach(function (number) {
if(number % 2 === 0) {
result += number;
}
});
console.log(result);
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-08T00:19:37.973",
"Id": "381898",
"Score": "3",
"body": "Welcome to Code Review! I hope you get some great answers."
}
] | [
{
"body": "<p>Your code looks great! A couple suggestions, though:</p>\n\n<ol>\n<li>I would recommend either:<br>\nA. Putting the code you put in the <code>forEach</code> directly in the <code>while</code> loop.<br>\nB. Changing the <code>forEach</code> to a combination of <code>filter</code> and <code>sum</cod... | {
"AcceptedAnswerId": "198050",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-07T23:27:53.853",
"Id": "198046",
"Score": "5",
"Tags": [
"javascript",
"programming-challenge",
"fibonacci-sequence"
],
"Title": "Project Euler #2 with a fibSequence and result"
} | 198046 |
<p>I have just started learning Python. This is code for a TicTacToe game. Can you please suggest any improvements?</p>
<pre><code>pos_matrix=[[' ',' ',' '],[' ',' ',' '],[' ',' ',' ']]
def my_tictactoe(pos,symbol):
if pos_matrix[pos[0]-1][pos[1]-1]!=' ':
print('Invalid input')
exit
else:
pos_matrix[pos[0]-1][pos[1]-1]=symbol
for i in range(0,3):
print(pos_matrix[i][0]+' | '+pos_matrix[i][1]+' | '+pos_matrix[i][2])
print('--|---|--')
if is_win():
print('GAME OVER. \n Player with symbol {x} wins!'.format(x=pos_matrix[pos[0]-1][pos[1]-1]))
for i in [0,1,2]:
pos_matrix[i][0]=pos_matrix[i][1]=pos_matrix[i][2]=' '
def is_win():
for i in [0,1,2]:
if pos_matrix[i][0]==pos_matrix[i][1]==pos_matrix[i][2]!=' ':
return True
elif pos_matrix[0][i]==pos_matrix[1][i]==pos_matrix[2][i]!=' ':
return True
if pos_matrix[0][0]==pos_matrix[1][1]==pos_matrix[2][2]!=' ':
return True
elif pos_matrix[0][2]==pos_matrix[1][1]==pos_matrix[2][0]!=' ':
return True
else:
return False
my_tictactoe((1,1),'o')
my_tictactoe((2,2),'x')
my_tictactoe((3,2),'o')
my_tictactoe((1,3),'x')
my_tictactoe((2,1),'o')
my_tictactoe((3,3),'x')
my_tictactoe((3,1),'o')
my_tictactoe((1,2),'x')
</code></pre>
| [] | [
{
"body": "<p>What if someone tries <code>my_tictactoe((1,2),'p')?</code></p>\n\n<p>In addition, a python thing: You can have a main function to turn this into a module of sorts.</p>\n\n<p>At the end of the file, you would add:</p>\n\n<pre><code>def main():\n #test game here\n\n\nif __name__ == \"__main__\":... | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-08T03:35:52.587",
"Id": "198053",
"Score": "3",
"Tags": [
"python",
"python-3.x",
"tic-tac-toe"
],
"Title": "TicTacToe in Python 3"
} | 198053 |
<p>I have an application using tkinter where different actions are required on mouse click, double click and when the mouse is being moved. The following class works however I wonder if there is no easier- or tkinter builtin way of doing this?</p>
<pre><code>from tkinter import Tk, Canvas
class MouseControl:
''' Class for mouse control to establish if there is a 'click',
'double click' or mouse is being moved '''
def __init__(self, aw):
self.double_click_flag = False
self.button_released_flag = False
self.aw = aw
self.aw.bind('<Button-1>', self.clicked) # bind left mouse click
self.aw.bind('<Double-1>', self.double_click) # bind double left clicks
self.aw.bind('<ButtonRelease-1>', self.button_released) # bind button release
self.aw.bind('<B1-Motion>', self.moved) # bring when mouse is moved
def clicked(self, event):
''' add a little delay before calling action to allow for double click
and button released to have occurred '''
self.double_click_flag, self.button_released_flag = False, False
self.aw.after(300, self.action, event)
def double_click(self, event):
''' set flag when there is a double click '''
self.double_click_flag = True
def button_released(self, event):
''' set flag when button is released '''
self.button_released_flag = True
def moved(self, event):
''' define action on when mouse is moved in this case just printing
the coordinates'''
print('mouse position is at ({:03}. {:03})'.
format(event.x, event.y), end='\r')
def action(self, event):
''' define action on click and double click in this case just printing
the event '''
if self.button_released_flag:
if self.double_click_flag:
print('double mouse click event')
else:
print('single mouse click event')
root = Tk()
window = Canvas(root, width=400, height=400, bg='grey')
mouse = MouseControl(window)
window.place(x=0, y=0)
window.mainloop()
</code></pre>
| [] | [
{
"body": "<h2>Avoid wildcard imports</h2>\n\n<p>You should use import <code>tkinter as tk instead</code> of <code>from tkinter import Tk, Canvas</code>. This is a <a href=\"https://www.python.org/dev/peps/pep-0008/?#imports\" rel=\"nofollow noreferrer\">PEP8</a> recommendation where you can find the reason of ... | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-08T05:25:20.510",
"Id": "198056",
"Score": "3",
"Tags": [
"python",
"python-3.x",
"tkinter"
],
"Title": "On click, doubleclick and mouse moving"
} | 198056 |
<p>I came up with this code as a solution to a contest question. The original question can be viewed here for attribution sake: <a href="https://www.hackerrank.com/challenges/30-2d-arrays/problem" rel="nofollow noreferrer">Hackerrank 2d array problem</a></p>
<p>Sample input is like this:</p>
<pre><code>1 1 1 0 0 0
0 1 0 0 0 0
1 1 1 0 0 0
0 0 2 4 4 0
0 0 0 2 0 0
0 0 1 2 4 0
</code></pre>
<p>Sample output is like this:</p>
<pre><code>19
</code></pre>
<p>My actual code input from the submission website is as follows:</p>
<pre><code>import math
import os
import random
import re
import sys
if __name__ == "__main__":
arr = []
for _ in range(6):
arr.append(list(map(int, input().rstrip().split())))
total = 0
max_total = -1073741824
for i in range(len(arr)):
for j in range(len(arr[i])):
if (j+2 < 6) and (i+2 < 6):
total = arr[i][j] + arr[i][j+1] + arr[i][j+2]+arr[i+1][j+1]+arr[i+2][j]+arr[i+2][j+1]+arr[i+2][j+2]
if max_total < total:
max_total = total
print(max_total)
</code></pre>
<p>There were several code listings on a different StackOverflow posting <a href="https://stackoverflow.com/questions/38019861/hourglass-sum-in-2d-array">C++/Ruby solutions to 2d array problem</a>. Being an absolute beginner in Python, I am still coming up to speed with advanced concepts in Python so my solution presented here is "un-Pythonic" and am sure not at all times optimized. How can I rewrite this code to be more "Pythonic"? I understand list comprehensions, but how can they be applied to multi-dimensional arrays like this case? Also, would rewriting the code to be Pythonic actually optimize the solution?</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-08T17:05:32.173",
"Id": "381957",
"Score": "5",
"body": "Please add a description of the problem to your post, not only a link to the problem."
}
] | [
{
"body": "<p>Your main algorithm is fine, and the logic cannot be further optimized.\nYou can eliminate an unnecessary condition by reducing the ranges:</p>\n\n<pre><code>for i in range(len(arr) - 2):\n for j in range(len(arr[i]) - 2):\n total = arr[i][j] + arr[i][j+1] + arr[i][j+2] + arr[i+1][j+1] +... | {
"AcceptedAnswerId": "198063",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-08T05:43:29.863",
"Id": "198059",
"Score": "6",
"Tags": [
"python",
"python-3.x",
"programming-challenge",
"array"
],
"Title": "Hacker rank 30 days of code Maximum Sum of Hourglass"
} | 198059 |
<p>I'm writing a command line app in node.js. At this stage, the app does the following:</p>
<ol>
<li>Get the version from <code>package.json</code></li>
<li>Update the package.json with a new version depending on the command line argument</li>
<li>Commit the changes</li>
<li>Tag the commit</li>
<li>Push commits and tags to the remote</li>
</ol>
<p>Some comments:</p>
<ul>
<li>I'm really new to async/await and promises so I may be using those incorrectly in my code.</li>
<li>A lot of my code is wrapped in <code>try-catch</code> blocks which I understand is not supposed to be the case with async/await or Promises. I'm not sure how to fix this.</li>
<li>There's a lot of duplication with the spinner initialisation code. I am aware the <a href="https://www.npmjs.com/package/ora" rel="nofollow noreferrer"><code>ora</code></a> has an <code>ora.promise</code> method as well. I couldn't get this to work.</li>
<li>Another example of duplication is with the <code>process.exit(1)</code> line within each <code>catch</code> block. Is this really needed or are there better ways to achieve this?</li>
<li>Do I really need to use the async IIFE at the end or is there a better way to do this?</li>
<li>I would also like feedback on whether I've divided my code into functions adequately.</li>
<li>I haven't added much error checking yet. For example, later, I'd like to check if a <code>package.json</code> exists, and if it doesn't, get the current version from git tags. How can I structure my code in such a way that I can easily add such functionality in the future?</li>
</ul>
<p>Any other feedback is also welcome. If you can address even some of the above, I would appreciate it.</p>
<p>Usage: </p>
<pre><code>ship <major|premajor|minor|preminor|patch|prepatch|prerelease>
</code></pre>
<p>(I named the script <code>index.js</code>, and created a symbolic link <code>ship</code> to it in <code>/usr/local/bin</code>)</p>
<pre><code>#!/usr/bin/env node
'use strict';
const fs = require('fs');
const semver = require('semver');
const readPkg = require('read-pkg');
const writePkg = require('write-pkg');
const git = require('simple-git/promise')(process.cwd());
const ora = require('ora');
const chalk = require('chalk');
const env = process.env;
const validArgs = [
'major', 'premajor', 'minor', 'preminor', 'patch', 'prepatch', 'prerelease'
];
const argv = require('yargs').argv;
const arg = argv._[0];
let spinner;
if (arg === undefined) {
console.error(chalk.red(`Missing argument.`));
console.error(chalk.red(`Should be one of ${validArgs.join(', ')}.`));
process.exit(1);
}
if (!validArgs.includes(arg)) {
console.error(chalk.red(`Invalid argument ${arg}`));
process.exit(1);
}
async function nextVersion() {
let current;
try {
const data = await readPkg();
current = data.version;
} catch(err) {
process.exit(1);
// todo: get version from git tags
}
return semver.inc(current, arg);
}
async function updatePkg(version) {
spinner = ora('Writing package.json').start();
try {
const data = await readPkg();
delete data._id;
data.version = version;
await writePkg(data);
spinner.succeed();
} catch (err) {
spinner.fail();
process.exit(1);
}
}
async function commit(msg) {
spinner = ora('Commiting changes').start();
try {
await git.add('package.json');
await git.commit(msg);
spinner.succeed();
} catch (err) {
spinner.fail();
process.exit(1);
}
}
async function makeTags(name) {
spinner = ora('Adding tag').start();
try {
await git.addTag(name);
spinner.succeed();
} catch (err) {
spinner.fail();
process.exit(1);
}
}
async function push() {
spinner = ora('Pushing changes').start();
try {
// both of these may run together
await git.push();
await git.pushTags();
spinner.succeed();
} catch (err) {
spinner.fail();
process.exit(1);
}
}
(async () => {
const next = await nextVersion();
console.log(); // gap between input and spinners
await updatePkg(next);
await commit(next);
await makeTags(next);
await push();
})();
</code></pre>
| [] | [
{
"body": "<p><em>(Disclaimer: I'm not a JavaScript expert and I don't have much experience with async/await either, so take my advices with a grain of salt. I hope you will find it helpful anyway.)</em></p>\n\n<h3>Running async calls in parallel</h3>\n\n<p>If you assume these will run in parallel, they won't:<... | {
"AcceptedAnswerId": "198069",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-08T08:44:29.790",
"Id": "198066",
"Score": "4",
"Tags": [
"javascript",
"node.js",
"console",
"async-await"
],
"Title": "CLI to bump package.json version and add git tags"
} | 198066 |
<p>I've written a small script, which calculates hours since the birth. I ask use about how old they are in years, months and day. I show them approximately how many hours they have lived. Below is the code.</p>
<p>Please tell me how can I improve it, in terms of algorithms, time/date calculation, UX, and python best practices.</p>
<pre><code>#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
File: ageinhours.py
Author: Santosh Kumar
Github: @santosh
Description: Calculate age in hours.
"""
import sys
try:
from PySide import QtGui, QtCore
except ModuleNotFoundError:
from PySide2.QtWidgets import QtGui
from PySide2 import QtCore
class AgeInHours(QtGui.QMainWindow):
"""The main window of AgeInHours"""
def __init__(self):
super(self.__class__, self).__init__()
self.setWindowTitle("Age in Hours")
self.setGeometry(200, 200, 350, 150)
# self.setWindowIcon(QtGui.QIcon("favicon.png"))
self.initUi()
def initUi(self):
self.centralWidget = QtGui.QWidget(self)
lyt_central = QtGui.QVBoxLayout(self.centralWidget)
lbl_instructions = QtGui.QLabel("How much time has passed \
since your birth?")
lyt_year = QtGui.QHBoxLayout()
lbl_year = QtGui.QLabel("Year: ")
self.slr_year = QtGui.QSlider(QtCore.Qt.Horizontal)
self.slr_year.setMinimum(0)
self.slr_year.setMaximum(25)
self.slr_year.setValue(21)
self.slr_year.setTickPosition(QtGui.QSlider.TicksBelow)
self.slr_year.setTickInterval(1)
self.slr_year.valueChanged.connect(self.year_change)
self.slr_year.valueChanged.connect(self.calculate_hours)
self.led_year = QtGui.QLineEdit()
self.led_year.returnPressed.connect(
lambda: self.slr_year.setValue(int(self.led_year.text())))
self.led_year.setFixedWidth(55)
lyt_year.addWidget(lbl_year)
lyt_year.addWidget(self.slr_year)
lyt_year.addWidget(self.led_year)
lyt_month = QtGui.QHBoxLayout()
lbl_month = QtGui.QLabel("Month: ")
self.slr_month = QtGui.QSlider(QtCore.Qt.Horizontal)
self.slr_month.setMinimum(0)
self.slr_month.setMaximum(12)
self.slr_month.setValue(8)
self.slr_month.setTickPosition(QtGui.QSlider.TicksBelow)
self.slr_month.setTickInterval(1)
self.slr_month.valueChanged.connect(self.month_change)
self.slr_month.valueChanged.connect(self.calculate_hours)
self.led_month = QtGui.QLineEdit()
self.led_month.returnPressed.connect(
lambda: self.slr_month.setValue(int(self.led_month.text())))
self.led_month.setFixedWidth(55)
lyt_month.addWidget(lbl_month)
lyt_month.addWidget(self.slr_month)
lyt_month.addWidget(self.led_month)
lyt_day = QtGui.QHBoxLayout()
lbl_day = QtGui.QLabel("Day: ") # extra spaces to match alignment
self.slr_day = QtGui.QSlider(QtCore.Qt.Horizontal)
self.slr_day.setMinimum(0)
self.slr_day.setMaximum(31)
self.slr_day.setValue(7)
self.slr_day.setTickPosition(QtGui.QSlider.TicksBelow)
self.slr_day.setTickInterval(1)
self.slr_day.valueChanged.connect(self.day_change)
self.slr_day.valueChanged.connect(self.calculate_hours)
self.led_day = QtGui.QLineEdit()
self.led_day.returnPressed.connect(
lambda: self.slr_day.setValue(int(self.led_day.text())))
self.led_day.setFixedWidth(55)
lyt_day.addWidget(lbl_day)
lyt_day.addWidget(self.slr_day)
lyt_day.addWidget(self.led_day)
lyt_output = QtGui.QHBoxLayout()
lbl_output = QtGui.QLabel("Your age in hours is approximately: ")
self.lbl_output_data = QtGui.QLabel()
lyt_output.addWidget(lbl_output)
lyt_output.addWidget(self.lbl_output_data)
lyt_central.addWidget(lbl_instructions)
lyt_central.addLayout(lyt_year)
lyt_central.addLayout(lyt_month)
lyt_central.addLayout(lyt_day)
lyt_central.addLayout(lyt_output)
self.setCentralWidget(self.centralWidget)
def year_change(self, value):
self.led_year.setText(str(value))
def month_change(self, value):
self.led_month.setText(str(value))
def day_change(self, value):
self.led_day.setText(str(value))
def calculate_hours(self):
"""Get years, months and days and update the age."""
year = int(self.slr_year.value())
month = int(self.slr_month.value())
day = int(self.slr_day.value())
final_output = (year * 365.25 * 24) + (month * 30 * 24) + (day * 24)
self.lbl_output_data.setText(str(final_output))
def keyPressEvent(self, e):
"""Response to keypresses."""
if e.key() == QtCore.Qt.Key_Escape:
self.close()
if __name__ == "__main__":
app = QtGui.QApplication(sys.argv)
w = AgeInHours()
w.show()
sys.exit(app.exec_())
</code></pre>
| [] | [
{
"body": "<p>It looks like you're manually trying to calculate the amount of hours since birth, which will be difficult because of leap years and the general difficulty of working with dates. I would recommend using the <code>datetime</code> module instead:</p>\n\n<pre><code>from datetime import datetime\ncurr... | {
"AcceptedAnswerId": "198166",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-08T13:28:17.960",
"Id": "198075",
"Score": "4",
"Tags": [
"python",
"datetime",
"calculator",
"qt"
],
"Title": "Age in hours calculator"
} | 198075 |
<p>I'm currently creating my own microframework for learning purpose and I want to make it more powerful by providing a way to register classes and instantiate them (once) only when needed. So here is my try :</p>
<pre><code><?php
namespace Framework\Core;
use Exception;
use ReflectionClass;
/**
* Class Container
*
* @package App\Core
*
* Depandancies injection and lazy loading, I guess ? (not sure how to call it for now)
*
*/
class Container
{
/**
* @var array Contains all classes instance.
*/
private static $instances = array();
/**
* @var array Contains all fully qualified classes name.
*/
private static $classes = array();
/**
* @var string Should contain the name of the last registered class name.
*/
private static $lastRegistered;
/**
* Container constructor.
*/
private function __construct() {}
/**
* Prevents cloning.
*/
private function __clone() {}
/**
* Prevents deserialization.
*/
private function __wakeup() {}
/**
* Gets a class instance.
*
* @param $name
* @param null $renew
* @return mixed
* @throws Exception
*/
public static function get($name = NULL) {
$name = (!$name) ? self::$lastRegistered : $name;
if (self::$classes[$name]) {
if (self::$instances[$name]) {
return self::$instances[$name];
} else {
self::$instances[$name] = new self::$classes[$name];
return self::$instances[$name];
}
} else {
throw new Exception('The following class name could not be found: ' . $name);
}
}
/**
* Registers a class.
*
* @param $name
* @param $class
* @return $this|null
* @throws Exception
*/
public static function register($name, $class) {
$reflection = new ReflectionClass($class);
if (!$reflection->isInstantiable()) {
throw new Exception('The provided class is not instantiable: ' . $class);
}
if (!in_array($name, self::$classes)) {
self::$classes[$name] = $class;
}
self::$lastRegistered = $name;
return __CLASS__;
}
/**
* Returns an array of all registered classes.
*
* @return array
*/
public static function getRegisteredClasses() {
return self::$classes;
}
/**
* Returns an array of all instantiated classes.
*
* @return array
*/
public static function getInstantiatedClasses() {
return self::$instances;
}
}
</code></pre>
<p>So basically, what it does it that it allows you to register a class name as follow :</p>
<pre><code>Container::register('config', \Framework\Core\Config::class);
</code></pre>
<p>And then you can get the class instance like this :</p>
<pre><code>Container::get('config');
</code></pre>
<p>You can also register() and immediately get() the class instance like this :</p>
<pre><code>Container::register('config', \Framework\Core\Config::class)::get();
</code></pre>
<p>I added this "feature" into my microframework in order to prevent instantiating a class more than one time.</p>
<p>The interesting part is that it instantiates the class <strong>only</strong> when you call the get() method, not when you register it. It allows me to register all framework dependancies at once when the app starts and then get their instances later.</p>
<p>Obvisouly, this class needs improvement in terms of "options". Because, what if I need to register() and get() a class that needs arguments to be passed into its constructor ? I'm aware about that and before making this class more "flexible" I just wanted to know if it's useful to have a "feature" like this in my microframework.</p>
<hr>
<p>My question is :
How is this called ? Singleton ? Container ? Dependency injection ?<br>
Also, can my microframework benefits from having this "feature" ? </p>
| [] | [
{
"body": "<p>Before addressing the main question, I would like to compare two of the primary methods: <code>register</code> and <code>get</code>. The <code>register</code> method is written well in terms of <code>return</code>ing early.</p>\n<blockquote>\n<pre><code> public static function register($name, $cl... | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-08T13:50:02.160",
"Id": "198076",
"Score": "3",
"Tags": [
"php",
"object-oriented",
"collections"
],
"Title": "Dependency Container"
} | 198076 |
<p>Using Python 3.7.0, I've programmed a 'Game of Life' simulator. The output is displayed using tkinter. It's not meant to be limited to just Game of Life, though, as it's meant to also be used for a simple physics simulation project.</p>
<pre><code>import tkinter as tk
#import pdb
class Cell:
#ref_dict allows the coords to act as a pointer to the cell.
ref_dict = {}
"""active_cells allows the grid to determine sim_cells.
Thus, it reduces the number of cells the grid needs to simulate.
"""
active_cells = set()
def __init__(
self, coords, size, grid_size, conditions = {},
active_color = "black", inactive_color = "white", state = False):
"""Create a new cell.
Positional arguments:
coords ---------- Coordinates of the cell within the grid.
Tuple (x, y)
size ------------ Side length of the cell in pixels.
Integer.
grid_size ------- Side length of the grid, in squares.
Integer.
Keyword arguments:
conditions ------ Dict of conditions the cell has.
Used for complex simulations.
Keys as names, values as floats.
E.g. 'temperature': 50.4
Dictionary.
active_color ---- Color of the cell when alive.
String or color reference.
inactive_color -- Color of the cell when dead.
String or color reference.
state ----------- Whether the cell is alive or dead.
Boolean.
This object simulates a cell, which evolves over time.
Here, the rules for evolution are from 'Conway's game of life'.
"""
self.coords = coords
self.size = size
self.grid_size = grid_size
self.conditions = conditions
self.active_color = active_color
self.inactive_color = inactive_color
self.state = state
"""The cell won't update it's state straight away.
Otherwise, it could cause a knock-on effect,
changing the number of neighbors for other cells.
To avoid this, the cell will calculate its new_state first.
Then, it can set self.state = self.new_state after all updates.
"""
self.new_state = False
self.neighbor_coords = ()
self.get_neighbor_coords()
self.alive_neighbors = 0
"""This allows instantiation without variable assignment,
by letting the coordinates act as a pointer.
"""
Cell.ref_dict[self.coords] = self
def valid_coord(self, coord):
"""Determine whether a given coordinate is within the grid.
x coordinates are measured from the origin.
Hence, they should not be >= to the grid_size.
This would indicate it was referring to a column right of the
rightmost column, due to everything being 0-indexed.
Similar rules apply for the y coordinate.
"""
(x, y) = coord
return (0 <= x < self.grid_size) and (0 <= y < self.grid_size)
def get_neighbor_coords(self):
"""Construct neighbor_coords."""
(x, y) = self.coords
self.neighbor_coords = tuple(filter(self.valid_coord,
[(x + a, y + b)
for a in range(-1, 2) for b in range(-1, 2) if a != 0 or b != 0]))
return self
def get_alive_neighbors(self):
"""Determine alive_neighbors."""
self.alive_neighbors = 0
for n in self.neighbor_coords:
if Cell.ref_dict[n].state:
self.alive_neighbors += 1
return self
def get_new_state(self):
"""Determine what the new state of the cell should be.
Here is where any different rules can be configured.
"""
if not self.neighbor_coords:
self.get_neighbor_coords().get_alive_neighbors()
else:
self.get_alive_neighbors()
if self.state:
if not 2 <= self.alive_neighbors <= 3:
self.new_state = False
else:
self.new_state = True
else:
if self.alive_neighbors == 3:
self.new_state = True
else:
self.new_state = False
return self
def update_state(self):
"""Set self.state to self.new_state; reset self.new_state.
Also will add/remove the cell from active_cells.
"""
self.state = self.new_state
if self.state and self.coords not in Cell.active_cells:
Cell.active_cells.add(self.coords)
elif not self.state and self.coords in Cell.active_cells:
Cell.active_cells.remove(self.coords)
self.new_state = False
return self
class Grid:
def __init__(
self, size, cell_size, active_color = "black",
inactive_color = "white", condition_dict = {},
initial_active_cells = []):
"""Create a new grid.
Positional arguments:
size ----------------- Size of the grid in cells.
Integer.
cell_size ------------ Size of a cell in pixels.
Integer.
Keyword arguments:
active_color --------- Color of a cell when alive.
String or color reference.
inactive_color ------- Color of a cell when dead.
String or color reference.
condition_dict ------- Nested dictionary.
Coordinates as keys, dicts of conditions as values.
Dictionary.
initial_active_cells - List of cells that start alive.
List.
"""
self.size = size
self.cell_size = cell_size
self.active_color = active_color
self.inactive_color = inactive_color
self.condition_dict = condition_dict
self.initial_active_cells = initial_active_cells
"""Only active cells and neighbors are simulated.
Coords in self.sim_cells. This attempts to reduce CPU usage.
"""
self.sim_cells = set()
self.create_cells().set_active_cells(initial_active_cells)
def create_cells(self):
"""Instantiate all new cells with required parameters."""
"""Conditions may not be specified.
The if statement thus avoids KeyErrors.
"""
if self.condition_dict:
for x in range(0, self.size):
for y in range(0, self.size):
Cell(
(x, y), self.cell_size, self.size,
conditions = self.condition_dict[(x, y)],
active_color = self.active_color,
inactive_color = self.inactive_color)
else:
for x in range(0, self.size):
for y in range(0, self.size):
Cell(
(x, y), self.cell_size, self.size,
active_color = self.active_color,
inactive_color = self.inactive_color)
return self
def set_active_cells(self, initial_active_cells):
"""Set states of cells specified by a list to True."""
for coord in initial_active_cells:
Cell.ref_dict[coord].new_state = True
Cell.ref_dict[coord].update_state()
return self
def get_sim_cells(self):
"""Get all cells that need to be simulated."""
self.sim_cells = set()
for coord in Cell.active_cells:
self.sim_cells.add(coord)
"""This finds all neighbors of active cells,
to determine which cells need to be simulated."""
self.sim_cells.update(
[(x + a, y + b)
for a in range(-1,2) for b in range(-1,2)
for (x,y) in self.sim_cells
if Cell.valid_coord(Cell.ref_dict[(x,y)], (x + a, y + b))])
return self
def update_grid(self):
"""Update simulated cells, and update the set of sim_cells."""
self.get_sim_cells()
"""Two loops are used to stop early death or birth of cells.
The grid is meant to evolve as a whole each tick,
and not cell-by-cell.
"""
for coord in self.sim_cells:
Cell.ref_dict[coord].get_new_state()
for coord in self.sim_cells:
Cell.ref_dict[coord].update_state()
return self
class App:
#Matches cell coordinates to the canvas squares.
canvas_dict = {}
def __init__(
self, grid_size, cell_size,
active_color = "black", inactive_color = "white",
condition_dict = {}, initial_active_cells = []):
"""Start a new game.
Positional arguments:
grid_size ------------ Size of grid, in cells.
Integer.
cell_size ------------ Size of a cell, in pixels.
Integer.
Keyword arguments:
active_color --------- Color of a cell when alive.
String or color reference.
inactive_color ------- Color of a cell when dead.
String or color reference.
condition_dict ------- Nested dictionary.
Coordinates as keys, dicts of conditions as values.
Dictionary.
initial_active_cells - List of cells that start alive.
List.
"""
self.grid_size = grid_size
self.cell_size = cell_size
self.active_color = active_color
self.inactive_color = inactive_color
self.condition_dict = condition_dict
self.initial_active_cells = initial_active_cells
self.size = grid_size * cell_size
self.grid = Grid(
self.grid_size, self.cell_size,
active_color = self.active_color,
inactive_color = self.inactive_color,
condition_dict = self.condition_dict,
initial_active_cells = self.initial_active_cells)
self.root = tk.Tk()
self.canvas = tk.Canvas(
self.root, bg = "white",
height = self.size, width = self.size)
self.canvas.pack()
self.render_canvas(canvas_created = False)
self.root.after(1000, self.refresh_display)
self.root.mainloop()
def refresh_display(self):
"""Update both grid and canvas."""
self.grid.update_grid()
self.render_canvas(canvas_created = True)
self.root.after(50, self.refresh_display)
def render_canvas(self, canvas_created = False):
if not canvas_created:
for x in range(0, self.grid_size):
for y in range(0, self.grid_size):
if (x, y) in self.initial_active_cells:
#This specifies the corners of the polygon.
App.canvas_dict[(x, y)] = self.canvas.create_polygon(
x * self.cell_size, y * self.cell_size,
(x+1) * self.cell_size, y * self.cell_size,
(x+1) * self.cell_size, (y+1) * self.cell_size,
x * self.cell_size, (y+1) * self.cell_size,
fill = self.active_color, outline = "black")
else:
App.canvas_dict[(x, y)] = self.canvas.create_polygon(
x * self.cell_size, y * self.cell_size,
(x+1) * self.cell_size, y * self.cell_size,
(x+1) * self.cell_size, (y+1) * self.cell_size,
x * self.cell_size, (y+1) * self.cell_size,
fill = self.inactive_color, outline = "black")
else:
for coord in self.grid.sim_cells:
if Cell.ref_dict[coord].state:
self.canvas.itemconfig(
App.canvas_dict[coord], fill = self.active_color)
else:
self.canvas.itemconfig(
App.canvas_dict[coord], fill = self.inactive_color)
if __name__ == "__main__":
#This gives the default pattern of a Gosper glider gun.
app = App(60, 5, initial_active_cells = [
(25,1), (23,2), (25,2), (13,3),
(14,3), (21,3), (22,3), (35,3),
(36,3), (12,4), (16,4), (21,4),
(22,4), (35,4), (36,4), (1,5),
(2,5), (11,5), (17,5), (21,5),
(22,5), (1,6), (2,6), (11,6),
(15,6), (17,6), (18,6), (23,6),
(25,6), (11,7), (17,7), (25,7),
(12,8), (16,8), (13,9), (14,9)])
</code></pre>
<p>My skill level is a beginner - this is my first non-trivial project that makes use of OOP concepts like classes. Most of my previous projects have been algorithm-based, for example writing an algorithm to crack the Caesar cipher.</p>
<p>I'm looking for feedback on how to make the code faster (the glider gun provided slows down after making about 3 gliders), as well as error handling. I haven't implemented any yet, but I'm not sure how much I need to account for - does every function need a <code>try</code> ... <code>except</code> statement? Only every <code>__init__</code> function? Any feedback in this area would be greatly appreciated.</p>
<p>Here is <a href="https://codereview.stackexchange.com/questions/185040/conways-game-of-life-in-python-3-using-tkinter">the code from a previous Q</a>. I used this as a reference, but I tried my best not to directly copy it. However, some elements are quite similar to it (for example, both have 3 classes of Square/Cell, Grid and App).</p>
<p>I also have a problem with trying to import this module and changing the behaviour of ‘Cell’. To do this, I have been told to make a subclass, and override when needed. However, ‘Grid’ creates new cells using the original ‘Cell’ constructor, so any changes I make won’t affect the cells Grid creates.</p>
<p>Is there any way I can edit the behaviour of Cell and get Grid to make the new objects, without rewriting lots of functions?</p>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-08T14:14:55.163",
"Id": "198077",
"Score": "4",
"Tags": [
"python",
"beginner",
"python-3.x",
"game-of-life"
],
"Title": "Game of Life simulator, Python 3"
} | 198077 |
<p>I am getting a TLE on my submission to <a href="https://www.spoj.com/problems/AGGRCOW/" rel="nofollow noreferrer">AGGRCOW - Aggressive cows</a> on SPOJ:</p>
<blockquote>
<p>Farmer John has built a new long barn, with N (2 <= N <= 100,000)
stalls. The stalls are located along a straight line at positions
x1,...,xN (0 <= xi <= 1,000,000,000).</p>
<p>His C (2 <= C <= N) cows don't like this barn layout and become
aggressive towards each other once put into a stall. To prevent the
cows from hurting each other, FJ wants to assign the cows to the
stalls, such that the minimum distance between any two of them is as
large as possible. What is the largest minimum distance?</p>
<p><strong>Input</strong></p>
<p>t – the number of test cases, then t test cases follows.<br>
* Line 1: Two space-separated integers: N and C<br>
* Lines 2..N+1: Line i+1 contains an integer stall location, xi </p>
<p><strong>Output</strong> </p>
<p>For each test case output one integer: the largest minimum distance.</p>
<p><strong>Example</strong></p>
<p>Input:</p>
<pre><code>1
5 3
1
2
8
4
9
</code></pre>
<p>Output:</p>
<pre><code>3
</code></pre>
<p><strong>Output details:</strong></p>
<p>FJ can put his 3 cows in the stalls at positions 1, 4 and 8,
resulting in a minimum distance of 3.</p>
</blockquote>
<p>I tried checking starting from smallest minimum distance i.e zero to the largest minimum distance that will be the solution. I used recursion to solve this question but getting TLE. How can I use binary search in this problem for making it more efficient.</p>
<pre><code>#include<bits/stdc++.h>
using namespace std;
bool CanBeMin( vector<long long int> arr, unsigned int b,int s,unsigned int
cnt,long long int k){
if(cnt == b ) return true;
if(arr[s+1]=='\0') return false;
for(unsigned int i=s+1 ; arr[i]!='\0'; i++){
if (arr[i] - arr[s] > k && b-cnt <= arr.size() - i) {
cnt ++;
return CanBeMin ( arr , b , i , cnt , k);}
}
return false;}
int count ( vector <long long int> arr, unsigned int b){
long long int k=0;
while (CanBeMin ( arr , b , 0 , 0 , k)) {
k=k+1;}
return k;}
int main(){
int t;
cin >> t;
while ( t-- ){
int a , b;
cin >> a >> b;
vector<long long int> arr(a);
for( int i = 0; i < a; i++) {
cin >> arr[i];}
sort ( arr.begin(), arr.end());
if (b <= a)
cout << count (arr, b-1);
else cout<<"0";
cout << endl; }
}
</code></pre>
| [] | [
{
"body": "<ol>\n<li><p>Well, your indentation gives me a headache. I think there might be a pattern in it, but I don't see it, so I'll reformat it for writing my answer.</p></li>\n<li><p><a href=\"https://stackoverflow.com/questions/31816095/why-should-i-not-include-bits-stdc-h/31816096#31816096\"><code><bi... | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-08T14:36:32.290",
"Id": "198078",
"Score": "3",
"Tags": [
"c++",
"programming-challenge",
"time-limit-exceeded",
"c++14"
],
"Title": "AGGRCOW on SPOJ – Maximize the minimum distance between aggressive cows"
} | 198078 |
<p>So I programmed 2048 in python3 and a simple solver, which will just target a high numbers on the board (not the best tactic, I know), but I have the problem, that this move calculation is painfully slow. Any ideas on how to speed this up are appreciated. (The logic should be fine)</p>
<pre><code>from enum import Enum
from typing import List, Tuple
class MoveDirection(Enum):
UP = (0, -1)
DOWN = (0, 1)
LEFT = (-1, 0)
RIGHT = (1, 0)
BoardType = List[List[int]]
Pos = Size = Tuple[int, int]
Move = Tuple[Pos, Pos, bool]
def move(board: BoardType, direction: MoveDirection) -> Tuple[BoardType, BoardType, List[Move]]:
old, board = board, [c[:] for c in board]
size = len(board), len(board[0])
already_merged = []
moves = []
if direction == MoveDirection.UP:
for x in range(size[0]):
for y in range(1, size[1]):
v = board[x][y]
if v == 0:
continue
board[x][y] = 0
for ny in reversed(range(0, y)):
if board[x][ny] == v and (x, ny) not in already_merged:
board[x][ny] = v + 1
already_merged.append((x, ny))
moves.append(((x, y), (x, ny), True))
break
elif board[x][ny] != 0:
board[x][ny + 1] = v
if ny + 1 != y:
moves.append(((x, y), (x, ny + 1), False))
break
else:
board[x][0] = v
moves.append(((x, y), (x, 0), False))
elif direction == MoveDirection.DOWN:
for x in range(size[0]):
for y in reversed(range(size[1] - 1)):
v = board[x][y]
if v == 0:
continue
board[x][y] = 0
for ny in range(y + 1, size[1]):
if board[x][ny] == v and (x, ny) not in already_merged:
board[x][ny] = v + 1
already_merged.append((x, ny))
moves.append(((x, y), (x, ny), True))
break
elif board[x][ny] != 0:
board[x][ny - 1] = v
if ny - 1 != y:
moves.append(((x, y), (x, ny - 1), False))
break
else:
board[x][-1] = v
moves.append(((x, y), (x, size[1] - 1), False))
elif direction == MoveDirection.LEFT:
for y in range(size[1]):
for x in range(1, size[0]):
v = board[x][y]
if v == 0 or x == 0:
continue
board[x][y] = 0
for nx in reversed(range(0, x)):
if board[nx][y] == v and (nx, y) not in already_merged:
board[nx][y] = v + 1
already_merged.append((nx, y))
moves.append(((x, y), (nx, y), True))
break
elif board[nx][y] != 0:
board[nx + 1][y] = v
if nx + 1 != x:
moves.append(((x, y), (nx + 1, y), False))
break
else:
board[0][y] = v
moves.append(((x, y), (0, y), False))
elif direction == MoveDirection.RIGHT:
for y in range(size[1]):
for x in reversed(range(size[0] - 1)):
v = board[x][y]
if v == 0:
continue
board[x][y] = 0
for nx in range(x + 1, size[0]):
if board[nx][y] == v and (nx, y) not in already_merged:
board[nx][y] = v + 1
already_merged.append((nx, y))
moves.append(((x, y), (nx, y), True))
break
elif board[nx][y] != 0:
board[nx - 1][y] = v
if nx - 1 != x:
moves.append(((x, y), (nx - 1, y), False))
break
else:
board[-1][y] = v
moves.append(((x, y), (size[0] - 1, y), False))
else:
raise ValueError()
return old, board, moves
</code></pre>
<p>The code in context and with a pygame visualization can be seen here: <a href="https://github.com/MegaIng1/2048" rel="nofollow noreferrer">https://github.com/MegaIng1/2048</a>)</p>
| [] | [
{
"body": "<h3>1. Review</h3>\n\n<ol>\n<li><p>There are no docstrings. What does <code>move</code> do? What does it return?</p></li>\n<li><p><code>move</code> always returns its first argument as the first element of the returned tuple. This seems pointless since the caller obviously has the argument in hand at... | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-08T15:22:16.897",
"Id": "198080",
"Score": "3",
"Tags": [
"python",
"performance",
"python-3.x",
"2048"
],
"Title": "2048 movement calculation"
} | 198080 |
<p>I am doing a college assignment where I have to count the number of inversions in an array/list. An inversion is defined as a tuple where <code>i<j and a[i]>a[j]</code>. For example in this array</p>
<pre><code>val arr = Array(3, 1, 2, 4)
</code></pre>
<p>The inversions are (3,1), (3,2). So total count of inversions is 2.</p>
<p>I wrote a divide and conquer algorithm to find this. it works for small arrays. but for large inputs like this one </p>
<p><a href="https://github.com/abhsrivastava/ArrayInversions/blob/master/src/main/resources/inversions.txt" rel="nofollow noreferrer">https://github.com/abhsrivastava/ArrayInversions/blob/master/src/main/resources/inversions.txt</a></p>
<p>there is always an out of memory error. My code is below</p>
<pre><code>import scala.io.Source
import Sort._
object CountInversions extends App {
val data = Source.fromResource("inversions.txt").getLines.map(_.toInt).toList
val inversions = countInversions(data)
println(s"number of inversions ${inversions}")
def countInversions(input: List[Int]): Int = {
input match {
case Nil => 0
case List(a) => 0
case _ =>
val mid = input.size / 2
val left = input.slice(0, mid)
val right = input.slice(mid, input.size)
val l1 = countInversions(left)
val l2 = countInversions(right)
val l3 = splitInversions(left, right)
l1 + l2 + l3
}
}
// assuming l1 and l2 are almost of same size.
// total complexity 2(nlogn + n)
def splitInversions(l1: List[Int], l2: List[Int]): Int = {
val sortedL1 = mergeSort(l1) // nlogn
val sortedL2 = mergeSort(l2) // nlogn
(sortedL1, sortedL2) match {
case (Nil, Nil) => 0
case (Nil, _) => 0
case (_, Nil) => 0
case (_, _) if sortedL1.head > sortedL2.head =>
val result = splitInversions(sortedL1, sortedL2.tail)
sortedL1.size + result
case (_, _) =>
splitInversions(sortedL1.tail, sortedL2)
}
}
}
</code></pre>
<p>I am not posting the code for mergeSort here. it is just a simple merge sort.</p>
<p>My objective is to be able to determine the inversions in O(nlogn) time and be able to process the large file. I also want to keep my code functional.</p>
<p>How can I optimize my code?</p>
| [] | [
{
"body": "<p>A few things I've noticed.</p>\n\n<ol>\n<li>You use <code>List</code> to represent the input data. Lists are inefficient (linear) for things like <code>input.size</code> (which you do twice on the same input) and <code>input.slice()</code>.</li>\n<li>Both <code>countInversions()</code> and <code>s... | {
"AcceptedAnswerId": "201430",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-08T17:02:34.270",
"Id": "198084",
"Score": "0",
"Tags": [
"algorithm",
"scala"
],
"Title": "Finding the number of inversions in an Array"
} | 198084 |
<p>After receiving advice from my <a href="https://codereview.stackexchange.com/questions/197572/title-case-converter">last question</a>, I reworked the design of my program to be more generic, expandable and easier to use. This is the excerpt of the requirements: </p>
<blockquote>
<h3>Step 1: Basic Title Case</h3>
<p>For each word in a sentence, make all of its
letters lower case, except the first one that would be in upper case.</p>
<p>There is a list of “exceptions” words that need to be entirely in
lower case, including their first letter. This lists includes “at” and
“to”, along with another dozen words. For the sake of this project
let’s say that the list of exceptions is: a, an, the, at, by, for, in,
of, on, to, and, as and or.</p>
<p>Note that in all cases, the first word of the string must start with a
capital letter.</p>
<h3>Step 2: Title Case with customizations</h3>
<p>Make the list of exceptions
customizable: the library user can add new exceptions, replace the
list with their own, or add words that should not be changed by the
library.</p>
<p>An additional requirement is that words in all caps should be left as
is (“STL” must remain “STL”, and not be changed into “Stl”), but the
library user should be able to opt-out of this feature.</p>
<h3>Step 3: Other capitalizations</h3>
<p>Title Case is one of the various forms
of capitalisation there is. Other examples include UPPER CASE, lower
case, snake_case, Start case, and so on.</p>
<p>Implement at least two other forms of capitalizations in the library,
by reusing as much code as possible from the previous steps. The point
of this step is to make a smooth introduction of new features into
existing code via a form of polymorphism (runtime, static, other… you
choose).</p>
</blockquote>
<p>Any advice would be appreciated. </p>
<h2>Case.h</h2>
<pre><code>#ifndef CASE_POLICY_H
#define CASE_POLICY_H
#include <utility>
#include <cctype>
#include <array>
namespace case_utils {
namespace helper {
//converts const_iterator to iterator, needed to convert result of find_next_word() without changing
//param to StringType& which contradicts the purpose of the function
template <typename Container, typename ConstIterator>
inline typename Container::iterator remove_constness(Container& c, ConstIterator it)
{
return c.erase(it, it);
}
}
namespace defaults {
const auto to_upper = [](int c)->char { return std::toupper(static_cast<unsigned char>(c)); };
const auto to_lower = [](char c)->char { return std::tolower(static_cast<unsigned char>(c)); };
const auto is_upper = [](char c)->bool { return std::isupper(static_cast<unsigned char>(c)); };
const auto is_not_letter = [](char c)->bool {return !std::isalpha(static_cast<unsigned char>(c)); };
const auto is_space = [](char c)->bool { return std::isspace(static_cast<unsigned char>(c)); };
}
template<typename StringType>
class CasePolicy {
public:
using string_type = StringType;
using iterator = typename StringType::iterator;
using const_iterator = typename StringType::const_iterator;
virtual std::pair<const_iterator, const_iterator> find_next_word(const StringType& text, const_iterator first) = 0;
virtual void transform_word(iterator begin_word, iterator end_word, StringType& text) = 0;
virtual bool meets_pred(const_iterator begin_word, const_iterator end_word) = 0;
};
template<typename StringType, typename PolicyString>
decltype(auto) transform_text(StringType&& text, CasePolicy<PolicyString>* policy)
{
using std::begin;
using std::end;
PolicyString text_copy{ std::forward<StringType>(text) };
auto first_word = policy->find_next_word(text_copy, begin(text_copy));
auto begin_word = helper::remove_constness(text_copy, first_word.first);
auto end_word = helper::remove_constness(text_copy, first_word.second);
if (end_word == end(text_copy)) //check if there's only one word in string or string is empty
{
if (begin_word == end_word) return text_copy; //empty
if (policy->meets_pred(begin_word, end_word)) {
policy->transform_word(begin_word, end_word, text_copy);
}
return text_copy;
}
while (begin_word != end_word) // no more whitespace delimited words in the string
{
if (policy->meets_pred(begin_word, end_word)) {
policy->transform_word(begin_word, end_word, text_copy);
}
if (end_word == end(text_copy)) break; // no more characters to observe in the string
auto next_word = policy->find_next_word(text_copy, end_word + 1);
begin_word = helper::remove_constness(text_copy, next_word.first);
end_word = helper::remove_constness(text_copy, next_word.second);
}
return text_copy;
}
}
#endif
</code></pre>
<h2>TitleCase.h</h2>
<pre><code>#ifndef TITLE_CASE_H
#define TITLE_CASE_H
#include "Case.h"
#include <algorithm>
#include <array>
#include <iterator>
#include <memory>
namespace case_utils {
namespace defaults {
using sv = std::string_view;
constexpr auto title_case_exceptions_list = std::array{ sv{ "a" }, sv{ "an" }, sv{ "and" }, sv{ "as" }, sv{ "at" }, sv{ "by" }, sv{ "for" }, sv{ "in" }, sv{ "of" }, sv{ "on" }, sv{ "to" }, sv{ "or" }, sv{ "the" } };
}
template<typename InputIterator, typename ForwardRange>
bool is_exception(InputIterator begin_word, InputIterator end_word, const ForwardRange& exceptions)
{
using std::begin; using std::end;
for (const auto& exception : exceptions)
{
if (std::equal(begin(exception), end(exception), begin_word, end_word))
{
return true;
}
}
return false;
}
template<typename InputIterator, typename IsUpperPred>
bool is_acronym(InputIterator begin_word, InputIterator end_word, IsUpperPred is_upper_pred)
{
return std::all_of(begin_word, end_word, is_upper_pred);
}
template<typename StringType, typename ForwardRange, typename IsWhitespace, typename IsUpperPred, typename ToUpperFunction, typename UnaryToLowerFunction>
class TitleCasePolicy : public CasePolicy<StringType> {
const ForwardRange& m_exceptions;
IsWhitespace m_is_whitespace;
IsUpperPred m_is_upper_pred;
ToUpperFunction m_to_upper;
UnaryToLowerFunction m_to_lower;
public:
using typename CasePolicy<StringType>::iterator;
using typename CasePolicy<StringType>::const_iterator;
TitleCasePolicy(const ForwardRange& exceptions, IsWhitespace is_white_space, IsUpperPred is_upper_pred, ToUpperFunction to_upper, UnaryToLowerFunction to_lower)
:m_exceptions{ exceptions }, m_is_whitespace{ is_white_space }, m_is_upper_pred{ is_upper_pred }, m_to_upper{ to_upper }, m_to_lower{ to_lower } {}
//find first whitespace-delimited word starting from position first
std::pair<const_iterator, const_iterator> find_next_word(const StringType& text, const_iterator first) override
{
using std::end;
const_iterator begin_word = std::find_if_not(first, end(text), m_is_whitespace);
const_iterator end_word = std::find_if(begin_word, end(text), m_is_whitespace);
return { begin_word, end_word };
}
void transform_word(iterator begin_word, iterator end_word, StringType&) override
{
*begin_word = m_to_upper(*begin_word);
while (++begin_word != end_word) { *begin_word = m_to_lower(*begin_word); }
}
bool meets_pred(const_iterator begin_word, const_iterator end_word) override
{
return !is_acronym(begin_word, end_word, m_is_upper_pred) && !is_exception(begin_word, end_word, m_exceptions);
}
const ForwardRange& exceptions() { return m_exceptions; }
};
template<typename StringType, typename ForwardRange, typename IsWhitespace, typename IsUpperPred, typename ToUpperFunction, typename UnaryToLowerFunction>
class TitleCasePolicyIncludingAllCaps : public TitleCasePolicy<StringType, ForwardRange, IsWhitespace, IsUpperPred, ToUpperFunction, UnaryToLowerFunction>
{
public:
using Base = TitleCasePolicy<StringType, ForwardRange, IsWhitespace, IsUpperPred, ToUpperFunction, UnaryToLowerFunction>;
TitleCasePolicyIncludingAllCaps(const ForwardRange& exceptions, IsWhitespace is_white_space, IsUpperPred is_upper_pred, ToUpperFunction to_upper, UnaryToLowerFunction to_lower)
: Base{ exceptions, is_white_space, is_upper_pred, to_upper, to_lower } {}
using typename CasePolicy<StringType>::const_iterator;
bool meets_pred(const_iterator begin_word, const_iterator end_word) override
{
return !is_exception(begin_word, end_word, this->exceptions());
}
};
//helper function similar to make_pair b/c constructors can't be used to deduce template class types
template<typename StringType, typename ForwardRange = decltype(defaults::title_case_exceptions_list),
typename IsWhitespace = decltype(defaults::is_not_letter), typename IsUpperPred = decltype(defaults::is_upper),
typename ToUpperFunction = decltype(defaults::to_upper), typename UnaryToLowerFunction = decltype(defaults::to_lower)>
inline auto make_title_case_policy(bool ignore_acronyms = true, const ForwardRange& exceptions = defaults::title_case_exceptions_list,
IsWhitespace is_white_space = defaults::is_not_letter, IsUpperPred is_upper_pred = defaults::is_upper,
ToUpperFunction to_upper = defaults::to_upper, UnaryToLowerFunction to_lower = defaults::to_lower)
->std::unique_ptr<TitleCasePolicy<StringType, ForwardRange, IsWhitespace, IsUpperPred, ToUpperFunction, UnaryToLowerFunction>>
{
using TCP = TitleCasePolicy<StringType, ForwardRange, IsWhitespace, IsUpperPred, ToUpperFunction, UnaryToLowerFunction>;
using TCPIAC = TitleCasePolicyIncludingAllCaps<StringType, ForwardRange, IsWhitespace, IsUpperPred, ToUpperFunction, UnaryToLowerFunction>;
if (ignore_acronyms)
{
return std::make_unique<TCP>(exceptions, is_white_space, is_upper_pred, to_upper, to_lower);
}
else
{
return std::make_unique <TCPIAC>(exceptions, is_white_space, is_upper_pred, to_upper, to_lower);
}
}
template<typename StringType, typename ForwardRange>
inline decltype(auto) title_case(StringType&& text, bool ignore_acronyms, const ForwardRange& exceptions)
{
using string_type = typename std::decay_t<StringType>;
static auto policy = make_title_case_policy<string_type>(ignore_acronyms, exceptions);
return transform_text(std::forward<StringType>(text), policy.get());
}
template<typename StringType>
inline decltype(auto) title_case(StringType&& text)
{
return title_case(std::forward<StringType>(text), true, defaults::title_case_exceptions_list);
}
template<typename StringType, typename ForwardRange>
inline decltype(auto) title_case(StringType&& text, const ForwardRange& exceptions)
{
return title_case(std::forward<StringType>(text), true, exceptions);
}
template<typename StringType>
inline decltype(auto) title_case(StringType&& text, bool ignore_acronyms)
{
return title_case(std::forward<StringType>(text), ignore_acronyms, defaults::title_case_exceptions_list);
}
}
#endif
</code></pre>
<h2>UpperCase.h</h2>
<pre><code>#ifndef UPPER_CASE_H
#define UPPER_CASE_H
#include "Case.h"
#include <memory>
#include <iterator>
#include <utility>
namespace case_utils {
template<typename StringType, typename ToUpper>
class UpperCasePolicy : public CasePolicy<StringType>
{
ToUpper m_to_upper;
public:
using typename CasePolicy<StringType>::iterator;
using typename CasePolicy<StringType>::const_iterator;
UpperCasePolicy(ToUpper to_upper) : m_to_upper{ to_upper } {}
std::pair<const_iterator, const_iterator> find_next_word(const StringType& text, const_iterator first) override
{
using std::begin; using std::end;
return { begin(text), end(text) };
}
void transform_word(iterator begin_word, iterator end_word, StringType&) override
{
while (begin_word != end_word)
{
*begin_word = m_to_upper(*begin_word);
++begin_word;
}
}
bool meets_pred(const_iterator begin_word, const_iterator end_word) override
{
return true;
}
};
template<typename StringType, typename ToUpper = decltype(defaults::to_upper)>
inline auto make_upper_case_policy(ToUpper to_upper = defaults::to_upper) ->std::unique_ptr<UpperCasePolicy<StringType, ToUpper>>
{
using UPC = UpperCasePolicy<StringType, ToUpper>;
return std::make_unique<UPC>(to_upper);
}
template<typename StringType, typename ToUpper>
inline decltype(auto) upper_case(StringType&& text, ToUpper to_upper)
{
using string_type = typename std::decay_t<StringType>;
static auto policy = make_upper_case_policy<string_type>(to_upper);
return transform_text(std::forward<StringType>(text), policy.get());
}
template<typename StringType>
inline decltype(auto) upper_case(StringType&& text)
{
return upper_case(std::forward<StringType>(text), defaults::to_upper);
}
}
#endif
</code></pre>
<h2>SnakeCase.h</h2>
<pre><code>#ifndef SNAKE_CASE_H
#define SNAKE_CASE_H
#include "Case.h"
#include <iterator>
#include <memory>
#include <utility>
namespace case_utils {
template<typename StringType, typename CharT, typename IsWhitespace, typename ToLower>
class SnakeCasePolicy : public CasePolicy<StringType> {
private:
CharT m_underscore;
IsWhitespace m_is_whitespace;
ToLower m_to_lower;
public:
using typename CasePolicy<StringType>::iterator;
using typename CasePolicy<StringType>::const_iterator;
SnakeCasePolicy(CharT underscore, IsWhitespace is_whitespace, ToLower to_lower)
: m_underscore{ underscore }, m_is_whitespace{ is_whitespace }, m_to_lower{ to_lower } {}
std::pair<const_iterator, const_iterator> find_next_word(const StringType& text, const_iterator first) override
{
using std::begin; using std::end;
const_iterator begin_word = std::find_if_not(begin(text), end(text), m_is_whitespace);
const_iterator end_word = std::find_if(begin_word, end(text), m_is_whitespace);
return { begin_word, end_word };
}
void transform_word(iterator begin_word, iterator end_word, StringType& text) override
{
while (begin_word != end_word)
{
*begin_word = m_to_lower(*begin_word);
++begin_word;
}
if (end_word != end(text))
{
transform_whitespace(end_word, text);
}
}
void transform_whitespace(iterator end_word, StringType& text)
{
using std::end;
*end_word = m_underscore;
++end_word; //beginning of whitespace
auto end_whitespace = std::find_if_not(end_word, end(text), m_is_whitespace);
text.erase(end_word, end_whitespace);
}
virtual bool meets_pred(const_iterator begin_word, const_iterator end_word)
{
return true;
}
};
template<typename StringType, typename CharT = char, typename IsWhitespace = decltype(defaults::is_space),
typename ToLower = decltype(defaults::to_lower)>
inline auto make_snake_case_policy(CharT underscore = '_', IsWhitespace is_whitespace = defaults::is_space,
ToLower to_lower = defaults::to_lower)->std::unique_ptr<SnakeCasePolicy<StringType, CharT, IsWhitespace, ToLower>>
{
using SCP = SnakeCasePolicy<StringType, CharT, IsWhitespace, ToLower>;
return std::make_unique<SCP>(underscore, is_whitespace, to_lower);
}
template<typename StringType, typename CharT, typename IsWhitespace, typename ToLower>
inline decltype(auto) snake_case(StringType&& text, CharT underscore, IsWhitespace is_whitespace, ToLower to_lower)
{
using string_type = typename std::decay_t<StringType>;
static auto policy = make_snake_case_policy<string_type>(underscore, is_whitespace, to_lower);
return transform_text(std::forward<StringType>(text), policy.get());
}
template<typename StringType>
inline decltype(auto) snake_case(StringType&& text)
{
return snake_case(std::forward<StringType>(text), '_', defaults::is_space, defaults::to_lower);
}
template<typename StringType, typename CharT>
inline decltype(auto) snake_case(StringType&& text, CharT underscore)
{
return snake_case(std::forward<StringType>(text), underscore, defaults::is_space, defaults::to_lower);
}
template<typename StringType, typename CharT, typename IsWhitespace>
inline decltype(auto) snake_case(StringType&& text, CharT underscore, IsWhitespace is_whitespace)
{
return snake_case(std::forward<StringType>(text), underscore, is_whitespace, defaults::to_lower);
}
}
#endif
</code></pre>
| [] | [
{
"body": "<h1><code>Case.h</code></h1>\n\n<p>I suggest naming C++ headers with <code>.hpp</code> or <code>.hh</code> or <a href=\"https://gcc.gnu.org/onlinedocs/gcc/Overall-Options.html\" rel=\"noreferrer\">something else recognized as a C++ header extension</a>. <code>.h</code> \"works\", but when I see a <co... | {
"AcceptedAnswerId": "198106",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-08T17:24:53.980",
"Id": "198085",
"Score": "6",
"Tags": [
"c++",
"strings"
],
"Title": "Generic Case Converter"
} | 198085 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.