body stringlengths 25 86.7k | comments list | answers list | meta_data dict | question_id stringlengths 1 6 |
|---|---|---|---|---|
<p>I am trying to achieve an event system, which I refer as actions, and would like your ideas about what I come up with so far. I have made research on several design patterns, and several systems used for jobs like this, like <strong>Signal & Slots</strong>, Observer and command patterns etc. However, I have found several various implementations, which were probably way better than what I have come up with, but I had some hard time trying to understand some points and use cases in most of them. Instead of using something that I can not extend when I need, I decided the come up with my own designs inspired by them. I am currently working on an experimental project, which is only purpose is for me to <strong>learn</strong> more and more about architectural and functional design in C++. I am not a beginner programmer, but I can say I am somewhat experimental in C++, did not have a lot of background on it. So basically, I am doing trial & error, seeing what happens, and the pros and cons of the system I come up with by using them. So there is no problem about revisions and refactoring, I can do it all day.</p>
<p>Anyways coming back to my system, in the most event handling systems I had searched, there was mostly only 1 logic, where an event is dispatched to subscribed listeners, and it was listener's job to check the desired parameters and act upon it. However, currently what I need is a system, that checks the events itself, <strong>on the choices of the listeners</strong> and sends them to the listeners only if they are fully interested. What i mean is that, consider this example:</p>
<pre><code>// Dispatcher sends this to all listeners.
onKeyPressEvent.dispatch(pressedKey, Key_A);
// And listener does something like this
onKeyPressEvent.subscribe(myLambdaWithParameter);
</code></pre>
<p>And when it receives the event, it checks it. For example, a keypress event is SENT to <strong>every listener who listens to key presses</strong>, whether they are interested in that particular key or not, they still receive the event, and do the checks whether they want it on their own or not. I want to change that, I don't want the keyboard press event with the Key P for example to be sent to someone who looks for the Key K.</p>
<p>So here is my design, first we have an event dispatcher.</p>
<pre><code>class Lina_ActionDispatcher
{
public:
Lina_ActionDispatcher()
{
}
std::list<Lina_ActionHandlerBase*> m_TestListeners;
};
</code></pre>
<p>Currently as you can see, I don't have any subscribe & unsubscribe method, which is going to be its own challenge because I want to handle the cases where the handler dies before the dispatcher or vice versa. Need recommendations on that as well. Anyways, I have a class called Lina_ActionHandlerBase, which is the base class for all actions. Since actions will be of type T, I basically wrote this base class as a wrapper. I hold raw pointer for them, firstly because I want to use polymorphism mainly, and also because these handlers will be created on the objects who wants to check for a particular action and will be passed to the dispatcher. So maybe a weak_ptr would be a better idea, so that I can check the expiration and clear the handler from the list when necessary. Looking for ideas here.</p>
<p>The dispatcher, would do this, when it wants to dispatch an action:</p>
<pre><code>// it is the iterated element of the list, compare the action types (enumeration) call the control if they match
if(it->m_ActionType == action.m_ActionType)
it->Control(&action);
</code></pre>
<p>So, now let's take a look at the action classes.</p>
<pre><code>// Base wrapper class for actions.
class Lina_ActionBase
{
public:
Lina_ActionBase(){};
~Lina_ActionBase(){};
Lina_ActionBase(ActionType at) : m_ActionType(at) {};
virtual void* GetData() { return 0; }
inline ActionType GetActionType() { return m_ActionType; }
private:
Lina_ActionBase(const Lina_ActionBase& rhs) = delete;
ActionType m_ActionType;
};
</code></pre>
<p>So this is the wrapper base class, that uses no templates, so I can hold a list in the dispatcher with pointers that point to an object of the base class. We have an ActionType, which basically the identifier of the event, like keyPress, physicsStepCalled, editorRendered etc. GetData is a virtual method, it returns void* because the type is undefined yet. The return type will be of type T in the derived, actual Action class, which is:</p>
<pre><code>// Template class used for actions.
template<typename T>
class Lina_Action : public Lina_ActionBase
{
public:
Lina_Action() {}
~Lina_Action() { }
inline void SetData(T t) { m_Value = t; }
virtual void* GetData() { return &m_Value; }
private:
T m_Value;
};
</code></pre>
<p>As you can see, now we can create any action with the value of type T. My Action structure is like this, we have an identifier of the action(m_ActionType) and the value of the action. For example a window operation, "windowClosed" can be id, while the value can be "textureWindow", or it can be an action of a key press, id would be "keyPressed", while value can be "KEY_F" you get the idea.</p>
<p>Now let's go to the real deal, the action handlers. As I have mentioned earlier, my dispatchers will hold a list of ActionHandlers, and these handlers can be any type T, so I have written a base wrapperclass for my handlers. </p>
<pre><code>// Base wrapper class for action handlers.
class Lina_ActionHandlerBase
{
public:
Lina_ActionHandlerBase() {}
~Lina_ActionHandlerBase() {}
Lina_ActionHandlerBase(ActionType at) : m_ActionType(at) {};
inline ActionType GetActionType() { return m_ActionType; }
inline void SetActionType(ActionType t) { m_ActionType = t; }
virtual void Control(Lina_ActionBase& action) { };
virtual void Execute(Lina_ActionBase& action) {};
private:
ActionType m_ActionType;
};
</code></pre>
<p>As i said earlier, what a dispatcher does is, when it receives an action, it iterates through the handlers, and asks them to control this event whether they want it or not. So my base class has a Control method, to be overriden in the derived handler classes.</p>
<p>I wanted to have handlers with diffent behaviour. For example, I could have a listener, who listens to key events, and doesn't care which key it is, it checks if the Action's identifier is "keyPress", if so, it just executes. Another handler may do the same, but also control which key was pressed. So here comes my concept of <strong>Condition</strong>. Some actions handlers may have conditions of type U, and what they will be doing is to check whether this type U is the same type with the action, then it would check whether the action has the same value as their condition value. So I have written another base class, which actually drives from the above ActionHandlerBase.</p>
<pre><code>// Service class for actions handlers, determines the behaviour choices of actions.
template<typename T>
class Lina_ActionHandler_ConditionCheck : public Lina_ActionHandlerBase
{
public:
Lina_ActionHandler_ConditionCheck() {};
~Lina_ActionHandler_ConditionCheck() {};
Lina_ActionHandler_ConditionCheck(ActionType at) :
Lina_ActionHandlerBase::Lina_ActionHandlerBase(at) {};
inline void SetCondition(T t) { m_Condition = t; }
inline T GetCondition() { return m_Condition; }
// Control block called by the dispatchers.
virtual void Control(Lina_ActionBase& action) override
{
// Cast from action base class void* type to T*.
T* dataPointer = static_cast<T*>(action.GetData());
// Compare the type of the member attribute of type of the value value received from the action.
// If types are the same, then check the values, if they are the same, execute
if (CompareType(*dataPointer) && CompareValue(*dataPointer))
Execute(action);
}
// Compares the data type U with member attribute of type T.
template<typename U>
bool CompareType(U u)
{
if (std::is_same<U, T>::value)
return true;
return false;
}
// Compares the value of a variable typed U with the value of member attribute typed T.
template<typename U>
bool CompareValue(U u)
{
return LinaEngine::Internal::comparison_traits<T>::equal(m_Condition, u);
}
private:
T m_Condition;
};
</code></pre>
<p>So, as you can see, I have a condition of type T. When the Control method is called, it uses this condition. ( Whether the Control of this class will be called or not will be determined by another subclass, which is our actual action handler class, which i will explain below, so dont worry about it now ) What control does is, it extracts the void* typed value from the action base, casts it to a pointer of type T. What I am worried about here is the usage of static_cast, is there any better options or what do you guys think? Going on, then it uses is_same to check if they are the same type. As you can see in the if clause, if type check returns true, then we check for the value equality. I use comparison_trait struct to check the equality, which is this:</p>
<pre><code>template <typename T> struct comparison_traits {
static bool equal(const T& a, const T& b) {
return a == b;
}
};
</code></pre>
<p>So if the action's value and the handlers condition is the same, our control succeeds and calls the execution method. What this gives is the flexibility of passing any kind of value to an action and action handler. I can pass ClassB, and as long as I have a comparison operator overloaded for ClassB, i can control how they are compared and everything would be fine.(in theory) So, if a control succeeds, then our execution is called. Let's look at the actual ActionHandler I will be using for handling stuff:</p>
<pre><code>// Main derived class used for action handlers.
template<typename T = int>
class Lina_ActionHandler : public Lina_ActionHandler_ConditionCheck<T>
{
public:
Lina_ActionHandler() {}
~Lina_ActionHandler() {}
Lina_ActionHandler(ActionType at) :
Lina_ActionHandler_ConditionCheck<T>::Lina_ActionHandler_ConditionCheck(at) {};
inline void SetUseCondition(bool b) { m_UseCondition = b; }
inline void SetUseBinding(bool b) { m_UseBinding = b; }
inline void SetUseParamCallback(bool b) { m_UseParamCallback = b; }
inline void SetUseNoParamCallback(bool b) { m_UseNoParamCallback = b; }
inline bool GetUseBinding() { return m_UseBinding; }
inline bool GetConditionCheck() { return m_UseCondition; }
inline bool GetUseParamCallback() { return m_UseParamCallback; }
inline bool GetUseNoParamCallback() { return m_UseNoParamCallback; }
virtual void Control(Lina_ActionBase& action) override
{
// If condition check is used, call the control of the behaviour base class so it can compare it's member attribute T with the action's value.
if (m_UseCondition)
Lina_ActionHandler_ConditionCheck<T>::Control(action);
else
Execute(action); // Execute the action if no check is provided.
}
virtual void Execute(Lina_ActionBase& action) override
{
// Call the callback with no parameters
if (m_UseNoParamCallback)
m_CallbackNoParam();
// If we use parameterized callback or binding, we will extract the value from the action.
// However, if we have not used condition, it means whe have not typed checked this value. So type check it first.
if ((m_UseParamCallback || m_UseBinding))
{
// Cast from polymorphic action base class void* type to T*.
T* typePointer = static_cast<T*>(action.GetData());
if (!m_UseCondition)
{
// If the types do not match, simply exit.
if (!Lina_ActionHandler_ConditionCheck<T>::CompareType(*typePointer))
return;
}
// Call the callback with parameters, cast and pass in the data from the action.
if (m_UseParamCallback)
m_CallbackParam(*typePointer);
// Bind the value.
if (m_UseBinding)
*m_Binding = *typePointer;
}
}
void SetParamCallback(std::function<void(T)> && cbp) { m_CallbackParam = cbp; }
void SetNoParamCallback(std::function<void()>&& cb) { m_CallbackNoParam = cb; }
void SetBinding(T* binding) { m_Binding = binding; }
private:
bool m_UseParamCallback = false;
bool m_UseNoParamCallback = false;
bool m_UseBinding = false;
bool m_UseCondition = false;
T* m_Binding;
std::function<void()> m_CallbackNoParam;
std::function<void(T)> m_CallbackParam;
};
</code></pre>
<p>I wanted the action handlers to have different capabilities. They can check of a condition, or not. Completely seperate from conditions, their execution behaviours can be various. They can call a method, without any parameters upon execution, or they can call these methods with the parameter, received from the action (basically what the most of the event dispatching systems I have found does, they don't do any checks for anything else, they just send the action value to listeners.), or handlers can bind a particular value of type T, to the action value, for example a mouse motion event. You can pass a float to your handler, and the "mouseMotionX" action's value would be binded to your float, as soon as their types match and every object coupled are alive, you only have to bind once.</p>
<p>So remember, my dispatchers hold a list of ActionHandlerBase, but I will be creating objects of this ActionHandler class, and passing these objects to the list. So, since I use pointers in my dispatchers, the corresponding object methods, which will be ActionHandler class instances, would be called. Basically, whenever we call Control, it will be the Control of ActionHandler and it will execute from there according to the specified behaviour.</p>
<p>And to use the system, I would do:</p>
<pre><code> int toBind = 2;
Lina_ActionDispatcher* disp = new Lina_ActionDispatcher;
Lina_Action<float> action;
action.SetData(22.5);
auto f = []() {std::cout << "Non-Parameterized Callback Called" << std::endl; };
auto f2 = [](float f) {std::cout << "Parameterized Callback Called, Value is : " << f << std::endl; };
Lina_ActionHandler<float> b(ActionType1);
b.SetUseCondition(true);
b.SetUseNoParamCallback(true);
b.SetUseParamCallback(true);
b.SetCondition(22.5);
b.SetNoParamCallback(f);
b.SetParamCallback(f2);
disp->m_TestListeners.push_back(&b);
// TODO: Check action type before calling control.
disp->m_TestListeners.front()->Control(action);
std::cout << "Binded Variable Is: " << toBind;
</code></pre>
<p>So basically, this is my whole structure. I have couple of worries, about using *void in the ActionBase class, or using static_cast to cast it to type T in the condition checking and parameterized method calling or value binding. Also, if an handler doesnt use any condition, any parameterized callback or any binding, just a simple callback, then the condition, param. callback function pointer and binder pointer will be uninitialized. What should I do about them? Also I have worries about whether I have abused the boundaries of polymorphism, or used it in a silly way. I am looking for every single kind of recommendation, comment, advice from a single line to whole system architecture, and if I have left out anything to explain, please do state it. And also, you can read the full header file on <a href="https://github.com/lineupthesky/LinaEngine/blob/master/LinaEngine/inc/Lina_Actions.h" rel="nofollow noreferrer">Github</a>, if the sharing is not allowed, please let me know.</p>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-10-07T13:38:38.733",
"Id": "205106",
"Score": "3",
"Tags": [
"c++",
"event-handling"
],
"Title": "C++ Generic Action Dispatching & Handling System"
} | 205106 |
<p>I often find myself in the following position: I have created a class in some file, and would like to add a new data member to that class without changing the original class definition. Now, you cannot actually add a new data member to a class without changing the class definition. So instead, I'd like to "simulate" (in some sense) a new data member.</p>
<p>What do I mean by this? In an implementation of the disjoint sets data structure, objects in the disjoint sets have two properties - they have a "rank" (which is an integer) and they have a "parent" (which is another object of the same class). In Kruskal's algorithm, such a disjoint union data structure is used to represent disjoint sets of vertices. It makes no sense to break abstraction barriers, jump into the implementation of "vertex", and place a vertex pointer called "Vertex *parent" and an integer "rank" in each the class definition of Vertex. Instead, I need some other way to access the rank/parent of a Vertex in O(1) time. How should I do this? Is there a canonical way? Do I use a hash table? How does one hash a vertex?</p>
<p>I suspect I can be more helpful in asking my question if I include my attempt at an implementation to get over this problem. I implemented a "hash map" that uses the address of the object as a key.</p>
<p>This is the implementation of "HashMap", which will key objects by their address and store a pointer to something of class val. This file is what my question focuses on.</p>
<p>File hashMap.h:</p>
<pre><code>#include <unordered_map>
template <class keyed, class val>
class HashMap
{
public:
HashMap(){}
~HashMap(){}
long keyOf(keyed &item){ return (long) &item; }
val* &operator[](keyed &item)
{
long key = keyOf(item);
return _uomap[key];
}
private:
std::unordered_map<long, val*> _uomap;
};
</code></pre>
<p>This is a file that includes an implementation of the DisjointSets data
structure. It isn't very important - I've included it just for
concreteness. Notice that "_rankOf" and "_parentOf" will, in a certain
sense, "simulate" data members T.rank and T.parent which may not
already appear in the implementation of whatever is used for T.</p>
<p>File disjoint.h:</p>
<pre><code>#include "hashMap.h"
template <class T>
class DisjointSets
{
public:
DisjointSets(){}
~DisjointSets(){}
void makeSet(T &elem)
{
int elemRank = 0;
_parentOf[elem] = &elem;
_rankOf[elem] = &elemRank;
++_numSets;
}
T &findSet(T &elem)
{
if (_parentOf[elem] != &elem)
_parentOf[elem] = &findSet(*_parentOf[elem]);
return (*_parentOf[elem]);
}
void unify(T &elemA, T &elemB)
{
link(findSet(elemA), findSet(elemB));
--_numSets;
}
void link(T &setA, T &setB)
{
if (*_rankOf[setA] < *_rankOf[setB])
_parentOf[setA] = &setB;
else
{
_parentOf[setB] = &setA;
if (*_rankOf[setB] == *_rankOf[setA])
++(*_rankOf[setB]);
}
}
private:
HashMap<T, T> _parentOf;
HashMap<T, int> _rankOf;
int _numSets = 0;
};
</code></pre>
<p>In a separate file, you might want to actually use the disjoint data structure to do something. Here is an example of such a file. Note that Vertex doesn't have a rank data member or a parent data member.</p>
<p>File vertex.cc:</p>
<pre><code>#include "disjoint.h"
#include <iostream>
using namespace std;
class Vertex
{
public:
Vertex(int val): _val (val){}
~Vertex(){}
int valOf(){ return _val; }
private:
int _val = 0;
};
int main()
{
//Have fun with Kruskal's algorithm or whatever
DisjointSets<Vertex> sets;
Vertex a(1);
Vertex b(2);
sets.makeSet(a);
sets.makeSet(b);
//etc.
return 1;
}
</code></pre>
<p>This gets the job done, but I really don't like it. It seems very hacky. I have to use the address as a hash, which doesn't seem safe. I have to use pointers as the stored value of the HashMap, which isn't quite like a real data member.</p>
<p>Any advice is appreciated. Alternatively, if this whole approach is bad, please let me know what the better alternative is. I've been told that I shouldn't find myself in a position where I want to add a new data member without changing the original class definition - I feel I've given a good example here of where this is necessary.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-10-07T16:41:25.767",
"Id": "395577",
"Score": "2",
"body": "Adding new features to existing classes in C++ is typically done by *aggregation* or *inheritance*. It's not clear to me why neither of these mechanisms is used, and not clear t... | [] | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-10-07T13:52:17.283",
"Id": "205107",
"Score": "1",
"Tags": [
"c++",
"graph",
"c++14",
"hash-map"
],
"Title": "Using HashMaps to track parent and rank of graph nodes"
} | 205107 |
<p>I wrote the Python3 code below. This is actually a stripped down version of a bigger project, but in essence it boils down to this code. There are two classes: <code>Point</code>, which is a point in 3D space and <code>PointCloud</code>, which is a sequence (list) of points.</p>
<p>In the <code>PointCloud</code> class, I have a method to calculate the minimum and maximum values for each axis: <code>minmax_coords</code>, which returns a dict (keys: the axes 'x', 'y', 'z') of a dict (keys: 'min' and 'max'). So you can do: <code>somepointcloud.minmax_coords()['x']['min']</code> for the minimal x-axis value.</p>
<p>As it is, the code doesn't feel very pythonic and isn't really self-explanatory.</p>
<p>My question is: <em>please review the code of the <code>minmax_coord</code> method and give me some suggestions how to refactor the code to make it more pythonic and more self explanatory</em>.</p>
<p>Any suggestions to improve the code are welcome.</p>
<p><a href="https://repl.it/@Albertten/minmaxcoordinates" rel="nofollow noreferrer">Repl link to the code.</a></p>
<pre><code>class Point:
""" Point with coordinate """
def __init__(self, coordinate=None):
""" Constructor """
self.coordinate = coordinate
class PointCloud:
""" A cloud (list) of Points """
def __init__(self, point_list=None):
""" Constructor """
self.points = point_list
def minmax_coords(self):
""" Return minimum and mainum coordinate for each axis """
if not self.points:
raise IndexError("PointCloud has no Points.")
result = {'x': {}, 'y': {}, 'z': {}}
for i, axis in zip(range(3), ['x', 'y', 'z']):
result[axis]['min'] = self.points[0].coordinate[i]
result[axis]['max'] = self.points[0].coordinate[i]
for point in self.points:
for i, axis in zip(range(3), ['x', 'y', 'z']):
result[axis]['min'] = min(result[axis]['min'],
point.coordinate[i])
result[axis]['max'] = max(result[axis]['max'],
point.coordinate[i])
return result
if __name__ == "__main__":
P = PointCloud([Point((1, 2, 3)), Point((5, 4, 3))])
print(f"Minimum and maximum coordinates: {P.minmax_coords()}")
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-10-07T17:44:49.150",
"Id": "395582",
"Score": "3",
"body": "Is there anything else in these classes? It's hard to advise you when you say that it's stripped down, but we don't know what is omitted. Based on the little bit that you've show... | [
{
"body": "<p>As @200_success mentions, these classes seem a bit sparse, and you shouldn't bother with classes for them in the first place.</p>\n\n<p>For instance, <code>Point</code> could be nicely replaced with a <code>namedtuple</code>.</p>\n\n<pre><code>>>> from collections import namedtuple\n>&... | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-10-07T15:46:58.180",
"Id": "205111",
"Score": "0",
"Tags": [
"python",
"python-3.x",
"coordinate-system"
],
"Title": "Find minimum and maximum coordinates for a set of points"
} | 205111 |
<p>I have a <code>Throttler</code> and <code>Debouncer</code> functions that I took from an <a href="https://github.com/soffes/RateLimit" rel="nofollow noreferrer">unmaintained library</a>. I added my own tests, but not sure if the tests fully prove that it works and can be trusted. If the tests are good, then I’d feel a lot better about using it and can refactor if needed. Below is what I got.</p>
<p><strong>Throttler:</strong></p>
<pre><code>/// The Throttler will ignore work items until the time limit for the preceding call is over.
public final class Throttler {
// MARK: - Properties
public let limit: TimeInterval
public private(set) var lastExecutedAt: Date?
private let syncQueue = DispatchQueue(label: "com.stackexchange.throttle", attributes: [])
/// Initialize a new throttler with given time interval.
///
/// - Parameter limit: The number of seconds for throttle work items.
public init(limit: TimeInterval) {
self.limit = limit
}
/// Submits a work item and ensures it is not called until the delay is completed.
///
/// - Parameter block: The work item to be invoked on the throttler.
@discardableResult public func execute(_ block: () -> Void) -> Bool {
let executed = syncQueue.sync { () -> Bool in
let now = Date()
// Lookup last executed
let timeInterval = now.timeIntervalSince(lastExecutedAt ?? .distantPast)
// If the time since last execution is greater than the limit, execute
if timeInterval > limit {
// Record execution
lastExecutedAt = now
// Execute
return true
}
return false
}
if executed {
block()
}
return executed
}
/// Cancels all work items to allow future work items to be executed with the specified delayed.
public func reset() {
syncQueue.sync {
lastExecutedAt = nil
}
}
}
</code></pre>
<p><strong>Debouncer:</strong></p>
<pre><code>/// The Debouncer will delay work items until time limit for the preceding call is over.
public final class Debouncer {
// MARK: - Properties
private let limit: TimeInterval
private let queue: DispatchQueue
private var workItem: DispatchWorkItem?
private let syncQueue = DispatchQueue(label: "com.stackexchange.debounce", attributes: [])
/// Initialize a new debouncer with given delay limit for work items.
///
/// - Parameters:
/// - limit: The number of seconds until the execution block is called.
/// - queue: The queue to run the execution block asynchronously.
public init(limit: TimeInterval, queue: DispatchQueue = .main) {
self.limit = limit
self.queue = queue
}
/// Submits a work item and ensures it is not called until the delay is completed.
///
/// - Parameter block: The work item to be invoked on the debouncer.
@objc public func execute(block: @escaping () -> Void) {
syncQueue.async { [weak self] in
if let workItem = self?.workItem {
workItem.cancel()
self?.workItem = nil
}
guard let queue = self?.queue, let limit = self?.limit else { return }
let workItem = DispatchWorkItem(block: block)
queue.asyncAfter(deadline: .now() + limit, execute: workItem)
self?.workItem = workItem
}
}
/// Cancels all work items to allow future work items to be executed with the specified delayed.
public func reset() {
syncQueue.async { [weak self] in
self?.workItem?.cancel()
self?.workItem = nil
}
}
}
</code></pre>
<p><strong>Unit Tests:</strong></p>
<pre><code>import XCTest
class RateLimitTests: XCTestCase {
}
// MARK: - Debounce
extension RateLimitTests {
func testDebouncer() {
let promise = expectation(description: "Debouncer executed")
let limiter = Debouncer(limit: 1)
var currentValue = 0
limiter.execute {
currentValue += 1
}
XCTAssertEqual(0, currentValue)
limiter.execute {
currentValue += 1
}
XCTAssertEqual(0, currentValue)
limiter.execute {
currentValue += 1
promise.fulfill()
}
XCTAssertEqual(0, currentValue)
waitForExpectations(timeout: 2)
XCTAssertEqual(1, currentValue)
// Sleep for a bit
sleep(2)
let promise2 = expectation(description: "Debouncer execute 2")
limiter.execute {
currentValue += 1
}
XCTAssertEqual(1, currentValue)
limiter.execute {
currentValue += 1
promise2.fulfill()
}
XCTAssertEqual(1, currentValue)
waitForExpectations(timeout: 2)
XCTAssertEqual(2, currentValue)
}
func testDebouncerRunOnceImmediatly() {
let limiter = Debouncer(limit: 0)
let promise = expectation(description: "Run once and call immediatly")
limiter.execute {
promise.fulfill()
}
wait(for: [promise], timeout: 1)
}
func testDebouncerRunThreeTimesCountTwice() {
let limiter = Debouncer(limit: 0.5)
let promise = expectation(description: "should fulfill three times")
promise.expectedFulfillmentCount = 3
limiter.execute {
promise.fulfill()
}
DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(1), execute: {
limiter.execute {
promise.fulfill()
}
})
DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(3), execute: {
limiter.execute {
promise.fulfill()
}
})
wait(for: [promise], timeout: 5)
}
func testDebouncerRunTwiceCountTwice() {
let limiter = Debouncer(limit: 1)
let promise = expectation(description: "should fulfill twice")
promise.expectedFulfillmentCount = 2
limiter.execute {
promise.fulfill()
}
DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(1), execute: {
limiter.execute {
promise.fulfill()
}
})
wait(for: [promise], timeout: 3)
}
func testDebouncerRunTwiceCountOnce() {
let limiter = Debouncer(limit: 1)
let promise = expectation(description: "should fullfile once, because calls are both runned immediatly and second one should get ignored")
promise.expectedFulfillmentCount = 1
limiter.execute {
promise.fulfill()
}
limiter.execute {
promise.fulfill()
}
wait(for: [promise], timeout: 5)
}
}
// MARK: - Throttle
extension RateLimitTests {
func testThrottler() {
let limiter = Throttler(limit: 2)
// It should get excuted first
let promise1 = expectation(description: "Throttler execute 1")
var reported = limiter.execute {
promise1.fulfill()
}
XCTAssertTrue(reported)
waitForExpectations(timeout: 0, handler: nil)
// Not right away after
reported = limiter.execute {
XCTFail("This shouldn't have run.")
}
XCTAssertFalse(reported)
// Sleep for a bit
sleep(2)
// Now it should get executed
let promise2 = expectation(description: "Throttler execute 2")
reported = limiter.execute {
promise2.fulfill()
}
XCTAssertTrue(reported)
waitForExpectations(timeout: 0, handler: nil)
}
func testThrottler2() {
let limiter = Throttler(limit: 1)
let promise = expectation(description: "Run once and call immediately")
var value = 0
limiter.execute {
value += 1
}
limiter.execute {
value += 1
}
limiter.execute {
value += 1
}
limiter.execute {
value += 1
}
limiter.execute {
value += 1
}
limiter.execute {
value += 1
}
DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(1)) {
guard value == 1 else {
XCTFail("Failed to throttle, calls were not ignored.")
return
}
promise.fulfill()
}
wait(for: [promise], timeout: 2)
}
func testThrottlerResetting() {
let limiter = Throttler(limit: 1)
// It should get excuted first
let promise1 = expectation(description: "Throttler execute 1")
let reported1 = limiter.execute {
promise1.fulfill()
}
XCTAssertTrue(reported1)
waitForExpectations(timeout: 0, handler: nil)
// Not right away after
let reported2 = limiter.execute {
XCTFail("This shouldn't have run.")
}
XCTAssertFalse(reported2)
// Reset limit
limiter.reset()
// Now it should get executed
let promise2 = expectation(description: "Throttler execute 2")
let reported3 = limiter.execute {
promise2.fulfill()
}
XCTAssertTrue(reported3)
waitForExpectations(timeout: 0, handler: nil)
}
}
</code></pre>
<p>Is there a better, cleaner way to test the throttle and denouncer functionality?</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-10-08T11:13:33.097",
"Id": "395619",
"Score": "0",
"body": "Are you only asking for a review of your unit tests, or are you asking about the library code as well? The latter *may* be off-topic, as only code that *you* own or maintain can ... | [] | {
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-10-07T16:22:38.190",
"Id": "205113",
"Score": "2",
"Tags": [
"swift"
],
"Title": "Swift Throttler and Debouncer"
} | 205113 |
<p>I wrote this code to make a non-blocking server without using <code>select()</code>, my main concern is to catch as many exceptions as possible for worst case scenarios (so I would appreciate some feedback on cases I missed), and to let each client to be handled separately by its own thread.</p>
<p>Any feedback on style/performance/good or bad coding practice is welcome.</p>
<pre><code>import socket
import logging
import threading
import sys
class EchoServer:
BUFFER_SIZE = 1024
# size limit in bytes for the client message to be received
MAX_MSG_SIZE = 1024 * 5
# this maps connected clients socket objects returned from accept() to their address tuple
connected_clients = {}
def __init__(self, port):
self.hostname = 'localhost'
self.port = port
try:
self.sockfd = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.sockfd.bind((self.hostname, self.port))
self.sockfd.listen(10)
self.sockfd.setblocking(False)
except socket.error as e:
logging.critical(e)
logging.critical('Could not start up server. Exiting.')
sys.exit(-1)
def look_for_connections(self):
while True:
try:
client_connfd, client_addr = self.sockfd.accept()
logging.info('Connection from client {!r}'.format(client_addr))
self.connected_clients[client_connfd] = client_addr
client_handling_thread = threading.Thread(target=self.handle_client, args=(client_connfd,))
client_handling_thread.start()
except BlockingIOError:
# no active clients trying to connect, nothing to do
continue
def handle_client(self, connfd: socket.socket):
msg = self.get_client_msg(connfd)
logging.info('Client: {} sent {} bytes.'.format(self.connected_clients[connfd], len(msg)))
sent_bytes_size = self.send_client_msg(connfd, msg)
logging.info('Server sent {} bytes to client: {!r}'.format(sent_bytes_size, self.connected_clients[connfd]))
del self.connected_clients[connfd]
connfd.close()
def startup_server_loop(self):
# this starts the main event loop (accepting connections from client)
# each client get handled by its own thread
server_thread = threading.Thread(target= self.look_for_connections)
server_thread.start()
def get_client_msg(self, connfd: socket.socket):
data = b''
while True:
try:
buffer = connfd.recv(self.BUFFER_SIZE)
if len(buffer) == 0 or len(data) >= self.MAX_MSG_SIZE:
break
else:
data += buffer
except BlockingIOError:
break
return data
def send_client_msg(self, connfd: socket.socket, msg: str):
sent_bytes = 0
total_bytes = len(msg)
total_sent = 0
if len(msg) == 0:
return total_sent
while True:
try:
sent_bytes = connfd.send(msg[sent_bytes: total_bytes])
total_sent += sent_bytes
if sent_bytes == 0:
return total_sent
except BlockingIOError:
return total_sent
# in case client disconnected before sending the echo
except ConnectionResetError:
logging.info('Client {!r} disconnected before sending echo.'.format(self.connected_clients[connfd]))
return total_sent
def __del__(self):
for client in self.connected_clients.keys():
del self.connected_clients[client]
self.sockfd.close()
if __name__ == '__main__':
logging.basicConfig(level=logging.INFO)
my_server = EchoServer(50000)
my_server.startup_server_loop()
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-10-08T07:17:48.443",
"Id": "395611",
"Score": "1",
"body": "Is there a purpose that you are not showing? Because I fail to understand why you'd want to **not** block, especially on the `accept` call: you do nothing in the meantime and rep... | [
{
"body": "<p>There seems to be a few misconceptions about blockings calls and the purpose of non-blocking sockets. You wrote in <a href=\"https://codereview.stackexchange.com/questions/205117/multithreaded-non-blocking-tiny-echo-server#comment395948_205117\">a comment</a>:</p>\n<blockquote>\n<p>I thought this ... | {
"AcceptedAnswerId": "205294",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-10-07T19:21:31.163",
"Id": "205117",
"Score": "1",
"Tags": [
"python",
"reinventing-the-wheel",
"socket",
"tcp"
],
"Title": "Multithreaded non-blocking tiny echo server"
} | 205117 |
<p>My code is a mix-up between dynamic programming with the <code>HashMap</code> and brute force with the way I reach out the results and substring. I don't know how to optimize my algorithm without googling and looking for already solved solutions with different approaches.</p>
<pre><code>class Solution {
public String longestPalindrome(String s) {
if (s.length() > 1000) return "";
if (s.length() == 0) return "";
HashSet<String> hs = new HashSet<>();
int size = 1;
String longest = s.substring(0, 1);
for (int i = 0; i < s.length(); i++)
{
for (int j = i; j < s.length() - 1; j++)
{
String ss = s.substring(i, j+2);
int ssl = ss.length();
if (hs.contains(ss))
{
if (ssl > size) {
size = ssl;
longest = ss;
}
}
else{
if (isPalindrome(ss)){
hs.add(ss);
if (ssl > size) {
size = ssl;
longest = ss;
}
}
}
}
}
return longest;
}
public boolean isPalindrome(String s) {
int j = s.length() - 1;
int i = 0;
while (i < j){
if (s.charAt(i) != s.charAt(j)){
return false;
}
i++;
j--;
}
return true;
}
}
</code></pre>
<p>The webpage where this problem is posted says the max size of the string can be 1000. However if a string of that size is the input the algorithm takes 200-210 ms to execute and return the substring.</p>
<p>I'm 100% sure it works, but it's slow.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-10-08T10:17:54.500",
"Id": "395617",
"Score": "1",
"body": "Why are you not using algorythm from https://en.wikipedia.org/wiki/Longest_palindromic_substring ? The optimal solution is O(n), yours is O(n^2) just from 2 for loops and either ... | [] | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-10-07T21:52:53.907",
"Id": "205125",
"Score": "2",
"Tags": [
"java",
"performance",
"algorithm",
"palindrome"
],
"Title": "Longest Palindromic Substring challenge"
} | 205125 |
<p>I am writing a function to raise an error if a csv/tsv file does not use valid separators. However, due to existing code, currently I am handling all other exceptions to be handled silently. (There are other function in the existing code to handle the exception scenarios, and raising these exceptions here breaks a lot of tests that I don't have enough knowledge of to rewrite myself).</p>
<p>Initially I was using <code>pass</code> to not do anything about these exceptions, but while writing the unit tests for the function, I decided to chnage the function so that it would add all the silently handled exceptions to a list and return the list. I could then manually raise the exceptions in that list during tests to confirm the functionality.</p>
<p>Here's the function:</p>
<pre><code>def _verify_events_file_uses_tab_separators(events_files):
valid_separators = [',', '\t']
events_files = [events_files] if not isinstance(events_files, (list, tuple)) else events_files
errors_raised = []
for events_file_ in events_files:
try:
with open(events_file_, 'r') as events_file_obj:
events_file_sample = events_file_obj.readline()
except TypeError as type_err:
errors_raised.append([events_file_, type_err]) # events is Pandas dataframe.
except UnicodeDecodeError as unicode_err:
errors_raised.append([events_file_, unicode_err]) # py3:if binary file
except IOError as io_err:
errors_raised.append([events_file_, io_err]) # if invalid filepath.
else:
try:
csv.Sniffer().sniff(sample=events_file_sample,
delimiters=valid_separators,
)
except csv.Error:
raise ValueError(
'The values in the events file are not separated by tabs; '
'please enforce tabs/commas conventions',
events_file_)
return errors_raised
</code></pre>
<p>Then I can test the silent functions this way (an example):</p>
<pre><code>def test_for_invalid_filepath():
filepath = ['junk_file_path1.csv', 'junk_file_path2.csv']
result = _verify_events_file_uses_tab_separators(events_files=filepath)
expected_error = result[0][1]
with assert_raises(IOError):
raise expected_error
</code></pre>
<p>Since the function is not public facing, I figured this won't be a problem. It works as intended, but the whole thing seems rather inelegant to me. </p>
<p>Is there a better way of doing this? </p>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-10-01T09:37:45.187",
"Id": "205128",
"Score": "1",
"Tags": [
"python",
"unit-testing"
],
"Title": "Proper design for testing silently passed errors"
} | 205128 |
<p>I am implementing a new compression algorithm for the weights of a neural network for the <a href="http://lczero.org" rel="nofollow noreferrer">Leela Chess project</a>. the weights are roughly <code>100Mb</code> of <code>float32</code>s which I want to compress as small as possible. Error tolerance for this application is <code>2^-17</code>, so lossy compression is clearly the right answer here. All of the weights are between -5 and 5, but 99.995% are in (-.25,.25) and most reasonably closely clumped around zero.</p>
<p>The basic idea with this algorithm is to turn floats into integer multiples of the error tolerance, and then use a utf-8 inspired encoding to represent small values with only 1 byte.</p>
<pre><code>import numpy as np
import bz2
def compress(in_path, out_path):
with open(in_path, 'rb') as array:
net = np.fromfile(in_path, dtype=np.float32)
# Quantize
net = np.asarray(net * 2**17, np.int32)
# Zigzag encode
net = (net >> 31) ^ (net << 1)
# To variable length
result = np.zeros(len(net)*3, dtype=np.uint8)
for i in range(3):
big = (net >= 128) << 7
result[i::3] = (net % 128) + big
net >>= 7
# Delete non-essential indices
zeroes = np.where(result == 0)[0]
zeroes = zeroes[np.where(zeroes % 3 != 0)]
result = np.delete(result, zeroes)
with bz2.open(out_path, 'wb') as out:
out.write(result.tobytes())
def decompress(in_path, out_path):
with bz2.open(in_path, 'rb') as array:
result = np.frombuffer(array.read(), dtype=np.uint8)
start_inds = np.where(result<128)[0]
not_zeroed = np.ones(len(start_inds), dtype=np.bool)
# append zeroe so loop doesn't go out of bounds
result = np.append(result, np.zeros(4, dtype=np.uint8))
# Get back fixed length from variable length
net = np.zeros(len(start_inds), dtype=np.uint32)
for i in range(3):
change = (result[start_inds] % 128) * not_zeroed
net[np.where(not_zeroed)[0]] *= 128
net += change
start_inds += 1
not_zeroed &= result[start_inds] >= 128
# Zigzag decode
net = (net >> 1) ^ -(net & 1)
print(np.mean(net))
# Un-quantize
net = np.asarray(net, np.float32)
net /= 2**17
with open(out_path, 'wb') as out:
out.write(version)
out.write(net.tobytes())
compress('diff.hex','diff.bz2')
decompress('diff.bz2','round.hex')
</code></pre>
<p>The main type of advice I'm looking for is algorithm and performance advice, but ways to make the code readable are always nice.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-10-08T07:09:24.997",
"Id": "395606",
"Score": "0",
"body": "Did you confirm that the variable length encoding is an improvement over feeding the zigzag directly into bz2?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate":... | [] | {
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-10-08T01:08:06.910",
"Id": "205131",
"Score": "3",
"Tags": [
"python",
"numpy",
"floating-point",
"compression"
],
"Title": "Variable bit length lossy floating point compression"
} | 205131 |
<p>I have been studying C#, and I am trying to model the Random number guessing game.</p>
<p>1 User inputs the number of try.<br>
2 Computer generates random number.<br>
3 If numbers doesn't match user lose one try
and if they match user gets two bonus try. </p>
<p>Is my program reasonable or is there anything I need to improve?</p>
<p>As player goes to next round, I also want
to increase random number range by 100 to increase
difficulty.For example, first round 1-100
next round 1-200 and so on.
How can I do that? Any help would be appreciated.</p>
<pre><code> public class GuessGame
{
public class Game
{
public int attemp { set; get; } = 0;
public override string ToString()
{
return $"The player's attemp <{attemp}>";
}
}
public static void Test()
{
Console.WriteLine("Lets play the Low or High Game");
var game = new Game();
game.attemp = InputAttempt();
PlayGame(game);
}
public static void PlayGame(Game game)
{
Console.WriteLine(game);
var comNum = GenerateComNum();
Console.WriteLine($"This is for test: ComNum is {comNum}");
do
{
var userNum = GenerateUserNum();
CompareNum(userNum, comNum, game);
Console.WriteLine(game);
} while (game.attemp >0 );
}
static void CompareNum(int userNum, int comNum,Game game)
{
if (userNum < comNum)
{
Console.WriteLine("User num is too Low try again");
Console.WriteLine();
game.attemp--;
}
else if(userNum > comNum)
{
Console.WriteLine("User num is too High try again");
Console.WriteLine();
game.attemp--;
}
else if(userNum == comNum)
{
Console.WriteLine("You got the answer!!");
Console.WriteLine();
game.attemp += 2;
PlayGame(game);
}
}
static int GenerateUserNum()
{
int userNum;
Console.Write("Please enter the num btw 1-100\t\t");
while (!Int32.TryParse(Console.ReadLine(), out userNum))
{
Console.WriteLine("Invalid num please input whole num");
}
return userNum;
}
static int GenerateComNum()
{
Random rnd = new Random();
var comNum = rnd.Next(1,101);
return comNum;
}
static int InputAttempt()
{
var attempt = 0;
Console.Write("How many Attemps would you like?\t");
while (!Int32.TryParse(Console.ReadLine(), out attempt))
{
Console.WriteLine("Invalid num please input whole num");
}
return attempt;
}
}
</code></pre>
| [] | [
{
"body": "<p>1) Avoid using <code>var</code> if you want your code to be more readable.</p>\n\n<p>2) Both <code>CompareNum()</code> and <code>PlayGame()</code> methods should be defined within the <code>Game</code> class as they rely on a game (which means they don't need to have a game as argument anymore)</p... | {
"AcceptedAnswerId": "205134",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-10-08T05:31:37.057",
"Id": "205132",
"Score": "2",
"Tags": [
"c#",
"number-guessing-game"
],
"Title": "Simple random number guessing game with various difficulties"
} | 205132 |
<p>Recently, I had a sick leave and to had some fun and improve coding skills I got a challenge to write a Snake Game for WPF.</p>
<p><strong>Desired RESULT</strong></p>
<p>1) Game must be in separate .dll library;</p>
<p>2) Must have settings;</p>
<p>3) Must use Canvas as playing field.</p>
<p><strong>SOURCE</strong></p>
<p>If you want to skip reading or just to watch and to make review - you're welcome <a href="https://github.com/HelloNetWorld/SnakeGameOnWPF" rel="nofollow noreferrer">here</a>.</p>
<p><strong>HOW TO PLAY</strong></p>
<p><a href="https://i.stack.imgur.com/Hsfee.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Hsfee.png" alt="enter image description here"></a></p>
<p>If you dowload source there would be additional Escape key to Close Main window</p>
<p><strong>USAGE</strong></p>
<p>This library must be used as you might expect. Just add library to your wpf-project, and instantiate <code>SnakeGame</code> class with input parameters:</p>
<pre><code>public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
Loaded += SnakeGameLoader;
KeyDown += new KeyEventHandler(CloseOnEsc);
}
private void SnakeGameLoader(object sender, RoutedEventArgs e)
{
var snakeGame = new SnakeGame
{
Snake = new Snake(
length: 3,
startPosition: StartPosition.Center,
bodyColor: Brushes.Red,
headColor: Brushes.Black),
GameField = new GameField(
pixelSize: 50,
playingField: playingField,
pixelType: PixelType.Square),
Difficulty = Difficulty.Hard,
FoodColor = Brushes.GreenYellow,
AmountOfFood = 6
};
snakeGame.Start();
}
private void CloseOnEsc(object sender, KeyEventArgs e)
{
if (e.Key == Key.Escape) Close();
}
}
</code></pre>
<p><strong>SnakeGame.cs</strong></p>
<pre><code>public class SnakeGame
{
#region Properties
public Snake Snake { get; set; }
public GameField GameField { get; set; }
public Difficulty Difficulty { get; set; }
public int AmountOfFood { get; set; }
public SolidColorBrush FoodColor { get; set; }
#endregion
#region Public methods
public void Start()
{
if (GameField == null)
{
throw new ArgumentNullException(nameof(GameField));
}
if (Snake == null)
{
throw new ArgumentNullException(nameof(Snake));
}
if (Difficulty < Difficulty.Impossible || Difficulty > Difficulty.Easy)
{
throw new ArgumentException($"{nameof(Difficulty)} illegal enum value");
}
Snake.InitializeSnake(GameField, Difficulty);
Snake.OnLackOfFood += InitializeFood;
Snake.OnSnakeCrash += GameOver;
Snake.StartMoving();
}
#endregion
#region Private methods
private void InitializeFood(object sender, EventArgs e)
{
if (FoodColor == null)
{
throw new ArgumentNullException(nameof(FoodColor));
}
if (AmountOfFood <= 0)
{
throw new ArgumentOutOfRangeException($"{nameof(AmountOfFood)} must be positive");
}
var emptyPixels = GameField.GetPixels().Where(s => s.GetFillColor == null).ToArray();
var random = new Random();
int foodCount = 0;
do
{
var randomIndex = random.Next(0, emptyPixels.Length);
emptyPixels[randomIndex].Fill(FoodColor);
emptyPixels[randomIndex].IsFood = true;
}
while (++foodCount < AmountOfFood);
}
private void GameOver(object sender, EventArgs e)
{
GameField.Clear();
GameField.ResultBoard(Snake.MovesCount, Snake.ScoreCount);
Snake.OnLackOfFood -= InitializeFood;
}
#endregion
}
</code></pre>
<p><strong>GameField.cs</strong></p>
<p>Actually <code>GameField</code> is a Matrix[M,N] where M - amount of Rows, N - amount of Columns. </p>
<pre><code>public class GameField
{
#region Fields
private readonly Pixel[,] _pixels;
#endregion
#region Ctor
/// <summary>
/// Initializes a new instance of GameField
/// </summary>
/// <param name="pixelSize">Size of squares in pixels (must be between 10 and 100)</param>
/// <param name="playingField">Playing field</param>
/// <param name="pixelType">Pixels type</param>
public GameField(int pixelSize, Canvas playingField, PixelType pixelType)
{
if (pixelType < PixelType.Circle || pixelType > PixelType.Square)
{
throw new ArgumentException($"{nameof(pixelType)} illegal enum value");
}
Pixel.PixelType = pixelType;
if (pixelSize < 10 || pixelSize > 100)
{
throw new ArgumentOutOfRangeException($"{nameof(pixelSize)} must be between '5' and '100'");
}
Pixel.Canvas = playingField ?? throw new ArgumentNullException(nameof(playingField));
Pixel.Size = pixelSize;
Rows = (int)Math.Floor(playingField.ActualHeight / pixelSize);
Columns = (int)Math.Floor(playingField.ActualWidth / pixelSize);
Pixel.Corrective = Tuple.Create(
playingField.ActualHeight % pixelSize / Rows,
playingField.ActualWidth % pixelSize / Columns);
_pixels = new Pixel[Rows, Columns];
for (int i = 0; i < Rows; i++)
{
for (int j = 0; j < Columns; j++)
{
_pixels[i, j] = new Pixel(i, j);
}
}
}
#endregion
#region Public methods
public void ResultBoard(int movesCount, double scoreCount)
{
var grid = new Grid
{
Height = Pixel.Canvas.ActualHeight,
Width = Pixel.Canvas.ActualWidth
};
var label = new Label
{
Content = $"GAME OVER\nMoves: {movesCount}, Score: {scoreCount: 0}",
Foreground = Brushes.GreenYellow,
FontSize = 50,
HorizontalAlignment = HorizontalAlignment.Center,
VerticalAlignment = VerticalAlignment.Center
};
grid.Children.Add(label);
Pixel.Canvas.Children.Add(grid);
}
internal IEnumerable<Pixel> GetPixels()
{
for (int i = 0; i < Rows; i++)
{
for (int j = 0; j < Columns; j++)
{
yield return _pixels[i, j];
}
}
}
public void Clear() => Pixel.Canvas.Children.Clear();
public (int i, int j) GetStartingPoint(StartPosition startPosition)
{
switch (startPosition)
{
case StartPosition.Center:
return (Rows / 2, Columns / 2);
case StartPosition.LeftDownCorner:
return (Rows - 2, 1);
case StartPosition.LeftUpCorner:
return (1, 1);
case StartPosition.RightDownCorner:
return (Rows - 2, Columns - 2);
case StartPosition.RightUpCorner:
return (1, Columns - 2);
default: return (Rows / 2, Columns / 2);
}
}
public bool IsLackOfFood => !GetPixels().Any(p => p.IsFood);
#endregion
#region Indexer
internal Pixel this[int i, int j]
{
get
{
if (i < 0 || i >= Rows)
{
throw new ArgumentOutOfRangeException($"{nameof(i)} must be between '0' and '{Rows}'");
}
if (j < 0 || j >= Columns)
{
throw new ArgumentOutOfRangeException($"{nameof(j)} must be between '0' and '{Columns}'");
}
return _pixels[i, j];
}
}
#endregion
#region Properties
public int Rows { get; }
public int Columns { get; }
#endregion
}
</code></pre>
<p><strong>Pixel</strong></p>
<p>Pixel instance is an element of Matrix(gamefield), where i - row, j - column. It has Shape - circle or square - depends on SnakeGame input settings.</p>
<pre><code>internal class Pixel
{
#region Fields
private readonly Shape _pixel;
#endregion
#region Ctor
public Pixel(int i, int j)
{
I = i;
J = j;
double yCoordinate = i * (Size + Corrective.Item1);
double xCoordinate = j * (Size + Corrective.Item2);
if (PixelType == PixelType.Circle)
{
_pixel = new Ellipse();
}
else
{
_pixel = new Rectangle();
}
IsFood = false;
_pixel.Height = Size;
_pixel.Width = Size;
Canvas.Children.Add(_pixel);
Canvas.SetLeft(_pixel, xCoordinate);
Canvas.SetTop(_pixel, yCoordinate);
}
#endregion
#region Public methods
public void Fill(SolidColorBrush brush) => _pixel.Fill = brush;
public void Unfill() => _pixel.Fill = null;
#endregion
#region Properties
public static Canvas Canvas { get; set; }
public static PixelType PixelType { get; set; }
public static Tuple<double,double> Corrective { get; set; }
public static int Size { get; set; }
public Brush GetFillColor => _pixel.Fill;
public int I { get; set; }
public int J { get; set; }
public bool IsFood { get; set; }
#endregion
}
</code></pre>
<p><strong>Snake.cs</strong></p>
<pre><code>public class Snake
{
#region Fields
private GameField _gameField;
private readonly DispatcherTimer _dispatcherTimer;
#endregion
#region Ctors
private Snake(int length)
{
if (length <= 0)
{
throw new ArgumentOutOfRangeException($"{nameof(length)} must be positive");
}
Body = new List<Pixel>();
MovingDirection = Direction.Right;
_dispatcherTimer = new DispatcherTimer();
_dispatcherTimer.Tick += Move;
Length = length;
}
/// <summary>
/// Initializes a new instance of Snake
/// </summary>
/// <param name="length">Length (must be between 3 and 10)</param>
/// <param name="startPosition">Start position</param>
/// <param name="bodyColor">Body Color</param>
/// <param name="headColor">Head Color</param>
public Snake(int length, StartPosition startPosition, SolidColorBrush bodyColor,
SolidColorBrush headColor) : this(length)
{
StartPosition = startPosition;
BodyColor = bodyColor;
HeadColor = headColor;
}
#endregion
#region Events
/// <summary>
/// Occurs when snake crashes
/// </summary>
public event EventHandler OnSnakeCrash;
/// <summary>
/// Occurs when there is no food
/// </summary>
public event EventHandler OnLackOfFood;
#endregion
#region Public methods
/// <summary>
/// Initializes a snake on game field
/// </summary>
/// <param name="gamefield">Game Field</param>
/// <param name="difficulty">Difficulty</param>
public void InitializeSnake(GameField gamefield, Difficulty difficulty)
{
_dispatcherTimer.Interval = new TimeSpan(0, 0, 0, 0, (int)difficulty);
_gameField = gamefield ?? throw new ArgumentNullException(nameof(gamefield));
var startingPoint = gamefield.GetStartingPoint(StartPosition);
Head = gamefield[startingPoint.i, startingPoint.j];
Head.Fill(HeadColor);
for (int i = 1; i <= Length; i++)
{
var square = gamefield[startingPoint.i, startingPoint.j - i];
square.Fill(BodyColor);
Body.Add(square);
}
Pixel.Canvas.Focusable = true;
Keyboard.Focus(Pixel.Canvas);
Pixel.Canvas.KeyDown += OnKeyDown;
}
/// <summary>
/// Starts moving in MovingDirection
/// </summary>
public void StartMoving() => _dispatcherTimer.Start();
/// <summary>
/// Stops moving
/// </summary>
public void StopMoving() => _dispatcherTimer.Stop();
#endregion
#region Properties
public SolidColorBrush BodyColor { get; set; }
public SolidColorBrush HeadColor { get; set; }
public Direction MovingDirection { get; set; }
public StartPosition StartPosition { get; set; }
/// <summary>
/// Length without Head
/// </summary>
public int Length { get; private set; }
internal List<Pixel> Body { get; }
internal Pixel Head { get; private set; }
public int MovesCount { get; set; }
public double ScoreCount { get; set; }
#endregion
#region Private methods
private void Move(object sender, EventArgs e)
{
if (MovingDirection < Direction.Up || MovingDirection > Direction.Left)
{
throw new ArgumentException($"{nameof(MovingDirection)} illegal enum value");
}
// Speed changes every 100 moves
if (++MovesCount % 100 == 0)
{
SpeedUp();
}
if (_gameField.IsLackOfFood)
{
OnLackOfFood?.Invoke(this, null);
}
Head.Fill(BodyColor);
Body.Insert(0, Head); // Insert head into body - oh my Gosh
try
{
switch (MovingDirection)
{
//gets a brand new Head ;)
case Direction.Down:
Head = _gameField[Head.I + 1, Head.J];
break;
case Direction.Up:
Head = _gameField[Head.I - 1, Head.J];
break;
case Direction.Left:
Head = _gameField[Head.I, Head.J - 1];
break;
case Direction.Right:
Head = _gameField[Head.I, Head.J + 1];
break;
}
}
catch (ArgumentOutOfRangeException)
{
StopMoving();
_dispatcherTimer.Tick -= Move;
OnSnakeCrash?.Invoke(this, null);
}
Head.Fill(HeadColor);
if (Head.IsFood)
{
Head.IsFood = false;
ScoreCount = Math.Ceiling(10 + (0.5 * MovesCount));
Length++;
}
else
{
Body.Last().Unfill();
Body.RemoveAt(Length);
}
if (IsBodyRammedByHead())
{
StopMoving();
_dispatcherTimer.Tick -= Move;
OnSnakeCrash?.Invoke(this, null);
}
}
private void OnKeyDown(object sender, KeyEventArgs eventArgs)
{
switch (eventArgs.Key)
{
case Key.W:
if (MovingDirection != Direction.Down)
MovingDirection = Direction.Up;
break;
case Key.S:
if (MovingDirection != Direction.Up)
MovingDirection = Direction.Down;
break;
case Key.A:
if (MovingDirection != Direction.Right)
MovingDirection = Direction.Left;
break;
case Key.D:
if (MovingDirection != Direction.Left)
MovingDirection = Direction.Right;
break;
case Key.P:
if (_dispatcherTimer.IsEnabled)
{
StopMoving();
}
else
{
StartMoving();
}
break;
}
}
/// <summary>
/// Indicating whether Body was rammed by Head ;)
/// </summary>
/// <returns></returns>
private bool IsBodyRammedByHead() => Body.Contains(Head);
/// <summary>
/// Accelerates snake movement
/// </summary>
private void SpeedUp()
{
int currentInterval = _dispatcherTimer.Interval.Milliseconds;
int subtractor = currentInterval / 3;
_dispatcherTimer.Interval = new TimeSpan(0, 0, 0, 0, currentInterval - subtractor);
}
#endregion
}
</code></pre>
<p><strong>ENUMS</strong></p>
<pre><code>public enum Direction
{
Up,
Down,
Right,
Left
}
public enum PixelType
{
Circle,
Square
}
public enum StartPosition
{
Center,
[Obsolete("Not supported")]
LeftUpCorner,
[Obsolete("Not supported")]
LeftDownCorner,
[Obsolete("Not supported")]
RightUpCorner,
[Obsolete("Not supported")]
RightDownCorner
}
public enum Difficulty
{
Easy = 300,
Normal = 250,
Hard = 200,
VeryHard = 180,
Impossible = 140
}
</code></pre>
<p>What I wrote seems to work although would be very helpfull if you point to my strong and weak points in c# codding.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-10-08T12:36:04.777",
"Id": "395625",
"Score": "0",
"body": "After a fast review : \n\n1) Avoid using `var` it makes the code way less readable.\n\n2) You have some bad indentation\n\n3) `SnakeGame.InitializeFood()` in there you create a `... | [
{
"body": "<h2>Mixing responsibilities</h2>\n\n<pre><code>var snakeGame = new SnakeGame\n{\n Snake = new Snake(\n length: 3,\n startPosition: StartPosition.Center,\n bodyColor: Brushes.Red,\n headColor: Brushes.Black),\n GameField = new GameField(\n pixelSize: 50,\n ... | {
"AcceptedAnswerId": "205152",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-10-08T12:07:36.183",
"Id": "205140",
"Score": "3",
"Tags": [
"c#",
"game",
"wpf",
"library"
],
"Title": "Snake Game Library for WPF"
} | 205140 |
<p>I have a dictionary <code>self.indexList = {}</code> filled with 3-item-lists <code>values = [lineId, nominalLineId, vertex]</code> for each dictionary key (its a supplement to a QgsSpatialIndex in PyQGIS, btw).</p>
<p>I need to reverse-search this dictionary for matching tuples of <code>lineId</code> and <code>vertex</code>. This function is the dealbreaker in a larger PyQGIS algorithm; called multiple times (almost 40.000 with a large test dataset) and causing 2/3 of total running time.</p>
<pre><code>def get_idx_from_values(instance, lineID, vertex):
"""Searches the indexList for a lineID and a vertex number (= unique line segment).
Returns dic index (=fid)."""
items = instance.indexList.items()
for idx, values in items:
if values[0] == lineID and values[2] == vertex:
return idx
print("No index entry found for line " + str(lineID) + ", Vertex " + str(vertex))
return None
</code></pre>
<p>I already found <a href="https://codereview.stackexchange.com/questions/124377/search-in-a-big-dictionary-python">Search in a big dictionary Python</a> where a second dictionary with a reversion of key and value is suggested.</p>
<p>I consider this, but I'm open for other suggestions how to speed up the code above, as my case - matching two values with a certain key - adds complexity to the simple key/value reversion.</p>
| [] | [
{
"body": "<p>Tuples can be used as dictionary keys, so creating a second dictionary for reverse lookups can be as simple as:</p>\n\n<pre><code>reverse_lookup = {(lineID, vertex): idx \n for idx, (lineId, _, vertex) \n in instance.indexList.items()}\n</code></pre>\n",
"comm... | {
"AcceptedAnswerId": "205144",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-10-08T12:17:12.300",
"Id": "205141",
"Score": "1",
"Tags": [
"python",
"performance",
"python-3.x",
"hash-map"
],
"Title": "Search dictionary for matching values"
} | 205141 |
<p>I want to implement a directed graph which has 3 main kind of edges:</p>
<ul>
<li>self referencing edges</li>
<li>non directional edges between two nodes</li>
<li>directional edges between two nodes</li>
</ul>
<p><a href="https://i.stack.imgur.com/K9Dz3.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/K9Dz3.png" alt="Three-node graph. A has a self-edge, a bidirectional edge with B, and a unidirectional edge to C."></a></p>
<p>Also I want to be able to do global operations on the graph, like e.g. counting or removing all edges fulfilling certain criteria.</p>
<p>The easiest program structure I came up with is:</p>
<pre><code>#include <unordered_set>
using namespace std;
struct Edge;
struct Node
{
Node(std::string name):name(name){}
string name;
std::unordered_set<Edge*> edges;
};
struct Edge
{
Edge(Node * node1): node1(node1){}
double weight;
Node * node1;
};
struct EdgeBetweenTwoNodes: public Edge
{
EdgeBetweenTwoNodes(Node * node1, Node * node2 ): Edge(node1), node2(node2){}
Node * node2;
};
struct DirectionalEdge: public EdgeBetweenTwoNodes
{
DirectionalEdge(Node * node1, Node * node2, bool direction ): EdgeBetweenTwoNodes(node1,node2), direction(direction){}
bool direction;
};
struct EdgesContainer
{
std::unordered_set<Edge*> all_edges;
void register_new_edge(Edge * edge)
{
all_edges.insert(edge);
}
//do all kind of manipulations on all edges of a cetain type...
};
struct EdgeFactory
{
EdgeFactory(){}
void create_edge(Node* node1,EdgesContainer & edge_container)
{
Edge * edge = new Edge(node1);
node1->edges.insert(edge);
edge_container.register_new_edge(edge);
}
void create_edge(Node* node1, Node* node2, EdgesContainer & edge_container)
{
EdgeBetweenTwoNodes * edge = new EdgeBetweenTwoNodes(node1,node2);
node1->edges.insert(edge);
node2->edges.insert(edge);
edge_container.register_new_edge(edge);
}
void create_edge(Node* node1, Node* node2, bool direction, EdgesContainer & edge_container)
{
DirectionalEdge * edge = new DirectionalEdge(node1,node2,direction);
node1->edges.insert(edge);
node2->edges.insert(edge);
edge_container.register_new_edge(edge);
}
};
int main()
{
Node * A = new Node("A");
Node * B= new Node("B");
Node * C= new Node("C");
EdgesContainer edges;
EdgeFactory edge_factory;
edge_factory.create_edge(A,edges);
edge_factory.create_edge(A,B,edges);
edge_factory.create_edge(A,C,1,edges);
return 0;
}
</code></pre>
<p>What do you think about it? Is this the correct use of a so called "Factory?"</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-10-08T17:01:16.243",
"Id": "395675",
"Score": "1",
"body": "Please do not update the code in your question to incorporate feedback from answers, doing so goes against the Question + Answer style of Code Review. This is not a forum where y... | [
{
"body": "<p>Don't use <code>using namespace std;</code> it pollutes the namespace and creates name collisions. Only do this with concrete classes and only within a namespace or cpp file.</p>\n\n<hr>\n\n<p><code>new</code> without <code>delete</code> => leaks. Instead use smart pointers or store them by value ... | {
"AcceptedAnswerId": "205173",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-10-08T12:42:20.537",
"Id": "205142",
"Score": "7",
"Tags": [
"c++",
"graph"
],
"Title": "Factory for constructing directed graphs in C++"
} | 205142 |
<p>So I have some test, maybe the given side of that test is not so important to catch the point of my confusion. I wrote </p>
<pre><code>List<LinkedHashMap> failedEvents = ...
//...
assertEquals(failedEvents.size(),1 );
assertTrue(failedEvents.stream().allMatch(x -> x.get("eventId").equals("EVENT3")));
</code></pre>
<p>and in the result my code review said I should avoid stream on single element. But I think is clear and readable to show that all elements pass specific matching rule.
Also I though about assertThat, but I ended with much bigger and more complicated piece of code.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-10-08T13:37:27.033",
"Id": "395643",
"Score": "0",
"body": "Your title should explain what the code does, not what your question asks."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-10-08T13:39:11.180",
"Id"... | [
{
"body": "<p>One cannot say anything against</p>\n\n<pre><code>assertEquals(failedEvents.size(), 1);\nassertEquals(failedEvents.get(0).get(\"eventId\"), \"EVENT3\");\n</code></pre>\n\n<p>It is even shorter and more clear.</p>\n\n<p>However your argument of an <strong>invariant</strong> on the entire collection... | {
"AcceptedAnswerId": "205147",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-10-08T12:47:53.637",
"Id": "205143",
"Score": "0",
"Tags": [
"java",
"unit-testing",
"validation",
"junit"
],
"Title": "Assert LinkedHashMap element in jUnit test"
} | 205143 |
<p><a href="https://ctan.org/pkg/pgf" rel="nofollow noreferrer">PGF</a> is a graphics framework for <span class="math-container">\$\TeX\$</span> and friends. It supports shadings (gradients), but only in RGB.</p>
<p>There is often a need to output shadings in CMYK and I am having a go at implementing this.</p>
<p>I'm looking for feedback from those who know PGF well as to whether my strategy is good or not and what things I might not have considered.</p>
<p>At present, only axial and radial shadings are supported (not functional ones).</p>
<p>The package is for *<span class="math-container">\$\LaTeX\$</span>, not ConTeXt or Plain <span class="math-container">\$\TeX\$</span>.</p>
<p>And not all backends are supported (only <code>pdftex</code>, <code>luatex</code>, <code>xetex</code>, and <code>dvipdfmx</code>).</p>
<p>This code is currently implemented as a separate package to <code>pgf</code>, but could possibly be included in the main package in the future.</p>
<p>The code is hosted on GitHub at <a href="https://github.com/dcpurton/pgf-cmykshadings/tree/52bf22b3f770415bc9b66913307e17155fad835f" rel="nofollow noreferrer">https://github.com/dcpurton/pgf-cmykshadings</a></p>
<h1>Main style file (<code>pgf-cmykshadings.sty</code>)</h1>
<pre class="lang-tex prettyprint-override"><code>\ProvidesPackage{pgf-cmykshadings}[2018/10/08 CMYK shadings support for PGF (DCP)]
\RequirePackage{pgf}
% macros from pgfcoreshade.code.tex
\def\pgf@parsefunccmyk#1{%
\edef\temp{{#1}}%
\expandafter\pgf@convertcmykstring\temp%
\edef\temp{{\pgf@cmykconv}}%
\expandafter\pgf@@parsefunccmyk\temp}
\def\pgf@@parsefunccmyk#1{%
\let\pgf@bounds=\pgfutil@empty%
\let\pgf@funcs=\pgfutil@empty%
\let\pgf@psfuncs=\pgfutil@empty%
\let\pgf@encode=\pgfutil@empty%
\let\pgf@sys@shading@ranges=\pgfutil@empty%
\pgf@sys@shading@range@num=0\relax%
\pgf@parsefirstcmyk[#1; ]%
\pgf@parselastdomcmyk[#1; ]%
\pgf@parsemidcmyk[#1; ]%
\ifx\pgf@bounds\pgfutil@empty%
\edef\pgf@pdfparseddomain{0 1}%
\edef\pgf@pdfparsedfunction{\pgf@singlefunc\space}%
\else%
\edef\pgf@pdfparseddomain{\pgf@doma\space\pgf@domb}%
\edef\pgf@pdfparsedfunction{%
<< /FunctionType 3 /Domain [\pgf@doma\space\pgf@domb] /Functions
[\pgf@funcs\space] /Bounds [\pgf@bounds] /Encode [0 1 \pgf@encode]
>> }% <<
\fi%
\xdef\pgf@psfuncs{\pgf@psfuncs}%
}
\def\pgf@parsefirstcmyk[cmyk(#1)=(#2,#3,#4,#5)#6]{%
\pgfmathsetlength\pgf@x{#1}%
\edef\pgf@sys@shading@start@pos{\the\pgf@x}%
\pgf@sys@bp@correct\pgf@x%
\edef\pgf@doma{\pgf@sys@tonumber{\pgf@x}}%
\edef\pgf@prevx{\pgf@sys@tonumber{\pgf@x}}%
\pgf@getcmyktuplewithmixin{#2}{#3}{#4}{#5}%
\edef\pgf@sys@shading@start@cmyk{\pgf@sys@cmyk}%
\let\pgf@sys@prevcolor=\pgf@sys@shading@start@cmyk%
\let\pgf@sys@prevpos=\pgf@sys@shading@start@pos%
\edef\pgf@prevcolor{\pgf@cmyk}%
\edef\pgf@firstcolor{\pgf@cmyk}}
\def\pgf@parselastdomcmyk[cmyk(#1)=(#2,#3,#4,#5); {%
\pgfutil@ifnextchar]{%
\pgfmathsetlength\pgf@x{#1}%
\edef\pgf@sys@shading@end@pos{\the\pgf@x}%
\pgf@max=\pgf@x\relax%
\pgf@sys@bp@correct\pgf@x%
\edef\pgf@domb{\pgf@sys@tonumber{\pgf@x}}%
\pgf@getcmyktuplewithmixin{#2}{#3}{#4}{#5}%
\edef\pgf@sys@shading@end@cmyk{\pgf@sys@cmyk}%
\pgfutil@gobble}{\pgf@parselastdomcmyk[}}
\def\pgf@parsemidcmyk[cmyk(#1)=(#2,#3,#4,#5); {\pgf@parserestcmyk[}
\def\pgf@parserestcmyk[cmyk(#1)=(#2,#3,#4,#5); {%
\advance\pgf@sys@shading@range@num by1\relax%
\pgfutil@ifnextchar]{%
\pgf@getcmyktuplewithmixin{#2}{#3}{#4}{#5}%
\edef\pgf@singlefunc{\space%
<< /FunctionType 2 /Domain [0 1] /C0
[\pgf@prevcolor] /C1 [\pgf@cmyk] /N 1 >> }% <<
\edef\pgf@funcs{\pgf@funcs\space%
<< /FunctionType 2 /Domain [\pgf@doma\space\pgf@domb] /C0
[\pgf@prevcolor] /C1 [\pgf@cmyk] /N 1 >> }% <<
\edef\pgf@psfuncs{\pgf@prevx\space \pgf@cmyk\space \pgf@prevcolor\space pgfshade \pgf@psfuncs}%
\pgfmathsetlength\pgf@x{#1}%
\edef\pgf@sys@shading@ranges{\pgf@sys@shading@ranges{{\pgf@sys@prevpos}{\the\pgf@x}{\pgf@sys@prevcolor}{\pgf@sys@cmyk}}}%
\edef\pgf@sys@prevpos{\the\pgf@x}%
\let\pgf@sys@prevcolor=\pgf@sys@cmyk%
\pgfutil@gobble}{%
\pgfmathsetlength\pgf@x{#1}%
\pgf@getcmyktuplewithmixin{#2}{#3}{#4}{#5}%
\edef\pgf@sys@shading@ranges{\pgf@sys@shading@ranges{{\pgf@sys@prevpos}{\the\pgf@x}{\pgf@sys@prevcolor}{\pgf@sys@cmyk}}}%
\edef\pgf@sys@prevpos{\the\pgf@x}%
\let\pgf@sys@prevcolor=\pgf@sys@cmyk%
\edef\pgf@psfuncs{\pgf@prevx\space \pgf@cmyk\space \pgf@prevcolor\space pgfshade \pgf@psfuncs}%
\pgf@sys@bp@correct\pgf@x%
\edef\pgf@prevx{\pgf@sys@tonumber{\pgf@x}}%
\edef\pgf@bounds{\pgf@bounds\space\pgf@sys@tonumber{\pgf@x}}%
\edef\pgf@encode{\pgf@encode\space0 1}%
\edef\pgf@singlefunc{\space%
<< /FunctionType 2 /Domain [0 1] /C0
[\pgf@prevcolor] /C1 [\pgf@cmyk] /N 1 >> }% <<
\edef\pgf@funcs{\pgf@funcs\space%
<< /FunctionType 2 /Domain [\pgf@doma\space\pgf@domb] /C0
[\pgf@prevcolor] /C1 [\pgf@cmyk] /N 1 >> }% <<
\edef\pgf@prevcolor{\pgf@cmyk}%
\pgf@parserestcmyk[}}
\def\pgf@getcmyktuplewithmixin#1#2#3#4{%
\pgfutil@definecolor{pgfshadetemp}{cmyk}{#1,#2,#3,#4}%
\pgfutil@ifundefined{applycolormixins}{}{\applycolormixins{pgfshadetemp}}%
\pgfutil@extractcolorspec{pgfshadetemp}{\pgf@tempcolor}%
\expandafter\pgfutil@convertcolorspec\pgf@tempcolor{cmyk}{\pgf@cmykcolor}%
\expandafter\pgf@getcmyk@@\pgf@cmykcolor!}
\def\pgf@getcmyk@@#1,#2,#3,#4!{%
\def\pgf@cmyk{#1 #2 #3 #4}%
\def\pgf@sys@cmyk{{#1}{#2}{#3}{#4}}%
}
\def\pgf@convertcmykstring#1{%
\def\pgf@cmykconv{}%
\pgf@converttocmyk#1]%
}
\def\pgf@converttocmyk{%
\pgfutil@ifnextchar]{\pgfutil@gobble}%done!
{%
\pgfutil@ifnextchar;{\pgf@grabsemicolorcmyk}%
{%
\pgfutil@ifnextchar c{\pgf@gobblec}%
{%
\pgfutil@ifnextchar g{\pgf@grabgraycmyk}%
{%
\pgfutil@ifnextchar o{\pgf@grabcolorcmyk}%
{%
\pgfutil@ifnextchar m{\pgf@grabcmyk}%
{%
\pgfutil@ifnextchar r{\pgf@grabrgbcmyk}%
{\pgferror{Illformed shading
specification}\pgf@converttocmyk}%
}%
}%
}%
}%
}%
}%
}
\def\pgf@grabsemicolorcmyk;{%
\edef\pgf@cmykconv{\pgf@cmykconv; }\pgf@converttocmyk}
\def\pgf@gobblec c{\pgf@converttocmyk}
\def\pgf@grabrgbcmyk rgb(#1)=(#2,#3,#4){%
\pgfutil@definecolor{pgf@tempcol}{rgb}{#2,#3,#4}%
\pgfutil@extractcolorspec{pgf@tempcol}{\pgf@tempcolor}%
\expandafter\pgfutil@convertcolorspec\pgf@tempcolor{cmyk}{\pgf@cmykcolor}%
\expandafter\pgf@convgetcmyk@\expandafter{\pgf@cmykcolor}{#1}%
}
\def\pgf@grabcmyk myk(#1)=(#2,#3,#4,#5){%
\edef\pgf@cmykconv{\pgf@cmykconv cmyk(#1)=(#2,#3,#4,#5)}\pgf@converttocmyk}
\def\pgf@grabgraycmyk gray(#1)=(#2){%
\edef\pgf@cmykconv{\pgf@cmykconv cmyk(#1)=(0,0,0,#2)}\pgf@converttocmyk}
\def\pgf@grabcolorcmyk olor(#1)=(#2){%
\pgfutil@colorlet{pgf@tempcol}{#2}%
\pgfutil@extractcolorspec{pgf@tempcol}{\pgf@tempcolor}%
\expandafter\pgfutil@convertcolorspec\pgf@tempcolor{cmyk}{\pgf@cmykcolor}%
\expandafter\pgf@convgetcmyk@\expandafter{\pgf@cmykcolor}{#1}%
}
\def\pgf@convgetcmyk@#1#2{%
\edef\pgf@cmykconv{\pgf@cmykconv cmyk(#2)=(#1)}\pgf@converttocmyk}
\def\pgfdeclarehorizontalcmykshading{\pgfutil@ifnextchar[\pgf@declarehorizontalcmykshading{\pgf@declarehorizontalcmykshading[]}}%
\def\pgf@declarehorizontalcmykshading[#1]#2#3#4{%
\expandafter\def\csname pgf@deps@pgfshading#2!\endcsname{#1}%
\expandafter\ifx\csname pgf@deps@pgfshading#2!\endcsname\pgfutil@empty%
\pgfsys@horicmykshading{#2}{#3}{#4}%
\else%
\expandafter\def\csname pgf@func@pgfshading#2!\endcsname{\pgfsys@horicmykshading}%
\expandafter\def\csname pgf@args@pgfshading#2!\endcsname{{#3}{#4}}%
\expandafter\let\csname @pgfshading#2!\endcsname=\pgfutil@empty%
\fi}
\def\pgfdeclareverticalcmykshading{\pgfutil@ifnextchar[\pgf@declareverticalcmykshading{\pgf@declareverticalcmykshading[]}}%
\def\pgf@declareverticalcmykshading[#1]#2#3#4{%
\expandafter\def\csname pgf@deps@pgfshading#2!\endcsname{#1}%
\expandafter\ifx\csname pgf@deps@pgfshading#2!\endcsname\pgfutil@empty%
\pgfsys@vertcmykshading{#2}{#3}{#4}%
\else%
\expandafter\def\csname pgf@func@pgfshading#2!\endcsname{\pgfsys@vertcmykshading}%
\expandafter\def\csname pgf@args@pgfshading#2!\endcsname{{#3}{#4}}%
\expandafter\let\csname @pgfshading#2!\endcsname=\pgfutil@empty%
\fi}
\def\pgfdeclareradialcmykshading{\pgfutil@ifnextchar[\pgf@declareradialcmykshading{\pgf@declareradialcmykshading[]}}%
\def\pgf@declareradialcmykshading[#1]#2#3#4{%
\expandafter\def\csname pgf@deps@pgfshading#2!\endcsname{#1}%
\expandafter\ifx\csname pgf@deps@pgfshading#2!\endcsname\pgfutil@empty%
\pgfsys@radialcmykshading{#2}{#3}{#4}%
\else%
\expandafter\def\csname pgf@func@pgfshading#2!\endcsname{\pgfsys@radialcmykshading}%
\expandafter\def\csname pgf@args@pgfshading#2!\endcsname{{#3}{#4}}%
\expandafter\let\csname @pgfshading#2!\endcsname=\pgfutil@empty%
\fi}
\def\pgfusecmykshading#1{%
\edef\pgf@shadingname{@pgfshading#1}%
\pgf@tryextensions{\pgf@shadingname}{\pgfalternateextension}%
\expandafter\pgfutil@ifundefined\expandafter{\pgf@shadingname}%
{\pgferror{Undefined shading "#1"}}%
{%
{%
\pgfutil@globalcolorsfalse%
\def\pgf@shade@adds{}%
\pgfutil@ifundefined{pgf@deps\pgf@shadingname}%
{}%
{%
\edef\@list{\csname pgf@deps\pgf@shadingname\endcsname}%
\pgfutil@for\@temp:=\@list\do{%
{%
\pgfutil@ifundefined{applycolormixins}{}{\applycolormixins{\@temp}}%
\pgfutil@extractcolorspec{\@temp}{\pgf@tempcolor}%
\expandafter\pgfutil@convertcolorspec\pgf@tempcolor{cmyk}{\pgf@cmykcolor}%
\xdef\pgf@shade@adds{\pgf@shade@adds,\pgf@cmykcolor}%
}%
}%
}%
\expandafter\pgf@strip@shadename\pgf@shadingname!!%
\pgfutil@ifundefined{@pgfshading\pgf@basename\pgf@shade@adds!}%
{%
{%
\expandafter\def\expandafter\@temp\expandafter{\csname pgf@func\pgf@shadingname\endcsname}%
\edef\@args{{\pgf@basename\pgf@shade@adds}}%
\expandafter\expandafter\expandafter\def%
\expandafter\expandafter\expandafter\@@args%
\expandafter\expandafter\expandafter{\csname pgf@args\pgf@shadingname\endcsname}%
\expandafter\expandafter\expandafter\@temp\expandafter\@args\@@args%
%
}%
}%
{}%
\pgf@invokeshading{\csname @pgfshading\pgf@basename\pgf@shade@adds!\endcsname}%
}%
}%
}
% load the correct driver
\def\pgfutilgetcmykshadingsdriver{%
\expandafter\pgfutil@getcmykshadingsdriver\pgfsysdriver[
}
\def\pgfutil@getcmykshadingsdriver pgfsys-#1[{%
\edef\pgfsyscmykshadingsdriver{pgfsys-cmykshadings-#1}%
}
\pgfutilgetcmykshadingsdriver
\input\pgfsyscmykshadingsdriver
% style options to make use CMYK gradients by default or not
\let\pgfdeclarehorizontalrgbshading\pgfdeclarehorizontalshading
\let\pgfdeclareverticalrgbshading\pgfdeclareverticalshading
\let\pgfdeclareradialrgbshading\pgfdeclareradialshading
\let\pgfusergbshading\pgfuseshading
\DeclareOption{default}{%
\let\pgfdeclarehorizontalshading\pgfdeclarehorizontalcmykshading
\let\pgfdeclareverticalshading\pgfdeclareverticalcmykshading
\let\pgfdeclareradialshading\pgfdeclareradialcmykshading
\let\pgfuseshading\pgfusecmykshading
}
\DeclareOption{nodefault}{%
\let\pgfdeclarehorizontalshading\pgfdeclarehorizontalrgbshading
\let\pgfdeclareverticalshading\pgfdeclareverticalrgbshading
\let\pgfdeclareradialshading\pgfdeclareradialrgbshading
\let\pgfuseshading\pgfusergbshading
}
\ExecuteOptions{default}
\ProcessOptions\relax
</code></pre>
<h1><code>pdftex</code> driver (<code>pgfsys-cmykshadings-pdftex.def</code>)</h1>
<p>Other drivers are analogous.</p>
<pre class="lang-tex prettyprint-override"><code>\ProvidesFile{pgfsys-cmykshadings-pdftex.def}[2018/10/08 CMYK shadings support for PGF pdftex driver (DCP)]
\def\pgfsys@horicmykshading#1#2#3{%
{%
\pgf@parsefunccmyk{#3}%
\pgfmathparse{#2}%
\setbox\pgfutil@tempboxa=\hbox to\pgf@max{\vbox to\pgfmathresult pt{\vfil\pgfsys@invoke{/Sh sh}}\hfil}%
\pgf@process{\pgfpoint{\pgf@max}{#2}}%
\immediate\pdfxform resources {%
/Shading << /Sh << /ShadingType 2
/ColorSpace /DeviceCMYK
/Domain [\pgf@pdfparseddomain]
/Coords [\pgf@doma\space0 \pgf@domb\space0]
/Function \pgf@pdfparsedfunction
/Extend [false false] >> >>}\pgfutil@tempboxa% <<
\expandafter\xdef\csname @pgfshading#1!\endcsname{\leavevmode\noexpand\pdfrefxform\the\pdflastxform}%
}%
}
\def\pgfsys@vertcmykshading#1#2#3{%
{%
\pgf@parsefunccmyk{#3}%
\pgfmathparse{#2}%
\setbox\pgfutil@tempboxa=\hbox to\pgfmathresult pt{\vbox to\pgf@max{\vfil\pgfsys@invoke{/Sh sh}}\hfil}%
\pgf@process{\pgfpoint{#2}{\pgf@max}}%
\immediate\pdfxform resources {%
/Shading << /Sh << /ShadingType 2
/ColorSpace /DeviceCMYK
/Domain [\pgf@pdfparseddomain]
/Coords [0 \pgf@doma\space0 \pgf@domb]
/Function \pgf@pdfparsedfunction
/Extend [false false] >> >>}\pgfutil@tempboxa% <<
\expandafter\xdef\csname @pgfshading#1!\endcsname{\leavevmode\noexpand\pdfrefxform\the\pdflastxform}%
}%
}
\def\pgfsys@radialcmykshading#1#2#3{%
{%
\pgf@parsefunccmyk{#3}%
\setbox\pgfutil@tempboxa=\hbox to2\pgf@max{\vbox to2\pgf@max{\vfil\pgfsys@invoke{/Sh sh}}\hfil}%
\pgf@process{#2}%
\pgf@xa=\pgf@x%
\pgf@ya=\pgf@y%
\pgf@process{\pgfpoint{\pgf@max}{\pgf@max}}%
\advance\pgf@xa by \pgf@x%
\advance\pgf@ya by \pgf@y%
\pgf@sys@bp@correct{\pgf@x}%
\pgf@sys@bp@correct{\pgf@y}%
\pgf@sys@bp@correct{\pgf@xa}%
\pgf@sys@bp@correct{\pgf@ya}%
\immediate\pdfxform resources {%
/Shading << /Sh << /ShadingType 3
/ColorSpace /DeviceCMYK
/Domain [\pgf@pdfparseddomain]
/Coords [\pgf@sys@tonumber{\pgf@xa} \pgf@sys@tonumber{\pgf@ya} \pgf@doma\space \pgf@sys@tonumber{\pgf@x} \pgf@sys@tonumber{\pgf@y} \pgf@domb]
/Function \pgf@pdfparsedfunction
/Extend [true false] >> >>}\pgfutil@tempboxa% <<
\expandafter\xdef\csname @pgfshading#1!\endcsname{\leavevmode\noexpand\pdfrefxform\the\pdflastxform}%
}%
}
\endinput
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-10-08T14:04:09.140",
"Id": "395651",
"Score": "0",
"body": "@200_success, perhaps this site is not suitable for my question then. I can post the code, but my question is mainly about whether my method of integrating my code with the *very... | [] | {
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-10-08T12:51:50.120",
"Id": "205145",
"Score": "5",
"Tags": [
"graphics",
"pdf",
"tex"
],
"Title": "CMYK shadings implementation for PGF"
} | 205145 |
<p>I am really excited that I just wrote my Haskell maze solution in bfs. This is my very first haskell (and I still haven't tried to build a maze in haskell so that maze is hard coded xD)</p>
<p>ANY suggestions all super welcome!!!</p>
<pre><code>maze = [[0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 2, 2, 2, 2, 2, 2, 2, 0],
[0, 2, 0, 0, 0, 0, 0, 0, 0],
[0, 2, 2, 2, 0, 2, 2, 2, 0],
[0, 0, 0, 2, 0, 2, 0, 2, 0],
[0, 2, 2, 2, 0, 2, 0, 2, 0],
[0, 2, 0, 0, 0, 2, 0, 2, 0],
[0, 2, 2, 2, 2, 2, 0, 2, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0]]
start = (7, 7)
end = (1, 7)
validPosition x y maze = (x >= 0) && (y >= 0) && (length maze) > y && (length (maze !! 0)) > x
getNode x y = if (validPosition x y maze) then Just ((maze !! y) !! x) else Nothing
getNeighborNode x y closed = filter (\(i, j) -> (getNode i j) == (Just 2) && (elem (i,j) closed) == False) [(x+a, y+b) | (a,b) <- [(0,-1),(0,1),(1,0),(-1,0)]]
bfsSolver ((i,j):xs) closed meta
| ((i,j) /= end) = (bfsSolver (xs++neighbors) (closed++[(i,j)]) (meta++[((a,b), (i,j)) | (a,b)<-neighbors]))
| otherwise = (constructPath (i,j) meta [])
where neighbors = (getNeighborNode i j closed)
constructPath (i,j) meta route
| (length points) > 0 = (constructPath (head points) meta (route++[(i,j)]))
| otherwise = route++[(i,j)]
where points = [(x,y) | ((a,b),(x,y)) <- meta, (a,b) == (i,j)]
-- bfsSolver [start] [] []
</code></pre>
| [] | [
{
"body": "<p>I've hardly done any Haskell - so it's probably a positive thing that I can easily understand your code - but since you've no answer yet, I'll have a go. Anyway, take everything I say with a pinch of salt, and it'll just be surface stuff since I don't have experience to draw on.</p>\n\n<hr />\n\n<... | {
"AcceptedAnswerId": "205204",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-10-08T13:35:16.663",
"Id": "205150",
"Score": "6",
"Tags": [
"beginner",
"haskell",
"pathfinding",
"breadth-first-search"
],
"Title": "Maze solver BFS in Haskell"
} | 205150 |
<p>So again, I am a bit confused about some notes that i'am getting from my reviewer. I have some kind of utils, to print/prepare log messages. Yea, maybe I am a bit fanatic java 8 lambda guy but I think it is still under control. :)</p>
<p>So its looks like that [I hide 'sensitive' data]</p>
<pre><code>public class ExceptionUtils {
private static final BiFunction<String, String, String> CUSTOM_EXCEPTION_MESSAGE_FORMAT =
(typeOfError, typeOfEndpoint) -> "[XXX] " + typeOfError + " Error during process bulk " + typeOfEndpoint + " events. "
+ "Event "
+ "occurrences time: %d "
+ "event retry count: %d, "
+ "session: %s";
public static String validationMessageException(String endpoint, long timestamp, int retryCount, String sessionToken) {
return String.format(CUSTOM_EXCEPTION_MESSAGE_FORMAT.apply("Validation", endpoint), timestamp, retryCount, sessionToken);
}
public static String unknownMessageException(String endpoint, long timestamp, int retryCount, String sessionToken) {
return String.format(CUSTOM_EXCEPTION_MESSAGE_FORMAT.apply("Unknown", endpoint), timestamp, retryCount, sessionToken);
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-10-08T13:44:28.807",
"Id": "395647",
"Score": "0",
"body": "I fix it, I have some problems if I copy paste then last brace is braking indents."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-10-08T22:30:50.573",
... | [
{
"body": "<p>What is the point of adding some parameters as part of format string when others are simply passed to String.format? You might as well just do the latter:</p>\n\n<pre><code>public class ExceptionUtils {\n\n private static final String CUSTOM_EXCEPTION_MESSAGE_FORMAT\n = \"[XXX] %s Er... | {
"AcceptedAnswerId": "205154",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-10-08T13:38:19.010",
"Id": "205151",
"Score": "0",
"Tags": [
"java",
"error-handling",
"formatting",
"logging",
"static"
],
"Title": "Logging util with static lambda function"
} | 205151 |
<p>I wrote a basic menu application for my intro to python. I'm fairly new, and python does look promising.</p>
<pre><code>the_burger = 16.99;
french_fries = 5.99;
currie_sauce = 19.99;
napkins_with_chocolates = 10.50;
juice_box = 89.01;
takeout = 18.99;
total = 0.0;
DONE = False
print("""
+-------------------------------------------+
| The Restaurant at the End of the Universe |
+---------------------------------+---------+
| A\tThe "Big Boy" Burger | $""" + str(the_burger) + """ |
+---------------------------------+---------+
| B\tFrench Fries | $""" + str(french_fries) + """ |
+---------------------------------+---------+
| C\tCurrie sauce | $""" + str(currie_sauce) + """ |
+---------------------------------+---------+
| D\tNapkins with Chocolates | $""" + str(napkins_with_chocolates) + str(0) + """ |
+---------------------------------+---------+
| E\tJuice Box | $""" + str(juice_box) + """ |
+---------------------------------+---------+
| F\tTakeout | $""" + str(takeout) + """ |
+---------------------------------+---------+
""");
while(not DONE):
print("Total:", total);
Item = input("Select a letter or 'done': ");
if Item is "A":
total += the_burger;
elif Item is "B":
total += french_fries;
elif Item is "C":
total += currie_sauce;
elif Item is "D":
total += napkins_with_chocolates;
elif Item is "E":
total += juice_box;
elif Item is "F":
total += takeout;
elif Item is "done":
print("Final total:", total);
DONE = True
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-10-08T14:52:36.007",
"Id": "395657",
"Score": "4",
"body": "It will let you use Unicode - and probably much more of Unicode than you're already using..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-10-08T14:55... | [
{
"body": "<p><strong>Huge bug in 3.5.2</strong></p>\n\n<p>Entering done does nothing in Python 3.5.2, use <code>==</code> instead of <code>is</code> to fix this. In general <code>is</code> asks if two objects are the same object not if the contents are the same, this can give results different from what you ex... | {
"AcceptedAnswerId": "205172",
"CommentCount": "14",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-10-08T14:47:04.210",
"Id": "205155",
"Score": "8",
"Tags": [
"python",
"python-3.x"
],
"Title": "Restaurant Menu System"
} | 205155 |
<pre><code> //not an elf file. try PE parser
PE pe=PEParser.parse(path);
if(pe!=null)
{
PESignature ps =pe.getSignature();
if(ps==null||!ps.isValid())
{
//What is it?
Toast.makeText(this,"The file seems that it is neither an Elf file or PE file!",3).show();
throw new IOException(e);
}
}
else
{
//What is it?
Toast.makeText(this,"The file seems that it is neither an Elf file or PE file!",3).show();
throw new IOException(e);
}
</code></pre>
<p>How can I organize the above code, so that </p>
<blockquote>
<pre><code> //What is it?
Toast.makeText(this,"The file seems that it is neither an Elf file or PE file!",3).show();
throw new IOException(e);
</code></pre>
</blockquote>
<p>Appears only once, or just be better-looking(easy to read)?</p>
<p><strong>Summary</strong></p>
<p>Please comment or advise on organizing the <code>if statements.</code></p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-10-08T16:31:57.617",
"Id": "395669",
"Score": "3",
"body": "The current question title, which states your concerns about the code, applies to too many questions on this site to be useful. The site standard is for the title to simply state... | [
{
"body": "<p>Your business logic is getting muddled with your error-checking logic. I would recommend extracting your \"null-to-Exception\" conversions into different methods, so they don't appear here.</p>\n\n<p>Ideally, <code>PEParser.parse()</code> and <code>PE.getSignature()</code> would not return null va... | {
"AcceptedAnswerId": "205160",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-10-08T16:10:05.480",
"Id": "205158",
"Score": "1",
"Tags": [
"java",
"error-handling",
"exception"
],
"Title": "Exception handling with null check in java"
} | 205158 |
<p>I got a forms list, and it has a tags list. I received from my front end app an array of tags (<code>String</code>), gotta filter these forms by these tags.</p>
<pre><code>forms.forEach(form -> {
br.com.softplan.ungp.dynamic.form.api.model.Form formJson = new Gson()
.fromJson(form.getSchema(), br.com.softplan.ungp.dynamic.form.api.model.Form.class);
tags.forEach(tag -> formJson.getTags().forEach(formTag -> {
if (tag.toUpperCase().equals(formTag.getText().toUpperCase())) {
if (map.containsKey(tag)) {
List<FormSummary> list = new ArrayList<>(map.get(tag));
list.add(new FormSummary(form.getId(), form.getName()));
map.put(tag,list);
} else {
map.put(tag, Collections.singletonList(new FormSummary(form.getId(), form.getName())));
}
}
}));
});
</code></pre>
<p>This code is already working as expected. I just want to improve it, writing less code using Java utilities.</p>
<p>What I was trying to do is to map all the result inside a map into its own iteration, using <code>stream.map()</code> or the <code>Collectors.toMap()</code>, but couldn't achieve what I wanted.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-10-09T04:38:08.400",
"Id": "395753",
"Score": "3",
"body": "The current question title, which states your concerns about the code, is too general to be useful here. The site standard is for the title to simply state the task accomplished ... | [
{
"body": "<p>Your code is not easy to understand. However, you might replace the inner if-else construct with</p>\n\n<pre><code>map.computeIfAbsent(tag, t -> new ArrayList<>())\n .add(new FormSummary(form.getId(), form.getName()));\n</code></pre>\n\n<p>for brevity.</p>\n\n<p>Note that the nested <co... | {
"AcceptedAnswerId": "205165",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-10-08T17:43:29.800",
"Id": "205163",
"Score": "-1",
"Tags": [
"java",
"stream"
],
"Title": "How to use java 8 streams to get more readability and performance to this code"
} | 205163 |
<p>This function was built to replace DLookup so that i could pass in parameterized queries for a speed increase. I also wanted a simple way to get more than one value if needed. For example, if i want 4 or 5 fields out of a particular record or maybe 4 or 5 records with only one field, I could get that with this function.</p>
<p>EDIT: the whole filter string portion of the fuction is legacy functionality from when i initially built this function and had to leave in untill all of the places that use this piece of code have been updated.</p>
<pre><code>Public Function Qlookup(ByVal argQuery As String, Optional ByRef argParameters As Variant = Null, Optional ByVal argIsFilterString As Boolean = False) As Variant
'Parameters -
'argQuery: the query definition name
'argParameters: the list of parameters (can come in an array or not) that should be in the order and starting at 0
'argIsFilterString: Allows you to use a 'Where' Clause instead of a parameter list
'that the parameters in your query are.
'Output -
'Will output a single item, 1d array or 2d array depending on the query you feed it.
'This comment line is here to fix the formatting messing up.
If Not BasicInclude.DebugMode Then On Error GoTo Error_Handler
Dim rs As DAO.Recordset
Dim qry As QueryDef
Dim u As Long
Dim out() As Variant
Dim i As Long
Dim j As Long
Qlookup = Null
Set qry = dbLocal.QueryDefs(argQuery)
If argIsFilterString Then
Set rs = qry.OpenRecordset(dbOpenSnapshot)
rs.filter = argParameters
Set rs = rs.OpenRecordset(dbOpenSnapshot)
Else
If IsArray(argParameters) Then
u = UBound(argParameters)
If u = (qry.Parameters.count - 1) Then
For i = 0 To u
qry.Parameters(i).value = argParameters(i)
Next i
Else
Err.Raise vbObjectError, "Qlookup", "Number of Parameters in query(" & qry.Parameters.count & ") do not match the number of parameters passed in(" & u + 1 & ")"
End If
Else
If Not (IsNull(argParameters)) And qry.Parameters.count = 1 Then
qry.Parameters(0).value = argParameters
ElseIf qry.Parameters.count = 0 And Not (IsNull(argParameters)) Then
Err.Raise vbObjectError + 1, "Qlookup", "Number of Parameters in query(" & qry.Parameters.count & ") do not match the number of parameters passed in(1)"
ElseIf qry.Parameters.count = 0 And (IsNull(argParameters)) Then
End If
End If
Set rs = qry.OpenRecordset(dbOpenSnapshot)
End If
If rs.RecordCount Then
rs.MoveFirst
rs.MoveLast
rs.MoveFirst
If rs.RecordCount > 1 Then
If rs.Fields.count > 1 Then
ReDim out(rs.RecordCount - 1, rs.Fields.count - 1)
For i = 0 To rs.RecordCount - 1
For j = 0 To rs.Fields.count - 1
out(i, j) = rs.Fields(j).value
Next
rs.MoveNext
Next
Else
ReDim out(rs.RecordCount - 1)
For i = 0 To rs.RecordCount - 1
out(i) = rs.Fields(0).value
rs.MoveNext
Next
End If
Qlookup = out
Else
If rs.Fields.count > 1 Then
ReDim out(rs.RecordCount - 1, rs.Fields.count - 1)
For i = 0 To rs.RecordCount - 1
For j = 0 To rs.Fields.count - 1
out(i, j) = rs.Fields(j).value
Next
rs.MoveNext
Next
Qlookup = out
Else
Qlookup = rs.Fields(0).value
End If
End If
End If
Error_Exit:
Set rs = Nothing
Set qry = Nothing
Exit Function
Error_Handler:
StandardErrorBox "Qlookup", Err, Errors
Qlookup = Null
Resume Error_Exit
End Function
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-10-09T14:42:22.313",
"Id": "395820",
"Score": "1",
"body": "I have rolled back your last edit. Please do not update the code in your question to incorporate feedback from answers, doing so goes against the Question + Answer style of Code ... | [
{
"body": "<p>Declaring <code>qry As QueryDef</code> is unnecessarily limiting your function to Queries. With a few changes the function could be ran against Queries or Tables.</p>\n\n<blockquote>\n<pre><code>Dim qry As Object 'QueryDef or TableDef\nOn Error Resume Next\nSet qry = dbLocal.QueryDefs(argQuery)\n... | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-10-08T19:53:59.673",
"Id": "205175",
"Score": "2",
"Tags": [
"vba",
"ms-access"
],
"Title": "A function that replicates DLookup, and can use parameterized queries"
} | 205175 |
<p>In my intro CS class we're reviewing data structures. I'm currently working on implementing a stack using a linked list (LIFO) in C. I'd appreciate a review of the implementation as well as of my understanding of how a stack should work.</p>
<pre><code>// This program is implementation of stack data structure
// via linked list (LAST IN FIRST OUT STRUCTURE) LIFO
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct node
{
char string[20];
struct node *next;
} node;
node *push(char *element, node *head);
node *pop(node *head);
void destroy_stack(node *p);
int main(void)
{
// create new stack
node *stack = NULL;
// push 6 "functions" to the stack
char *function[6] = {"first funct", "second funct", "third funct",
"fourth funct", "fifth funct", "sixt funct"};
for (int i = 0; i < 6; i++)
{
printf("function is : %s\n",function[i]);
stack = push(function[i], stack);
if (!stack)
{
fprintf(stderr,"Not enough memory space for new list");
return 1;
}
}
// display the stack
for (node *temp = stack; temp != NULL; temp = temp -> next)
{
printf("Elements of the stack are: %s\n", temp -> string);
}
// pop the elements from the stack
while (stack != NULL)
{
printf("Popped elemet is: %s\n", stack -> string);
stack = pop(stack);
}
destroy_stack(stack);
return 0;
}
node *push(char *element, node *head)
{
// create space for new element on stack
node *temp = malloc(sizeof(node));
if (!temp)
{
return NULL;
}
// if stack is empty
if (head == NULL)
{
strcpy(temp -> string, element);
temp -> next = NULL;
return temp;
}
strcpy(temp -> string, element);
temp -> next = head;
return temp;
}
node *pop(node * head)
{
// create a new head
node *newHead = head->next;
// pop the element from stack
free(head);
return newHead;
}
void destroy_stack(node *p)
{
if ( p == NULL )
{
return;
}
else
{
destroy_stack(p -> next);
}
free(p);
}
</code></pre>
| [] | [
{
"body": "<h3>Redundant Code</h3>\n\n<p>In your <code>push()</code> function, you have these two cases which are redundant:</p>\n\n<blockquote>\n<pre><code>// if stack is empty\nif (head == NULL)\n{\n strcpy(temp -> string, element);\n temp -> next = NULL;\n return temp;\n}\n\nstrcpy(temp -> ... | {
"AcceptedAnswerId": "205178",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-10-08T20:50:42.377",
"Id": "205176",
"Score": "2",
"Tags": [
"c",
"linked-list",
"stack"
],
"Title": "Implementing a stack using a linked-list"
} | 205176 |
<p>I just faced a problem where I needed to know if extra data was present in a given collection after a <code>Take</code> operation took place. Specifically, this is related to generating <code>@odata.nextLink</code> values in an OData-enabled API only if there is remaining data on the server: the user should not receive a "nextLink" if no more data is available, so that he can properly rely on this value for paging purposes.</p>
<p>The common strategy used in these cases AFAIK is to take one more element on the target, and then check if the results "went past" the limit or not. </p>
<p>For example, when we want to return 10 results:</p>
<pre><code>const int pageSize = 10;
var data = dataSource
.Take(pageSize + 1)
.ToList();
var hasRemainingData = data.Count > pageSize;
return new PageResult(
data: data.Take(pageSize),
nextLink: hasRemainingData ? CreateNextLink(pageSize) : null);
</code></pre>
<p>Now this all felt a bit convoluted to me, so I created an extension method to abstract part of the logic away:</p>
<pre><code>public static (IEnumerable<T> Data, bool HasRemainingData) TakeWithRemainder<T>(this IEnumerable<T> sequence, int count)
{
if (sequence == null)
throw new ArgumentNullException(nameof(sequence));
if (count < 0)
throw new ArgumentOutOfRangeException(nameof(count));
var data = sequence.Take(count + 1).ToArray();
return (new ArraySegment<T>(data, 0, count), data.Length > count);
}
</code></pre>
<p>This allows me to clean up the original code significantly, like this:</p>
<pre><code>const int pageSize = 10;
var results = dataSource.TakeWithRemainder(pageSize);
return new PageResult(
data: results.Data,
nextLink: results.HasRemainingData ? CreateNextLink(pageSize) : null);
</code></pre>
<hr>
<p>I have a few problems with the extension though, and was wondering if you've got any ideas to make this better:</p>
<ol>
<li><p><strong>It materializes the collection</strong></p>
<p>Not sure if there is a way to avoid this since we need to count the elements anyways, but it sounds unexpected to have a <code>Take</code> overload that materializes the results vs the normal one that does not. Right now it seems like I'm violating the Principle of Least Astonishment here. Should I consider an approach that does not materialize the collection, or should I rename it to something else? Other options?</p>
<p>.</p></li>
<li><p><strong>It relies on <code>ArraySegment</code> to avoid unneeded iteration</strong></p>
<p>The original code had 2 <code>Take</code> calls in it, which is kinda bad in and of itself. I decided to try using something more decent and went with <code>ArraySegment</code>. Is that intuitive enough to you? I found the code somewhat hard to follow with that in place. Any other options that would still allow me to avoid multiple enumeration are more than welcome.</p>
<p>.</p></li>
<li><p><strong>It uses a value <code>Tuple</code> to get the results out</strong></p>
<p>Would also want to see your take on this aspect. The named tuple seemed like the most straightforward way to get both the data and the boolean indicator. This of course "breaks" the fluent chain, as you can't immediately chain extra LINQ methods on top of the whole tuple (which could again be seen as a Principle of Least Astonishment violation). Should I consider something else, like a custom iterator class with an extra property that still implemented <code>IEnumerable<T></code>? That would allow callers to access the boolean, but still chain more LINQ calls as needed. </p>
<p>At the same time, I wonder if it wouldn't be extra misleading due to the materialization of the collection.</p>
<p>.</p></li>
<li><p><strong><code>HasRemainingData</code> and <code>TakeWithRemainder</code> seem like poor names to me</strong></p>
<p>I'm not liking these 2 names, but I'm failing to thinking of something better for them if I am to keep this approach.</p></li>
</ol>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-10-09T09:38:40.573",
"Id": "395782",
"Score": "0",
"body": "In what context are you using OData? Because Web API has paging built-in: https://www.c-sharpcorner.com/article/paging-with-odata-and-Asp-Net-web-api/"
},
{
"ContentLicen... | [
{
"body": "<p>You should be aware that </p>\n\n<p><code>return (new ArraySegment<T>(data, 0, count), data.Length > count);</code></p>\n\n<p>throws an exception if <code>count > data.Count()</code></p>\n\n<p>The normal <code>Take()</code> doesn't behave that way - it takes <code>min(count, data.Count... | {
"AcceptedAnswerId": "205200",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-10-08T22:31:53.857",
"Id": "205181",
"Score": "3",
"Tags": [
"c#",
".net",
"linq",
"extension-methods",
"pagination"
],
"Title": "Determining if there is data left after fetching a page of data"
} | 205181 |
<p>I came up with this simple function to return the length of a double, working fine in all my test but want to make sure that this code will work in all doubles, can't think of a case in which it would not work but I'm sure if there is, then you can find it, here it is:</p>
<pre><code>int length(double number){
int result = 0;
if ( number < 0 ) number *= -1;
while ( number > 1){
result++;
number /= 10;
}
return result + ( number == 1 );
}
</code></pre>
<p>I think that the <code>(number == 1)</code> is pretty clever, but there might be some better way to accomplish the correct result. It's meant to work whenever the number is an exact power of ten but I think it might be a bit cryptic.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-10-08T23:39:30.533",
"Id": "395719",
"Score": "2",
"body": "It would be easier to tell if it was working if you gave a little more description of what you want it to do."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": ... | [
{
"body": "<p>Your <code>+(number == 1)</code> code is tricky and non-obvious. Why is 1 a special case (yes, I know for exact powers of 10). Why is adding a Boolean to an integer count a valid operation, and what does it do, or is it an implementation dependent undefined operation?</p>\n\n<p>Can we rewrite th... | {
"AcceptedAnswerId": "205226",
"CommentCount": "10",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-10-08T23:00:47.187",
"Id": "205183",
"Score": "4",
"Tags": [
"c"
],
"Title": "Length of the integer part of a double in C without math.h"
} | 205183 |
<p>I'm very new to the programming world and have been working exclusively with console window applications in C# thus far. I've created a program which took me way too long to produce but I'm very proud to have completed it exactly as I set out to make it. It does what I wanted it to do, however the code is separated into many different methods. Again, being a newbie, I don't know a lot about formatting my code for readability's sake, so I'd love to have some outside opinions about what you would change, if anything, about the text so that I may be pointed in the right direction for future applications I create.</p>
<pre><code>class Program
{
public static string Name { get; set; }
public static void Main()
{
Console.Write("Please Enter Your Name: ");
Name = Console.ReadLine();
SearchBarStart(Name);
}
public static void SearchBarStart(string searchName)
{
Console.WriteLine("Welcome, {0}", searchName);
Thread.Sleep(1000);
SearchChecker();
}
public static void SearchBar(string searchName)
{
Console.Clear();
Console.WriteLine("Welcome back, {0}", searchName);
Thread.Sleep(1000);
SearchChecker();
}
public static void SearchChecker()
{
Item Ball = new Item() { Name = "Ball", Price = 100.001F, Popularity = 1 };
Item Book = new Item() { Name = "Book", Price = 210.1F, Popularity = 5 };
Item Bag = new Item() { Name = "Bag", Price = 300F, Popularity = 4 };
List<Item> items = new List<Item>();
items.Add(Ball);
items.Add(Book);
items.Add(Bag);
string userChoice = string.Empty;
do
{
Console.Write("Please enter which item would you like to view: ");
userChoice = Console.ReadLine();
Item resultItem = items.Find(item => item.Name == userChoice);
if (resultItem == null)
{
Console.WriteLine("Item name not valid");
SearchChecker();
}
else
{
Console.WriteLine("Item Name: {0}\n" +
"Item Price: {1:C}\n" +
"Item Popularity Hits: {2}\n",
resultItem.Name, resultItem.Price, resultItem.Popularity);
}
Console.WriteLine("Would you like to continue? (yes/no)");
userChoice = Console.ReadLine();
}
while (userChoice == "yes");
Exit();
}
public static void Exit()
{
Console.WriteLine("Are you sure? (yes/no)");
string answer = Console.ReadLine();
if (answer == "yes")
{
Console.WriteLine("Press enter again to exit");
Console.ReadLine();
}
else if (answer == "no")
{
SearchBar(Name);
}
else
{
Console.WriteLine("Sorry, I don't recognize {0}\n", answer);
Exit();
}
}
}
class Item
{
public string Name { get; set; }
public float Price { get; set; }
public int Popularity { get; set; }
}
</code></pre>
| [] | [
{
"body": "<p>First, I'm going to show you some interesting points.</p>\n\n<p><strong>1. The callstack</strong></p>\n\n<p>You're calling some methods <a href=\"https://www.dotnetperls.com/recursion\" rel=\"noreferrer\">recursively</a>. A recursive method calls itself. See in <code>SearchChecker()</code> and <co... | {
"AcceptedAnswerId": "205195",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-10-09T00:59:06.860",
"Id": "205189",
"Score": "5",
"Tags": [
"c#",
"beginner"
],
"Title": "Simple application to look up items in a list"
} | 205189 |
<p>I was recently tasked with determining which hex RGB colors in list <em>color_list</em> are nearest to each hex RGB color in list <em>target_colors</em>, using euclidean distance as the measuring stick, and only returning items that are within 10 distance from each target color. My first pass at this was for each item in <em>target_colors</em>, check the distance between it and everything in <em>color_list</em>, and return the colors at or below the target distance. This works well enough when <em>color_list</em> is small. But when <em>color_list</em> is large, looping over the entire list for each item in <em>target_colors</em> is slow. I am wondering if there is a better way to go about doing this, so that I don't have to loop over the entire list every time. </p>
<p>My first thought was to cache the results, but given that there are 16 million potential colors, that is potentially 2*16m^2 combinations, it would not be very space efficient. </p>
<p>My next thought was that perhaps the source color list can be sorted in a way that would make searching it faster, but I have to loop over all of the colors to get the distance as the thing to sort on, and I would not be in any better of shape. </p>
<p>My last thought was that given an r, g, or b color, perhaps I could eliminate colors that are obviously going to be out of range. If I have a color like #AABBAA, I instinctively know that #001100 is going to be way too far away, so I could sort the source list of colors l, then eliminate anything that smells like its out of range. But, I get back to the "well I would calculate the distance to figure out if it smells out of range", and I'm back to square one. </p>
<p>distance.rb:</p>
<pre><code>TARGET_DISTANCE = 10.0
# calculate the euclidiean distance between two hex colors
def color_distance(c1, c2)
c1_parts = c1.split('').each_slice(2).map{|c| c.join}.to_a
c2_parts = c2.split('').each_slice(2).map{|c| c.join}.to_a
r_diff = c1_parts[0].to_i(16) - c2_parts[0].to_i(16)
g_diff = c1_parts[1].to_i(16) - c2_parts[1].to_i(16)
b_diff = c1_parts[2].to_i(16) - c2_parts[2].to_i(16)
Math.sqrt(r_diff**2 + g_diff**2 + b_diff**2)
end
def random_color
3.times.map{rand(254).to_s(16).rjust(2, '0')}.join()
end
color_list = []
1.upto(10000) { color_list << random_color }
target_colors = []
1.upto(100) { target_colors << random_color }
results = {}
target_colors.each do |t|
results[t] ||= []
color_list.each do |c|
distance = color_distance(c, t)
if distance <= TARGET_DISTANCE
results[t] << [c, distance]
end
end
end
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-10-09T01:34:49.923",
"Id": "395736",
"Score": "0",
"body": "[octree](https://en.wikipedia.org/wiki/Octree) perhaps?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-10-09T01:53:19.430",
"Id": "395737",
"Sc... | [
{
"body": "<p>As @vnp says, a solution involving an <a href=\"https://en.wikipedia.org/wiki/Octree\" rel=\"nofollow noreferrer\">octree</a> would a more efficient way to find neighboring points.</p>\n\n<p>Before you implement one, though, there are some huge time savings you can get by making some trivial chang... | {
"AcceptedAnswerId": "205194",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-10-09T01:06:11.853",
"Id": "205190",
"Score": "1",
"Tags": [
"algorithm",
"ruby",
"time-limit-exceeded",
"clustering"
],
"Title": "Efficiently determining maximum allowed euclidean distance between lists of colors"
} | 205190 |
<p>Still learning Assembly. This program is a simple guessing game to test most of the new things I've learned! Any advice and all topical comments on code optimization and conventions is appreciated!</p>
<p>Compiled as follows using <code>VS2017 x64 Native Tools Command Prompt</code>:</p>
<blockquote>
<pre><code>> nasm -g -fwin64 guess.asm
> cl /Zi guess.obj msvcrt.lib legacy_stdio_definitions.lib
</code></pre>
</blockquote>
<p><strong>guess.asm</strong></p>
<pre><code>;; bits 64
default rel
extern time, srand, rand
extern printf, scanf
%macro str 2
%2: db %1, 0
%endmacro
; use DQ to define a quad-word, DD to define a double-word, DW to define a word, and DB to define a byte.
section .rdata ; immutable predefined variables
str "Enter your guess (1-100): ", prompt
str "%u", scan_fmt
str "ERROR! Input was not a number!", scan_fail
str {"Too high!", 10}, too_high
str {"Too low!", 10}, too_low
str {"You guessed it!", 13, 10}, congrats
; use RESQ to reserve a number of quad-words, RESD to reserve a number of double-words, RESW to reserve a number of words, and RESB to reserve a number of bytes.
section .bss ; mutable undefined variables
target: resb 4 ; 4 bytes of storage (enough for a 32bit number)
section .text
global main
main:
stack_reserve: equ 40 ; 32 + 8
sub rsp, stack_reserve ; shadow space for callees + 8 bytes for stack alignment
;; calculate the random number
xor rax, rax
mov rcx, rax ; clear rax and rcx
call time
mov rcx, rax
call srand
call rand
;; rand = (rand % 100) + 1
xor rdx, rdx ; clear rdx
mov rcx, 100
div rcx
inc rdx
mov [target], rdx
;mov rcx, scan_fmt
;call printf
.check:
lea rcx, [prompt]
call printf
; memory from rsp+0..31 has potentially been stepped on by printf
; leave RSP where it is, ready for another call
;;; scanf into that 8-byte block of stack space above the shadow space, or into our *own* shadow space
lea rdx, [rsp+32] ; stack addresses are normally 64-bit, can't get away with edx
lea rcx, [scan_fmt]
mov dword [rdx], 0 ; instead of error check, set n = 0 in case of I/O error
call scanf
cmp eax, 1 ; success = exactly 1 conversion
jnz .scanf_fail ; error check
mov r8d, [rsp+32] ; r8d: 32-bit unsigned number to be checked
cmp r8d, [target]
jg .too_high
jl .too_low
lea rcx, [congrats]
call printf
.end:
;xor eax,eax ; return 0
movzx eax, byte [rsp+32] ; return EXIT_SUCCESS(0) or EXIT_FAILURE(1)
add rsp, stack_reserve
ret
.too_high:
lea rcx, [too_high]
call printf
jmp .check
.too_low:
lea rcx, [too_low]
call printf
jmp .check
.scanf_fail:
lea rcx, [scan_fail]
call printf
jmp .end
</code></pre>
| [] | [
{
"body": "<p>The usage of <code>target</code> is not consistent:</p>\n\n<pre><code>target: resb 4 ; 4 bytes of storage (enough for a 32bit number)\n...\nmov [target], rdx ; store 8 bytes\n</code></pre>\n\n<p>That's easy to improve, just use <code>edx</code>.</p>\n\n<p>Using <code>rand</code> like this... | {
"AcceptedAnswerId": "205214",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-10-09T02:32:13.737",
"Id": "205193",
"Score": "1",
"Tags": [
"windows",
"assembly",
"number-guessing-game"
],
"Title": "Guessing game in NASM Win64 Assembly"
} | 205193 |
<p>I have created a sign up layout as image below.</p>
<p><a href="https://i.stack.imgur.com/ObyDD.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ObyDD.png" alt="enter image description here"></a></p>
<p>Does this part of code looked bad since the <code>dp</code> I used for the floating button are quite large. </p>
<pre><code> android:layout_marginTop="110dp"
android:layout_marginLeft="70dp"
</code></pre>
<p>If yes, how can I change it ?</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content" xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="vertical">
<RelativeLayout android:layout_width="match_parent" android:layout_height="wrap_content"
android:orientation="horizontal"
android:gravity="center">
<de.hdodenhof.circleimageview.CircleImageView
android:layout_marginTop="25dp"
android:id="@+id/imgProfilePicture"
android:layout_width="110dp"
android:layout_height="130dp"
app:civ_border_width="1dp"
app:civ_border_color="@color/colorPrimary"/>
<android.support.design.widget.FloatingActionButton
app:fabSize="mini"
android:layout_marginTop="110dp"
android:layout_marginLeft="70dp"
android:id="@+id/fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:elevation="2dp"
android:src="@drawable/camera" android:layout_alignRight="@+id/imgProfilePicture"/>
</RelativeLayout>
<TextView
android:layout_marginLeft="35dp"
android:backgroundTint="@color/colorPrimary"
android:layout_marginTop="30dp"
android:id="@+id/textViewUserId"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="USER ID "/>
<EditText android:layout_width="match_parent" android:layout_height="wrap_content"
android:layout_marginLeft="30dp"
android:layout_marginRight="30dp"
android:id="@+id/editTextUserId"
/>
<TextView
android:layout_marginLeft="30dp"
android:backgroundTint="@color/colorPrimary"
android:layout_marginTop="25dp"
android:id="@+id/textViewUserName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="USERNAME "/>
<EditText android:layout_width="match_parent" android:layout_height="wrap_content"
android:layout_marginLeft="30dp"
android:layout_marginRight="30dp"
android:id="@+id/editTextUsername"
/>
<TextView
android:layout_marginLeft="30dp"
android:backgroundTint="@color/colorPrimary"
android:layout_marginTop="25dp"
android:id="@+id/textViewPassword"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="PASSWORD "/>
<EditText android:layout_width="match_parent" android:layout_height="wrap_content"
android:layout_marginLeft="30dp"
android:layout_marginRight="30dp"
android:id="@+id/editTextUserPassword"
/>
<LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content"
android:orientation="horizontal"
>
<TextView
android:layout_marginLeft="30dp"
android:backgroundTint="@color/colorPrimary"
android:layout_marginTop="25dp"
android:id="@+id/textViewCourse"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="COURSE "/>
<TextView
android:layout_marginLeft="65dp"
android:layout_marginRight="30dp"
android:backgroundTint="@color/colorPrimary"
android:layout_marginTop="25dp"
android:id="@+id/textViewPhoneNum"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="PHONE NUMBER "/>
</LinearLayout>
<LinearLayout android:layout_width="match_parent" android:layout_height="match_parent"
android:orientation="horizontal">
<Spinner android:layout_width="wrap_content" android:layout_height="wrap_content"
android:layout_marginLeft="30dp"
android:layout_marginRight="30dp"
android:id="@+id/spinner"/>
<EditText android:layout_width="match_parent" android:layout_height="wrap_content"
android:layout_marginRight="30dp"
android:id="@+id/editTextPhoneNum"/>
</LinearLayout>
</LinearLayout>
</code></pre>
| [] | [
{
"body": "<p>Its not that bad, but in this case you might have to test it in different screen sizes Android devices, to see if it fits exactly where you want.</p>\n\n<p>In my opinion, better approach is to use <code>FrameLayout</code> instead of using relative layout. By using frame layout, you can use gravity... | {
"AcceptedAnswerId": "205719",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-10-09T06:29:40.327",
"Id": "205201",
"Score": "1",
"Tags": [
"java",
"android",
"xml",
"layout"
],
"Title": "Sign Up layout in android"
} | 205201 |
<p>I made a state machine.</p>
<p>You can press 0 and 1 to switch between the hypothetical menu and playing state.</p>
<p>I hope you can help me improve it further.</p>
<p><strong>StateManager.h</strong></p>
<pre><code>#pragma once
#ifndef StateManager_H
#define StateManager_H
#include <iostream>
#include "State.h"
/*
State classes
*/
class StateManager {
public:
// Define m_current_state upon the creation of this class (since that prevents there being a nullptr error in change_state
StateManager(State* state)
: m_current_state(state)
{}
void change_state(State* state) {
m_current_state->on_exit();
m_current_state = state;
m_current_state->on_enter();
}
void update_state(StateManager* manager) {
m_current_state->on_update(manager);
}
State* get_state() {
return m_current_state;
}
private:
State* m_current_state;
};
#endif
</code></pre>
<p><strong>State.h</strong></p>
<pre><code>#pragma once
#ifndef State_H
#define State_H
#include "StateManager.h"
// I'm using forward declaration here since I've had a problem with circular dependency
class StateManager;
class State {
public:
// All states have to have these three functions
virtual void on_enter() = 0;
virtual void on_update(StateManager* state_manager) = 0;
virtual void on_exit() = 0;
};
#endif
</code></pre>
<p><strong>IntroState.h</strong></p>
<pre><code>#pragma once
#ifndef IntroState_H
#define IntroState_H
#include "StateManager.h"
#include "State.h"
#include "GameState.h"
/*
Basic test state for demonstration
*/
class MenuState : public State {
public:
MenuState();
virtual void on_enter() override;
virtual void on_update(StateManager* state_manager) override;
virtual void on_exit() override;
private:
bool should_change_state;
};
#endif
</code></pre>
<p><strong>Introstate.cpp</strong></p>
<pre><code>#include "IntroState.h"
MenuState::MenuState()
: should_change_state(false)
{}
void MenuState::on_enter(){
std::cout << "Entering the menu state" << std::endl;
}
void MenuState::on_update(StateManager* state_manager){
// update the menu
std::cout << "Should the state be changed to the playing state" << std::endl;
std::cin >> should_change_state;
if (should_change_state == true) {
state_manager->change_state(new PlayingState());
}
}
void MenuState::on_exit(){
std::cout << "Exiting the menu state" << std::endl;
}
</code></pre>
<p><strong>GameState.h</strong></p>
<pre><code>#pragma once
#ifndef GameState_H
#define GameState_H
#include "IntroState.h"
#include "State.h"
/*
Basic test state for demonstration
*/
class PlayingState : public State {
public:
PlayingState();
virtual void on_enter() override;
virtual void on_update(StateManager* state_manager) override;
virtual void on_exit() override;
private:
bool should_change_state;
};
#endif
</code></pre>
<p><strong>GameState.cpp</strong></p>
<pre><code>#include "GameState.h"
PlayingState::PlayingState()
: should_change_state(false)
{}
void PlayingState::on_enter() {
std::cout << "Entering the playing state" << std::endl;
}
void PlayingState::on_update(StateManager* state_manager) {
// update the menu
std::cout << "Should the state be changed to the menu state" << std::endl;
std::cin >> should_change_state;
if (should_change_state == true) {
state_manager->change_state(new MenuState());
}
}
void PlayingState::on_exit() {
std::cout << "Exiting the playing state" << std::endl;
}
</code></pre>
<p><strong>Source.cpp</strong></p>
<pre><code>#include "StateManager.h"
#include "State.h"
#include "IntroState.h"
int main() {
StateManager* manager = new StateManager(new MenuState());
int exit = 0;
while (exit != 1) {
manager->update_state(manager);
}
return 0;
}
</code></pre>
<p>Thanks!</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-10-09T08:58:12.867",
"Id": "395778",
"Score": "0",
"body": "You could add a little more context. What is this state machine for? What *hypothetical* menu? What is played here?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationD... | [
{
"body": "<p>only include headers you actually need in that file. No need to <code>#include <iostream></code> in StateManager.h.</p>\n\n<p>Leaks abound. You <code>new</code> every state but I don't see anywhere you <code>delete</code> them. Use smart pointers or have States clean themselves up <code>on_e... | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-10-09T06:35:21.183",
"Id": "205202",
"Score": "4",
"Tags": [
"c++",
"beginner",
"object-oriented",
"design-patterns",
"state-machine"
],
"Title": "Finite State Machine in C++"
} | 205202 |
<p>I have this piece of code in Python 2.7:
As you can see is very hard to read the SQL query, what is the best way to re-write it?</p>
<pre><code> try:
if title and url:
sql_query = "INSERT INTO news (title, author, description, " \
"content, url, url_to_image, source_id, source, " \
"campaign, published_at, score, magnitude, sentiment, " \
"inserted_at ) VALUES ('%s','%s','%s','%s'," \
"'%s','%s','%s','%s','%s','%s', %s, %s, '%s', '%s')" \
% ( title.replace("'", "''"),
author.replace("'", "''"),
description.replace("'", "''"),
content[:settings.content_size].replace("'", "''"),
url,
url_to_image,
source_id,
source,
campaign,
published_at,
score,
magnitude,
sentiment,
DB_NOW)
db = Db.Db()
db.initialize(dsn=settings.SQLALCHEMY_DSN)
return db.insert_content(sql_query, 'news_id')
except psycopg2.ProgrammingError as exception:
log.exception(exception)`enter code here`
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-10-09T07:44:00.533",
"Id": "395773",
"Score": "0",
"body": "which python version?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-10-09T07:47:31.940",
"Id": "395776",
"Score": "1",
"body": "Python ver... | [
{
"body": "<p>You can use multiline sting <code>\"\"\"</code> and <a href=\"https://docs.python.org/2.7/library/string.html#formatstrings\" rel=\"nofollow noreferrer\"><code>string.format</code></a></p>\n\n<pre><code>try:\n if title and url:\n sql_query = \"\"\"\n INSERT INTO news (\n ti... | {
"AcceptedAnswerId": "205210",
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-10-09T07:43:23.520",
"Id": "205207",
"Score": "0",
"Tags": [
"python",
"python-2.x"
],
"Title": "Python Readability for SQL query"
} | 205207 |
<p>I've created a relatively simple Blackjack game in java. The reason why I decided to do this specific project was to improve my object orientated programming in java. </p>
<p>I will post my code so feel free to come with criticism etc. I am reading my first course in Java, have that in mind. </p>
<p>Player class</p>
<pre><code>import java.util.ArrayList;
public class Player {
private String nickName;
private int playerNumOfCards;
ArrayList<Card> playerHand;
public Player (String name){
this.nickName = name;
playerHand = new ArrayList<Card>();
}
public String getNickName() {
return nickName;
}
public void addCard(Card aCard){
playerHand.add(aCard);
this.playerNumOfCards++;
}
public int getHandSum(){
int totalSum = 0;
for(Card countSum: playerHand){
totalSum = totalSum + countSum.getFace();
}
return totalSum;
}
public void getPlayerHand(boolean hideCard) {
System.out.println(this.nickName + "s current hand.");
for ( int c = 0; c < playerNumOfCards; c++){
if(c == 0 && !hideCard){
System.out.println("[Hidden card]");
} else {
System.out.println(playerHand.get(c).toString());
}
}
}
}
</code></pre>
<p>Card class</p>
<pre><code>public class Card {
private Face face; //Face of card, i.e "King" & "Queen"
private Suit suit; //Suit of card, i.e "Hearts" & "diamonds"
int total = 0;
public Card (Face cardFace, Suit cardSuit){ //Constructor which initializes card's face and suit
this.face = cardFace;
this.suit = cardSuit;
}
public int getFace(){
return face.getFaceValue();
}
public String getSuit(){
return suit.PrintSuitText();
}
public String toString(){ //return String representation of Card
return face + " of " + suit;
}
}
</code></pre>
<p>Suit enum</p>
<pre><code>public enum Suit {
HEARTS(" Hearts"),
SPADES(" Spades"),
DIAMONDS(" Diamonds"),
CLUBS(" Clubs");
private final String suitText;
private Suit(String suitText){
this.suitText = suitText;
}
public String PrintSuitText(){
return suitText;
}
}
</code></pre>
<p>Face enum</p>
<pre><code>public enum Face {
ACE(1), DEUCE (2), THREE (3),
FOUR(4), FIVE(5), SIX(6),
SEVEN(7), EIGHT(8), NINE(9),
TEN(10), JACK(10), QUEEN(10),
KING(10);
private final int faceValue;
private Face(int faceValue){
this.faceValue = faceValue;
}
public int getFaceValue(){
return faceValue;
}
}
</code></pre>
<p>DeckOfCard class</p>
<pre><code>import java.util.Random;
public class DeckOfCards {
private Card[] deck;
private static final Random random = new Random();
private int currentCard; //index of next Card to be deal (0-51)
private static int NUMBER_OF_CARDS = 52; //Constant number of cards
public DeckOfCards(){
Face [] faces = {Face.ACE, Face.DEUCE, Face.THREE, Face.FOUR, Face.FIVE, Face.SIX,
Face.SEVEN, Face.EIGHT, Face.NINE, Face.TEN, Face.JACK, Face.QUEEN,
Face.KING};
Suit[] suits = {Suit.HEARTS, Suit.SPADES, Suit.DIAMONDS, Suit.CLUBS};
deck = new Card [NUMBER_OF_CARDS]; // create array with Cards (52)
currentCard = 0;
//Populate deck with Cards
for(int count = 0; count < deck.length; count++)
deck [count] = new Card(faces [count % 13], suits [count / 13]);
}
public void shuffleDeck(){
currentCard = 0;
for (int first = 0; first < deck.length; first++){
int second = random.nextInt(NUMBER_OF_CARDS); //Select a random card from number 0-51 (Number_of_cards)
//Loops through all the cards and swaps it with the "Second" card which is randomly chosen card from hte same list.
Card temp = deck[first];
deck [first] = deck [second];
deck [second] = temp;
}
}
public void getCardDeck(){
int start = 1;
for(Card k : deck) {
System.out.println("" + start + "/52 " + k);
start++;
}
}
public Card dealNextCard(){
//Get the top card
Card topCard = this.deck[0];
//shift all the subsequent cards to the left by one index
for(int currentCard = 1; currentCard < NUMBER_OF_CARDS; currentCard ++){
this.deck[currentCard-1] = this.deck[currentCard];
}
this.deck[NUMBER_OF_CARDS-1] = null;
//decrement the number of cards in our deck
this.NUMBER_OF_CARDS--;
return topCard;
}
}
</code></pre>
<p>Main class</p>
<pre><code>import java.util.Scanner;
public class BlackJackGame {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
boolean stay = false;
System.out.println("What nickName would you like to have?");
String pAnswer = scanner.nextLine();
Player me = new Player(pAnswer);
Player dealer = new Player("Dealer");
System.out.println("Would you like to start a new game? 'Yes/No' :");
pAnswer = scanner.nextLine();
if (pAnswer.equalsIgnoreCase("Yes")) {
DeckOfCards deck1 = new DeckOfCards();
Card card1 = new Card(Face.ACE, Suit.CLUBS);
deck1.shuffleDeck();
me.addCard(deck1.dealNextCard());
me.addCard(deck1.dealNextCard());
me.getPlayerHand(true);
System.out.println(" ");
dealer.addCard(deck1.dealNextCard());
dealer.addCard(deck1.dealNextCard());
dealer.getPlayerHand(false);
//PLAYER
do {
System.out.println("Would " + me.getNickName() + " like to bust or stay? 'Bust/Stay'");
pAnswer = scanner.nextLine();
//BUST
if (pAnswer.equalsIgnoreCase("Bust")) {
me.addCard(deck1.dealNextCard());
System.out.println(me.getHandSum());
if (me.getHandSum() > 21) {
System.out.println("You busted and got a total of " + me.getHandSum() + ". Dealer wins this time! ");
System.exit(0);
}
}
//STAY
if (pAnswer.equalsIgnoreCase("stay")) {
System.out.println("You have chosen to stay. Your hand: " + me.getHandSum());
}
} while (pAnswer.equalsIgnoreCase("Bust"));
//DEALER
stay = false;
do {
System.out.println("");
System.out.println("- Dealers turn -");
//DRAW CARD
if (dealer.getHandSum() <= 15) {
dealer.addCard(deck1.dealNextCard());
if(dealer.getHandSum() == 15){
System.out.println("Blackjack! Dealer won.");
System.exit(0);
}
if (dealer.getHandSum() > 21) {
System.out.println("Dealer busted and got a total of " + dealer.getHandSum() + ". " + me.getNickName() + " wins this time!");
System.exit(0);
}
} else {
System.out.println("Dealer has chosen to stay!");
int totalDealerSum = dealer.getHandSum();
int totalPlayerSum = me.getHandSum();
if(totalDealerSum > totalPlayerSum){
System.out.println("Both players has decided to stay. The winner is " + dealer.getNickName() + " with a total of " + totalDealerSum + ".");
} else {
System.out.println("Both players has decided to stay. The winner is " + me.getNickName() + " with a total of " + totalPlayerSum + ".");
}
stay = false;
}
} while (stay);
}
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-10-09T10:34:44.687",
"Id": "395787",
"Score": "2",
"body": "DeckOfCards.faces and DeckOfCards.suits are a bit redundant - why not use `Face.values()` and `Suit.values()` ?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate"... | [
{
"body": "<p>Overall, the quality of the code is very good. \nThere is good breakdown of the code into classes and methods, good utilization of OO paradigms like data abstraction, proper use of features like enums.</p>\n\n<p>Here are my comments:</p>\n\n<h2>Player class</h2>\n\n<ul>\n<li><p><code>getPlayerHand... | {
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-10-09T07:52:04.760",
"Id": "205208",
"Score": "0",
"Tags": [
"java",
"beginner",
"object-oriented",
"playing-cards"
],
"Title": "Simple OOP Blackjack game in Java"
} | 205208 |
<p>I have the following code where I try to manage user roles in teams:</p>
<p>Teams have entries, an entry has a creator. This creator is member of a team and has a specified role. Moderators may delete all entries, users may only delete their own entries. Here is how I implemented this:</p>
<pre><code>public class TeamMember implements TeamRole {
public String rank = "rank: Member";
@Override
public boolean deleteEntry(AbstractUser requester, Team team, Entry entry) throws IllegalAccessException {
if(requester.getUid().equals(entry.getCreator().getUid())) {
team.delete(entry);
System.out.println("Member " + requester.getName() + " deleted own entry: " + entry.toString() + "from " + team.toString());
return true;
}
throw new IllegalAccessException("Team members can only delete their own entries!");
}
</code></pre>
<p>Moderator:</p>
<pre><code>public class TeamModerator implements TeamRole {
public String rank = "rank: Moderator";
@Override
public boolean deleteEntry(AbstractUser requester, Team team, Entry entry) throws IllegalAccessException {
team.delete(entry);
System.out.println("Moderator " + requester.getName() + " deleted entry: " + entry.toString() + "from " + team.toString());
return true;
}
</code></pre>
<p>Team: </p>
<pre><code>public class Team {
private List<Entry> entries;
private Map<AbstractUser, TeamRole> memberPerms;
private String id;
private String name;
public TeamRole findPermissionsForUser(AbstractUser user) {
return memberPerms.get(user);
}
}
</code></pre>
<p>And the method that handles the request: </p>
<pre><code>@RequestMapping(value = "/rest/entries/delete/userid/{userId}/teamid/{teamId}/entryid/{entryId}")
public ResponseEntity<Team> deleteEntry(@PathVariable String userId, @PathVariable String teamId, @PathVariable String entryId) {
Optional<Team> team = Repository.findTeamById(teamId);
Optional<AbstractUser> user = Repository.findUserById(userId);
Optional<Entry> entry = Repository.findEntryById(teamId, entryId);
if (!(team.isPresent())) {
return new ResponseEntity("team not found", HttpStatus.BAD_REQUEST);
}
if (!(user.isPresent())) {
return new ResponseEntity("user not found", HttpStatus.BAD_REQUEST);
}
if (!(entry.isPresent())) {
return new ResponseEntity("entry not found", HttpStatus.BAD_REQUEST);
}
return EntryService.deleteEntry(user.get(), team.get(), entry.get());
}
</code></pre>
<p>The service that does the delete: </p>
<pre><code>public class EntryService {
public static ResponseEntity<Team> deleteEntry(AbstractUser requester, Team team, Entry e) {
try {
team.findPermissionsForUser(requester).deleteEntry(requester, team, e);
return new ResponseEntity(team, HttpStatus.OK);
} catch (IllegalAccessException e1) {
e1.printStackTrace();
return new ResponseEntity(e1.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
}
}
}
</code></pre>
<p>This is just a MVCE which does not contain user authentication, it trustst that the passed <code>userid</code> is correct.<br>
I think that this is not a good implementation, how would you model this?</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-10-09T11:44:46.710",
"Id": "395794",
"Score": "1",
"body": "Beware [stringly typed](http://wiki.c2.com/?StringlyTyped) code!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-10-09T12:00:15.140",
"Id": "395797"... | [
{
"body": "<p>I would change this calls sequence</p>\n\n<pre><code>Optional<Team> team = Repository.findTeamById(teamId);\nOptional<AbstractUser> user = Repository.findUserById(userId);\nOptional<Entry> entry = Repository.findEntryById(teamId, entryId);\nif (!(team.isPresent())) {\n return ... | {
"AcceptedAnswerId": "205217",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-10-09T08:06:37.203",
"Id": "205209",
"Score": "6",
"Tags": [
"java"
],
"Title": "Java user roles modeling"
} | 205209 |
<p>This is a code uses mergesort algorithm to sort a list of elements.What are the possible improvements on the code?Also are there any unhealthy coding practice involved in this code?</p>
<pre><code>#include<iostream>
#include<vector>
#include<random>
#include<chrono>
using namespace std;
using namespace std::chrono;
vector<int> merge(vector<int> a,vector<int> b){
int i=0;
int j=0;
vector<int> result;
while(i<a.size()&&j<b.size()){
if(a[i]<b[j]){
result.push_back(a[i]);
i++;
}
else{
result.push_back(b[j]);
j++;
}
}
while(i<a.size()){
result.push_back(a[i]);
i++;
}
while(j<b.size()){
result.push_back(b[j]);
j++;
}
return result;
}
vector<int> mergesort(vector<int> a,int low,int hi){
vector<int> b,c,result;
if(low==hi)
return {a[hi]};
b=mergesort(a,low,(low+hi)/2);
c=mergesort(a,(hi+low)/2+1,hi);
result=merge(b,c);
return result;
}
int main(){
std::random_device rd; // obtain a random number from hardware
std::mt19937 eng(rd()); // seed the generator
std::uniform_int_distribution<> distr(0,90); // define the range
vector <int> num;
for(int i=0;i<30;i++)
num.push_back(distr(eng));
vector<int> a=mergesort(num,0,num.size()-1);
for(auto &i:a)
cout<<i<<" ";
}
</code></pre>
| [] | [
{
"body": "<pre><code>#include<iostream>\n#include<vector>\n#include<random>\n#include<chrono>\n</code></pre>\n\n<p>Leave some space between the <code>#include</code>s and the rest of your code, that's easier to read. Besides, I really like <code><chrono></code> myself too, but you... | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-10-09T10:46:21.520",
"Id": "205219",
"Score": "5",
"Tags": [
"c++",
"mergesort"
],
"Title": "C++ code to sort a list of elements"
} | 205219 |
<p>A generic class to get object collection from csv string. I would like to know if there's any better way? </p>
<p><strong>Converter class</strong></p>
<pre><code>public class CsvConverter<T>:List<T> where T:class
{
private readonly string _csvText;
private readonly string _separetor;
/// <summary>
/// Get object collection from CSV string
/// </summary>
/// <param name="csvText">CSV string with Title</param>
/// <param name="separator">CSV line separator</param>
public CsvConverter(string csvText, string separator= "\r\n")
{
this._csvText = csvText;
_separetor = separator;
BuildObject();
}
/// <summary>
/// Get CSV string from collection of objects
/// </summary>
/// <param name="collection">Pass collection of objects</param>
public CsvConverter(IEnumerable<T> collection)
{
foreach (var item in collection)
{
this.Add(item);
}
}
/// <summary>
/// Create new Instance of T object
/// </summary>
/// <returns></returns>
protected T GetObject()
{
return (T)Activator.CreateInstance(typeof(T),true);
}
/// <summary>
/// Build object from CSV string to collection
/// </summary>
private void BuildObject()
{
if (!string.IsNullOrEmpty(_csvText))
{
//Get first line from CSV string, than split by comma to get column names
var _csvLines = _csvText.Split(_separetor);
var _columnName =_csvLines[0].Split(',');
for (int i = 1; i < _csvLines.Length; i++)
{
var line = _csvLines[i].Split(',');
T obj = GetObject();
Type t = obj.GetType();
PropertyInfo[] props = t.GetProperties();
int colIndx = 0;
foreach (string str in line)
{
PropertyInfo find = props.First(x => x.Name == _columnName[colIndx]);
find.SetValue(obj, Convert.ChangeType(str,find.PropertyType),null);
//propertyInfo.SetValue(propertyInfo.PropertyType, line[0]);
colIndx++;
}
this.Add(obj);
}
}
else
{
throw new System.NullReferenceException("No CSV string has passed in the parameter");
}
}
/// <summary>
/// Returns CSV string from collection of T object
/// </summary>
/// <returns>string</returns>
public string GetCsvString()
{
StringBuilder sb = new StringBuilder();
foreach (var item in this)
{
Type t = item.GetType();
PropertyInfo[] props = t.GetProperties();
string ln = "";
foreach (PropertyInfo prp in props)
{
ln= ln+($"{prp.GetValue(item)},");
}
sb.AppendLine($"{ln.TrimEnd(',')}");
}
return sb.ToString();
}
}
</code></pre>
<p><strong>get collection of object from csv string</strong></p>
<pre><code> var csv = await System.IO.File.ReadAllTextAsync("test.csv");
List<TestC> csvBarcode = new CsvConverter<TestC>(csv.TrimEnd());
</code></pre>
<p><strong>get csv string from collection of object</strong></p>
<pre><code> CsvConverter<TestC> b = new CsvConverter<TestC>(list);
return Content(b.GetCsvString());
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-10-09T13:26:46.713",
"Id": "395808",
"Score": "0",
"body": "Why does your class _inherit_ from `List<T>`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-10-10T06:26:56.677",
"Id": "395941",
"Score": "0",... | [
{
"body": "<p>I would rather see 2 static methods to convert a CSV to a collection of objects, and vice versa.</p>\n\n<p>A constructor should be as quick as possible to construct a new instance. You violate this with the call to <code>BuildObject()</code>.</p>\n\n<p>In <code>GetCsvString</code>, the variable <... | {
"AcceptedAnswerId": "205229",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-10-09T11:34:53.653",
"Id": "205222",
"Score": "2",
"Tags": [
"c#",
"object-oriented",
"generics"
],
"Title": "Get collection of objects from CSV string and vise-versa"
} | 205222 |
<p>I created a simple guessing game for the sake of practice, it's been a while since I've had any code reviewed. I do have a tendency to over-engineer things sometimes and I'm not typically aware of it until well after the programs creation, so please let me know if I've done such a thing. Other than that, I'm open to any and all suggestions.</p>
<p>Note, I did use mathematical notation of [1, 101) to denote that 1 is in the valid range of numbers and 101 in not included in the valid range of numbers.</p>
<p><strong>Program.cs</strong></p>
<pre><code>public class Program
{
private const string IntroductionStatement = "Guess the randomly chosen number.\r\nYou will be told if the number is LARGER or SMALLER than your guess after each attempt.";
private const string VictoryStatement = "You have won the game!";
private const string DefeatStatement = "Sorry, you have lost the game!";
private const string IncorrectGuessStatement = "Sorry that was incorrect.";
private const string PromptStatement = "How many attempts would you like? ";
private const string GuessStatement = "Your Guess: ";
private const string NumberRangeStatement = "The possible range of numbers is [{0}, {1}).\r\n";
private const string CurrentAttemptStatement = "\r\nAttempt #{0} of {1}.";
private const string LargerSmallerStatment = "The number is {0} than your guess.";
private const string AnswerStatement = "The number was {0}.";
static void Main(string[] args)
{
Console.WriteLine(IntroductionStatement);
Console.WriteLine(String.Format(NumberRangeStatement, GuessThatNumberGame.MinimumNumber, GuessThatNumberGame.MaximumNumber));
int maxAttempts = GetMaxAttemptsFromPlayer();
var game = new GuessThatNumberGame(maxAttempts);
do
{
Console.WriteLine(String.Format(CurrentAttemptStatement, game.Attempt, game.MaxAttempts));
var playerGuess = GetNumberGuessFromPlayer();
game.SubmitGuess(playerGuess);
if (game.HasBeenWon != true)
{
Console.WriteLine(IncorrectGuessStatement + " " + String.Format(LargerSmallerStatment, game.Number > playerGuess ? "LARGER" : "SMALLER"));
}
} while (game.HasBeenWon == null); // True means we've won, False means we've lost. Null means it's still in progress.
Console.WriteLine($"\r\n{(game.HasBeenWon == true ? VictoryStatement : DefeatStatement)}");
Console.WriteLine(String.Format(AnswerStatement, game.Number));
Console.ReadKey();
}
private static int GetMaxAttemptsFromPlayer()
{
return GetNumberFromPlayer(PromptStatement);
}
private static int GetNumberGuessFromPlayer()
{
return GetNumberFromPlayer(GuessStatement);
}
private static int GetNumberFromPlayer(string prompt)
{
var number = 0;
do
{
Console.Write(prompt);
} while (Int32.TryParse(Console.ReadLine(), out number) == false);
return number;
}
}
</code></pre>
<p><strong>GuessThatNumberGame.cs</strong></p>
<pre><code>public class GuessThatNumberGame
{
private static Random _Randomizer = new Random();
public const int MinimumNumber = 1;
public const int MaximumNumber = 101;
public int Attempt { get; private set; }
public int MaxAttempts { get; private set; }
public int Number { get; private set; }
public bool? HasBeenWon { get; private set; }
public GuessThatNumberGame(int maxAttempts)
{
if (maxAttempts <= 0)
{
throw new ArgumentOutOfRangeException("maxAttempts");
}
Number = _Randomizer.Next(MinimumNumber, MaximumNumber);
MaxAttempts = maxAttempts;
Attempt = 1;
}
/// <summary>
/// Enter a guess from the player.
/// </summary>
public void SubmitGuess(int guessedNumber)
{
// No more attempts if they've already lost.
if (HasBeenWon == false)
{
return;
}
// Add this to the number of attempts.
Attempt += 1;
// If they guessed correctly set to victory.
if (guessedNumber == Number)
{
HasBeenWon = true;
}
// This was their last attempt if we're over the max now.
if (Attempt > MaxAttempts)
{
HasBeenWon = false;
}
}
}
</code></pre>
<p><strong>Sample: Victory</strong></p>
<blockquote>
<p>Guess the randomly chosen number. You will be told if the number is
LARGER or SMALLER than your guess after each attempt. The possible
range of numbers is [1, 101).</p>
<p>How many attempts would you like? 10</p>
<p>Attempt #1 of 10. Your Guess: 50
Sorry that was incorrect. The number is SMALLER than your guess.</p>
<p>Attempt #2 of 10. Your Guess: 25
Sorry that was incorrect. The number is LARGER than your guess.</p>
<p>Attempt #3 of 10. Your Guess: 35
Sorry that was incorrect. The number is LARGER than your guess.</p>
<p>Attempt #4 of 10. Your Guess: 40
Sorry that was incorrect. The number is LARGER than your guess.</p>
<p>Attempt #5 of 10. Your Guess: 45
Sorry that was incorrect. The number is SMALLER than your guess.</p>
<p>Attempt #6 of 10. Your Guess: 43
Sorry that was incorrect. The number is LARGER than your guess.</p>
<p>Attempt #7 of 10. Your Guess: 44</p>
<p>You have won the game! The number was 44.</p>
</blockquote>
<p><strong>Sample: Defeat</strong></p>
<blockquote>
<p>Guess the randomly chosen number. You will be told if the number is
LARGER or SMALLER than your guess after each attempt. The possible
range of numbers is [1, 101).</p>
<p>How many attempts would you like? 5</p>
<p>Attempt #1 of 5. Your Guess: 50
Sorry that was incorrect. The number is SMALLER than your guess.</p>
<p>Attempt #2 of 5. Your Guess: 25
Sorry that was incorrect. The number is SMALLER than your guess.</p>
<p>Attempt #3 of 5. Your Guess: 12
Sorry that was incorrect. The number is SMALLER than your guess.</p>
<p>Attempt #4 of 5. Your Guess: 6
Sorry that was incorrect. The number is SMALLER than your guess.</p>
<p>Attempt #5 of 5. Your Guess: 3
Sorry that was incorrect. The number is LARGER than your guess.</p>
<p>Sorry, you have lost the game! The number was 4.</p>
</blockquote>
| [] | [
{
"body": "<h2>Magic Values</h2>\n\n<p>I took a look on your source code. It is quite good, and I like the way you define constants for values, but there are still some magic values, such as <strong>\"maxAttempts\"</strong>.</p>\n\n<h2>Exceptions</h2>\n\n<p>In side the method <strong>GuessThatNumberGame(int max... | {
"AcceptedAnswerId": "205236",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-10-09T13:16:50.213",
"Id": "205230",
"Score": "3",
"Tags": [
"c#",
"number-guessing-game"
],
"Title": "Guess that number, Larger or Smaller?"
} | 205230 |
<p>Consider the pattern below, where multiple async calls are made in parallel:</p>
<pre><code>var thisTask = ThisAsync();
var thatTask = ThatAsync();
await Task.WhenAll(thisTask, thatTask);
var this = await thisTask;
var that = await thatTask;
</code></pre>
<p>While it works fine, I find it a bit too verbose for what it is doing.</p>
<p>While having some fun with tuple types, I came up with the following approach that results in the same behavior:</p>
<pre><code>var (this, that) = await (ThisAsync(), ThatAsync()).ResultsAsync();
</code></pre>
<p>It relies on an extension method on a tuple of Tasks, like below:</p>
<pre><code>static class ParallelTasksExtensions
{
static async Task<(T1, T2)> ResultsAsync<T1, T2>(this (Task<T1>, Task<T2>) tasks)
{
await Task.WhenAll(tasks.Item1, tasks.Item2);
return (await tasks.Item1, await tasks.Item2);
}
}
</code></pre>
<p>With a couple overloads (wish C# supported variadic generic types like C++ does in templates) this can be extended to an arbitrary number of parallel calls, so that we can have something like this:</p>
<pre><code>var (one, two, three, four) = await (OneAsync(), TwoAsync(), ThreeAsync(), FourAsync()).ResultsAsync();
</code></pre>
<p>I like it quite a bit because of the following reasons:</p>
<ul>
<li>Is is dramatically shorter. Usually shorter code leads to less chance of problems (not a golden rule of course, but I feel it applies here)</li>
<li>It requires less state to be maintained (less variables)</li>
<li>It avoids people calling <code>.Result</code> instead of <code>await</code> on the original tasks (<a href="https://stackoverflow.com/a/17197786/1946412">a common bad practice</a>)</li>
</ul>
<p>Another option that would result in the same behavior would be to create an extension class instead of coding this as an extension method.</p>
<p>For example:</p>
<pre class="lang-or-tag-here prettyprint-override"><code>var (this, that) = await TaskEx.WhenAll((ThisAsync(), ThatAsync()));
</code></pre>
<p>This approach would be more inline with existing, non-tuple based overloads of <code>Task.WhenAll</code>.</p>
<p>Thoughts?</p>
<ul>
<li>Is it "too clever" in your opinion? I don't think there is any similar native construct that achieves this so it could be seen as clever by some I'm sure.</li>
<li>Do you consider this over-engineering?</li>
<li>Is it more readable/intuitive to you?</li>
<li>Do you have other suggestions for the method name?</li>
</ul>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-10-11T07:41:31.963",
"Id": "396168",
"Score": "0",
"body": "Is there even a reason for the `await WhenAll`? C# tasks run from the moment they're started, so they would still run in parallel even if you await them individually."
}
] | [
{
"body": "<p>I am fairly new to Asynchronous programming in c# but I have infact programmed parallel systems using C++. From all of my experience dealing from novice to seasoned programmers, I normally try and write code in a way in which other people reading my code would understand it one shot.</p>\n\n<p>Sin... | {
"AcceptedAnswerId": "205364",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-10-09T13:56:00.103",
"Id": "205231",
"Score": "4",
"Tags": [
"c#",
"asynchronous",
"async-await"
],
"Title": "Initializing multiple variables with different types using parallel calls"
} | 205231 |
<p>I am implementing an algorithm to find the pair of integers in the given array which have minimum XOR value.</p>
<p>Ex:</p>
<p><strong>Input</strong>:</p>
<pre><code> 0 2 5 7
</code></pre>
<p><strong>Output</strong>:</p>
<pre><code> 2 (value of 0 XOR 2).
</code></pre>
<p>Then bellow is my solution:</p>
<pre><code> public int findMinXor(List<int> A)
{
var min = int.MaxValue;
for (int i = 0; i < A.Count - 1; i++)
{
for (int j = i + 1; j < A.Count; j++)
{
var tmp = A[i] ^ A[j];
if (tmp < min)
{
min = tmp;
}
}
}
return min;
}
</code></pre>
<p>What should I do to improve the solution (clean code, performance, DRY,...)?
Any help are appriciate!</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-10-09T19:58:33.610",
"Id": "395888",
"Score": "1",
"body": "Spoiler at https://www.geeksforgeeks.org/minimum-xor-value-pair/ :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-10-11T06:58:57.340",
"Id": "3961... | [
{
"body": "<p>The program is running in quadratic time. As usual, to improve performance you need to change the algorithm.</p>\n\n<p>Sort the numbers into 32 buckets, according to where the most significant bit of the number is. Convince yourself that if a bucket contains more than one number, it makes no sense... | {
"AcceptedAnswerId": "205284",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-10-09T15:51:27.297",
"Id": "205240",
"Score": "4",
"Tags": [
"c#",
"algorithm"
],
"Title": "Find minimum XOR values in a given array"
} | 205240 |
<p>This is my first attempt at implementing a heap data structure and I've decided to cover the methods <code>Peek</code>, <code>Pop</code>, <code>Push</code>, and <code>Replace</code>. Think appear to work correctly but I admittedly had a lot of trouble figuring out the "ideal" way to implement each function as the reference implementations I found were all over the place.</p>
<p>Any feedback, especially if it addresses concerns that aren't related to formatting/naming, is most appreciated.</p>
<pre><code>public class BinaryHeap<T>
{
private readonly Func<T, T, bool> m_comparer;
private readonly IList<T> m_values;
private int m_nextIndex;
public int Capacity => m_values.Count;
public int Count => m_nextIndex;
public BinaryHeap(IList<T> values, Func<T, T, bool> comparer) {
m_comparer = comparer;
m_values = values;
Grow(checked((int)(Operations.NextPowerOf2(Capacity) - 1)));
Rebuild();
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public T Peek() {
return m_values[0];
}
public T Pop() {
if (TryPop(out T value)) {
return value;
}
else {
throw new InvalidOperationException(message: "heap is empty");
}
}
public int Push(T value) {
var offset = Count;
if (!(offset < Capacity)) {
Grow(checked((int)(Operations.NextPowerOf2(Capacity + 1) - 1)));
}
while (0 < offset) {
var parent = ((offset - 1) >> 1);
if (m_comparer(m_values[parent], value)) {
break;
}
m_values[offset] = m_values[parent];
offset = parent;
}
m_values[offset] = value;
return m_nextIndex++;
}
public T Replace(T newValue) {
if (TryReplace(newValue, out T oldValue)) {
return oldValue;
}
else {
throw new InvalidOperationException(message: "heap is empty");
}
}
public bool TryReplace(T newValue, out T oldValue) {
if (0 < Count) {
oldValue = Peek();
m_values[0] = newValue;
Heapify(0);
return true;
}
else {
oldValue = default;
return false;
}
}
public bool TryPop(out T value) {
if (0 < Count) {
value = Peek();
m_values[0] = m_values[--m_nextIndex];
m_values[m_nextIndex] = default;
Heapify(0);
return true;
}
else {
value = default;
return false;
}
}
private void Grow(int maxCapacity) {
var currentCapacity = Capacity;
for (var i = currentCapacity; (i < maxCapacity); i++) {
m_values.Add(default);
}
m_nextIndex = currentCapacity;
}
private void Heapify(int offset) {
var count = Count;
while (offset < count) {
var left = ((offset << 1) + 1);
var right = (left + 1);
var parent = offset;
if ((left < count) && m_comparer(m_values[left], m_values[parent])) {
parent = left;
}
if ((right < count) && m_comparer(m_values[right], m_values[parent])) {
parent = right;
}
if (offset == parent) {
return;
}
Swap(ref offset, ref parent);
}
}
private void Rebuild() {
for (var i = ((Count - 1) >> 1); (-1 < i); i--) {
Heapify(i);
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private void Swap(ref int x, ref int y) {
var temp = m_values[x];
m_values[x] = m_values[y];
m_values[y] = temp;
x = y;
}
}
</code></pre>
<p>As requested, here are the missing method(s):</p>
<pre><code>public static class Operations
{
public static long NextPowerOf2(long value) {
return ((long)NextPowerOf2((ulong)value));
}
public static ulong NextPowerOf2(ulong value) {
return (FoldBits(value) + 1);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static ulong FoldBits(ulong value) {
value |= (value >> 1);
value |= (value >> 2);
value |= (value >> 4);
value |= (value >> 8);
value |= (value >> 16);
return (value | (value >> 32));
}
}
</code></pre>
| [] | [
{
"body": "<p>I don't like the <code>Swap</code> method. The two <code>ref</code> parameters suggest that the values passed are swapped. Instead, the values are taken as indexes in <code>m_values</code> whose values are swapped. It also has an unexpected side-effect as it changes the index <code>x</code>. Also,... | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-10-09T16:48:50.643",
"Id": "205244",
"Score": "8",
"Tags": [
"c#",
"algorithm",
"heap"
],
"Title": "Binary Heap (list-based)"
} | 205244 |
<p>The program that contains the function I'm asking (<code>handle_non_exact_answer</code>) about has several instances of a class <code>Test</code>, with some options the user can set that determines the behavior of the class. If the class has certain options, we handle the class differently, so I deal with these cases in a separate function, which is below.</p>
<p>I would like to learn a) how to better write the function (ideally in the "most pythonic" way,) and b) how to resolve a <code>pylint</code> warning related to this function: <code>Unnecessary "else" after "return"</code>.</p>
<pre><code>import random
class Test:
def __init__(self):
self.precision = None
self.expected_result = None
def handle_non_exact_answer(test, answer):
if test.precision not in {"less", "more", "lesser", "greater"}:
return False
else:
if test.precision == "less" and answer < test.expected_result:
print("passed")
elif test.precision == "more" and answer > test.expected_result:
print("passed")
elif test.precision == "lesser" and answer <= test.expected_result:
print("passed")
elif test.precision == "greater" and answer >= test.expected_result:
print("passed")
else:
print("failed")
return True
def main():
test = Test()
test.precision = "greater"
test.expected_result = 0
test1 = Test()
test1.precision = "lesser"
test1.expected_result = 0
test2 = Test()
test2.precision = "more"
test2.expected_result = 0
test3 = Test()
test3.precision = "less"
test3.expected_result = 0
tests = [test, test1, test2, test3]
for test in tests:
handle_non_exact_answer(test, random.randint(-10,10))
if __name__ == "__main__":
main()
</code></pre>
| [] | [
{
"body": "<p>That's a very unconventional usage of the term <a href=\"https://en.wikipedia.org/wiki/Precision_%28computer_science%29\" rel=\"noreferrer\">\"precision\"</a>. I think that \"comparison\" would be the appropriate word here.</p>\n\n<p>The <code>Test</code> class is severely underdeveloped. The co... | {
"AcceptedAnswerId": "205253",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-10-09T16:58:18.227",
"Id": "205246",
"Score": "1",
"Tags": [
"python",
"object-oriented",
"python-3.x"
],
"Title": "Function that performs a test of whether a number is greater or less than some expected result"
} | 205246 |
<p>I've already posted <a href="https://codereview.stackexchange.com/questions/205132/simple-random-number-guessing-game-with-various-difficulties">a first attempt</a> on Code review. Here is a new version that takes into account the answers I've received.</p>
<p>Is my program now reasonable or are there still things I need to improve?</p>
<p>As I am learning programming I do not want to develop bad habit.
Any tips on what is good to do and what is bad to do would be grateful.</p>
<pre><code>public class GuessGame
{
public static Random rnd = new Random();
public int Attemp { get; set; } = 0;
public bool Win { get; set; } = true;
public bool EndGame { get; set; } = true;
public void PlayGame()
{
// <Program outline>
// Ask how many attemp
// computer generate rnd#
// While attemps are left
// prompt for guess
// compare num
// correct? jump out wrong? loop until attemps runs out
// end while
// do you want to play again?
while (EndGame)
{
Console.WriteLine("Lets play the Low or High Game");
Attemp = InputAttempt();
var comNum = GenerateComNum();
do
{
// Console.WriteLine(comNum);
var userNum = InputUserNum();
CompareNum(userNum, comNum);
} while (Attemp > 0 && Win);
PlayAgain();
}
}
void PlayAgain()
{
label:
Console.WriteLine("Play again? press 1 for yes/ press 2 for n");
int again = 0;
while (!Int32.TryParse(Console.ReadLine(), out again))
{
Console.WriteLine("Please input whole number");
}
while (again !=1 && again != 2)
{
goto label;
}
if (again == 1)
{
Console.Clear();
}
else if (again == 2)
{
Console.WriteLine("Good Bye Thank you for playing");
EndGame = false;
}
}
int InputUserNum()
{
int userNum = 0;
Console.Write("Please guess the number btw 1-100 ?\t");
while (!Int32.TryParse(Console.ReadLine(), out userNum))
{
Console.WriteLine("Invalid num please input whole num");
}
return userNum;
}
int InputAttempt()
{
label:
int Attemp = 0;
Console.Write("How many Attemps would you like?\t");
while (!Int32.TryParse(Console.ReadLine(), out Attemp))
{
Console.WriteLine("Invalid num please input whole num");
}
if (Attemp == 0)
{
Console.WriteLine("Do not input 0");
goto label;
}
return Attemp;
}
int GenerateComNum()
{
return rnd.Next(1, 101);
}
void CompareNum(int userNum, int comNum)
{
if (userNum == comNum)
{
Console.WriteLine("You have guessed right number!!\n");
Win = false;
}
else if (userNum > comNum)
{
Attemp--;
Console.WriteLine($"Your number is too High! \t Attemp<{Attemp}>left\n");
}
else if (userNum < comNum)
{
Attemp--;
Console.WriteLine($"Your number is too Low! !\t Attemp<{Attemp}>left\n");
}
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-10-10T06:55:05.367",
"Id": "395946",
"Score": "0",
"body": "This isn't nice. You haven't accepted any answer under your [last](https://codereview.stackexchange.com/questions/205132/simple-random-number-guessing-game-with-various-difficult... | [
{
"body": "<p>A couple of things:</p>\n\n<p>The word is <code>attempt</code>. You get it right in some places but not all. Be consistent.</p>\n\n<p>You've hardcoded this for a local console. Personally I like to pass the input and output streams to the class. This gives you the flexibility to use network st... | {
"AcceptedAnswerId": "205268",
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-10-09T17:57:07.257",
"Id": "205251",
"Score": "1",
"Tags": [
"c#",
"number-guessing-game"
],
"Title": "NumberGuessGame"
} | 205251 |
<p>I have some code that takes some JSON, parses it, and given an optional filter, will attempt to find any key (or nested key) that includes the filter (partial matching - it does not match values). The difficult part was handling deeply nested objects and arrays. </p>
<p>For example, given the following JSON:</p>
<pre><code>{
"a": {
"b": 2,
"c": 3,
"d": [{ "b": 4, "c": 4 }, { "e": 5 }]
}
}
</code></pre>
<p>If I filter with the key <code>'b'</code> the output should retain the object in <code>'a'</code> and the first object in <code>'d'</code>:</p>
<pre><code>{
a: {
b: 2,
d: [{ b: 4 }]
}
}
</code></pre>
<p>The same goes with arrays - I must search down into an array of objects and retain the array if a nested object has a key that includes the filter.</p>
<p>The following is an example, filtering out user data by <code>'id'</code>:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const json = '[{"_id":"5bbce9314d255887d3583cb1","index":0,"guid":"05b45bf7-dc1e-4db0-a378-f29c7967c36e","isActive":false,"balance":"$1,099.18","picture":"http://placehold.it/32x32","age":23,"eyeColor":"brown","name":"Polly Hammond","gender":"female","company":"NETILITY","email":"pollyhammond@netility.com","phone":"+1 (953) 480-3232","address":"438 Jardine Place, Brandywine, Minnesota, 238","about":"Fugiat mollit reprehenderit adipisicing minim irure amet dolor excepteur veniam laborum. Velit velit ullamco nostrud laboris enim ex reprehenderit magna esse voluptate et et velit elit. Lorem adipisicing do elit enim esse ad. Esse ea ex ex labore aute aliquip duis elit voluptate proident cillum. Esse qui duis reprehenderit cillum ad proident proident. Incididunt incididunt culpa labore laborum proident labore adipisicing nisi dolor. Dolore cillum do officia cupidatat sit enim deserunt incididunt dolore reprehenderit ullamco adipisicing est.","registered":"2017-04-10T09:25:00 +04:00","latitude":-65.127935,"longitude":-124.785612,"tags":["cupidatat","tempor","duis","magna","culpa","magna","duis"],"friends":[{"id":0,"name":"Dawson Rollins"},{"id":1,"name":"Roberts Carroll"},{"id":2,"name":"Bowen Farley"}],"greeting":"Hello, Polly Hammond! You have 1 unread messages.","favoriteFruit":"strawberry"},{"_id":"5bbce93106cdc523057314ef","index":1,"guid":"85fa0c63-d97c-4592-9b87-85953ad4172b","isActive":false,"balance":"$1,401.63","picture":"http://placehold.it/32x32","age":37,"eyeColor":"green","name":"Shelley Carrillo","gender":"female","company":"SONIQUE","email":"shelleycarrillo@sonique.com","phone":"+1 (880) 428-3366","address":"679 Fountain Avenue, Enoree, Puerto Rico, 1210","about":"Culpa labore sit velit Lorem officia proident aute duis ullamco non est. Lorem veniam voluptate non ullamco cillum nisi id sint esse. Id labore sunt incididunt laboris eu nulla esse do proident commodo est commodo nisi nulla. Sunt sit aute eu pariatur irure laboris minim sint consectetur magna dolore occaecat deserunt. In aute proident ex culpa ea adipisicing ea laborum irure.","registered":"2016-08-05T01:07:31 +04:00","latitude":-34.270418,"longitude":-146.16793,"tags":["adipisicing","reprehenderit","ipsum","quis","do","excepteur","aliquip"],"friends":[{"id":0,"name":"Gross Murray"},{"id":1,"name":"Norman Hubbard"},{"id":2,"name":"Winnie Reed"}],"greeting":"Hello, Shelley Carrillo! You have 5 unread messages.","favoriteFruit":"apple"}]'
const isObject = o => typeof o === 'object' && o !== null;
const isArray = Array.isArray;
const parseJson = (json, filter) => {
const pJson = JSON.parse(json);
const parseArray = array => {
// remove non-objects from the array
const arrayObjects = array.filter(isObject);
return arrayObjects.map(o => {
if (isArray(o)) {
return parseArray(o);
} else if (isObject(o)) {
return parseObject(o);
}
}).filter(o => isArray(o) ? o.length : Object.keys(o).length);
};
const parseObject = object => {
if (isArray(object)) {
return parseArray(object);
}
let output = {};
const keys = Object.keys(object);
for (const key of keys) {
if (isArray(object[key])) {
const array = parseArray(object[key]);
if (array && array.length) {
output[key] = array;
} else if (key.includes(filter)) {
output[key] = [];
}
} else if (isObject(object[key])) {
const nestedObject = parseObject(object[key]);
if (Object.keys(nestedObject).length) {
output[key] = {...nestedObject};
} else if (key.includes(filter)) {
output[key] = {};
}
} else if (key.includes(filter)) {
// store the value on output if the property name has a match
output[key] = object[key];
}
}
return output;
};
return filter
? parseObject(pJson)
: pJson;
};
console.log(parseJson(json, 'id'));</code></pre>
</div>
</div>
</p>
<p>The code works, and seems to perform decently even with large sets of data, but it feels a bit messy due to having to check multiple times whether I'm dealing with an array or an object. Since it's a personal project I'm not opposed to shortcuts/operators/etc. that would normally be frowned upon in a shared project.</p>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-10-09T17:57:47.783",
"Id": "205252",
"Score": "1",
"Tags": [
"javascript",
"recursion",
"json"
],
"Title": "Recursive object/array filter by key"
} | 205252 |
<p>I've only ever made small programs. So, I've tried to make something large but easily reusable/extendable. Posted below are the beginnings of a graph library I've written up.</p>
<p>One particular point I'd like to ask about is my use of the class <code>HashMap</code>. I wanted to be able to hash easily and by memory address. This approach gives me a lot of flexibility, but it also feels hacky. I'd like to get a sense from people if this approach seems too strange, or if it is acceptable.</p>
<p>Anyway, it's sort of a lot of code. You're obviously not obligated to look at all (or any!) of it. Any comments, even if on a small segment of the code, are appreciated.</p>
<p>The files are: <code>hashMap.h</code> > <code>disjointSets.h</code> > <code>graph.h</code> > <code>minSpanTree.h</code>, with dependencies in that order.</p>
<h3>hashMap.h</h3>
<pre><code>#ifndef HASHMAP_H
#define HASHMAP_H
#include <unordered_map>
template <class keyed, class val>
class HashMap
{
public:
HashMap(){}
~HashMap(){}
long keyOf(keyed &item){ return (long) &item; }
val &operator[](keyed &item)
{
long key = keyOf(item);
return _uomap[key];
}
private:
std::unordered_map<long, val> _uomap;
};
#endif
</code></pre>
<h3>graph.h:</h3>
<pre><code>#ifndef GRAPH_H
#define GRAPH_H
#include <iostream>
#include <vector>
#include "hashMap.h"
using namespace std;
class Vertex
{
public:
Vertex(float val): _val (val), _id (0) {}
Vertex(int id): _val (0), _id (id) {}
Vertex(int id, float val): _val (val), _id (id) {}
~Vertex(){}
int id() const { return _id; }
int val() const { return _val; }
private:
float _val;
int _id;
};
class Edge
{
public:
Edge(Vertex *to, Vertex *from): _to (to), _from (from), _weight (1.){}
Edge(Vertex *to, Vertex *from, float w): _to (to), _from (from), _weight (w){}
~Edge(){}
void show()
{
cout << (*_to).id() << " <-(" << _weight;
cout << ")- " << (*_from).id() << endl;
}
Vertex &to() const { return *_to; }
Vertex &from() const { return *_from; }
float weight() const { return _weight; }
private:
Vertex *_to;
Vertex *_from;
float _weight;
};
class Graph
{
public:
Graph(int numVertices)
{
_numVertices = 0;
for(int i=0; i < numVertices; i++)
{
_vertices.push_back( Vertex(_numVertices) );
++_numVertices;
}
}
~Graph(){}
vector<Vertex*> adj(Vertex &v){ return _adjHashMap[v]; }
vector<Vertex> &vertices(){ return _vertices; }
vector<Edge> &edges(){ return _edges; }
void connectTo(Vertex &v, Vertex &u, float weight)
{ //TODO: if isConnectedTo, don't connect!
Vertex *uptr = &u;
Vertex *vptr = &v;
_adjHashMap[v].push_back(uptr);
Edge newEdge(uptr, vptr, weight);
_edges.push_back(newEdge);
}
void connectTo(Vertex &v, Vertex &u){ connectTo(v, u, 1.); }
bool isConnectedTo(Vertex &v, Vertex &u)
{
vector<Vertex* > adj = _adjHashMap[v];
for(Vertex *vptr : adj)
if (vptr == &u) return true;
return false;
}
private:
vector<Vertex> _vertices;
vector<Edge> _edges;
HashMap<Vertex, vector<Vertex*> > _adjHashMap;
int _numVertices;
};
#endif
</code></pre>
<h3>disjoint.h:</h3>
<pre><code>#ifndef DISJOINT_H
#define DISJOINT
#include "hashMap.h"
template <class T>
class DisjointSets
{
public:
DisjointSets(){}
~DisjointSets(){}
void makeSet(T &elem)
{
_parentOf[elem] = &elem;
_rankOf[elem] = 0;
++_numSets;
}
T &findSet(T &elem)
{
if (_parentOf[elem] != &elem)
_parentOf[elem] = &findSet(*_parentOf[elem]);
return (*_parentOf[elem]);
}
void unify(T &elemA, T &elemB)
{
link(findSet(elemA), findSet(elemB));
--_numSets;
}
void link(T &setA, T &setB)
{
if (_rankOf[setA] < _rankOf[setB])
_parentOf[setA] = &setB;
else
{
_parentOf[setB] = &setA;
if (_rankOf[setB] == _rankOf[setA])
++(_rankOf[setB]);
}
}
int numSets(){ return _numSets; }
private:
HashMap<T, T*> _parentOf;
HashMap<T, int> _rankOf;
int _numSets = 0;
};
#endif
</code></pre>
<h3>minSpanTree.h:</h3>
<pre><code>#ifndef MST_H
#define MST_H
#include <algorithm>
#include "graph.h"
#include "disjoint.h"
using namespace std;
struct weight_less_than
{
inline bool operator() (const Edge& a, const Edge &b)
{
return a.weight() < b.weight();
}
};
vector<Edge> kruskal(Graph &g)
{
vector<Edge> mst;
vector<Edge> &es = g.edges();
std::sort( es.begin(), es.end(), weight_less_than());
vector<Vertex> &vs = g.vertices();
DisjointSets<Vertex> sets;
for (Vertex &v : vs)
sets.makeSet(v);
for (Edge &e : es)
{
Vertex &to = e.to();
Vertex &from = e.from();
if (&(sets.findSet(to)) != &(sets.findSet(from)))
{
sets.unify(to, from);
mst.push_back(e);
}
}
return mst;
}
#endif
</code></pre>
<p>One thing I quite like about how the code turned out was that the implementation of <a href="https://en.wikipedia.org/wiki/Kruskal%27s_algorithm" rel="nofollow noreferrer">Kruskal's algorithm</a> seems very readable, and very close to pseudo-code (at least for me - maybe I've become too familiar with it).</p>
<p>Any feedback appreciated.</p>
| [] | [
{
"body": "<p>I see a number of 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... | {
"AcceptedAnswerId": "205280",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-10-09T18:55:36.200",
"Id": "205255",
"Score": "1",
"Tags": [
"c++",
"tree",
"graph",
"union-find"
],
"Title": "Graph library including minimum spanning tree using Kruskal's Algorithm"
} | 205255 |
<p>Successful attempt at the <a href="https://naq18.kattis.com/problems/froggie" rel="nofollow noreferrer"><strong>ICPC North America Qualifier 2018</strong> Problem D</a> "Froggie." Any advice and all topical comments on code optimization and performance enhancement is appreciated!</p>
<h1>Problem Summary</h1>
<blockquote>
<p>You are recreating the classic ‘Frogger’ video game.</p>
<p>Each level consists of a road with multiple lanes, with cars traveling in both directions. Cars within each lane are evenly-spaced and move at the same speed and in the same direction. Lane directions alternate, with the top lane moving left to right.</p>
<p>‘Froggie’ starts below the bottom lane and she travels across the road from the bottom to the top. At each time step, Froggie hops one space in one of four directions: up, down, left, or right. The goal of the game is to get Froggie across the road and above the top lane without her getting hit by a car.</p>
<h2>Goal</h2>
<p>Given a description of the road, car positions and speeds, and Froggie’s starting positions and moves, determine her outcome after the simulation. There are two possible outcomes: safely exiting the top lane or getting squished.</p>
<p>In order to better plan her travel, Froggie may move left or right before entering the road. Once Froggie has entered the road she may only exit through the top of the road. That is, Froggie’s path never exits the left, right, or bottom lane boundaries.</p>
<h2>Input</h2>
<p>Each input describes one simulation. The first line of input contains two integers separated by a space: <span class="math-container">\$L\$</span> and <span class="math-container">\$W\$</span>. The number of lanes is given by <span class="math-container">\$L\$</span> (<span class="math-container">\$1≤L≤10\$</span>), while <span class="math-container">\$W\$</span> (<span class="math-container">\$3≤W≤20\$</span>) defines the width (in number of cells) of the grid.</p>
<p>This is followed by <span class="math-container">\$L\$</span> lines each describing the car configuration for a lane (from top to bottom). Each line contains three integers: <span class="math-container">\$O\$</span>, the starting offset of the first car; <span class="math-container">\$I\$</span>, the interval between cars; and <span class="math-container">\$S\$</span>, the speed of the cars. The bounds are <span class="math-container">\$0≤O<I≤W\$</span> and <span class="math-container">\$0≤S≤W\$</span>. All offsets should be computed based on the direction of lane movement.</p>
<p>The final line of input starts with a single integer, <span class="math-container">\$P\$</span> (<span class="math-container">\$0≤P≤W−1\$</span>) followed by a space and then a string of <span class="math-container">\$M\$</span> characters (<span class="math-container">\$1≤M≤L⋅W\$</span>) from the set <span class="math-container">\$\{U,D,L,R\}\$</span>. <span class="math-container">\$P\$</span> defines the starting position of Froggie, starting from the left. The string of characters defines the sequence of moves (up, down, left, right) that Froggie makes during the simulation.</p>
<h2>Output</h2>
<p>If Froggie successfully crosses the road (exiting the road from the top lane), output “safe”. If Froggie is hit by a car, or does not end above the road, output “squish”.</p>
</blockquote>
<p><strong>froggie.py</strong></p>
<pre><code>l, w = map(int, input().split())
cars = []
for i in range(l):
cars.append(list(map(int, input().split())))
if i % 2 != 0:
cars[-1][0] = w - cars[-1][0] - 1
pos, moves = input().split()
pos = (l, int(pos))
dirs = { 'U': (-1, 0), 'D': (1, 0), 'L': (0, -1), 'R': (0, 1) }
for i, c in enumerate(moves):
pos = list(map(sum, zip(pos, dirs[c])))
row = pos[0]
if row == -1:
print('safe')
exit(0)
elif row >= l:
continue
car = cars[row]
diff = car[0] + car[2] * (i + 1) if row % 2 == 0 else car[0] - car[2] * (i + 1)
if (diff - pos[1]) % car[1] == 0:
print('squish')
exit(0)
print('squish')
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-10-09T22:35:05.453",
"Id": "395907",
"Score": "1",
"body": "Please include a brief summary of the challenge to be performed. Just including the link is insufficient."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "201... | [
{
"body": "<p>The code in the post does not solve the problem. Consider the following input:</p>\n\n<pre><code>1 6\n0 3 3\n1 UU\n</code></pre>\n\n<p>The code in the post prints \"safe\", but in fact the frog is squished, since the cars have speed 3 and separation 3, meaning that a car crosses every square in th... | {
"AcceptedAnswerId": "205277",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-10-09T20:48:17.237",
"Id": "205259",
"Score": "2",
"Tags": [
"python",
"programming-challenge",
"simulation"
],
"Title": "NAQ 2018 Problem D Froggie"
} | 205259 |
<p>I was asked for an example of a class to wrap dynamically added controls as I suggested in this <a href="https://codereview.stackexchange.com/a/205212/171419">Answer</a>. Although it is out of the context of a Code Review, I thought that it would make an interesting post.</p>
<p>I'm looking for feedback on not only "How to improve my code" but also "How to better explain my code". </p>
<hr>
<h2>Basic Custom Control Pattern</h2>
<p><a href="https://i.stack.imgur.com/fBbbD.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/fBbbD.png" alt="Basic Custom Control Pattern"></a></p>
<h2>Userform1: Userform</h2>
<ul>
<li>CustomControls:Collection - Used to store the CustomControls in memory.</li>
<li>AddCustomControls() - Add new controls to Userform1, links them to a New CustomControl. The New CustomControl is then added to the CustomControls collection.</li>
<li>CustomCombo_Change(Item:CustomContol): This public method is called by a CustomControl when the CustomControls.Combo Change event is fired.</li>
</ul>
<h2>CustomControl: Class</h2>
<p><a href="https://i.stack.imgur.com/kXoty.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/kXoty.png" alt="Withevents Demo Image"></a></p>
<ul>
<li>WithEvents Combo:MsForms.ComboBox - Using WithEvents allows the class to receive the controls events</li>
<li>Form:UserForm1 - The class stores a reference to the parent Userform so that it can trigger custom Userform events. Typically a references to either the class of to one of the classes controls is passed back to the parent form.</li>
</ul>
<hr>
<h2>Advanced Custom Control Pattern</h2>
<p>This pattern has the userform Implement an Interface. The custom class references the userform's Interface instead of the actual userform. In this way, the Custom class can be used with any other class or userform that Implements the Interface.</p>
<p><a href="https://i.stack.imgur.com/r2q7h.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/r2q7h.png" alt="advanced custom control pattern"></a></p>
<hr>
<h2>Advanced Pattern Demo</h2>
<p>This code applies the Advanced Pattern to this post: [Loop through different controls and enabled the state of the whole group VBA]
(<a href="https://codereview.stackexchange.com/q/205096/171419">Loop through different controls and enabled the state of the whole group VBA</a>).</p>
<p>Download the demo: <a href="https://drive.google.com/open?id=1wImzlPIHT85pQRCs1GDBFWv8NlQII_xk" rel="nofollow noreferrer">dynamic-control-rows.xlsm</a>. Note: The workbook also contains the TemplateForm that I used to generate most of the code for the controls.</p>
<h2>IItemsForm:Interface</h2>
<pre><code>Public Sub ItemRowUpdated(Item As ItemRow)
End Sub
</code></pre>
<h2>ItemsForm:UserForm</h2>
<pre><code>Option Explicit
Implements IItemsForm
Private ItemRows As New Collection
Private Sub btnAddRows_Click()
Dim Item As New ItemRow
Item.Init FrameItems, Me
Item.cboItem.List = Array("Jumper", "Shirt", "Trouser")
ItemRows.Add Item
SpaceItems
End Sub
Private Sub SpaceItems()
Const PaddingTop As Double = 5
Dim Top As Double
Dim Item As ItemRow
Top = PaddingTop
Dim n As Long
For n = 1 To ItemRows.Count
Set Item = ItemRows(n)
Item.ckItemNo.Caption = n
Item.Top = Top
Top = Top + Item.Frame.Height + PaddingTop
Next
EnableItems
End Sub
Private Sub EnableItems()
Dim Item As ItemRow, PreviousItem As ItemRow
Dim n As Long
Dim Enabled As Boolean
Enabled = True
For n = 2 To ItemRows.Count
Set PreviousItem = ItemRows(n - 1)
Set Item = ItemRows(n)
Item.Enabled = PreviousItem.cboItem.Value <> vbNullString
Next
End Sub
Private Sub btnDeleteSelectedRows_Click()
Dim Item As New ItemRow
Dim n As Long
For n = ItemRows.Count To 1 Step -1
Set Item = ItemRows(n)
If Item.ckItemNo.Value = True Then
ItemRows.Remove n
FrameItems.Controls.Remove Item.Frame.Name
End If
Next
SpaceItems
End Sub
Private Sub IItemsForm_ItemRowUpdated(Item As ItemRow)
EnableItems
End Sub
Private Sub UserForm_Initialize()
btnAddRows_Click
End Sub
</code></pre>
<h2>ItemRow: Class</h2>
<pre><code>Option Explicit
Public Form As IItemsForm
Public Frame As MSForms.Frame
Public ckItemNo As MSForms.CheckBox
Public WithEvents cboItem As MSForms.ComboBox
Public txtQty As MSForms.TextBox
Public txtUnitPrice As MSForms.TextBox
Public txtSubTotal As MSForms.TextBox
Public optIn As MSForms.OptionButton
Public optOut As MSForms.OptionButton
Public txtComments As MSForms.TextBox
Public Sub Init(TargetFrame As MSForms.Frame, TargetForm As IItemsForm)
Set Form = TargetForm
Set Frame = TargetFrame.Controls.Add("Forms.Frame.1")
Frame.Height = 24
Frame.Width = 630
With Frame.Controls
Set ckItemNo = .Add(bstrProgID:="Forms.CheckBox.1")
With ckItemNo
.Top = 0
.Left = 6
.Width = 57
.Height = 18
End With
Set cboItem = .Add(bstrProgID:="Forms.ComboBox.1")
With cboItem
.Top = 0
.Left = 78
.Width = 120
.Height = 18
End With
Set txtQty = .Add(bstrProgID:="Forms.TextBox.1")
With txtQty
.Top = 0
.Left = 204
.Width = 30
.Height = 18
End With
Set txtUnitPrice = .Add(bstrProgID:="Forms.TextBox.1")
With txtUnitPrice
.Top = 0
.Left = 240
.Width = 60
.Height = 18
End With
Set txtSubTotal = .Add(bstrProgID:="Forms.TextBox.1")
With txtSubTotal
.Top = 0
.Left = 306
.Width = 60
.Height = 18
End With
Set optIn = .Add(bstrProgID:="Forms.OptionButton.1")
With optIn
.Top = 0
.Left = 378
.Width = 27
.Height = 18
.Caption = "IN"
End With
Set optOut = .Add(bstrProgID:="Forms.OptionButton.1")
With optOut
.Top = 0
.Left = 408
.Width = 38.25
.Height = 18
.Caption = "OUT"
End With
Set txtComments = .Add(bstrProgID:="Forms.TextBox.1")
With txtComments
.Top = 0
.Left = 456
.Width = 168
.Height = 18
End With
End With
End Sub
Public Property Get Top() As Double
Top = Frame.Top
End Property
Public Property Let Top(ByVal Value As Double)
Frame.Top = Value
End Property
Public Property Get Enabled() As Boolean
Enabled = Frame.Enabled
End Property
Public Property Let Enabled(ByVal Value As Boolean)
Frame.Enabled = Value
Dim Ctrl As MSForms.Control
For Each Ctrl In Frame.Controls
Ctrl.Enabled = Frame.Enabled
Next
End Property
Private Sub cboItem_Change()
Form.ItemRowUpdated Me
End Sub
</code></pre>
<p><a href="https://i.stack.imgur.com/kMuUO.gif" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/kMuUO.gif" alt="Advanced Pattern Demo"></a></p>
<hr>
<h2>Addendum</h2>
<p>@sifar pointed out that after deleting the first row the second row will not enable itself. The frame scrollbar also needed to be set to <code>fmScrollBarsVertical</code> and its <code>ScrollHeight</code> set when there are more items then can be seen.</p>
<h2>Code FIx</h2>
<pre><code>Private Sub SpaceItems()
Const PaddingTop As Double = 5
Dim Top As Double
Dim Item As ItemRow
Top = PaddingTop
Dim n As Long
For n = 1 To ItemRows.Count
Set Item = ItemRows(n)
Item.ckItemNo.Caption = n
Item.Top = Top
Top = Top + Item.Frame.Height + PaddingTop
Next
EnableItems
Top = Top - PaddingTop
With Me.FrameItems
.ScrollBars = IIf(Top > .Height, fmScrollBarsVertical, fmScrollBarsNone)
.ScrollHeight = Top
End With
End Sub
Private Sub EnableItems()
Dim Item As ItemRow, PreviousItem As ItemRow
Dim n As Long
If ItemRows.Count > 0 Then ItemRows(1).Enabled = True
For n = 2 To ItemRows.Count
Set PreviousItem = ItemRows(n - 1)
Set Item = ItemRows(n)
Item.Enabled = PreviousItem.cboItem.Value <> vbNullString
Next
End Sub
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-10-10T12:34:51.320",
"Id": "395993",
"Score": "0",
"body": "Thank you for the above this will help me a lot. Much appreciated you taking the time to write all this valuable knowledge."
},
{
"ContentLicense": "CC BY-SA 4.0",
"C... | [] | {
"AcceptedAnswerId": null,
"CommentCount": "11",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-10-10T00:27:17.743",
"Id": "205263",
"Score": "7",
"Tags": [
"vba",
"excel"
],
"Title": "Responding to Events of Dynamically added Controls"
} | 205263 |
<p>On my Arch Linux system I have created a script that should do the following on system startup:</p>
<ul>
<li>detect all network interfaces</li>
<li>check if physical interfaces are up</li>
<li>check if bridge interfaces are up</li>
<li>determine if physical interfaces have IPv4 addresses and delete them</li>
<li>check if physical interfaces have IPv6 addresses</li>
<li>delete global IP addresses from physical interfaces</li>
<li>delete link local IP addresses from physical interfaces</li>
<li>check if wan bridge interface has an IPv4 address</li>
<li>check if wan bridge interface has global IPv6 addresses</li>
<li>delete global IPv6 addresses from wan bridge interface</li>
<li>check if wan bridge interface has link local IPv6 addresses</li>
<li>delete link local IPv6 addresses from wan bridge interface</li>
<li>check if other bridge interfaces except the lan bridge interface have an IPv4 address</li>
<li>delete IPv4 addresses from those interfaces</li>
<li>check if other bridge interfaces except the lan bridge</li>
<li>interface have IPv6 addresses</li>
<li>delete IPv6 addresses from those interfaces</li>
<li>check if spezific vm is running</li>
<li>start specific vm if it is not running</li>
<li>check if this specific vm is now running</li>
<li>change network configuration for lan bridge interface to use dhcp</li>
<li>restart systemd-networkd to reflect new network configuration for lan bridge interface</li>
<li>verify that lan bridge interface got IPv4 and IPv6 addresses</li>
<li>start other vms on purpose</li>
<li>verify that other vms are running</li>
<li>log everything to a log file</li>
</ul>
<p>and another one to restore the startup network configuration on shutdown.</p>
<p>Due to the long list of tasks especially the first script became very complex and long (over 1500 lines). To make it worse I do not like programming and normally avoid doing this. So my knowledge is on a very basic level. Although the scripts seem to be working I must written most of them in a fit of deliriousness. When I now review them I do not understand most of the stuff I have written there.</p>
<p>So please review the script for any bugs and possible optimisations. They should be as foolproof and general (i.e. the names of the network interfaces should be assigned to variables) as possible.</p>
<pre><code>### uncomment to send all output to vmrun.log file
### save stdout and stderr to file descriptors 3 and 4, then
### redirect them to /var/log/vmrun.log
###
exec 3>&1 4>&2 >/var/log/vmrun.log 2>&1
### declare global variables
# equivalent for DOS pause command
declare -r pausearg="Press any key to continue..."
# naming convention, bridge interfaces should start with br
declare -r bridgeinterfacestart="br"
# lan bridge interface
declare -r lanbr="brlan"
# string variable for IPv4 address of lan bridge interface
declare -r lanbr_ipv4_addr="192.168.3.4"
# wan bridge interface
declare -r wanbr="brwan"
# dmz bridge interface
declare -r dmzbr="brdmz"
# amount of seconds to sleep
declare -r sleeptime=3
# max counter value for loops
declare -r maxcounter=10
# string varibale for vm state shut off when locale is not set or C
declare -r vmstate_shutoff="shut off"
# string varibale for vm state running when locale is not set or C
declare -r vmstate_running="running"
# To handle the state of the vms correctly you need to set the
# variables vmstate_localized_shutoff and vmstate_localized_running in
# the "Global variables" section to the values the command
# "virsh list --all" returns for machines in shut down and running state
# for your locale
# In this script they are set for german language
# string variable for vm state shut off when locale set to german language
declare -r vmstate_shutoff_localized="ausschalten"
# string variable for vm state running when locale set to german language
declare -r vmstate_running_localized="laufend"
# name of first vm
declare -r vm1_name="lede"
# IPv4 address of vm1 for ping
declare -r vm1_ipv4_addr="192.168.3.1"
# boolean variable vor vm status
declare vmstate=0
# string variable for name of startup network config file for openvswitch
# lan bridge interface
declare -r brlan_config="/etc/systemd/network/50-ovs-brlan.network"
# string variable for name of safety copy of network config file for
# openvswitch lan bridge interface
declare -r brlan_config_startup="/etc/systemd/network/50-ovs-brlan.startup"
# string variable for name of network config file for openvswitch lan
# bridge interface to use after virtual machine vm1_name started up
declare -r brlan_config_aftervm="/etc/systemd/network/50-ovs-brlan.aftervm"
# string variable for md5 checksumfile for network config files for
# openvswitch lan bridge interface
declare -r brlan_configs_md5="/opt/vmchecks/50-ovs-brlan.md5"
# string variable for sha checksumfile for network config files for
# openvswitch lan bridge interface
declare -r brlan_configs_sha="/opt/vmchecks/50-ovs-brlan.sha"
# array with variable names of network config files
declare -r -a arr_brlan_config_files=(brlan_config brlan_config_startup brlan_config_aftervm)
# array with variable names of checksum files
declare -r -a arr_checksum_brlan_config_files=(brlan_configs_md5 brlan_configs_sha)
# array with the lines from the checksum files
declare -a arr_checksum_lines
# string variable for config file name
declare conf_file=""
# string variable for checksum file name
declare checksum_file=""
# string variable for checksum filename from array arr_checksum_lines
declare checksum_filename_from_arr
# string variable for saving current IFS
declare IFS_SAVE=""
# array with needed external programs
declare -a arr_ext_programs_needed=(md5sum sha512sum ip awk sed lshw grep ethtool systemctl cp diff virsh sleep date cat sysctl cut)
# array for list of all interfaces
declare -a arr_iface_all=()
# array for list of physical interfaces
declare -a arr_iface_phy=()
# array for list of virtual interfaces
declare -a arr_iface_virt=()
# array for list of virtual bridge interfaces
declare -a arr_iface_virt_bridge=()
# array for list of virtual openvswitch bridge interfaces
declare -a arr_iface_virt_ovsbridge=()
# array for list of virtual nonbridge interfaces
declare -a arr_iface_virt_nonbridge=()
# array for interfaces with ip address
declare -a arr_iface_withip=()
### declare functions
# function to emulate DOS pause command
declare -f func_pause
# function to check if all needed external programs are installed
declare -f func_needed_ext_progs
# function to get an array with all known interfaces
declare -f func_arr_iface_all
# function to get an array with all physical interfaces
declare -f func_arr_iface_phy
# function to get an array with all virtual interfaces
declare -f func_arr_iface_virt
# function to build array with virtual bridge interfaces
declare -f func_arr_iface_virt_bridge
# function to build array with virtual openvswitch bridge interfaces
declare -f func_arr_iface_virt_ovsbridge
# function to build array with virtual nonbridge interfaces
declare -f func_arr_iface_virt_nonbridge
# function to test if all physical interfaces are connected
declare -f func_iface_phy_carrier
# function to check if an interface is up
declare -f func_iface_up
# function to check if an interface has an IPv4 address
declare -f func_iface_ipv4
# function to check if an interface has an IPv6 address
declare -f func_iface_ipv6
# function to delete IPv4 addresses from an interface
declare -f func_iface_del_ipv4
# function to delete IPv6 addresses not starting with fe80: from an
# interface
declare -f func_iface_del_ipv6
# function to delete IPv6 addresses starting with fe80: from an interface
declare -f func_iface_del_ipv6_fe80
# function to test if IPv4 addresses were deleted from an interface
declare -f func_iface_del_test_ipv4
# function to test if all IPv6 addresses not starting with fe80: were
# deleted from an interface
declare -f func_iface_del_test_ipv6
# function to disable IPv6 on physical interfaces
declare -f func_iface_ipv6_disable
# function to test if IPv6 is disabled on an inteface
declare -f func_iface_ipv6_disabled_test
# function to get state of a virtual machine
declare -f func_vm_state
# function to start a virtual machine
declare -f func_vm_start
# function to verify that a virtual machine is running
declare -f func_vm_start_verify
# function to wait for a virtual machine to fully start up
declare -f func_vm_start_completed
# function to check if file exists
declare -f func_file_exists
### name: func_pause
### function emulate the DOS pause command
### @param
### no arguments required
### @return
### returns nothing
function func_pause
{
read -n1 -r -p "$*"
}
### name: func_needed_ext_progs
### function to check if all needed external programs are installed
### @param
### no arguments required
### @return
### returns nothing
function func_needed_ext_progs
{
for ((i=0; i<${#arr_ext_programs_needed[@]}; i++))
do
if ! command -v "${arr_ext_programs_needed[i]}" &>/dev/null
then
echo -e >&2 "$(date '+%Y-%m-%d %H:%M:%S')\\t I require ${arr_ext_programs_needed[i]} but could not find it. Aborting."
exit 1
fi
done
}
### name: func_arr_iface_all
### function to get an array with all known interfaces excluding
### loopback (lo) and ovs-system interface
### @param
### no arguments required
### @return
### returns nothing
function func_arr_iface_all
{
#define local variables
# temporary array for interfaces list
local -a arr_iface_tmp=()
# counter variable
local -i i=0
# length of tremporary array with all known interfaces
local -i arr_iface_tmp_length=0
# get list of existing interfaces
arr_iface_tmp=( "$( ip -o link | awk '{ print $2 }' | sed 's/.$//' )" )
# get length of array
arr_iface_tmp_length=${#arr_iface_tmp[@]}
# delete loopback (lo) interface and ovs-system interface from array
# and build final array without them
for ((i=0; i<arr_iface_tmp_length; i++))
do
if [ "${arr_iface_tmp[i]}" == "lo" ] || [ "${arr_iface_tmp[i]}" == "ovs-system" ]
then
unset 'arr_iface_tmp[i]'
fi
done
IFS_SAVE=$IFS
IFS=$'\n'
read -d '' -r -a arr_iface_all <<< "${arr_iface_tmp[@]}"
IFS=$IFS_SAVE
}
### name: func_arr_iface_phy
### function to get an array with all physical interfaces
### @param
### no arguments required
### @return
### returns nothing
function func_arr_iface_phy
{
local -a arr_tmp
# get list of physical interfaces identified by lshw -c network -businfo
# assuming only physical interfaces have a non empty businfo field
arr_tmp="$( lshw -c network -businfo | grep '^[^ B=]' | awk '{ print $2 }' )"
IFS_SAVE=$IFS
IFS=$'\n'
read -d '' -r -a arr_iface_phy <<< "${arr_tmp[@]}"
IFS=$IFS_SAVE
}
### name: func_arr_iface_virt
### function to get an array with all virtual interfaces by deleting
### all physical interfaces from array of all known interfaces
### @param
### no arguments required
### @return
### returns nothing
function func_arr_iface_virt
{
local -a arr_iface_tmp=("${arr_iface_all[@]}")
local arr_iface_tmp_length=${#arr_iface_tmp[@]}
local arr_iface_phy_length=${#arr_iface_phy[@]}
local -i i=0
local -i j=0
for ((i=0; i<arr_iface_tmp_length; i++))
do
for ((j=0; j<arr_iface_phy_length; j++))
do
if [ "${arr_iface_tmp[i]}" == "${arr_iface_phy[j]}" ]
then
unset 'arr_iface_tmp[i]'
fi
done
done
arr_iface_virt=("${arr_iface_tmp[@]}")
}
### name: func_arr_iface_virt_bridge
### function to get an array with all virtual bridge interfaces by
### deleting all virtual non bridge interfaces from array of all
### virtual interfaces
### @param
### no arguments required
### @return
### returns nothing
function func_arr_iface_virt_bridge
{
local -a arr_iface_virt_bridge_tmp=("${arr_iface_virt[@]}")
local arr_iface_virt_bridge_tmp_length=${#arr_iface_virt_bridge_tmp[@]}
local -i i=0
# extract bridge interfaces from virtual interfaces
for ((i=0; i<arr_iface_virt_bridge_tmp_length; i++))
do
if [[ "${arr_iface_virt_bridge_tmp[i]}" != $bridgeinterfacestart* ]]
then
unset 'arr_iface_virt_bridge_tmp[i]'
fi
done
arr_iface_virt_bridge=("${arr_iface_virt_bridge_tmp[@]}")
}
### name: func_arr_iface_virt_nonbridge
### function to get an array with all virtual nonbridge interfaces
### by deleting all virtual bridge interfaces from array of all
### virtual interfaces
### @param
### no arguments required
### @return
### returns nothing
function func_arr_iface_virt_nonbridge
{
local -a arr_iface_virt_nonbridge_tmp=("${arr_iface_virt[@]}")
local arr_iface_virt_nonbridge_tmp_length=${#arr_iface_virt_nonbridge_tmp[@]}
local -i i=0
# extract nonbridge interfaces from virtual interfaces
for ((i=0; i<arr_iface_virt_nonbridge_tmp_length; i++))
do
if [[ "${arr_iface_virt_nonbridge_tmp[i]}" == $bridgeinterfacestart* ]]
then
unset 'arr_iface_virt_nonbridge_tmp[i]'
fi
done
arr_iface_virt_nonbridge=("${arr_iface_virt_nonbridge_tmp[@]}")
}
### name: func_arr_iface_virt_ovsbridge
### function to get an array with all virtual openvswitch bridge
### interfaces by deleting all non openvswitch virtual bridge
### interfaces from array of all virtual bridge interfaces
### @param
### no arguments required
### @return
### returns nothing
function func_arr_iface_virt_ovsbridge
{
local -a arr_iface_virt_ovsbridge_tmp=("${arr_iface_virt_bridge[@]}")
local arr_iface_virt_ovsbridge_tmp_length=${#arr_iface_virt_ovsbridge_tmp[@]}
local -i i=0
# build list of virtual openvswitch bridge interfaces
for ((i=0; i<arr_iface_virt_ovsbridge_tmp_length; i++))
do
if ethtool -i "${arr_iface_virt_ovsbridge_tmp[i]}" | grep -q openvswitch
then
unset 'arr_iface_virt_ovsbridge_tmp[i]'
fi
done
arr_iface_virt_ovsbridge=("${arr_iface_virt_ovsbridge_tmp[@]}")
}
### name: func_iface_phy_carrier
### function to test if all physical interfaces are connected
### @param
### no arguments required
### @return
### returns nothing
function func_iface_phy_carrier
{
local loc_iface
local -i loc_maxcount
local -i i=0
loc_maxcount=$((maxcounter-5))
for loc_iface in "${arr_iface_phy[@]}"
do
if ip link show "$loc_iface" | grep -q '\bNO-CARRIER\b'
then
for ((i=0; i<=loc_maxcount; i++))
do
sleep "$sleeptime"s
if ip link show "$loc_iface" | grep -q '\bNO-CARRIER\b'
then
break
fi
done
if [[ $i -gt $loc_maxcount ]]
then
echo -e >&2 "$(date '+%Y-%m-%d %H:%M:%S')\\t I require physical interface ${loc_iface} connected but it's not. Aborting."
exit 1
fi
else
echo -e >&2 "$(date '+%Y-%m-%d %H:%M:%S')\\t Physical interface ${loc_iface} is connected. OK."
fi
done
}
### name: func_iface_up
### function to test if an interface is up
### @param
### interface name required
### @return
### returns nothing
function func_iface_up
{
if ! ip link show "$1" | grep -q '\bUP\b'
then
echo -e >&2 "$(date '+%Y-%m-%d %H:%M:%S')\\t I require interface ${1} is UP but it's not. Aborting."
exit 1
else
echo -e >&2 "$(date '+%Y-%m-%d %H:%M:%S')\\t Interface ${1} is UP. OK."
fi
}
### name: func_iface_ipv4
### function to test if an interface has an IPv4 address
### @param
### interface name required
### @return
### returns nothing
function func_iface_ipv4
{
if [[ "$(ip -4 addr show "$1")" ]]
then
echo -e >&2 "$(date '+%Y-%m-%d %H:%M:%S')\\t Interface $1 has an IPv4 address."
arr_iface_withip+=( "$1" )
fi
}
### name: func_iface_del_ipv4
### function to delete IPv4 address from an interface
### @param
### interface name required
### @return
### returns nothing
function func_iface_del_ipv4
{
local -a loc_arr_addr=()
local addr
loc_arr_addr=("$(ip -4 addr show "$1" | grep '\binet\b' | awk '{ print $2 }')")
for addr in "${loc_arr_addr[@]}"
do
ip addr del "$addr" dev "$1"
done
}
### name: func_iface_del__test_ipv4
### function to test if IPv4 addresses were deleted from interface
### @param
### interface name required
### @return
### returns nothing
function func_iface_del_test_ipv4
{
if [[ -z $(ip -4 addr show "$1" | grep '\binet\b' | awk '{ print $2 }') ]]
then
echo -e >&2 "$(date '+%Y-%m-%d %H:%M:%S')\\t IPv4 Addresses successfully deleted from $1."
else
echo -e >&2 "$(date '+%Y-%m-%d %H:%M:%S')\\t IPv4 Addresses not deleted from $1. Aborting."
exit 1
fi
}
### name: func_iface_ipv6
### function to test if an interface has an IPv6 address
### @param
### interface name required
### @return
### returns nothing
function func_iface_ipv6
{
if [ "$(ip -6 addr show "$1")" ]
then
echo -e >&2 "$(date '+%Y-%m-%d %H:%M:%S')\\t Interface $1 has an IPv6 address."
arr_iface_withip+=( "$1" )
fi
}
### name: func_iface_del_ipv6
### function to delete IPv6 addresses except the ones starting with
### fe80: from an interface
### @param
### interface name required
### @return
### returns nothing
function func_iface_del_ipv6
{
local -a loc_arr_addr=()
local addr
loc_arr_addr=("$(ip -6 addr show "$1" | grep '\binet6\b' | awk '{ print $2 }')")
for addr in "${loc_arr_addr[@]}"
do
if [[ $addr != fe80:* ]]
then
ip -6 addr del "$addr" dev "$1"
else
echo -e "$(date '+%Y-%m-%d %H:%M:%S')\\t IPv6 address on interface $1 starts with fe80:. I will not delete it."
fi
done
}
### name: func_iface_del_ipv6_fe80
### function to delete IPv6 addresses starting with fe80: from an
### interface
### @param
### interface name required
### @return
### returns nothing
function func_iface_del_ipv6_fe80
{
local -a loc_arr_addr=()
local addr
loc_arr_addr=("$(ip -6 addr show "$1" | grep '\binet6\b' | awk '{ print $2 }')")
for addr in "${loc_arr_addr[@]}"
do
if [[ $addr = fe80:* ]]
then
ip -6 addr del "$addr" dev "$1"
else
echo -e "$(date '+%Y-%m-%d %H:%M:%S')\\t IPv6 address on interface $1 does not start with fe80:. I will not delete it."
fi
done
}
### name: func_iface_del__test_ipv6 ###
### function to test if all IPv6 addresses not starting with fe80: ###
### were deleted from interface
### @param ###
### interface name required
### @return ###
### returns nothing
function func_iface_del_test_ipv6
{
local -a loc_arr_addr=()
local -a loc_arr_addr_tmp=()
local addr=""
local -i loc_arr_addr_tmp_length=0
local -i i=0
loc_arr_addr_tmp=("$(ip -6 addr show "$1" | grep '\binet6\b' | awk '{ print $2 }')")
loc_arr_addr_tmp_length=${#loc_arr_addr_tmp[@]}
for ((i=0; i<loc_arr_addr_tmp_length; i++))
do
if [[ "${loc_arr_addr_tmp[i]}" == fe80:* ]]
then
unset 'loc_arr_addr_tmp[i]'
fi
done
loc_arr_addr=("${loc_arr_addr_tmp[@]}")
if [ ${#loc_arr_addr[@]} != 0 ]
then
echo -e "$(date '+%Y-%m-%d %H:%M:%S')\\t Not all IPv6 addresses not starting with fe80: were deleted from interface $1. Aborting."
exit 1
else
echo -e "$(date '+%Y-%m-%d %H:%M:%S')\\t All IPv6 addresses not starting with fe80: were deleted from interface $1. OK."
fi
}
########################################################################
### ###
### name: func_iface_del__test_ipv6_fe80 ###
### function to test if all IPv6 addresses starting with fe80: were ###
### deleted from interface ###
### ###
### @param ###
### interface name required ###
### ###
### @return ###
### returns nothing ###
### ###
########################################################################
function func_iface_del_test_ipv6_fe80
{
local -a loc_arr_addr=()
local -a loc_arr_addr_tmp=()
local addr=""
local -i loc_arr_addr_tmp_length=0
local -i i=0
loc_arr_addr_tmp=("$(ip -6 addr show "$1" | grep '\binet6\b' | awk '{ print $2 }')")
loc_arr_addr_tmp_length=${#loc_arr_addr_tmp[@]}
for ((i=0; i<loc_arr_addr_tmp_length; i++))
do
if [[ "${loc_arr_addr_tmp[i]}" != fe80:* ]]
then
unset 'loc_arr_addr_tmp[i]'
fi
done
loc_arr_addr=("${loc_arr_addr_tmp[@]}")
if [ ${#loc_arr_addr[@]} != 0 ]
then
echo -e "$(date '+%Y-%m-%d %H:%M:%S')\\t Not all IPv6 addresses starting with fe80: were deleted from interface $1. Aborting."
exit 1
else
echo -e "$(date '+%Y-%m-%d %H:%M:%S')\\t All IPv6 addresses starting with fe80: were deleted from interface $1. OK."
fi
}
########################################################################
### ###
### name: func_iface_ipv6_disable ###
### function to disable IPv6 on an interface ###
### ###
### @param ###
### interface name required ###
### ###
### @return ###
### returns nothing ###
### ###
########################################################################
function func_iface_ipv6_disable
{
sysctl -w net.ipv6.conf."$1".disable_ipv6=1
}
########################################################################
### ###
### name: func_iface_ipv6_disabled_test ###
### function to test if IPv6 is disabled on an interface ###
### ###
### @param ###
### interface name required ###
### ###
### @return ###
### returns nothing ###
### ###
########################################################################
function func_iface_ipv6_disabled_test
{
if [ "$( cat /proc/sys/net/ipv6/conf/"$1"/disable_ipv6 )" -eq 1 ]
then
echo -e >&2 "$(date '+%Y-%m-%d %H:%M:%S')\\t IPv6 is disabled on $1."
else
echo -e >&2 "$(date '+%Y-%m-%d %H:%M:%S')\\t IPv6 is not disabled on $1. Aborting"
exit 1
fi
}
########################################################################
### ###
### name: func_vm_state ###
### function to get status of a virtual machine ###
### ###
### @param ###
### vm name required ###
### ###
### @return ###
### returns nothing ###
### ###
########################################################################
function func_vm_state
{
local loc_vmstatus
local -i i=1
unset vmstate
for ((i=1; i<=maxcounter; i++))
do
loc_vmstatus=$( virsh list --all | grep "$1" | awk '{print $3}' )
case "$loc_vmstatus" in
"$vmstate_shutoff"|"$vmstate_shutoff_localized")
vmstate=0
break
;;
"$vmstate_running"|"$vmstate_running_localized")
vmstate=1
break
;;
*)
vmstate=2
;;
esac
sleep "$sleeptime"s
done
if [ $vmstate -eq 2 ]
then
echo -e >&2 "$(date '+%Y-%m-%d %H:%M:%S')\\t Could not get status of vm $1 after "$((maxcounter * sleeptime))"s waiting."
fi
}
########################################################################
### ###
### name: func_vm_start ###
### function to get status of a virtual machine ###
### ###
### @param ###
### vm name required ###
### ###
### @return ###
### returns nothing ###
### ###
########################################################################
function func_vm_start
{
local loc_vmstatus
local -i i=0
virsh start "$1" &>/dev/null
for ((i=0; i<=maxcounter; i++))
do
sleep "$sleeptime"s
loc_vmstatus=$( virsh list --all | grep "$1" | awk '{print $3}' )
if [ "$loc_vmstatus" == "$vmstate_running" ] || [ "$loc_vmstatus" == "$vmstate_running_localized" ]
then
break
fi
done
}
########################################################################
### ###
### name: func_vm_start_verify ###
### function to get status of a virtual machine ###
### ###
### @param ###
### vm name required ###
### ###
### @return ###
### returns nothing ###
### ###
########################################################################
function func_vm_start_verify
{
if [ $vmstate -eq 1 ]
then
echo -e >&2 "$(date '+%Y-%m-%d %H:%M:%S')\\t Virtual machine $1 is running."
else
echo -e >&2 "$(date '+%Y-%m-%d %H:%M:%S')\\t Virtual machine $1 is not properly running"
fi
}
########################################################################
### ###
### name: func_vm_start_completed ###
### function to wait for a virtual machine to fully start up ###
### assuming it is when it can be pinged ###
### ###
### @param ###
### vm name required ###
### vm IPv4 address required ###
### ###
### @return ###
### returns nothing ###
### ###
########################################################################
function func_vm_start_completed
{
local loc_ping_success=0
local -i maxcount=maxcounter+5
for ((i=0; i<=maxcount; i++))
do
if ping -4 -w1 -c1 "$2" &>/dev/null
then
loc_ping_success=1
echo -e >&2 "$(date '+%Y-%m-%d %H:%M:%S')\\t Start up of virtual machine $1 completed."
break
else
loc_ping_success=0
sleep "$sleeptime"s
fi
done
if [ $loc_ping_success -eq 0 ]
then
echo -e >&2 "$(date '+%Y-%m-%d %H:%M:%S')\\t Start up of virtual machine $1 did not complete after "$((maxcount * sleeptime))"s. Aborting."
exit 1
fi
}
########################################################################
### ###
### name: func_file_exists ###
### function to check if file exists ###
### ###
### @param ###
### filename with absolute path ###
### ###
### @return ###
### returns nothing ###
### ###
########################################################################
function func_file_exists
{
if ! [ -f "$1" ]
then
echo -e <&2 "$(date '+%Y-%m-%d %H:%M:%S')\\t $1 file does not exist. Aborting."
exit 1
else
echo -e <&2 "$(date '+%Y-%m-%d %H:%M:%S')\\t $1 file exists."
fi
}
########################################################################
### main program ###
### requires no arguments ###
########################################################################
# check if all needed external programs are installed
echo -e >&2 "$(date '+%Y-%m-%d %H:%M:%S')\\t Test if all needed external programms are installed."
func_needed_ext_progs
echo -e >&2 "$(date '+%Y-%m-%d %H:%M:%S')\\t Test if all needed external programms are installed finished."
# get list of existing interfaces in array variable arr_iface_all
echo -e >&2 "$(date '+%Y-%m-%d %H:%M:%S')\\t Get list of all known networkinterfaces."
func_arr_iface_all
echo -e >&2 "$(date '+%Y-%m-%d %H:%M:%S')\\t Get list of all known networkinterfaces finished."
# get list of physical interfaces in array variable arr_iface_phy
echo -e >&2 "$(date '+%Y-%m-%d %H:%M:%S')\\t Get list of all physical networkinterfaces."
func_arr_iface_phy
echo -e >&2 "$(date '+%Y-%m-%d %H:%M:%S')\\t Get list of all physical networkinterfaces finished."
# check if all physical interfaces have a carrier, required
echo -e >&2 "$(date '+%Y-%m-%d %H:%M:%S')\\t Start test if physical interfaces have a carrier."
func_iface_phy_carrier
echo -e >&2 "$(date '+%Y-%m-%d %H:%M:%S')\\t Test if physical interfaces have a carrier finished."
# build list of virtual interfaces
func_arr_iface_virt
# build list of virtual bridge interfaces
func_arr_iface_virt_bridge
# build list of virtual non bridge iterfaces
func_arr_iface_virt_nonbridge
# build list of virtual openvswitch bridge interfaces
func_arr_iface_virt_ovsbridge
# check if all physical interfaces are up, required
echo -e >&2 "$(date '+%Y-%m-%d %H:%M:%S')\\t Start test if physical interfaces are up."
for iface in "${arr_iface_phy[@]}"
do
func_iface_up "$iface"
done
echo -e >&2 "$(date '+%Y-%m-%d %H:%M:%S')\\t Test if physical interfaces are up finished."
unset iface
# check if all openvswitch bridge interfaces are up, required
echo -e >&2 "$(date '+%Y-%m-%d %H:%M:%S')\\t Start test if virtual openvswitch bridge interfaces are up."
for iface in "${arr_iface_virt_ovsbridge[@]}"
do
func_iface_up "$iface"
done
echo -e >&2 "$(date '+%Y-%m-%d %H:%M:%S')\\t Test if virtual openvswitch bridge interfaces are up finished."
unset iface
# in this System physical interfaces should not have an IPv4 address
# check if physical interfaces have an IPv4 address
echo -e >&2 "$(date '+%Y-%m-%d %H:%M:%S')\\t Start test if physical interfaces have an IPv4 address."
arr_iface_withip=()
for iface in "${arr_iface_phy[@]}"
do
func_iface_ipv4 "$iface"
done
unset iface
echo -e >&2 "$(date '+%Y-%m-%d %H:%M:%S')\\t Test if physical interfaces have an IPv4 address finished."
# deleting IPv4 addresses from physical interfaces
if [ ${#arr_iface_withip[@]} -ne 0 ]
then
echo -e <&2 "$(date '+%Y-%m-%d %H:%M:%S')\\t Some physical interfaces have an IPv4 address, deleting it"
for iface in "${arr_iface_withip[@]}"
do
func_iface_del_ipv4 "$iface"
done
fi
unset iface
echo -e <&2 "$(date '+%Y-%m-%d %H:%M:%S')\\t Deleting IPv4 addresses from physical interfaces finished"
# test if IPv4 adresses are deleted
echo -e <&2 "$(date '+%Y-%m-%d %H:%M:%S')\\t Test if IPv4 addresses, from physical interfaces are deleted."
if [ ${#arr_iface_withip[@]} -ne 0 ]
then
for iface in "${arr_iface_withip[@]}"
do
func_iface_del_test_ipv4 "$iface"
done
fi
unset iface
echo -e <&2 "$(date '+%Y-%m-%d %H:%M:%S')\\t Test if IPv4 addresses, from physical interfaces are deleted finished."
# in this System the openvswitch wan bridge interface should not have an IPv4 address
# check if openvswitch wan bridge interface has an IPv4 address
echo -e >&2 "$(date '+%Y-%m-%d %H:%M:%S')\\t Start test if openvswitch wan bridge has an IPv4 address."
arr_iface_withip=()
func_iface_ipv4 "$wanbr"
echo -e >&2 "$(date '+%Y-%m-%d %H:%M:%S')\\t Test if openvswitch wan bridge has an IPv4 address finished."
# deleting IPv4 addresses from openvswitch wan bridge interface
if [ ${#arr_iface_withip[@]} -ne 0 ]
then
echo -e <&2 "$(date '+%Y-%m-%d %H:%M:%S')\\t Openvswitch wan bridge interface has an IPv4 address, deleting it"
for iface in "${arr_iface_withip[@]}"
do
func_iface_del_ipv4 "$iface"
done
fi
unset iface
echo -e <&2 "$(date '+%Y-%m-%d %H:%M:%S')\\t Deleting IPv4 addresses from openvswitch wan bridge interface finished."
# test if IPv4 adresses are deleted
echo -e >&2 "$(date '+%Y-%m-%d %H:%M:%S')\\t Start test if IPv4 addresses from openvswitch wan bridge are deleted."
if [ ${#arr_iface_withip[@]} -ne 0 ]
then
for iface in "${arr_iface_withip[@]}"
do
func_iface_del_test_ipv4 "$iface"
done
fi
unset iface
echo -e >&2 "$(date '+%Y-%m-%d %H:%M:%S')\\t Test if IPv4 addresses from openvswitch wan bridge are deleted finished."
# in this System the openvswitch dmz bridge interface should not have an IPv4 address
# check if openvswitch dmz bridge interface has an IPv4 address
echo -e >&2 "$(date '+%Y-%m-%d %H:%M:%S')\\t Start test if openvswitch dmz bridge has an IPv4 address."
arr_iface_withip=()
func_iface_ipv4 "$dmzbr"
echo -e >&2 "$(date '+%Y-%m-%d %H:%M:%S')\\t Test if openvswitch dmz bridge has an IPv4 address finished."
# deleting IPv4 addresses from openvswitch dmz bridge interface
if [ ${#arr_iface_withip[@]} -ne 0 ]
then
echo -e <&2 "$(date '+%Y-%m-%d %H:%M:%S')\\t Openvswitch dmz bridge interface has an IPv4 address, deleting it"
for iface in "${arr_iface_withip[@]}"
do
func_iface_del_ipv4 "$iface"
done
fi
unset iface
echo -e <&2 "$(date '+%Y-%m-%d %H:%M:%S')\\t Deleting IPv4 addresses from openvswitch dmz bridge interface finished."
# test if IPv4 adresses are deleted
echo -e >&2 "$(date '+%Y-%m-%d %H:%M:%S')\\t Start test if IPv4 addresses from openvswitch dmz bridge are deleted."
if [ ${#arr_iface_withip[@]} -ne 0 ]
then
for iface in "${arr_iface_withip[@]}"
do
func_iface_del_test_ipv4 "$iface"
done
fi
unset iface
echo -e >&2 "$(date '+%Y-%m-%d %H:%M:%S')\\t Test if IPv4 addresses from openvswitch dmz bridge are deleted finished."
arr_iface_withip=()
# in this System physical interfaces should not have an IPv6 address
# check if physical interfaces have an IPv6 address except for the ones
echo -e >&2 "$(date '+%Y-%m-%d %H:%M:%S')\\t Start test if physical interfaces have an IPv6 address."
arr_iface_withip=()
for iface in "${arr_iface_phy[@]}"
do
func_iface_ipv6 "$iface"
done
unset iface
echo -e >&2 "$(date '+%Y-%m-%d %H:%M:%S')\\t Test if physical interfaces have an IPv6 address finished."
# delete IPv6 addresses from physical interfaces except for the ones
# starting with "fe80:"
if [ ${#arr_iface_withip[@]} -ne 0 ]
then
echo -e <&2 "$(date '+%Y-%m-%d %H:%M:%S')\\t Some physical interfaces have IPv6 addresses, deleting them if they start not with fe80:."
for iface in "${arr_iface_withip[@]}"
do
func_iface_del_ipv6 "$iface"
done
fi
unset iface
echo -e >&2 "$(date '+%Y-%m-%d %H:%M:%S')\\t Deleting IPv6 addresses not starting with fe80: from physical interfaces finished."
# test if IPv6 adresses except the ones starting with fe80: are deleted
echo -e >&2 "$(date '+%Y-%m-%d %H:%M:%S')\\t Test if IPv6 addresses from physical interfaces are deleted."
if [ ${#arr_iface_withip[@]} -ne 0 ]
then
for iface in "${arr_iface_withip[@]}"
do
func_iface_del_test_ipv6 "$iface"
done
fi
unset iface
echo -e >&2 "$(date '+%Y-%m-%d %H:%M:%S')\\t Test if IPv6 addresses from physical interfaces not starting with fe80: are deleted finished."
# delete IPv6 addresses from physical interfaces starting with "fe80:"
if [ ${#arr_iface_withip[@]} -ne 0 ]
then
echo -e <&2 "$(date '+%Y-%m-%d %H:%M:%S')\\t Some physical interfaces have IPv6 addresses, deleting them if they start with fe80:."
for iface in "${arr_iface_withip[@]}"
do
func_iface_del_ipv6_fe80 "$iface"
done
fi
unset iface
echo -e >&2 "$(date '+%Y-%m-%d %H:%M:%S')\\t Deleting IPv6 addresses starting with fe80: from physical interfaces finished."
# test if IPv6 adresses starting with fe80: are deleted
echo -e >&2 "$(date '+%Y-%m-%d %H:%M:%S')\\t Test if IPv6 addresses from physical interfaces are deleted."
if [ ${#arr_iface_withip[@]} -ne 0 ]
then
for iface in "${arr_iface_withip[@]}"
do
func_iface_del_test_ipv6_fe80 "$iface"
done
fi
unset iface
arr_iface_withip=()
echo -e >&2 "$(date '+%Y-%m-%d %H:%M:%S')\\t Test if IPv6 addresses from physical interfaces starting with fe80: are deleted finished."
# disabling IPv6 on physical interfaces to make sure that no communication via IPv6 is possible
#echo -e >&2 "$(date '+%Y-%m-%d %H:%M:%S')\\t Start disabling IPv6 on physical interfaces"
#for iface in "${arr_iface_phy[@]}"
#do
# func_iface_ipv6_disable "$iface"
#done
#unset iface
#echo -e >&2 "$(date '+%Y-%m-%d %H:%M:%S')\\t Disabling IPv6 on physical interfaces finished."
# test if IPv6 on physical interfaces is disabled
#echo -e >&2 "$(date '+%Y-%m-%d %H:%M:%S')\\t Test if IPv6 on physical interfaces is disabled"
#for iface in "${arr_iface_phy[@]}"
#do
# func_iface_ipv6_disabled_test "$iface"
#done
#unset iface
#echo -e >&2 "$(date '+%Y-%m-%d %H:%M:%S')\\t Test if IPv6 on physical interfaces is disabled finished."
# in this System the openvswitch wan bridge interface should not have an
# IPv6 address
# check if the openvswitch wan bridge interface have an IPv6 address
echo -e >&2 "$(date '+%Y-%m-%d %H:%M:%S')\\t Start test if the openvswitch wan bridge interface has an IPv6 address."
arr_iface_withip=()
func_iface_ipv6 "$wanbr"
echo -e >&2 "$(date '+%Y-%m-%d %H:%M:%S')\\t Test if openvswitch wan bridge have IPv6 addresses finished."
# delete IPv6 addresses from the openvswitch wan bridge interface except
# for the ones starting with "fe80:"
if [ ${#arr_iface_withip[@]} -ne 0 ]
then
echo -e <&2 "$(date '+%Y-%m-%d %H:%M:%S')\\t The openvswitch wan bridge interface has IPv6 addresses, deleting them if they start not with fe80:."
for iface in "${arr_iface_withip[@]}"
do
func_iface_del_ipv6 "$iface"
done
fi
unset iface
echo -e <&2 "$(date '+%Y-%m-%d %H:%M:%S')\\t Deleting IPv6 addresses from openvswitch wan bridge interface finished."
# test if IPv6 adresses except the ones starting with fe80: are deleted
echo -e <&2 "$(date '+%Y-%m-%d %H:%M:%S')\\t Test if IPv6 addresses from openvswitch wan bridge interface are deleted."
if [ ${#arr_iface_withip[@]} -ne 0 ]
then
for iface in "${arr_iface_withip[@]}"
do
func_iface_del_test_ipv6 "$iface"
done
fi
unset iface
echo -e <&2 "$(date '+%Y-%m-%d %H:%M:%S')\\t Test if IPv6 addresses not starting with fe80: from openvswitch wan bridge interface are deleted finished."
# delete IPv6 addresses from the openvswitch wan bridge interface starting with "fe80:"
if [ ${#arr_iface_withip[@]} -ne 0 ]
then
echo -e <&2 "$(date '+%Y-%m-%d %H:%M:%S')\\t The openvswitch wan bridge interface has IPv6 addresses, deleting them if they start with fe80:."
for iface in "${arr_iface_withip[@]}"
do
func_iface_del_ipv6_fe80 "$iface"
done
fi
unset iface
echo -e <&2 "$(date '+%Y-%m-%d %H:%M:%S')\\t Deleting IPv6 addresses starting with fe80: from openvswitch wan bridge interface finished."
# test if IPv6 adresses except the ones starting with fe80: are deleted
echo -e <&2 "$(date '+%Y-%m-%d %H:%M:%S')\\t Test if IPv6 addresses starting with fe80: from openvswitch wan bridge interface are deleted."
if [ ${#arr_iface_withip[@]} -ne 0 ]
then
for iface in "${arr_iface_withip[@]}"
do
func_iface_del_test_ipv6_fe80 "$iface"
done
fi
unset iface
arr_iface_withip=()
echo -e <&2 "$(date '+%Y-%m-%d %H:%M:%S')\\t Test if IPv6 addresses starting with fe80: from openvswitch wan bridge interface are deleted finished."
# disabling IPv6 on openvswitch wan interfaces to make sure that no communication via IPv6 is possible
#echo -e >&2 "$(date '+%Y-%m-%d %H:%M:%S')\\t Start disabling IPv6 on openvswitch wan interface"
#func_iface_ipv6_disable "$wanbr"
#echo -e >&2 "$(date '+%Y-%m-%d %H:%M:%S')\\t Disabling IPv6 on openvswitch wan interface finished."
# test if IPv6 on openvswitch wan interface is disabled
#echo -e >&2 "$(date '+%Y-%m-%d %H:%M:%S')\\t Test if IPv6 on openvswitch wan interface is disabled"
#func_iface_ipv6_disabled_test "$wanbr"
#echo -e >&2 "$(date '+%Y-%m-%d %H:%M:%S')\\t Test if IPv6 on openvswitch wan interface is disabled finished."
# in this System the openvswitch dmz bridge interface should not have an
# IPv6 address
# check if the openvswitch dmz bridge interface have an IPv6 address
# except for the ones starting with "fe80:"
echo -e >&2 "$(date '+%Y-%m-%d %H:%M:%S')\\t Start test if the openvswitch dmz bridge interface has an IPv6 address."
arr_iface_withip=()
func_iface_ipv6 "$dmzbr"
echo -e >&2 "$(date '+%Y-%m-%d %H:%M:%S')\\t Test if openvswitch dmz bridge has IPv6 addresses finished."
# delete IPv6 addresses from the openvswitch dmz bridge interface except
# for the ones starting with "fe80:"
echo -e <&2 "$(date '+%Y-%m-%d %H:%M:%S')\\t Deleting IPv6 addresses not starting with fe80: from openvswitch dmz bridge interface."
if [ ${#arr_iface_withip[@]} -ne 0 ]
then
echo -e <&2 "$(date '+%Y-%m-%d %H:%M:%S')\\t The openvswitch dmz bridge interface has IPv6 addresses, deleting them if they start not with fe80:."
for iface in "${arr_iface_withip[@]}"
do
func_iface_del_ipv6 "$iface"
done
fi
unset iface
echo -e <&2 "$(date '+%Y-%m-%d %H:%M:%S')\\t Deleting IPv6 addresses starting with fe80: from openvswitch dmz bridge interface finished."
# test if IPv6 adresses except the ones starting with fe80: are deleted
echo -e <&2 "$(date '+%Y-%m-%d %H:%M:%S')\\t Test if IPv6 addresses not starting with fe80: from openvswitch dmz bridge interface are deleted."
if [ ${#arr_iface_withip[@]} -ne 0 ]
then
for iface in "${arr_iface_withip[@]}"
do
func_iface_del_test_ipv6 "$iface"
done
fi
unset iface
arr_iface_withip=()
echo -e <&2 "$(date '+%Y-%m-%d %H:%M:%S')\\t Test if IPv6 addresses not starting with fe80: from openvswitch dmz bridge interface are deleted finished."
# delete IPv6 addresses from the openvswitch dmz bridge interface starting
# with "fe80:"
echo -e <&2 "$(date '+%Y-%m-%d %H:%M:%S')\\t Deleting IPv6 addresses starting with fe80: from openvswitch dmz bridge interface."
if [ ${#arr_iface_withip[@]} -ne 0 ]
then
echo -e <&2 "$(date '+%Y-%m-%d %H:%M:%S')\\t The openvswitch dmz bridge interface has IPv6 addresses, deleting them if they start with fe80:."
for iface in "${arr_iface_withip[@]}"
do
func_iface_del_ipv6_fe80 "$iface"
done
fi
unset iface
echo -e <&2 "$(date '+%Y-%m-%d %H:%M:%S')\\t Deleting IPv6 addresses starting with fe80: from openvswitch dmz bridge interface finished."
# test if IPv6 adresses starting with fe80: are deleted from openvswitch dmz bridge interface
echo -e <&2 "$(date '+%Y-%m-%d %H:%M:%S')\\t Test if IPv6 addresses starting with fe80: from openvswitch dmz bridge interface are deleted."
if [ ${#arr_iface_withip[@]} -ne 0 ]
then
for iface in "${arr_iface_withip[@]}"
do
func_iface_del_test_ipv6_fe80 "$iface"
done
fi
unset iface
arr_iface_withip=()
echo -e <&2 "$(date '+%Y-%m-%d %H:%M:%S')\\t Test if IPv6 addresses starting with fe80: from openvswitch dmz bridge interface are deleted finished."
arr_iface_withip=()
# disabling IPv6 on openvswitch dmz interfaces to make sure that no communication via IPv6 is possible
# echo -e >&2 "$(date '+%Y-%m-%d %H:%M:%S')\\t Start disabling IPv6 on openvswitch dmz interface"
# func_iface_ipv6_disable "$dmzbr"
# echo -e >&2 "$(date '+%Y-%m-%d %H:%M:%S')\\t Disabling IPv6 on openvswitch dmz interface finished."
# test if IPv6 on openvswitch dmz interface is disabled
#echo -e >&2 "$(date '+%Y-%m-%d %H:%M:%S')\\t Test if IPv6 on openvswitch dmz interface is disabled"
# func_iface_ipv6_disabled_test "$dmzbr"
# echo -e >&2 "$(date '+%Y-%m-%d %H:%M:%S')\\t Test if IPv6 on openvswitch dmz interface is disabled finished."
# test if virtual machine vm1_name is running and start it if not
# get status of virtual machine vm1_name
echo -e >&2 "$(date '+%Y-%m-%d %H:%M:%S')\\t Get status of virtual machine $vm1_name."
func_vm_state "$vm1_name"
echo -e >&2 "$(date '+%Y-%m-%d %H:%M:%S')\\t Getting status of virtual machine $vm1_name finished. State is $vmstate."
# starting virtual machine vm1_name if not running, do nothing if already running
# aborting script if not in running or shut down state
echo -e >&2 "$(date '+%Y-%m-%d %H:%M:%S')\\t Starting virtual machine $vm1_name if not running and in a state I can handle."
case $vmstate in
0)
echo -e >&2 "$(date '+%Y-%m-%d %H:%M:%S')\\t Virtual machine $vm1_name is not running, starting it."
func_vm_start "$vm1_name"
echo -e >&2 "$(date '+%Y-%m-%d %H:%M:%S')\\t Virtual machine $vm1_name started."
;;
1)
echo -e >&2 "$(date '+%Y-%m-%d %H:%M:%S')\\t Virtual machin $vm1_name is already running."
;;
2)
echo -e >&2 "$(date '+%Y-%m-%d %H:%M:%S')\\t Virtual machine vm1_name is in a status I cannot handle. Aborting."
exit 1
;;
*)
echo -e >&2 "$(date '+%Y-%m-%d %H:%M:%S')\\t Something in the function to get the state of the virtual machine $1 went wrong. Aborting."
exit 1
;;
esac
unset vmstate
echo -e >&2 "$(date '+%Y-%m-%d %H:%M:%S')\\t Starting of virtual machine $vm1_name finished."
#verifying that virtual machine vm1_name is running
echo -e >&2 "$(date '+%Y-%m-%d %H:%M:%S')\\t Verifying that virtual machine $vm1_name is running."
func_vm_state "$vm1_name"
func_vm_start_verify "$vm1_name"
if [ $vmstate -ne 1 ]
then
echo -e >&2 "$(date '+%Y-%m-%d %H:%M:%S')\\t Virtual machine $vm1_name is not running. Aborting."
exit 1
fi
echo -e >&2 "$(date '+%Y-%m-%d %H:%M:%S')\\t Verifying that virtual machine $vm1_name is running finished."
# wait for virtual machine vm1_name to fully startup
if [ $vmstate -eq 1 ]
then
echo -e >&2 "$(date '+%Y-%m-%d %H:%M:%S')\\t Wait for virtual machine $vm1_name to fully start up."
func_vm_start_completed "$vm1_name" "$vm1_ipv4_addr"
fi
echo -e >&2 "$(date '+%Y-%m-%d %H:%M:%S')\\t Wait for virtual machine $vm1_name to fully start up finished."
# now the the virtual machine vm1_name is running delete all IPv4 and
# IPv6 addresses from openvswitch lan bridge interface and get new ones
# via dhcp from virtual machine vm1_name
# check if openvswitch lan bridge interface has an IPv4 address
echo -e >&2 "$(date '+%Y-%m-%d %H:%M:%S')\\t Start test if openvswitch lan bridge has an IPv4 address."
arr_iface_withip=()
func_iface_ipv4 "$lanbr"
echo -e >&2 "$(date '+%Y-%m-%d %H:%M:%S')\\t Test if openvswitch lan bridge has an IPv4 address finished."
# deleting IPv4 addresses from openvswitch lan bridge interface
if [ ${#arr_iface_withip[@]} -ne 0 ]
then
echo -e <&2 "$(date '+%Y-%m-%d %H:%M:%S')\\t Openvswitch lan bridge interface has an IPv4 address, deleting it"
for iface in "${arr_iface_withip[@]}"
do
func_iface_del_ipv4 "$iface"
done
fi
unset iface
echo -e <&2 "$(date '+%Y-%m-%d %H:%M:%S')\\t Deleting IPv4 addresses from openvswitch lan bridge interface finished."
# test if IPv4 adresses are deleted
echo -e >&2 "$(date '+%Y-%m-%d %H:%M:%S')\\t Start test if IPv4 addresses from openvswitch lan bridge are deleted."
if [ ${#arr_iface_withip[@]} -ne 0 ]
then
for iface in "${arr_iface_withip[@]}"
do
func_iface_del_test_ipv4 "$iface"
done
fi
unset iface
echo -e >&2 "$(date '+%Y-%m-%d %H:%M:%S')\\t Test if IPv4 addresses from openvswitch lan bridge are deleted finished."
arr_iface_withip=()
# check if the openvswitch lan bridge interface have an IPv6 address
# except for the ones starting with "fe80:"
echo -e >&2 "$(date '+%Y-%m-%d %H:%M:%S')\\t Start test if the openvswitch lan bridge interface has an IPv6 address."
arr_iface_withip=()
func_iface_ipv6 "$lanbr"
echo -e >&2 "$(date '+%Y-%m-%d %H:%M:%S')\\t Test if openvswitch lan bridge has IPv6 addresses finished."
# delete IPv6 addresses from the openvswitch lan bridge interface except
# except for the ones starting with "fe80:"
echo -e <&2 "$(date '+%Y-%m-%d %H:%M:%S')\\t Deleting IPv6 addresses from openvswitch lan bridge interface finished."
if [ ${#arr_iface_withip[@]} -ne 0 ]
then
echo -e <&2 "$(date '+%Y-%m-%d %H:%M:%S')\\t The openvswitch lan bridge interface has IPv6 addresses, deleting them if they start not with fe80:."
for iface in "${arr_iface_withip[@]}"
do
func_iface_del_ipv6 "$iface"
done
fi
unset iface
echo -e <&2 "$(date '+%Y-%m-%d %H:%M:%S')\\t Deleting IPv6 addresses from openvswitch lan bridge interface finished."
# test if IPv6 adresses except the ones starting with fe80: are deleted
echo -e <&2 "$(date '+%Y-%m-%d %H:%M:%S')\\t Test if IPv6 addresses from openvswitch lan bridge interface are deleted."
if [ ${#arr_iface_withip[@]} -ne 0 ]
then
for iface in "${arr_iface_withip[@]}"
do
func_iface_del_test_ipv6 "$iface"
done
fi
unset iface
echo -e <&2 "$(date '+%Y-%m-%d %H:%M:%S')\\t Test if IPv6 addresses from openvswitch lan bridge interface are deleted finished."
arr_iface_withip=()
# replacing current network config file with the one for use after vm vm1_name is running
# checking if the files exists
# check if needed files exist
# check if needed network config files exist
echo -e <&2 "$(date '+%Y-%m-%d %H:%M:%S')\\t Check if network config files exist."
conf_file=""
for conf_file in "${arr_brlan_config_files[@]}"
do
func_file_exists "${!conf_file}"
done
conf_file=""
# check if needed checksum files exist
echo -e <&2 "$(date '+%Y-%m-%d %H:%M:%S')\\t Check if checksum files for network config files exist."
checksum_file=""
for checksum_file in "${arr_checksum_brlan_config_files[@]}"
do
func_file_exists "${!checksum_file}"
done
checksum_file=""
#check integrity of files against the checksum files
echo -e <&2 "$(date '+%Y-%m-%d %H:%M:%S')\\t Check integrity of network config files against the checksum files."
checksum_file=""
conf_file=""
for checksum_file in "${arr_checksum_brlan_config_files[@]}"
do
IFS_SAVE=$IFS
IFS=$'\n'
read -d '' -r -a arr_checksum < "${!checksum_file}"
IFS=$IFS_SAVE
for arr_checksum_lines in "${arr_checksum[@]}"
do
checksum_filename_from_arr="$(echo "$arr_checksum_lines" | awk '{print $2}')"
if [ "${!checksum_file:(-4)}" == .md5 ]
then
if [ "$(md5sum "$checksum_filename_from_arr" | awk '{print $1}')" == "$(echo "$arr_checksum_lines" | awk '{print $1}')" ]
then
echo -e <&2 "$(date '+%Y-%m-%d %H:%M:%S')\\t $checksum_filename_from_arr matches md5 checksum stored in ${!checksum_file}."
else
echo -e <&2 "$(date '+%Y-%m-%d %H:%M:%S')\\t $checksum_filename_from_arr does not match md5 checksum stored in ${!checksum_file}. Aborting."
exit 1
fi
fi
if [ "${!checksum_file:(-4)}" == .sha ]
then
if [ "$(sha512sum "$checksum_filename_from_arr" | awk '{print $1}')" == "$(echo "$arr_checksum_lines" | awk '{print $1}')" ]
then
echo -e <&2 "$(date '+%Y-%m-%d %H:%M:%S')\\t $checksum_filename_from_arr matches sha 512 checksum stored in ${!checksum_file}."
else
echo -e <&2 "$(date '+%Y-%m-%d %H:%M:%S')\\t $checksum_filename_from_arr does not match sha 512 checksum stored in ${!checksum_file}. Aborting."
exit 1
fi
fi
done
done
conf_file=""
checksum_file=""
# copy network config file for openvswitch lan bridge interface for run
# after virtual machine vm1_name startup but only if it differs from
# current network config file and startup network config file and
# current network config file equals startup network config file
if ! diff -q "$brlan_config" "$brlan_config_aftervm" >/dev/null
then
if ! diff -q "$brlan_config_aftervm" "$brlan_config_startup" >/dev/null
then
if diff -q "$brlan_config" "$brlan_config_startup"
then
cp -f "$brlan_config_aftervm" "$brlan_config"
else
echo -e <&2 "$(date '+%Y-%m-%d %H:%M:%S')\\t Network config file for use at system start differ from current network config file. You are in trouble. Aborting."
exit 1
fi
else
echo -e <&2 "$(date '+%Y-%m-%d %H:%M:%S')\\t Network config file for use after starting virtual machine does not differ from startup network config file. You are in trouble. Aborting."
exit 1
fi
else
echo -e <&2 "$(date '+%Y-%m-%d %H:%M:%S')\\t Network config file for use after starting virtual machine does not differ from current network config file. You are in trouble. Aborting."
exit 1
fi
# verifying that network config file was successful copied
if diff -q "$brlan_config" "$brlan_config_aftervm" >/dev/null
then
echo -e <&2 "$(date '+%Y-%m-%d %H:%M:%S')\\t Network config file was successful copied."
else
echo -e <&2 "$(date '+%Y-%m-%d %H:%M:%S')\\t Network config file was not successful copied. Aborting."
exit 1
fi
# Restarting systemd-networkd with new config file
echo -e <&2 "$(date '+%Y-%m-%d %H:%M:%S')\\t Restarting systemd-networkd."
systemctl restart systemd-networkd
echo -e <&2 "$(date '+%Y-%m-%d %H:%M:%S')\\t Restarting systemd-networkd finished."
# check if openvswitch lan bridge interface has an IPv4 address
echo -e >&2 "$(date '+%Y-%m-%d %H:%M:%S')\\t Start test if openvswitch lan bridge has an IPv4 address."
arr_iface_withip=()
if [ ${#arr_iface_withip[@]} -eq 0 ]
then
for ((i=1; i<=maxcounter; i++))
do
func_iface_ipv4 "$lanbr"
if [ ${#arr_iface_withip[@]} -eq 0 ]
then
sleep "$sleeptime"s
else
break
fi
done
fi
echo -e >&2 "$(date '+%Y-%m-%d %H:%M:%S')\\t Openvswitch lan bridge interface did not get an IPv4 address after"$((maxcounter * sleeptime))"s waiting."
if [ ${#arr_iface_withip[@]} -eq 0 ]
then
echo -e >&2 "$(date '+%Y-%m-%d %H:%M:%S')\\t Openvswitch lan bridge interface does not have an IPv4 address assinging one for emergency"
ip addr add $lanbr_ipv4_addr/24 dev $lanbr
# check if openvswitch lan bridge interface now has an IPv4 address
if [[ $(ip -4 addr show $lanbr | grep inet | awk '{print $2}' | cut -f1 -d"/") == "$lanbr_ipv4_addr" ]]
then
echo -e >&2 "$(date '+%Y-%m-%d %H:%M:%S')\\t Openvswitch lan bridge interface now has an emergency IPv4 address. Aborting."
exit 1
else
echo -e >&2 "$(date '+%Y-%m-%d %H:%M:%S')\\t Openvswitch lan bridge interface did not accept the emergency IPv4 address. You are in serious trouble. Aborting."
exit 1
fi
fi
echo -e >&2 "$(date '+%Y-%m-%d %H:%M:%S')\\t Test if openvswitch lan bridge has an IPv4 address finished."
# check if openvswitch lan bridge interface equals $lanbr_ipv4_addr
if [ ${#arr_iface_withip[@]} -ne 0 ]
then
if [[ $(ip -4 addr show $lanbr | grep inet | awk '{print $2}' | cut -f1 -d"/") == "$lanbr_ipv4_addr" ]]
then
echo -e >&2 "$(date '+%Y-%m-%d %H:%M:%S')\\t Assigned IPv4 address for openvswitch lan bridge interface is correct"
else
echo -e >&2 "$(date '+%Y-%m-%d %H:%M:%S')\\t Assigned IPv4 address for openvswitch lan bridge interface is not correct. Aborting."
exit 1
fi
fi
# check if openvswitch lan bridge interface IPv4 address was assigned via DHCP
if [ ${#arr_iface_withip[@]} -ne 0 ]
then
if [[ $(ip -4 addr show $lanbr | grep inet | awk '{print $7}') == "dynamic" ]]
then
echo -e >&2 "$(date '+%Y-%m-%d %H:%M:%S')\\t IPv4 address of openvswitch lan bridge interface was assigend via DHCP"
else
echo -e >&2 "$(date '+%Y-%m-%d %H:%M:%S')\\t IPv4 address of openvswitch lan bridge interface was not assigend via DHCP"
fi
fi
arr_iface_withip=()
# final message
echo -e <&2 "$(date '+%Y-%m-%d %H:%M:%S')\\t Script finished"
#func_pause "$pausearg"
# restoring original output and closing created file descriptors
exec 1>&3 2>&4 3>&- 4>&-
</code></pre>
<hr>
<p>I already checked the script with shellcheck.</p>
<p>The result:</p>
<pre class="lang-none prettyprint-override"><code>In line 133:
declare -r pausearg="Press any key to continue..."
^-- SC2034: pausearg appears unused. Verify use (or export if used externally).
</code></pre>
<p>This is intentionally left for later use, for debugging:</p>
<pre class="lang-none prettyprint-override"><code>In /opt/vmchecks/vmrun line 179:
declare -r brlan_configs_md5="/opt/vmchecks/50-ovs-brlan.md5"
^-- SC2034: brlan_configs_md5 appears unused. Verify use (or export if used externally).
In /opt/vmchecks/vmrun line 182:
declare -r brlan_configs_sha="/opt/vmchecks/50-ovs-brlan.sha"
^-- SC2034: brlan_configs_sha appears unused. Verify use (or export if used externally).
</code></pre>
<p>This is a false positive; it is used:</p>
<pre class="lang-none prettyprint-override"><code>In /opt/vmchecks/vmrun line 462:
arr_iface_virt_nonbridge=("${arr_iface_virt_nonbridge_tmp[@]}")
^-- SC2034: arr_iface_virt_nonbridge appears unused. Verify use (or export if used externally).
</code></pre>
<p>True. It's currently only initialized with values but not further used. It's kept for a possible later use.</p>
<p>Please review, find bugs and give hints to make them simpler and better.</p>
| [] | [
{
"body": "<p>Much of this seems ... unidiomatic for a shell script. It feels rather like a C program converted to shell. </p>\n\n<ul>\n<li>You don't need to <code>declare -f</code> functions before hand. In fact, <code>declare -f func_pause</code> is an error if <code>func_pause</code> wasn't <em>already</em> ... | {
"AcceptedAnswerId": "205273",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-10-10T00:51:56.857",
"Id": "205264",
"Score": "2",
"Tags": [
"bash",
"linux",
"networking"
],
"Title": "Bash script to change network interface parameters/configuration and start virtual machines"
} | 205264 |
<p>I am dealing with some older C style APIs, like Posix <code>execve</code> that take a <code>char**</code>. In the rest of my code, I prefer to use a fairly modern C++ style, so I have vector of <code>std::string</code>. Is this the best way to handle the glue between them?</p>
<pre><code>char ** strlist(std::vector<std::string> &input) {
char** result = new char*[input.size()];
result[input.size()] = nullptr;
for (int i=0; i<input.size(); i++) {
char *temp = new char[input[i].size()];
strcpy(temp, input[i].c_str());
result[i] = temp;
}
return result;
}
bool del_strlist(char ** strings, int limit=1024) {
bool finished = false;
for (int i=0; i<limit; i++) {
char *temp = strings[i];
if (temp == nullptr) {
finished = true;
break;
}
delete temp;
}
delete strings;
return !finished;
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-10-10T08:21:40.903",
"Id": "395962",
"Score": "1",
"body": "Can you explain *why* `del_strlist` returns a boolean? What is the result used for?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-10-10T09:04:46.863",... | [
{
"body": "<p>I can see a few potential problems here:</p>\n\n<ol>\n<li>Since you allocated a <code>char*</code> array of <code>input.size()</code> elements, <code>result[input.size()]</code> is out of bounds.</li>\n<li>Similarly, <code>std::string</code>'s <code>size()</code> is the number of characters - it d... | {
"AcceptedAnswerId": null,
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-10-10T03:12:58.230",
"Id": "205269",
"Score": "26",
"Tags": [
"c++",
"c",
"posix"
],
"Title": "Create a C style char** from a C++ vector<string>"
} | 205269 |
<p>I have a need to parse strings that contain pairs of <code>key : value</code>, and remove a specific pair, when I'm only given the key.</p>
<p>Example: </p>
<p>Given the string <code>char *in = "sha-auth privacy-protocol des authentication-password shapass123 privacy-password despass123 admin-status enabled";</code></p>
<p>and the key-word <code>char *kw = "authentication-password";</code></p>
<p>I want to get only <code>char *output = "sha-auth privacy-protocol des privacy-password despass123 admin-status enabled";</code></p>
<p>where the pair <code>{"authentication-password" : "shapass123"}</code> was removed.</p>
<p>This is my take:</p>
<pre><code>void remove_key_word_value_from_string(char *input, char *output, char *kw)
{
char *p = input;
char *kw_loc = strstr(p, kw); /* check if kw is in input */
if(kw_loc)
{
size_t offset = (size_t)(kw_loc - p);
strncpy(output, p, offset); /* copy until kw */
p = kw_loc + strlen(kw); /* move p past the key-word location */
while(isspace(*p++)); /* skip all white-spaces after keyword */
while(!isspace(*p++)); /* skip the value associated with keyword */
strcpy(output + offset, p); /* copy rest of input */
}
else /* no censoring is needed*/
{
strcpy(output, input);
}
}
char o[1024] = "";
char *in = "sha-auth privacy-protocol des authentication-password shapass123 privacy-password despass123 admin-status enabled";
remove_key_word_value_from_string(in, o, "authentication-password");
printf("output = %s\ninput = %s", o, in);
</code></pre>
<p>I wrote in C, but open to additions / changes in C++ as my code will actually run on a C++ compiler.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-10-10T09:47:31.627",
"Id": "395967",
"Score": "0",
"body": "\"This is my take\" Does it work? For what inputs did you test it?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-10-10T09:49:00.340",
"Id": "39596... | [
{
"body": "<p>There are a few things we don't see in your code, such as the way the memory for the <code>output</code> is allocated. The easiest way is to <code>malloc</code> as many bytes as needed for the the <code>input</code>, but it isn't optimal. It isn't optimal to allocate buffers every time you extract... | {
"AcceptedAnswerId": null,
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-10-10T09:12:05.117",
"Id": "205281",
"Score": "-2",
"Tags": [
"c++",
"c",
"strings",
"parsing"
],
"Title": "Remove key-value pairs from string when only key is given"
} | 205281 |
<p>This is the code I made to scan IP addresses. I am new to python and just want to learn how I can optimize it. I know the subprocess is slower than others to IP scanning but if there is a way to make it faster I would like to know how. :)</p>
<pre><code>#!/usr/bin/env python
# coding:utf-8
import subprocess
import datetime
hostname = input("Entrez la gateway de cette manière(example: 192.168.1)")
# Ask for gateway
while True:
file_name = input("Comment voulez-vous appelez votre dossier?Sans espace ni caratère spéciaux(example:file_name)")
# Ask how the user want to name the file where the result of the scan will be
if " " in file_name:
print("Réecrire le nom sans espace")
# check for spaces in the name file(impossible to create name files with spaces or special characters)
else:
break
with open(str(file_name) + ".txt", "w")as i:
i.write("Start time" + str(datetime.datetime.now()))
# print the start time of the scan process
for scan in range(1, 255):
i.write("-" * 100)
ip_address = str(hostname) + "." + str(scan)
ping_response = subprocess.Popen(["ping", ip_address, "-n", '1'], stdout=subprocess.PIPE).stdout.read()
#Ping the ip address
ping_response = ping_response.decode()
# (la réponse du ping est encoder , cette commande la decode)
print("-"*100)
print(ping_response)
i.write(str(ping_response))
if ip_address == hostname + "." + "254":
i.write("End time" + str(datetime.datetime.now()))
# print the end time of the scan process
i.close()
quit()
</code></pre>
| [] | [
{
"body": "<ol>\n<li>Use the <code>argparse</code> module for getting user input</li>\n<li>Validate user input</li>\n<li>Use <code>f\"{string}\"</code> or <code>\"{}\".format(string)</code> instead of manually concatting</li>\n<li>No need to do <code>i.close()</code> as the <code>with</code> automatically close... | {
"AcceptedAnswerId": "205292",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-10-10T12:03:34.440",
"Id": "205285",
"Score": "1",
"Tags": [
"python",
"beginner",
"python-3.x",
"networking",
"ip-address"
],
"Title": "IP Scanning program Python 3"
} | 205285 |
<p>Given below is my task</p>
<blockquote>
<p>Write a selenium test that makes a booking from Bangalore to New Delhi
for today's date with a return of tomorrow using makemytrip.com.
Select the cheapest flight and make sure that you come to the booking page.</p>
</blockquote>
<p>I'm pretty new to Selenium and I would like to know if my attempt at achieving the aforementioned task is as good as it can get or if there are certain aspects of my code that could be improved.</p>
<p>I've relied on some simple element selectors to achieve the task and one concern I have with automating a test case (such as the one mentioned above) for a web site is to do it in such a way that it remains change proof i.e. a test case written in such a way that it validates certain functions of the site without relying on the structure of the web page itself especially when the "id" attribute isn't available. Are there any general recommendations/practices as far as automation of web sites is concerned ? </p>
<pre><code>from selenium import webdriver,common
from selenium.webdriver.common.keys import Keys
from datetime import datetime
import time,re
def type_and_enter(element,text):
element.clear()
element.send_keys(text)
time.sleep(1)
element.send_keys(Keys.ENTER)
source = "Bangalore"
destination = "New Delhi"
# CREATE A NEW GOOGLE CHROME OBJECT & LOGIN TO makemytrip.com
chrome_browser = webdriver.Chrome()
chrome_browser.get("https://www.makemytrip.com/")
# ASSERT WE ARE ON THE CORRECT PAGE
assert "makemytrip" in chrome_browser.title.lower()
# ENTER VALUE FOR "FROM"
from_field = chrome_browser.find_element_by_id("hp-widget__sfrom")
type_and_enter(from_field,source)
# ENTER VALUE FOR "TO"
to_field = chrome_browser.find_element_by_id("hp-widget__sTo")
type_and_enter(to_field,destination)
# SET DEPART DATE TO PRESENT DAY
depart_field = chrome_browser.find_element_by_id("hp-widget__depart")
depart_field.click()
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-10-10T13:51:21.297",
"Id": "396006",
"Score": "0",
"body": "Is there a reason for the `time.sleep(1)`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-10-10T14:03:59.923",
"Id": "396009",
"Score": "0",
... | [
{
"body": "<p>I think the biggest thing you have to take into account is <strong>Separation of Concerns</strong>. You should definitely <em>separate page and element definitions from the actual logic of the test</em>. Put your element locators into <a href=\"https://selenium-python.readthedocs.io/page-objects.h... | {
"AcceptedAnswerId": "205302",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-10-10T12:46:02.783",
"Id": "205290",
"Score": "1",
"Tags": [
"python",
"selenium"
],
"Title": "Automate booking on a travel site"
} | 205290 |
<p><strong><em>NOTE</strong>: the Javascript is all I'm concerned about, the HTML/CSS is just DEMO code. One caveat is ARIA states or attributes, if you have input on that, by all means, dive in.</em></p>
<p>I had the need for and unobtrusive extensible toggle that could be applied to a handful of items: tooltips, accordions, panels, dropdowns, etc.</p>
<p>With the accordions, there is a need for a sidebar that also has accordion-like functionality with sub-links that reveal once clicked, this event triggers the accordion as well, so had to make paired events that triggered the actual accordion, as those sidebar sub-links anchor/smooth scroll into the accordion panels. </p>
<p>We're not utilizing babeljs so wrote this in ES5 compliant JS. Any recommendations to improve or areas that you see could pose an issue in compatibility, performance, maintainability, scalability, etc. feel free to offer advice. I am not a strong JS dev, know enough to get in trouble, so any advice on improvement is welcomed.</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 toggleAttribute = function (el, attr) {
!el.hasAttribute(attr) ?
el.setAttribute(attr, '') :
el.removeAttribute(attr);
};
var toggleValue = function (el, attr, on, off) {
el.setAttribute(
attr,
el.getAttribute(attr) === off ? on : off);
};
var eventHandler = function eventHandler(event, node, callback) {
window.addEventListener(
event,
function (e) {
if (!e.target.matches(node)) return;
callback.call(this, e);
},
false
);
};
var toggleMethod = function (target, identifier, active, attr, on, off) {
var d = document;
target.classList.add(active);
toggleValue(target, attr, on, off);
toggleAttribute(target.nextElementSibling, 'hidden')
if (target.hasAttribute('data-controls')) {
var pairedTarget = d.querySelector('#' + target.getAttribute('data-controls'));
toggleValue(pairedTarget, attr, on, off);
toggleAttribute(pairedTarget.nextElementSibling, 'hidden')
}
var selectorList = d.querySelectorAll(identifier);
//for (var i = 0, len = selectorList.length; i < len; ++i)
Array.from(selectorList)
.forEach(function (selector) {
if (
selector !== target &&
selector !== pairedTarget
) {
selector.classList.remove(active);
selector.setAttribute(attr, off);
selector.nextElementSibling.hidden = true;
}
});
};
eventHandler('click', '.toggle', function (e) {
toggleMethod(e.target, '.toggle', 'active', 'aria-expanded', 'true', 'false');
});</code></pre>
<pre class="snippet-code-css lang-css prettyprint-override"><code>@charset 'utf-8';
body {
margin: 0
}
body>div {
width: 49%;
display: inline-block;
}
.toggle {
display:block;
margin-right: 5px;
padding: 8px 12px 8px 8px;
}
.toggle:before {
content: '›';
margin-right: 8px;
display: inline-block;
}
.toggle[aria-expanded='true']:before {
transform: rotate(90deg);
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><div>
<div>
<div>
<a href="#" aria-describedby="message-0" aria-expanded="false" class="toggle" data-controls="toggle-a" id="toggle-b">paired</a>
<div class="message" hidden id="message-0">
<p>paired a message</p>
</div>
</div>
<div>
<a href="#" aria-describedby="message-1" aria-expanded="false" class="toggle">isolated</a>
<div class="message" hidden="" id="message-1">
<p>isolated a message</p>
</div>
</div>
</div>
</div>
<div>
<div>
<div>
<button aria-describedby="message-2" aria-expanded="false" class="toggle" data-controls="toggle-b" id="toggle-a">paired</button>
<div class="message" hidden id="message-2">
<p>paired b message</p>
</div>
</div>
<div>
<button aria-describedby="message-3" aria-expanded="false" class="toggle">isolated</button>
<div class="message-3" hidden id="message-3">
<p>isolated b message</p>
</div>
</div>
</div>
</div></code></pre>
</div>
</div>
</p>
| [] | [
{
"body": "<p>The code looks pretty good. There are only a few suggestions I have about it.</p>\n\n<p>While it doesn't depend on Babeljs, it appears that <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/from\" rel=\"nofollow noreferrer\"><code>Array.from()</code><... | {
"AcceptedAnswerId": "211295",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-10-10T14:17:47.063",
"Id": "205295",
"Score": "3",
"Tags": [
"javascript",
"html",
"event-handling",
"dom",
"iteration"
],
"Title": "Toggle Event Delegation"
} | 205295 |
<h2>Problem definition</h2>
<p>Find the longest word that doesn't contain any of the following characters: </p>
<pre><code>gkmqvwxz
</code></pre>
<p>Input comes from a file named <a href="https://mega.nz/#!V75TWKCT!R41D0y0pgnFXER5jU-Jb7-daAglZN1FNQuiQ-FQgHTw" rel="noreferrer"><code>words.txt</code></a> and contains one word per line. A word is anything that is not a whitespace.</p>
<hr>
<h2>The twist</h2>
<p>My C++ implementation posted below is surprisingly slow, taking 1.7 seconds to run, whereas my javascript implementation (<a href="https://repl.it/repls/WarlikeRedSphere" rel="noreferrer">link</a>, will obviously be slower because it's online) takes only 55ms. Is it possible to somehow optimize my C++ implementation?</p>
<pre><code>#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <cstdint>
#include "TimeUtil.h"
int main()
{
uint64_t begin_time = currentTimeNanoseconds();
std::string longestAcceptableWord; // Variable to contain the longest word
std::string currentLine;
const char badLetters[] = { 'g', 'k', 'm', 'q', 'v', 'w', 'x', 'z' };
std::ifstream in;
in.open("words.txt");
while (!in.eof()) // Loop through the entire file (466 544 lines, 4 749 kB).
{
getline(in, currentLine);
if (currentLine.length() <= longestAcceptableWord.length())
{
continue;
}
// If the word contains one of the bad letters, don't accept it.
for (unsigned int i = 0; i < sizeof(badLetters); i++)
{
if (currentLine.find(badLetters[i]) != std::string::npos)
{
continue;
}
}
// If the word is longer than the current longest word found,
// and doesn't have any bad letters, make it the new longest
// word found.
longestAcceptableWord = currentLine;
}
in.close();
std::cout << "[" << (double) ((currentTimeNanoseconds() - begin_time) / 1000) / 1000.0f << "ms] " << longestAcceptableWord << std::endl;
return 0;
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-10-10T16:12:51.120",
"Id": "396048",
"Score": "0",
"body": "are you sure it is 55ms and not 550ms? I'm getting 90-100ms on my computer with my C++ implementation."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-1... | [
{
"body": "<p>I'm not sure what <code>"TimeUtil.h"</code> contains, but the standard facilities (in <code>std::chrono</code>) are to be preferred for portable code:</p>\n<pre><code>#include <chrono>\n\nint main()\n{\n auto begin_time = std::chrono::high_resolution_clock::now();\n\n // ...\... | {
"AcceptedAnswerId": null,
"CommentCount": "18",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-10-10T15:11:51.013",
"Id": "205299",
"Score": "9",
"Tags": [
"c++",
"performance",
"strings",
"file"
],
"Title": "Program that finds the longest word not containing one of the disallowed characters"
} | 205299 |
<p>I'm pulling the values from the following XML based on the attribute name. </p>
<pre><code><DataRow>
<DataItem name="SYMBOL">MSFT-US</DataItem>
<DataItem name="NAME">Microsoft Corporation</DataItem>
<DataItem name="CUSIP">59491812311</DataItem>
<DataItem name="SEDOL">2588CFA</DataItem>
<DataItem name="CURRENCY">USD</DataItem>
<DataItem name="DATE">2018-10-05</DataItem>
<DataItem name="PRICE">100.25</DataItem>
</DataRow>
</code></pre>
<p>Here's my working code to select the values into a list:</p>
<pre><code>IEnumerable<XElement> xDoc = XDocument.Parse(xmlString).Descendants("DataRow");
var query = from item in xDoc
let symbol = (item.Elements("DataItem")
.Where(i => (string)i.Attribute("name") == "SYMBOL").Select(i => i.Value)).FirstOrDefault()
let compName = (item.Elements("DataItem")
.Where(i => (string)i.Attribute("name") == "NAME").Select(i => i.Value)).FirstOrDefault()
let cusip = (item.Elements("DataItem")
.Where(i => (string)i.Attribute("name") == "CUSIP").Select(i => i.Value)).FirstOrDefault()
let sedol = (item.Elements("DataItem")
.Where(i => (string)i.Attribute("name") == "SEDOL").Select(i => i.Value)).FirstOrDefault()
select new {
Symbol = symbol,
CompName = compName,
Cusip = cusip,
Sedol = sedol
};
</code></pre>
<p>I feel that this can be made cleaner. How can it be done?</p>
| [] | [
{
"body": "<p>If you don't want create a full-blown <code>xml</code> serializer (I wouldn't if it was a simple as that) all you can do is to just tide this up. This is, add a helper variable for <code>dataItems</code> and create a helper extension for finding elements based on the <code>Name</code> attribute. T... | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-10-10T15:58:19.857",
"Id": "205305",
"Score": "3",
"Tags": [
"c#",
"linq",
"xml"
],
"Title": "Get attribute values with LINQ to XML"
} | 205305 |
<p>I am working since a couple of weeks on my first Python application and I would love to have a review of the code I wrote so far.</p>
<p>The app has the purpose of controlling the cooling and lighting of an AIO water cooling kit from NZXT on Linux. The official software only supports Windows but the interface is USB so the community wrote some really nice CLI tools to control it on any OS. My goal is to write a GUI front-end for it.</p>
<p>This means that unfortunately to use the app you need to have both a GNU/Linux installation and a NZXT Kraken. If you can't run the app but want to see how it looks, you can check <a href="https://www.reddit.com/r/NZXT/comments/9m4wmh/linux_gui_to_control_cooling_and_soon_lighting_of/" rel="nofollow noreferrer">this video</a> or watch this gif:</p>
<p><a href="https://i.stack.imgur.com/07RJT.gif" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/07RJT.gif" alt="enter image description here"></a></p>
<p>The app I think is already in a good stage: It can monitor the status (water temp and RPM of fan and pump) and I can set some predefined profile.</p>
<p>I develop applications for Android since 2010 so I tried to apply my mobile dev knowledge to this project.</p>
<p>I choose to support Python 3.6+ and I pick GTK as graphical toolkit because my main target is GNU/Linux.</p>
<p>For the architecture of the app I tried to go for some kind of MVP+Clean, but I am not super strict on respecting it.</p>
<p>I am using <code>injector</code> to handle the dependency injection, <code>rx</code> for the streams and async tasks, <code>peewee</code> for the persistency of the data and <code>matplotlib</code> to plot the charts. The communication with the kit is done via <code>liquidctl</code>.</p>
<p>As I said I am not a Python developer and this is my first app that goes somehow public (even if in early stage of development) so I would really appreciate if I could get some corrections and tips from more experienced Python devs.</p>
<p>I really like static analysis on Android so I am trying to use it also for Python. So far I am using PyLint and Mypy.</p>
<p>The entire project source is available <a href="https://gitlab.com/leinardi/gkraken" rel="nofollow noreferrer">here</a>, but I am going to paste the full code on this post since I think is requested by the rules.</p>
<hr>
<p>main.py</p>
<pre><code>#!/usr/bin/env python3
import signal
import locale
import gettext
import logging
import sys
import gi
from os.path import abspath, join, dirname
from peewee import SqliteDatabase
from rx.disposables import CompositeDisposable
gi.require_version('Gtk', '3.0')
from gi.repository import GLib
from gkraken.repository import KrakenRepository
from gkraken.di import INJECTOR
from gkraken.app import Application
APP = "gkraken"
WHERE_AM_I = abspath(dirname(__file__))
LOCALE_DIR = join(WHERE_AM_I, 'mo')
FORMAT = '%(filename)15s:%(lineno)-4d %(asctime)-15s: %(levelname)s/%(threadName)s(%(process)d) %(message)s'
logging.basicConfig(level=logging.DEBUG, format=FORMAT)
logging.getLogger("Rx").setLevel(logging.INFO)
logging.getLogger('injector').setLevel(logging.INFO)
logging.getLogger('peewee').setLevel(logging.INFO)
logging.getLogger('matplotlib').setLevel(logging.INFO)
LOG = logging.getLogger(__name__)
# POSIX locale settings
locale.setlocale(locale.LC_ALL, locale.getlocale())
locale.bindtextdomain(APP, LOCALE_DIR)
gettext.bindtextdomain(APP, LOCALE_DIR)
gettext.textdomain(APP)
def __cleanup() -> None:
LOG.debug("cleanup")
composite_disposable: CompositeDisposable = INJECTOR.get(CompositeDisposable)
composite_disposable.dispose()
database = INJECTOR.get(SqliteDatabase)
database.close()
kraken_repository = INJECTOR.get(KrakenRepository)
kraken_repository.cleanup()
# futures.thread._threads_queues.clear()
def handle_exception(exc_type, exc_value, exc_traceback) -> None:
if issubclass(exc_type, KeyboardInterrupt):
sys.__excepthook__(exc_type, exc_value, exc_traceback)
return
LOG.critical("Uncaught exception", exc_info=(exc_type, exc_value, exc_traceback))
__cleanup()
sys.exit(1)
sys.excepthook = handle_exception
def main() -> int:
LOG.debug("main")
application: Application = INJECTOR.get(Application)
GLib.unix_signal_add(GLib.PRIORITY_DEFAULT, signal.SIGINT, application.quit)
exit_status = application.run(sys.argv)
__cleanup()
return sys.exit(exit_status)
if __name__ == "__main__":
main()
</code></pre>
<hr>
<p>app.py</p>
<pre><code>import logging
from gettext import gettext as _
from typing import Any, Optional
from gi.repository import Gtk, Gio, GLib
from injector import inject
from peewee import SqliteDatabase
from gkraken.conf import APP_NAME, APP_ID
from gkraken.model import SpeedProfile, SpeedStep, Setting, CurrentSpeedProfile
from gkraken.presenter import Presenter
from gkraken.util import load_db_default_data
from gkraken.view import View
LOG = logging.getLogger(__name__)
class Application(Gtk.Application):
@inject
def __init__(self,
database: SqliteDatabase,
view: View,
presenter: Presenter,
builder: Gtk.Builder,
*args: Any,
**kwargs: Any) -> None:
LOG.debug("init Application")
GLib.set_application_name(_(APP_NAME))
super().__init__(*args, application_id=APP_ID,
flags=Gio.ApplicationFlags.HANDLES_COMMAND_LINE,
**kwargs)
database.connect()
database.create_tables([SpeedProfile, SpeedStep, CurrentSpeedProfile, Setting])
if SpeedProfile.select().count() == 0:
load_db_default_data()
self.add_main_option("test", ord("t"), GLib.OptionFlags.NONE,
GLib.OptionArg.NONE, "Command line test", None)
self.__view = view
self.__presenter = presenter
self.__presenter.application_quit = self.quit
self.__window: Optional[Gtk.ApplicationWindow] = None
self.__builder: Gtk.Builder = builder
def do_activate(self) -> None:
if not self.__window:
self.__builder.connect_signals(self.__presenter)
self.__window: Gtk.ApplicationWindow = self.__builder.get_object("application_window")
self.__window.set_application(self)
self.__window.show_all()
self.__view.show()
self.__window.present()
def do_startup(self) -> None:
Gtk.Application.do_startup(self)
def do_command_line(self, command_line: Gio.ApplicationCommandLine) -> int:
options = command_line.get_options_dict()
# convert GVariantDict -> GVariant -> dict
options = options.end().unpack()
if "test" in options:
# This is printed on the main instance
print("Test argument recieved: %s" % options["test"])
self.activate()
return 0
</code></pre>
<hr>
<p>view.py</p>
<pre><code>import gi
import logging
from typing import Optional, Dict, Any, List, Tuple
from injector import inject, singleton
from gi.repository import Gtk
# AppIndicator3 may not be installed
from gkraken.interactor import SettingsInteractor
try:
gi.require_version('AppIndicator3', '0.1')
from gi.repository import AppIndicator3
except (ImportError, ValueError):
AppIndicator3 = None
from matplotlib.axes import Axes
from matplotlib.figure import Figure
from matplotlib.backends.backend_gtk3agg import FigureCanvasGTK3Agg as FigureCanvas
from gkraken.conf import APP_PACKAGE_NAME, APP_ID
from gkraken.model import Status, SpeedProfile, ChannelType
from gkraken.presenter import Presenter, ViewInterface
LOG = logging.getLogger(__name__)
if AppIndicator3 is None:
LOG.warning("AppIndicator3 is not installed. The app indicator will not be shown.")
# pylint: disable=too-many-instance-attributes
@singleton
class View(ViewInterface):
@inject
def __init__(self,
presenter: Presenter,
builder: Gtk.Builder,
settings_interactor: SettingsInteractor,
) -> None:
LOG.debug('init View')
self.__presenter: Presenter = presenter
self.__presenter.view = self
self.__builder: Gtk.Builder = builder
self.__settings_interactor = settings_interactor
self.__init_widgets()
def __init_widgets(self) -> None:
# self.refresh_content_header_bar_title()
self.__window = self.__builder.get_object("application_window")
self.__settings_dialog: Gtk.Dialog = self.__builder.get_object("settings_dialog")
self.__app_indicator_menu = self.__builder.get_object("app_indicator_menu")
self.__statusbar: Gtk.Statusbar = self.__builder.get_object('statusbar')
self.__context = self.__statusbar.get_context_id(APP_PACKAGE_NAME)
self.__cooling_fan_speed: Gtk.Label = self.__builder.get_object('cooling_fan_speed')
self.__cooling_fan_rpm: Gtk.Label = self.__builder.get_object('cooling_fan_rpm')
self.__cooling_liquid_temp: Gtk.Label = self.__builder.get_object('cooling_liquid_temp')
self.__cooling_pump_rpm: Gtk.Label = self.__builder.get_object('cooling_pump_rpm')
self.__firmware_version: Gtk.Label = self.__builder.get_object('firmware_version')
self.__cooling_fan_combobox: Gtk.ComboBox = self.__builder.get_object('cooling_fan_profile_combobox')
self.__cooling_fan_liststore: Gtk.ListStore = self.__builder.get_object('cooling_fan_profile_liststore')
self.__cooling_pump_combobox: Gtk.ComboBox = self.__builder.get_object('cooling_pump_profile_combobox')
self.__cooling_pump_liststore: Gtk.ListStore = self.__builder.get_object('cooling_pump_profile_liststore')
cooling_fan_scrolled_window: Gtk.ScrolledWindow = self.__builder.get_object('cooling_fan_scrolled_window')
cooling_pump_scrolled_window: Gtk.ScrolledWindow = self.__builder.get_object('cooling_pump_scrolled_window')
self.__cooling_fan_apply_button: Gtk.Button = self.__builder.get_object('cooling_fan_apply_button')
self.__cooling_pump_apply_button: Gtk.Button = self.__builder.get_object('cooling_pump_apply_button')
self.__init_plot_charts(cooling_fan_scrolled_window, cooling_pump_scrolled_window)
def show(self) -> None:
self.__presenter.on_start()
self.__init_app_indicator()
def __init_app_indicator(self) -> None:
self.__app_indicator: Optional[AppIndicator3.Indicator] = None
if AppIndicator3:
icon_theme = Gtk.IconTheme.get_default()
icon_name = icon_theme.lookup_icon('weather-showers-symbolic', 16, 0).get_filename()
self.__app_indicator = AppIndicator3.Indicator \
.new(APP_ID, icon_name, AppIndicator3.IndicatorCategory.HARDWARE)
self.__app_indicator.set_status(AppIndicator3.IndicatorStatus.PASSIVE)
self.__app_indicator.set_menu(self.__app_indicator_menu)
def toggle_window_visibility(self) -> None:
if self.__window.props.visible:
self.__window.hide()
else:
self.__window.show()
def show_add_speed_profile_dialog(self, channel: ChannelType) -> None:
LOG.debug("view show_add_speed_profile_dialog %s", channel.name)
def show_settings_dialog(self) -> None:
self.__settings_dialog.show()
def hide_settings_dialog(self) -> None:
self.__settings_dialog.hide()
def set_statusbar_text(self, text: str) -> None:
self.__statusbar.remove_all(self.__context)
self.__statusbar.push(self.__context, text)
def refresh_content_header_bar_title(self) -> None:
# contant_stack = self.__builder.get_object("content_stack")
# child = contant_stack.get_visible_child()
# if child is not None:
# title = contant_stack.child_get_property(child, "title")
# content_header_bar = self.__builder.get_object("content_header_bar")
# content_header_bar.set_title(title)
pass
def refresh_status(self, status: Optional[Status]) -> None:
LOG.debug('view status')
if status:
self.__cooling_fan_rpm.set_markup("<span size=\"xx-large\">%s</span> RPM" % status.fan_rpm)
self.__cooling_fan_speed.set_markup("<span size=\"xx-large\">%s</span> %%" %
('-' if status.fan_speed is None else status.fan_speed))
self.__cooling_liquid_temp.set_markup("<span size=\"xx-large\">%s</span> °C" % status.liquid_temperature)
self.__cooling_pump_rpm.set_markup("<span size=\"xx-large\">%s</span> RPM" % status.pump_rpm)
self.__firmware_version.set_label("firmware version %s" % status.firmware_version)
if self.__app_indicator:
if self.__settings_interactor.get_bool('settings_show_app_indicator'):
self.__app_indicator.set_status(AppIndicator3.IndicatorStatus.ACTIVE)
else:
self.__app_indicator.set_status(AppIndicator3.IndicatorStatus.PASSIVE)
if self.__settings_interactor.get_bool('settings_app_indicator_show_water_temp'):
self.__app_indicator.set_label(" %s°C" % status.liquid_temperature, " XX°C")
else:
self.__app_indicator.set_label("", "")
def refresh_chart(self, profile: SpeedProfile) -> None:
if profile.channel == ChannelType.FAN.value:
self.__plot_fan_chart(self.__get_speed_profile_data(profile))
elif profile.channel == ChannelType.PUMP.value:
self.__plot_pump_chart(self.__get_speed_profile_data(profile))
else:
raise ValueError("Unknown channel: %s" % profile.channel)
@staticmethod
def __get_speed_profile_data(profile: SpeedProfile) -> Dict[int, int]:
data = {p.temperature: p.duty for p in profile.steps}
if profile.single_step:
data.update({60: profile.steps[0].duty})
else:
data.update({60: 100})
return data
def refresh_profile_combobox(self, channel: ChannelType, data: List[Tuple[int, str]],
active: Optional[int]) -> None:
if channel is ChannelType.FAN:
for item in data:
self.__cooling_fan_liststore.append([item[0], item[1]])
self.__cooling_fan_combobox.set_model(self.__cooling_fan_liststore)
self.__cooling_fan_combobox.set_sensitive(len(self.__cooling_fan_liststore) > 1)
if active is not None:
self.__cooling_fan_combobox.set_active(active)
elif channel is ChannelType.PUMP:
for item in data:
self.__cooling_pump_liststore.append([item[0], item[1]])
self.__cooling_pump_combobox.set_model(self.__cooling_pump_liststore)
self.__cooling_pump_combobox.set_sensitive(len(self.__cooling_pump_liststore) > 1)
if active is not None:
self.__cooling_pump_combobox.set_active(active)
else:
raise ValueError("Unknown channel: %s" % channel.name)
def set_apply_button_enabled(self, channel: ChannelType, enabled: bool) -> None:
if channel is ChannelType.FAN:
self.__cooling_fan_apply_button.set_sensitive(enabled)
elif channel is ChannelType.PUMP:
self.__cooling_pump_apply_button.set_sensitive(enabled)
else:
raise ValueError("Unknown channel: %s" % channel.name)
# pylint: disable=attribute-defined-outside-init
def __init_plot_charts(self,
fan_scrolled_window: Gtk.ScrolledWindow,
pump_scrolled_window: Gtk.ScrolledWindow) -> None:
self.__fan_figure = Figure(figsize=(8, 6), dpi=72, facecolor='#00000000')
self.__fan_canvas = FigureCanvas(self.__fan_figure) # a Gtk.DrawingArea+
self.__fan_axis = self.__fan_figure.add_subplot(111)
self.__fan_line, = self.__init_plot_chart(
fan_scrolled_window,
self.__fan_figure,
self.__fan_canvas,
self.__fan_axis
)
self.__pump_figure = Figure(figsize=(8, 6), dpi=72, facecolor='#00000000')
self.__pump_canvas = FigureCanvas(self.__pump_figure) # a Gtk.DrawingArea+
self.__pump_axis = self.__pump_figure.add_subplot(111)
self.__pump_line, = self.__init_plot_chart(
pump_scrolled_window,
self.__pump_figure,
self.__pump_canvas,
self.__pump_axis
)
def refresh_settings(self, settings: Dict[str, Any]) -> None:
for key, value in settings.items():
if isinstance(value, bool):
switch: Gtk.Switch = self.__builder.get_object(key + '_switch')
switch.set_active(value)
@staticmethod
def __init_plot_chart(fan_scrolled_window: Gtk.ScrolledWindow,
figure: Figure,
canvas: FigureCanvas,
axis: Axes) -> Any:
axis.grid(True, linestyle=':')
axis.margins(x=0, y=0.05)
axis.set_facecolor('#00000000')
axis.set_xlabel('Liquid temperature [°C]')
axis.set_ylabel('Fan speed [%]')
figure.subplots_adjust(top=1)
canvas.set_size_request(400, 300)
fan_scrolled_window.add_with_viewport(canvas)
# Returns a tuple of line objects, thus the comma
lines = axis.plot([], [], 'o-', linewidth=3.0, markersize=10, antialiased=True)
axis.set_ybound(lower=0, upper=105)
axis.set_xbound(20, 60)
figure.canvas.draw()
return lines
def __plot_fan_chart(self, data: Dict[int, int]) -> None:
temperature = list(data.keys())
duty = list(data.values())
self.__fan_line.set_xdata(temperature)
self.__fan_line.set_ydata(duty)
self.__fan_canvas.draw()
self.__fan_canvas.flush_events()
def __plot_pump_chart(self, data: Dict[int, int]) -> None:
temperature = list(data.keys())
duty = list(data.values())
self.__pump_line.set_xdata(temperature)
self.__pump_line.set_ydata(duty)
self.__pump_canvas.draw()
self.__pump_canvas.flush_events()
</code></pre>
<hr>
<p>presenter.py</p>
<pre><code>import logging
import multiprocessing
import re
from typing import Optional, Any, List, Tuple, Dict, Callable
from gi.repository import Gtk
from injector import inject, singleton
from rx import Observable
from rx.concurrency import GtkScheduler, ThreadPoolScheduler
from rx.concurrency.schedulerbase import SchedulerBase
from rx.disposables import CompositeDisposable
from gkraken.conf import SETTINGS_DEFAULTS
from gkraken.interactor import GetStatusInteractor, SetSpeedProfileInteractor, SettingsInteractor
from gkraken.model import Status, SpeedProfile, ChannelType, CurrentSpeedProfile
LOG = logging.getLogger(__name__)
_REFRESH_INTERVAL_IN_MS = 3000
_ADD_NEW_PROFILE_INDEX = -10
class ViewInterface:
def toggle_window_visibility(self) -> None:
raise NotImplementedError()
def refresh_status(self, status: Optional[Status]) -> None:
raise NotImplementedError()
def refresh_profile_combobox(self, channel: ChannelType, data: List[Tuple[int, str]],
active: Optional[int]) -> None:
raise NotImplementedError()
def refresh_chart(self, profile: SpeedProfile) -> None:
raise NotImplementedError()
def set_apply_button_enabled(self, channel: ChannelType, enabled: bool) -> None:
raise NotImplementedError()
def set_statusbar_text(self, text: str) -> None:
raise NotImplementedError()
def refresh_content_header_bar_title(self) -> None:
raise NotImplementedError()
def refresh_settings(self, settings: Dict[str, Any]) -> None:
raise NotImplementedError()
def show_add_speed_profile_dialog(self, channel: ChannelType) -> None:
raise NotImplementedError()
def show_settings_dialog(self) -> None:
raise NotImplementedError()
def hide_settings_dialog(self) -> None:
raise NotImplementedError()
@singleton
class Presenter:
@inject
def __init__(self,
get_status_interactor: GetStatusInteractor,
set_speed_profile_interactor: SetSpeedProfileInteractor,
settings_interactor: SettingsInteractor,
composite_disposable: CompositeDisposable,
) -> None:
LOG.debug("init Presenter ")
self.view: ViewInterface = ViewInterface()
self.__scheduler: SchedulerBase = ThreadPoolScheduler(multiprocessing.cpu_count())
self.__get_status_interactor: GetStatusInteractor = get_status_interactor
self.__set_speed_profile_interactor: SetSpeedProfileInteractor = set_speed_profile_interactor
self.__settings_interactor = settings_interactor
self.__composite_disposable: CompositeDisposable = composite_disposable
self.__profile_selected: Dict[str, SpeedProfile] = {}
self.__should_update_fan_speed: bool = False
self.application_quit: Callable = lambda *args: None # will be set by the Application
def on_start(self) -> None:
self.__init_speed_profiles()
self.__init_settings()
self.__start_refresh()
def __start_refresh(self) -> None:
LOG.debug("start refresh")
self.__composite_disposable \
.add(Observable
.interval(_REFRESH_INTERVAL_IN_MS, scheduler=self.__scheduler)
.start_with(0)
.subscribe_on(self.__scheduler)
.flat_map(lambda _: self.__get_status())
.observe_on(GtkScheduler())
.subscribe(on_next=self.__update_status,
on_error=lambda e: LOG.exception("Refresh error: %s", str(e)))
)
def __update_status(self, status: Optional[Status]) -> None:
if status is not None:
if self.__should_update_fan_speed:
last_applied: CurrentSpeedProfile = CurrentSpeedProfile.get_or_none(channel=ChannelType.FAN.value)
if last_applied is not None:
duties = [i.duty for i in last_applied.profile.steps if status.liquid_temperature >= i.temperature]
if duties:
status.fan_speed = duties[-1]
self.view.refresh_status(status)
# def __load_last_profile(self) -> None:
# for current in CurrentSpeedProfile.select():
@staticmethod
def __get_profile_list(channel: ChannelType) -> List[Tuple[int, str]]:
return [(p.id, p.name) for p in SpeedProfile.select().where(SpeedProfile.channel == channel.value)]
def __init_speed_profiles(self) -> None:
for channel in ChannelType:
data = self.__get_profile_list(channel)
active = None
if self.__settings_interactor.get_bool('settings_load_last_profile'):
self.__should_update_fan_speed = True
current: CurrentSpeedProfile = CurrentSpeedProfile.get_or_none(channel=channel.value)
if current is not None:
active = next(i for i, item in enumerate(data) if item[0] == current.profile.id)
self.__set_speed_profile(current.profile)
data.append((_ADD_NEW_PROFILE_INDEX, "<span style='italic' alpha='50%'>Add new profile...</span>"))
self.view.refresh_profile_combobox(channel, data, active)
def __init_settings(self) -> None:
settings = {}
for key, default_value in SETTINGS_DEFAULTS.items():
if isinstance(default_value, bool):
settings[key] = self.__settings_interactor.get_bool(key)
self.view.refresh_settings(settings)
def on_menu_settings_clicked(self, *_: Any) -> None:
self.view.show_settings_dialog()
def on_settings_dialog_closed(self, *_: Any) -> bool:
self.view.hide_settings_dialog()
return True
def on_setting_changed(self, widget: Any, *args: Any) -> None:
if isinstance(widget, Gtk.Switch):
state = args[0]
key = re.sub('_switch$', '', widget.get_name())
self.__settings_interactor.set_bool(key, state)
def on_stack_visible_child_changed(self, *_: Any) -> None:
self.view.refresh_content_header_bar_title()
def on_fan_profile_selected(self, widget: Any, *_: Any) -> None:
profile_id = widget.get_model()[widget.get_active()][0]
self.__select_speed_profile(profile_id, ChannelType.FAN)
def on_pump_profile_selected(self, widget: Any, *_: Any) -> None:
profile_id = widget.get_model()[widget.get_active()][0]
self.__select_speed_profile(profile_id, ChannelType.PUMP)
def on_quit_clicked(self, *_: Any) -> None:
self.application_quit()
def on_toggle_app_window_clicked(self, *_: Any) -> None:
self.view.toggle_window_visibility()
def __select_speed_profile(self, profile_id: int, channel: ChannelType) -> None:
if profile_id == _ADD_NEW_PROFILE_INDEX:
self.view.set_apply_button_enabled(channel, False)
self.view.show_add_speed_profile_dialog(channel)
else:
profile: SpeedProfile = SpeedProfile.get(id=profile_id)
self.__profile_selected[profile.channel] = profile
self.view.set_apply_button_enabled(channel, True)
self.view.refresh_chart(profile)
@staticmethod
def __get_profile_data(profile: SpeedProfile) -> List[Tuple[int, int]]:
return [(p.temperature, p.duty) for p in profile.steps]
def on_fab_apply_button_clicked(self, *_: Any) -> None:
self.__set_speed_profile(self.__profile_selected[ChannelType.FAN.value])
self.__should_update_fan_speed = True
def on_pump_apply_button_clicked(self, *_: Any) -> None:
self.__set_speed_profile(self.__profile_selected[ChannelType.PUMP.value])
def __set_speed_profile(self, profile: SpeedProfile) -> None:
observable = self.__set_speed_profile_interactor \
.execute(profile.channel, self.__get_profile_data(profile))
self.__composite_disposable \
.add(observable
.subscribe_on(self.__scheduler)
.observe_on(GtkScheduler())
.subscribe(on_next=lambda _: self.__update_current_speed_profile(profile),
on_error=lambda e: (LOG.exception("Set cooling error: %s", str(e)),
self.view.set_statusbar_text('Error applying %s speed profile!'
% profile.channel))))
def __update_current_speed_profile(self, profile: SpeedProfile) -> None:
current: CurrentSpeedProfile = CurrentSpeedProfile.get_or_none(channel=profile.channel)
if current is None:
CurrentSpeedProfile.create(channel=profile.channel, profile=profile)
else:
current.profile = profile
current.save()
self.view.set_statusbar_text('%s cooling profile applied' % profile.channel.capitalize())
def __log_exception_return_empty_observable(self, ex: Exception) -> Observable:
LOG.exception("Err = %s", ex)
self.view.set_statusbar_text(str(ex))
return Observable.just(None)
def __get_status(self) -> Observable:
return self.__get_status_interactor.execute() \
.catch_exception(lambda ex: self.__log_exception_return_empty_observable(ex))
</code></pre>
<hr>
<p>interactor.py</p>
<pre><code>LOG = logging.getLogger(__name__)
@singleton
class GetStatusInteractor:
@inject
def __init__(self,
kraken_repository: KrakenRepository,
) -> None:
self.__kraken_repository = kraken_repository
def execute(self) -> Observable:
LOG.debug("GetStatusInteractor.execute()")
return Observable.defer(lambda: Observable.just(self.__kraken_repository.get_status()))
@singleton
class SetSpeedProfileInteractor:
@inject
def __init__(self,
kraken_repository: KrakenRepository,
) -> None:
self.__kraken_repository = kraken_repository
def execute(self, channel_value: str, profile_data: List[Tuple[int, int]]) -> Observable:
LOG.debug("SetSpeedProfileInteractor.execute()")
return Observable.defer(lambda: Observable.just(
self.__kraken_repository.set_speed_profile(channel_value, profile_data)))
@singleton
class SettingsInteractor:
@inject
def __init__(self) -> None:
pass
@staticmethod
def get_bool(key: str, default: Optional[bool] = None) -> bool:
if default is None:
default = SETTINGS_DEFAULTS[key]
setting: Setting = Setting.get_or_none(key=key)
if setting is not None:
return bool(setting.value)
return bool(default)
@staticmethod
def set_bool(key: str, value: bool) -> None:
setting: Setting = Setting.get_or_none(key=key)
if setting is not None:
setting.value = value
setting.save()
else:
Setting.create(key=key, value=value)
@staticmethod
def get_str(key: str, default: Optional[str] = None) -> str:
if default is None:
default = SETTINGS_DEFAULTS[key]
setting: Setting = Setting.get_or_none(key=key)
if setting is not None:
return str(setting.value.decode("utf-8"))
return str(default)
@staticmethod
def set_str(key: str, value: str) -> None:
setting: Setting = Setting.get_or_none(key=key)
if setting is not None:
setting.value = value.encode("utf-8")
setting.save()
else:
Setting.create(key=key, value=value.encode("utf-8"))
</code></pre>
<hr>
<p>repository.py</p>
<pre><code>import logging
import threading
from enum import Enum
from typing import Optional, List, Tuple
import liquidctl
from injector import singleton, inject
from liquidctl.driver.kraken_two import KrakenTwoDriver
from gkraken.model import Status
from gkraken.di import INJECTOR
from gkraken.util import synchronized_with_attr
LOG = logging.getLogger(__name__)
@singleton
class KrakenRepository:
@inject
def __init__(self) -> None:
self.lock = threading.RLock()
self.__driver: Optional[KrakenTwoDriver] = None
def cleanup(self) -> None:
LOG.debug("KrakenRepository cleanup")
if self.__driver:
self.__driver.finalize()
self.__driver = None
@synchronized_with_attr("lock")
def get_status(self) -> Optional[Status]:
self.__load_driver()
if self.__driver:
try:
status = [v for k, v, u in self.__driver.get_status()]
return Status(
status[_StatusType.LIQUID_TEMPERATURE.value],
status[_StatusType.FAN_RPM.value],
status[_StatusType.PUMP_RPM.value],
status[_StatusType.FIRMWARE_VERSION.value]
)
# pylint: disable=bare-except
except:
LOG.exception("Error getting the status")
self.cleanup()
return None
@synchronized_with_attr("lock")
def set_speed_profile(self, channel_value: str, profile_data: List[Tuple[int, int]]) -> None:
self.__load_driver()
if self.__driver and profile_data:
try:
if len(profile_data) == 1:
self.__driver.set_fixed_speed(channel_value, profile_data[0][1])
else:
self.__driver.set_speed_profile(channel_value, profile_data)
# pylint: disable=bare-except
except:
LOG.exception("Error getting the status")
self.cleanup()
def __load_driver(self) -> None:
if not self.__driver:
self.__driver = INJECTOR.get(Optional[KrakenTwoDriver])
if self.__driver:
liquidctl.util.verbose = True
self.__driver.initialize()
else:
raise ValueError("Kraken USB interface error (check USB cable connection)")
class _StatusType(Enum):
LIQUID_TEMPERATURE = 0
FAN_RPM = 1
PUMP_RPM = 2
FIRMWARE_VERSION = 3
</code></pre>
<hr>
<p>model.py</p>
<pre><code># pylint: disable=too-many-locals,too-many-instance-attributes
from enum import Enum
from typing import Optional
from peewee import Model, CharField, DateTimeField, SqliteDatabase, SQL, IntegerField, Check, \
ForeignKeyField, BooleanField, BlobField
from playhouse.sqlite_ext import AutoIncrementField
from gkraken.di import INJECTOR
class Status:
def __init__(self,
liquid_temperature: float,
fan_rpm: int,
pump_rpm: int,
firmware_version: str
) -> None:
self.liquid_temperature: float = liquid_temperature
self.fan_rpm: int = fan_rpm
self.fan_speed: Optional[int] = None
self.pump_rpm: int = pump_rpm
self.firmware_version: str = firmware_version
class ChannelType(Enum):
FAN = 'fan'
PUMP = 'pump'
class SpeedProfile(Model):
id = AutoIncrementField()
channel = CharField(constraints=[Check("channel='%s' OR channel='%s'"
% (ChannelType.FAN.value, ChannelType.PUMP.value))])
name = CharField()
read_only = BooleanField(default=False)
single_step = BooleanField(default=False)
timestamp = DateTimeField(constraints=[SQL('DEFAULT CURRENT_TIMESTAMP')])
class Meta:
legacy_table_names = False
database = INJECTOR.get(SqliteDatabase)
class SpeedStep(Model):
profile = ForeignKeyField(SpeedProfile, backref='steps')
temperature = IntegerField()
duty = IntegerField()
timestamp = DateTimeField(constraints=[SQL('DEFAULT CURRENT_TIMESTAMP')])
class Meta:
legacy_table_names = False
database = INJECTOR.get(SqliteDatabase)
class CurrentSpeedProfile(Model):
channel = CharField(primary_key=True, constraints=[Check("channel='%s' OR channel='%s'"
% (ChannelType.FAN.value, ChannelType.PUMP.value))])
profile = ForeignKeyField(SpeedProfile, unique=True)
timestamp = DateTimeField(constraints=[SQL('DEFAULT CURRENT_TIMESTAMP')])
class Meta:
legacy_table_names = False
database = INJECTOR.get(SqliteDatabase)
class Setting(Model):
key = CharField(primary_key=True)
value = BlobField()
class Meta:
legacy_table_names = False
database = INJECTOR.get(SqliteDatabase)
</code></pre>
<hr>
<p>di.py</p>
<pre><code>import logging
from typing import Optional
from gi.repository import Gtk
from injector import Module, provider, singleton, Injector
from liquidctl.cli import find_all_supported_devices
from liquidctl.driver.kraken_two import KrakenTwoDriver
from peewee import SqliteDatabase
from rx.disposables import CompositeDisposable
from gkraken.conf import APP_PACKAGE_NAME, get_data_path, APP_UI_NAME, get_config_path, APP_DB_NAME
LOG = logging.getLogger(__name__)
# pylint: disable=no-self-use
class ProviderModule(Module):
@singleton
@provider
def provide_builder(self) -> Gtk.Builder:
LOG.debug("provide Gtk.Builder")
builder = Gtk.Builder()
builder.set_translation_domain(APP_PACKAGE_NAME)
builder.add_from_file(get_data_path(APP_UI_NAME))
return builder
@singleton
@provider
def provide_thread_pool_scheduler(self) -> CompositeDisposable:
LOG.debug("provide CompositeDisposable")
return CompositeDisposable()
@singleton
@provider
def provide_database(self) -> SqliteDatabase:
LOG.debug("provide CompositeDisposable")
return SqliteDatabase(get_config_path(APP_DB_NAME))
@provider
def provide_kraken_two_driver(self) -> Optional[KrakenTwoDriver]:
LOG.debug("provide KrakenTwoDriver")
return next((dev for dev in find_all_supported_devices() if isinstance(dev, KrakenTwoDriver)), None)
INJECTOR = Injector(ProviderModule)
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-10-10T17:31:06.423",
"Id": "396088",
"Score": "0",
"body": "\"*to use the app you need to have ... a NZXT Kraken*\" Here's an argument for a separable design, with a clean interface so you can provide some sort of simulation in place of ... | [] | {
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-10-10T17:03:02.687",
"Id": "205311",
"Score": "3",
"Tags": [
"python",
"dependency-injection",
"matplotlib",
"orm",
"gtk"
],
"Title": "GUI to control a NZXT cooling and lighting system"
} | 205311 |
<p>I'm trying to code a simple person database using structs and arrays in assembly.</p>
<p>Each person has a <code>firstName</code>, <code>lastName</code>, <code>age</code> and <code>weight</code>. The goal is to have an infinite loop that asks the user whether they want to read or write to the array then ask them for a position to read or write to. Currently, the array is limited to a max of 5, plan is to increase that (as well as move the request for the position out both the <code>.writing</code> and <code>.reading</code> blocks).</p>
<p>A couple of questions:</p>
<ol>
<li><strong>Formatting</strong>: Is the overall structure of the assembly okay? Any improvements that could be made to the formatting and structure?</li>
<li><strong>Accessing the elements of the array</strong>: For simple integer arrays, you can access them with <code>[rax + rcx * (size of int)]</code> where <code>rax</code> is the pointer to the start of the array and <code>rcx</code> is the position in the array we want to access. That didn't work for the Person array; I couldn't use <code>[rax + rcx * Person.size]</code>. So is there a better way to do that access?</li>
<li>Other comments in general?</li>
</ol>
<p>Compiled as follows using <code>VS2017 x64 Native Tools Command Prompt</code>:</p>
<blockquote>
<pre><code>> nasm -g -fwin64 person.asm
> cl /Zi person.obj msvcrt.lib legacy_stdio_definitions.lib
</code></pre>
</blockquote>
<p><strong>person.asm</strong></p>
<pre><code>default rel
extern scanf
extern printf
STRUC Person
.first_name: resb 50
.last_name: resb 50
.age: resq 1
.weight: resq 1
.size:
ENDSTRUC
SECTION .data
number: dq 0
scanf_fmt_1: db " %s", 0
scanf_fmt_2: db " %lld", 0
scanf_fmt_3: db " %c", 0
printf_fmt_1: db "Enter a number (1-5): ", 0
printf_fmt_2: db "Enter a first_name: ", 0
printf_fmt_3: db "Enter a last_name: ", 0
printf_fmt_4: db "Enter an age: ", 0
printf_fmt_5: db "Enter a weight: ", 0
printf_fmt_6: db "[R]ead or [W]rite? ", 0
printf_fmt_7: db "Person (%s %s) is %d years old and weights %d", 10, 0
SECTION .bss
person_array: resb Person.size * 5
SECTION .text
global main
main:
sub rsp, 32
.continue_loop:
lea rax, [p] ; load address of p (or John Doe)
lea rcx, [printf_fmt_6] ; address of "[R]ead or [W]rite? "
call printf
lea rdx, [number] ; address of number variable
lea rcx, [scanf_fmt_3] ; address of " %c"
call scanf
cmp qword [number], 'W' ; compare read value against W
je .writing ; local writing label
jmp .reading ; local reading label
.writing:
lea rcx, [printf_fmt_1] ; address of "Enter a number (1-5): "
call printf
lea rdx, [number] ; address of number
lea rcx, [scanf_fmt_2] ; address of " %lld"
call scanf
lea rbx, [person_array] ; we can't use fancy address calculation so manual it is
mov rax, Person.size
imul qword [number]
sub rax, Person.size ; we force the user to start at 1, but we start counting at 0
add rbx, rax
lea rcx, [printf_fmt_2] ; address of "Enter a first_name: "
call printf
lea rdx, [rbx + Person.first_name] ; address of first name
lea rcx, [scanf_fmt_1] ; address of " %s"
call scanf
lea rcx, [printf_fmt_3] ; address of "Enter a last_name: "
call printf
lea rdx, [rbx + Person.last_name] ; address of last name
lea rcx, [scanf_fmt_1] ; address of " %s"
call scanf
lea rcx, [printf_fmt_4] ; address of "Enter an age: "
call printf
lea rdx, [rbx + Person.age] ; address of age
lea rcx, [scanf_fmt_2] ; address of " %lld"
call scanf
lea rcx, [printf_fmt_5] ; address of "Enter a weight: "
call printf
lea rdx, [rbx + Person.weight] ; address of weight
lea rcx, [scanf_fmt_2] ; address of " %lld"
call scanf
jmp .end
.reading:
lea rcx, [printf_fmt_1] ; address of "Enter a number (1-5): "
call printf
lea rdx, [number] ; address of number
lea rcx, [scanf_fmt_2] ; address of " %lld"
call scanf
lea rbx, [person_array] ; we can't use fancy address calculation so manual it is
mov rax, Person.size
imul qword [number]
sub rax, Person.size ; we force the user to start at 1, but we start counting at 0
add rbx, rax
push qword [rbx + Person.weight] ; value of weight
sub rsp, 32 ; personal shadow space because > 4 params
mov r9, [rbx + Person.age] ; value of age
lea r8, [rbx + Person.last_name] ; address of last name
lea rdx, [rbx + Person.first_name] ; address of first name
lea rcx, [printf_fmt_7] ; address of "Person (%s %s) is %d years old and weights %d"
call printf
.end:
jmp .continue_loop
ret
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-10-10T23:21:07.683",
"Id": "396151",
"Score": "0",
"body": "@Mr. Vix don't edit the code. Feel free to point out bugs in an answer. Red more in the answers to [this Meta post: _Should you edit someone else's code in a question?](https://c... | [] | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-10-10T17:46:02.140",
"Id": "205315",
"Score": "2",
"Tags": [
"array",
"windows",
"assembly",
"amd64"
],
"Title": "x64 Windows Assembly - Structs in Assembly"
} | 205315 |
<p>I have programmed a card game in Python. It is over 700 lines long. How can I improve the code?</p>
<p>There are two players. Every round, each player takes one card from the top of the deck. Those cards are compared, and the winner of the round is assigned based on the following rules:</p>
<ul>
<li>Red beats black</li>
<li>Black beats yellow</li>
<li>Yellow beats red</li>
</ul>
<p>If both cards have the same colour, the card with the highest number wins. If they have the same colour and number, it is a draw.</p>
<p>The winner of the round keeps both cards. If the round was a draw, the players keep their own cards.</p>
<p>This is repeated until the deck is empty. The winner is the person with the most cards at the end of the game.</p>
<p>I used an online IDE called Repl.it. You can view and run the program here: <a href="https://repl.it/@ajeshjhalli/NEA-Card-Game" rel="nofollow noreferrer">NEA Card Game</a></p>
<p>main.py:</p>
<pre><code>import pickle
import os
from random import randint, shuffle
from time import sleep
# Card index constants
COLOUR = 0
NUMBER = 1
# Player constants
DRAW = 'draw'
PLAYER1 = '1'
PLAYER2 = '2'
def clear():
print('\n' * 100)
def main():
clear()
#login()
game = Game()
menu_loop = True
while menu_loop:
clear()
with open('image.txt', 'r') as image_file:
image_text = image_file.read()
for c in image_text:
if c == '0':
print(' ', end='')
elif c == '1':
print('*', end='')
else:
print(c, end='')
print()
print('==============================================')
print('| |')
print('| 1 - Play game |')
print('| 2 - Create a new deck |')
print('| 3 - Load a deck |')
print('| 4 - Delete a deck |')
print('| 5 - Change the speed of the game |')
print('| 6 - View the leaderboard |')
print('| 7 - Quit |')
print('| |')
print('==============================================')
menu_option = input('\nEnter menu option: ')
if menu_option == '1':
clear()
game.play()
input('Press enter to continue.')
elif menu_option == '2':
clear()
new_deck_menu()
input('Press enter to continue.')
elif menu_option == '3':
clear()
change_deck_menu()
input('Press enter to continue.')
elif menu_option == '4':
clear()
delete_deck_menu()
input('Press enter to continue.')
elif menu_option == '5':
clear()
change_speed()
input('Press enter to continue.')
elif menu_option == '6':
clear()
top5 = FileFunctions.read_top5()
display_leaderboard(top5)
input('Press enter to continue.')
elif menu_option == '7':
print('\nGoodbye.')
menu_loop = False
else:
clear()
print('\nPlease choose a number from the menu.\n')
input('Press enter to continue.')
def login():
# The password (for now) is 'Python'.
password = FileFunctions.get_password()
valid = False
while not valid:
password_attempt = input('Enter password: ')
if password_attempt == password:
valid = True
else:
print('Incorrect password.')
# Returns a tuple containing a colour and a number.
def new_card(colour):
return (colour, randint(1, 10))
# Creates a new random deck.
# number_of_cards must be a multiple of 3 so there can
# be an even amount of each colour in the deck.
def new_random_deck(name, number_of_cards):
deck = []
for i in range(int(number_of_cards / 3)):
deck.append(new_card('red'))
deck.append(new_card('black'))
deck.append(new_card('yellow'))
FileFunctions.write_deck(name, deck)
def display_leaderboard(players):
length = 20
print('\nLEADERBOARD\n')
print('=' * (length + 2))
for i in range(len(players)):
score = len(players[i]) - 1
string_part1 = str(i+1) + ' | ' + players[i][0]
string_part2 = ' ' * (length - len(string_part1)) + str(score)
print("%s%s" % (string_part1, string_part2))
print('=' * (length + 2))
print('\n')
def change_deck_menu():
valid = False
while not valid:
yes_or_no = input('Loading a different deck will reset the leaderboard. Do you wish to proceed? (y/n)').lower()
if yes_or_no == 'y':
valid = True
elif yes_or_no == 'n':
print('\nDeck has not been loaded.\n')
return
else:
print('\nPlease answer with \'y\' or \'n\'.\n')
FileFunctions.clear_leaderboard()
valid = False
while not valid:
deck_name = input('\nEnter name of deck to load: ')
if deck_name.strip() == '':
print('\nThe deck name will contain at least one visible character.')
continue
try:
f = open(deck_name + '.bin', 'r')
f.close()
valid = True
except FileNotFoundError:
print('\nDeck \'%s\' does not exist.' % deck_name)
valid = False
FileFunctions.change_current_deck_name(deck_name)
print('\nDeck \'%s\' has been loaded.\n' % deck_name)
def new_deck_menu():
print('\n\n')
valid = False
while not valid:
yes_or_no = input('\nAre you sure you want to create a new deck? (y/n)')
yes_or_no = yes_or_no.lower()
valid = True
if yes_or_no == 'y':
name_valid = False
while not name_valid:
deck_name = input('\nEnter deck name: ')
if deck_name.strip() == '':
print('\nThe deck name must contain at least one visible character.\n')
elif ' ' in deck_name:
print('\nThe deck name cannot contain spaces.\n')
elif '.' in deck_name:
print('\nThe deck name cannot contain dots (the file extension will be added automatically).\n')
elif '\\' in deck_name or '/' in deck_name:
print('\nThe deck name cannot contain slashes.\n')
else:
name_valid = True
number_valid = False
while not number_valid:
number = int(input('Enter amount of cards: '))
if number % 2 == 0 and number % 3 == 0:
number_valid = True
else:
print('\nAmount must be an even multiple of 3.')
new_random_deck(deck_name, number)
print('\nThe new deck has been created.')
elif yes_or_no == 'n':
print('\nCreation of new deck has been cancelled.')
else:
print('\nPlease answer with \'y\' or \'n\'.')
valid = False
print('\n')
def change_speed():
valid = False
current_delay = FileFunctions.load_round_delay()
current_delay = round(current_delay, 3)
current_delay = str(current_delay)
while not valid:
print('The current round delay is %s seconds.' % (current_delay))
yes_or_no = input('Are you sure you want to change the speed of the game? (y/n)').lower()
valid = True
if yes_or_no == 'y':
input_loop = True
while input_loop:
input_loop = False
try:
seconds = float(input('\nEnter delay between each round in seconds: '))
if seconds < 0:
print('The round delay cannot be a negative number.')
input_loop = True
except ValueError:
input_loop = True
print('Please enter a float or an integer.')
FileFunctions.write_round_delay(seconds)
print('\nThe new round delay has been saved.')
elif yes_or_no == 'n':
print('\nChanging of game speed has been cancelled.')
else:
print('\nPlease answer with \'y\' or \'n\'.\n')
valid = False
def delete_deck_menu():
valid = False
while not valid:
deck_name = input('\nEnter the name of the deck you want to delete: ')
if deck_name.strip() == '':
print('\nThe deck name will contain at least one visible character.')
elif ' ' in deck_name:
print('\nThe deck name will not contain spaces.')
elif '.' in deck_name:
print('\nPlease only enter the name of the deck. The file extension will be added automatically.\n')
else:
try:
with open(deck_name + '.bin', 'r'):
valid = True
except FileNotFoundError:
valid = False
print('\nDeck \'%s\' could not be found. Make sure you have spelt the name correctly.' % deck_name)
os.remove(deck_name + '.bin')
print('\nDeck \'%s\' has been deleted.\n' % deck_name)
class Game:
def __init__(self):
self.player1_name = ''
self.player2_name = ''
def play(self):
round_delay = FileFunctions.load_round_delay()
self.player1_name, self.player2_name = self._get_names()
deck_name = FileFunctions.load_current_deck_name()
play_again = True
while play_again:
# Read the deck from the deck file.
try:
deck = FileFunctions.load_deck(deck_name)
except FileNotFoundError:
print('\nCould not find the deck file. Try loading a different deck with option 3 of the main menu.\n')
return
player1_cards = []
player2_cards = []
shuffle(deck)
game_round = 1
print('\n\n')
while len(deck) > 0:
sleep(round_delay)
player1_card = deck[-1]
player2_card = deck[-2]
deck.pop()
deck.pop()
print('ROUND', game_round, '\n')
self._display_cards(player1_card, player2_card)
winner = self._compare_cards(player1_card, player2_card)
if winner == PLAYER1:
print('\nWinner:', self.player1_name)
elif winner == PLAYER2:
print('\nWinner:', self.player2_name)
else:
print('\nWinner: draw')
print('\n\n')
if winner == PLAYER1:
player1_cards.append(player1_card)
player1_cards.append(player2_card)
elif winner == PLAYER2:
player2_cards.append(player1_card)
player2_cards.append(player2_card)
# If it is a draw, the players keep their own cards.
else:
player1_cards.append(player1_card)
player2_cards.append(player2_card)
game_round += 1
if len(player1_cards) > len(player2_cards):
winner = self.player1_name
winning_cards = player1_cards
elif len(player1_cards) < len(player2_cards):
winner = self.player2_name
winning_cards = player2_cards
else:
winner = DRAW
winning_cards = []
print('%s has %d cards.' % (self.player1_name, len(player1_cards)))
print('%s has %d cards.\n' % (self.player2_name, len(player2_cards)))
print('Winner of game:', winner)
if winner != DRAW:
FileFunctions.write_name_and_cards(winner, winning_cards)
self._display_winning_cards(winner, winning_cards)
valid = False
while not valid:
yes_or_no = input('\nWould you like to play again? (y/n)').lower()
valid = True
if yes_or_no == 'n':
play_again = False
elif yes_or_no != 'y':
print('Please answer with \'y\' or \'n\'.')
valid = False
print('\n\n')
def _get_names(self):
print('\n\n')
valid = False
while not valid:
player1_name = input('Enter player 1\'s name: ')
if '_' in player1_name:
print('Names cannot contain underscores.')
elif player1_name.strip() == '':
print('The name must contain at least one visible character.')
elif len(player1_name) > 15:
print('The name cannot contain more than 15 characters.')
else:
valid = True
valid = False
while not valid:
player2_name = input('Enter player 2\'s name: ')
if '_' in player2_name:
print('Names cannot contain underscores.')
elif player2_name.strip() == '':
print('The name must contain at least one visible character.')
elif player2_name == player1_name:
print('Player 1 and player 2 must have different names.')
elif len(player2_name) > 15:
print('The name cannot contain more than 15 characters.')
else:
valid = True
return (player1_name, player2_name)
def _display_cards(self, card1, card2):
space_length = 25 - len(self.player1_name)
players_string = ''
players_string += self.player1_name.upper()
players_string += ' ' * space_length
players_string += self.player2_name.upper()
print('=' * 40)
print(players_string)
print('=' * 40)
print('colour:', card1[COLOUR], end='')
space_length = 17 - len(card1[COLOUR])
print(space_length * ' ', end='')
print('colour:', card2[COLOUR])
print('number:', card1[NUMBER], end='')
space_length = 17 - len(str(card1[NUMBER]))
print(space_length * ' ', end='')
print('number:', card2[NUMBER])
def _compare_cards(self, card1, card2):
if card1[COLOUR] == card2[COLOUR]:
if card1[NUMBER] > card2[NUMBER]:
return PLAYER1
elif card1[NUMBER] < card2[NUMBER]:
return PLAYER2
else:
return DRAW
else:
if card1[COLOUR] == 'red':
return PLAYER1 if card2[COLOUR] == 'black' else PLAYER2
elif card1[COLOUR] == 'black':
return PLAYER1 if card2[COLOUR] == 'yellow' else PLAYER2
elif card1[COLOUR] == 'yellow':
return PLAYER1 if card2[COLOUR] == 'red' else PLAYER2
def _display_winning_cards(self, winner, winning_cards):
while winner[-1] == ' ':
winner = winner[:-1]
if winner[-1].lower() == 's':
winner += '\''
else:
winner += '\'s'
print('\n%s CARDS:\n' % winner.upper())
space_const = 15
space_after_colour = ''
length_of_largest_int = len( str( len(winning_cards) + 1 ) )
for i in range(len(winning_cards)):
card = winning_cards[i]
space_after_colour = ' ' * ( space_const - len(card[0]) )
space_after_number = length_of_largest_int - len(str(i+1))
card_string = str(i+1)
card_string += ' ' * space_after_number
card_string += ' | COLOUR: ' + card[0] + space_after_colour + 'NUMBER: ' + str(card[1])
print(card_string)
class FileFunctions:
# Reads the current deck's name
def load_current_deck_name():
with open('bin_files/current_deck_name.bin', 'rb') as cd_file:
return pickle.load(cd_file)
def change_current_deck_name(new_name):
with open('bin_files/current_deck_name.bin', 'wb') as cd_file:
pickle.dump(new_name, cd_file)
# Writes deck to a file
def write_deck(name, deck_array):
deck_string = ''
for card in deck_array:
deck_string += card[0]
deck_string += ','
deck_string += str(card[1])
deck_string += '\n'
with open(name + '.bin', 'wb') as deck_file:
pickle.dump(deck_string, deck_file)
# Reads deck from a file and returns it as an array
def load_deck(name):
deck_array = []
with open(name + '.bin', 'rb') as deck_file:
deck_text = pickle.load(deck_file)
deck_text = deck_text.split('\n')
for card_string in deck_text:
try:
card = card_string.split(',')
card[1] = int(card[1])
deck_array.append( (card[0], card[1]) )
except IndexError: # The line is empty
continue
return deck_array
def get_password():
with open('bin_files/password.bin', 'rb') as passcode_file:
return pickle.load(passcode_file)
def clear_leaderboard():
with open('bin_files/win.bin', 'wb') as win_file:
pickle.dump('', win_file)
# Writes name and cards to win.bin
def write_name_and_cards(name, cards):
# Write the name and cards to the file
try:
with open('bin_files/win.bin', 'rb') as win_file:
win_string = pickle.load(win_file)
except EOFError:
win_string = ''
win_string += name
for card in cards:
win_string += '\n'
win_string += card[0]
win_string += ','
win_string += str(card[1])
win_string += '_'
with open('bin_files/win.bin', 'wb') as win_file:
pickle.dump(win_string, win_file)
# Delete any players not in the top 5
# Read all players from win.bin
with open('bin_files/win.bin', 'rb') as win_file:
players_string = pickle.load(win_file)
# Convert the string into an array.
players = players_string.split('_')
# Convert the array into a 2D array.
for i in range(len(players)):
players[i] = players[i].split('\n')
# Remove ['']
while players[-1] == ['']:
players.pop()
top5 = []
while len(top5) < 5:
index_of_highest = 0
for i in range(len(players)):
if len(players[i]) > len(players[index_of_highest]):
index_of_highest = i
try:
top5.append(players[index_of_highest])
players.pop(index_of_highest)
except IndexError:
break # The players array contains less than 5 players.
top5_string = ''
for player in top5:
top5_string += '\n'.join(player)
top5_string += '_'
with open('bin_files/win.bin', 'wb') as win_file:
pickle.dump(top5_string, win_file)
# Returns the top 5 players from win.txt as a tuple
def read_top5():
with open('bin_files/win.bin', 'rb') as win_file:
players = pickle.load(win_file)
players = players.split('_')
for i in range(len(players)):
players[i] = players[i].split('\n')
try:
while players[-1] == ['']:
players.pop()
except IndexError: # The players array might be empty
pass
return players
def write_round_delay(seconds):
with open('bin_files/round_delay.bin', 'wb') as rd_file:
pickle.dump(seconds, rd_file)
def load_round_delay():
with open('bin_files/round_delay.bin', 'rb') as rd_file:
return pickle.load(rd_file)
if __name__ == '__main__':
main()
</code></pre>
<p>image.txt:</p>
<pre><code>==============================================
|00000000000000000000000000000000000000000000|
|00001111110000111100000111111000011111110000|
|00010000000001000010001000000100010000001000|
|00100000000010000001001000000100010000000100|
|00100000000011111111001111111000010000000100|
|00100000000010000001001000001000010000000100|
|00010000000010000001001000000100010000001000|
|00001111110010000001001000000010011111110000|
|00000000000000000000000000000000000000000000|
|00000000000000000000000000000000000000000000|
|00011111100000111100001100000110011111111000|
|00100000010001000010001010001010010000000000|
|01000000000010000001001001010010010000000000|
|01000001110011111111001000100010011111110000|
|01000000010010000001001000000010010000000000|
|00100000010010000001001000000010010000000000|
|00011111100010000001001000000010011111111000|
|00000000000000000000000000000000000000000000|
==============================================
</code></pre>
<p>When you first run the program, you will need to choose the create deck option, and then load it in the load deck option. Then you can choose the play game option.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-10-10T18:11:45.080",
"Id": "396103",
"Score": "0",
"body": "I [changed the title](https://codereview.stackexchange.com/revisions/205318/2) so that it describes what the code does per [site goals](https://codereview.stackexchange.com/quest... | [
{
"body": "<p>Well, for starters, you can make your script half the size by deleting all the unneeded blank lines...</p>\n\n<p>This is actually one of the things defined in Python's official style-guide, <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">PEP8</a>:</p>\n\n<blockquo... | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-10-10T18:06:16.750",
"Id": "205318",
"Score": "6",
"Tags": [
"python",
"python-3.x",
"playing-cards"
],
"Title": "Python card game"
} | 205318 |
<p>In my intro CS class we're reviewing data structures. I'm currently working on implementing a queue using a linked list (FIFO) in C. I'd appreciate a review of the implementation as well as of my understanding of how a queue should work</p>
<pre><code>// This program is implementation of queue data structure
// via linked list (FIFO)
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct node
{
int number;
struct node *next;
} node;
node *enqueue(int element, node *temp);
node *dequeue(int n, node *temp);
void display(node *temp);
void destroy_queue(node *temp);
int main()
{
node *queue = NULL;
// add some elements to queue
for (int i = 0; i < 5; i++)
{
queue = enqueue((i + 1), queue);
}
// display queue
display(queue);
// dequeue 2 elements from queue
printf("Removing two elements from queue...\n");
queue = dequeue(2, queue);
//display queue
display(queue);
// free memory
destroy_queue(queue);
}
node *enqueue(int element, node *temp)
{
node *newElement = malloc(sizeof(node));
node *head = temp;
if (newElement == NULL)
{
fprintf(stderr, "No memory for the new queue element");
return temp;
}
newElement->number = element;
newElement->next = NULL;
if (head == NULL)
{
return newElement;
}
else
{
while ((temp->next) != NULL)
{
temp = temp->next;
}
temp->next = newElement;
}
return head;
}
node *dequeue(int n, node *temp)
{
node *aux;
for (int i = 0; i < n; i++)
{
if (!temp)
{
fprintf(stderr,"No elements to remove!");
return temp;
}
aux = temp->next;
free(temp);
temp = aux;
}
return temp;
}
void display(node *temp)
{
while (temp)
{
printf("Elements in queue are: %i\n", temp->number);
temp = temp->next;
}
}
void destroy_queue(node *temp)
{
node *aux = temp;
while (temp)
{
aux = temp->next;
free(temp);
temp = aux;
}
}
</code></pre>
| [] | [
{
"body": "<ul>\n<li><p>Having a separate <code>queue</code> structure</p>\n\n<pre><code>typedef struct {\n node * head;\n node * tail;\n} queue;\n</code></pre>\n\n<p>will bring you several benefits:</p>\n\n<ul>\n<li><p>Most important, <code>enqueue</code> would take a constant time (vs linear in queue le... | {
"AcceptedAnswerId": "205339",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-10-10T19:16:48.947",
"Id": "205323",
"Score": "5",
"Tags": [
"c",
"linked-list",
"queue"
],
"Title": "Implementing a queue using a linked-list"
} | 205323 |
<p>I did a big mistake to create procedural C++ breakout game on start and now im having trouble converting it into OOP.</p>
<p>As far as I can see I need classes: Loptica (eng. Ball), Splav (eng. Paddle), Blok (eng. Block), Logika (eng. Logic), Kolizija (eng, Collision), Level (eng. Level)</p>
<p>Definition:</p>
<pre><code>#include "SDL.h"
#include "SDL_image.h"
#include <ctime>
#include <stdlib.h>
#include <iostream>
#include <Windows.h>
#include <utility>
#include <string>
#include <vector>
#include <algorithm>
#undef main
using namespace std;
SDL_Window *ekran;
SDL_Renderer * renderer = NULL;
SDL_Texture * pozadina = NULL; //background
SDL_Texture * splav = NULL; //paddle
SDL_Texture * loptica = NULL; //ball
SDL_Texture * block01 = NULL; //1st row of blocks
SDL_Texture * block02 = NULL; //2nd row of blocks
SDL_Texture * block03 = NULL; //3rd row of blocks
SDL_Texture * blockNeprobojni = NULL; //impenetrable block
SDL_Rect rectPozadina; //background rect
SDL_Rect rectSplav; //paddle rect
SDL_Rect rectLoptica; //ball rect
SDL_Rect rectBlock01; //block01 rect
SDL_Rect rectBlock02; //block02 rect
SDL_Rect rectBlock03; //block03 rect
SDL_Rect rectBlockNeprobojni; //impenetrable rect
SDL_Event problem;
const int sirinaEkrana = 1280, visinaEkrana = 720;
//sirinaEkrana= screenWidth, visinaEkrana=screenHeight
int brojZivota = 3; //number of lives
int brojBlokova = 36; //total amount of blocks on screen
vector< pair<pair<int, int>, int > > koordinateBlokovaVektor; //array for storing coordinates and impact count on every block
bool igra = true; //bool value for while loop in int main()
int gornjiOdstoj = 20; //space between top wall and 1st row of blocks
int razmakRedova = 5; //space between blocks in a row
int razmakStupaca = 5; //space between blocks in column
int sirinaBloka = 102; //width of the block
int visinaBloka = 20; //height of the block
//sirinaSplavi = paddleWidth, visinaSplavi=paddleHeight
const int sirinaSplavi = 200, visinaSplavi = 10;
//splavPocetniX=starting point X of paddle, splavPocetniY=starting point Y of paddle
const int splavPocetniX = sirinaEkrana / 2 - 100;
const int splavPocetniY = visinaEkrana - visinaSplavi;
//sirinaLoptice= ballWidth, visinaLoptice=ballHeight
const int sirinaLoptice = 20, visinaLoptice = 20;
//lopticaPocetniX = starting point X of the ball, lopticaPocetniY = starting point Y of the ball,
const int lopticaPocetniX = sirinaEkrana / 2;
const int lopticaPocetniY = visinaEkrana / 2;
//lopticaTrenutniX =current X point of the ball, lopticaTrenutniY =current Y point of the ball
int lopticaTrenutniX = 0, lopticaTrenutniY = 0;
//level
int level = 1;
int brojRedovaBlokova = 3; //number of block rows
int brojBlokovaRed = 12; //number of blocks in a row
</code></pre>
<p>Main function:</p>
<pre><code>int main(int argc, char*args[]) {
loadGame();
while (igra)
{
SDL_PollEvent(&problem);
if (problem.type == SDL_QUIT)
igra = false;
Logika();
Crtaj();
}
Quit();
return 0;
}
</code></pre>
<p>Quit function:</p>
<pre><code>void Quit() {
SDL_Quit();
}
</code></pre>
<p>Loading a game:</p>
<pre><code>void loadGame() {
SDL_Init(SDL_INIT_EVERYTHING);
ekran = SDL_CreateWindow("Breakout", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, sirinaEkrana, visinaEkrana, SDL_WINDOW_SHOWN);
renderer = SDL_CreateRenderer(ekran, -1, 0);
pozadina = IMG_LoadTexture(renderer, "Slike/pozadina1.png");
loptica = IMG_LoadTexture(renderer,"loptica.bmp");
splav = IMG_LoadTexture(renderer, "splav.bmp");
block01 = IMG_LoadTexture(renderer, "block01.bmp");
block02 = IMG_LoadTexture(renderer, "block02.bmp");
block03 = IMG_LoadTexture(renderer, "block03.bmp");
blockNeprobojni = IMG_LoadTexture(renderer, "blockNeprobojni.bmp");
rectLoptica.x = lopticaPocetniX; rectLoptica.y =lopticaPocetniY; rectLoptica.w = sirinaLoptice; rectLoptica.h = visinaLoptice;
rectSplav.x = splavPocetniX; rectSplav.y = splavPocetniY; rectSplav.w = sirinaSplavi; rectSplav.h = visinaSplavi;
rectPozadina.x = 0; rectPozadina.y = 0; rectPozadina.w = sirinaEkrana; rectPozadina.h = visinaEkrana;
Crtaj();
srand(time(NULL));
randomPocetniSmjer();
}
</code></pre>
<p>Game logic:</p>
<pre><code>void Logika() {
#pragma region Paddle movement
const Uint8 *tipka = SDL_GetKeyboardState(NULL);
if (tipka[SDL_SCANCODE_A] && rectSplav.x > 0)
rectSplav.x--;
if (tipka[SDL_SCANCODE_D] && rectSplav.x < 1080) //1280-200(paddle width)
rectSplav.x++;
#pragma endregion
#pragma region Ball movement
rectLoptica.x += lopticaTrenutniX;
rectLoptica.y += lopticaTrenutniY;
#pragma endregion
//UPPER WALL
if (rectLoptica.y < visinaLoptice) {
lopticaTrenutniY = -lopticaTrenutniY;
}
//DOWN WALL, RESET
if (rectLoptica.y > visinaEkrana) {
Sleep(2000);
randomPocetniSmjer();
brojZivota--;
if (brojZivota == 0) {
igra = false;
}
}
//LEFT WALL
if (rectLoptica.x < sirinaLoptice) {
lopticaTrenutniX = -lopticaTrenutniX;
}
//RIGHT WALL
if (rectLoptica.x > sirinaEkrana - sirinaLoptice) {
lopticaTrenutniX = -lopticaTrenutniX;
}
//checking collision of paddle and ball
if (provjeraKolizijeSplavi(rectSplav, rectLoptica) == true) {
lopticaTrenutniY = -lopticaTrenutniY;
}
//checking collision of ball and block
int velicinaPolja = koordinateBlokovaVektor.size();
for(int i=0;i<velicinaPolja;i++) {
if (provjeraKolizijeBloka(koordinateBlokovaVektor[i].first.first, koordinateBlokovaVektor[i].first.second,koordinateBlokovaVektor[i].second, rectLoptica) == true) {
lopticaTrenutniY = -lopticaTrenutniY;
koordinateBlokovaVektor[i].first.first = -1;
koordinateBlokovaVektor[i].first.second = -1;
koordinateBlokovaVektor[i].second--;
break;
}
}
Sleep(2);
}
</code></pre>
<p>Drawing function (doesnt work as it should with deleting blocks):</p>
<pre><code>void Crtaj() {
SDL_RenderClear(renderer);
SDL_RenderCopy(renderer, pozadina, NULL, &rectPozadina);
SDL_RenderCopy(renderer, splav, NULL, &rectSplav);
SDL_RenderCopy(renderer, loptica, NULL, &rectLoptica);
SDL_SetRenderTarget(renderer, pozadina);
SDL_SetRenderTarget(renderer, loptica);
SDL_SetRenderTarget(renderer, splav);
int prviRedBrojac = 0, drugiRedBrojac = 11, treciRedBrojac = 23;
#pragma region LVL 1
for (int j = 0; j < brojBlokovaRed; j++) {
int block1X = j*sirinaBloka + j*razmakRedova, block1Y = gornjiOdstoj;
int block2X = j*sirinaBloka + j*razmakRedova, block2Y = gornjiOdstoj + visinaBloka + razmakStupaca;
int block3X = j*sirinaBloka + j*razmakRedova, block3Y = gornjiOdstoj + 2 * visinaBloka + 2 * razmakStupaca;
spremiKoordinate(block1X, block1Y,1);
if (koordinateBlokovaVektor[j].first.first != -1 && koordinateBlokovaVektor[j].first.second != -1 && koordinateBlokovaVektor[j].second != 0) {
rectBlock01 = initRectBlock(block1X, block1Y, sirinaBloka, visinaBloka);
SDL_RenderCopy(renderer, block01, NULL, &rectBlock01);
SDL_SetRenderTarget(renderer, block01);
prviRedBrojac++;
}
else {
SDL_SetRenderTarget(renderer, NULL);
}
if ((j + 1) % 3 == 0) { //if its a impenetrable block
spremiKoordinate(block2X, block2Y,-1); //store -1 if its imprenetrable
if (koordinateBlokovaVektor[j+1].first.first != -1 && koordinateBlokovaVektor[j+1].first.second != -1 && koordinateBlokovaVektor[j+1].second != 0) {
rectBlock02 = initRectBlock(block2X, block2Y, sirinaBloka, visinaBloka);
SDL_RenderCopy(renderer, blockNeprobojni, NULL, &rectBlock02);
SDL_SetRenderTarget(renderer, blockNeprobojni);
drugiRedBrojac++;
}
else {
SDL_SetRenderTarget(renderer, NULL);
}
}
else {
spremiKoordinate(block2X, block2Y,2);
if (koordinateBlokovaVektor[j+1].first.first != -1 && koordinateBlokovaVektor[j+1].first.second != -1 && koordinateBlokovaVektor[j+1].second != 0) {
rectBlock02 = initRectBlock(block2X, block2Y, sirinaBloka, visinaBloka);
SDL_RenderCopy(renderer, block02, NULL, &rectBlock02);
SDL_SetRenderTarget(renderer, block02);
drugiRedBrojac++;
}
else {
SDL_SetRenderTarget(renderer, NULL);
}
}
spremiKoordinate(block3X, block3Y, 1);
if (koordinateBlokovaVektor[j+2].first.first != -1 && koordinateBlokovaVektor[j+2].first.second != -1 && koordinateBlokovaVektor[j+2].second != 0) {
rectBlock03 = initRectBlock(block3X, block3Y, sirinaBloka, visinaBloka);
SDL_RenderCopy(renderer, block01, NULL, &rectBlock03);
SDL_SetRenderTarget(renderer, block01);
}
else {
SDL_SetRenderTarget(renderer, NULL);
}
}
#pragma endregion
SDL_SetRenderTarget(renderer, NULL);
SDL_RenderPresent(renderer);
}
</code></pre>
<p>Storing coordinates in array:</p>
<pre><code>void spremiKoordinate(int x, int y,int brojUdaraca) {
if (koordinateBlokovaVektor.size() < 36 ) {
koordinateBlokovaVektor.push_back(make_pair(make_pair(x,y), brojUdaraca));
sort(koordinateBlokovaVektor.begin(), koordinateBlokovaVektor.end());
}
}
</code></pre>
<p>Initialize SDL_Rect:</p>
<pre><code>SDL_Rect initRectBlock(int x, int y, int sirina, int visina) {
SDL_Rect blok;
blok.x = x;
blok.y = y;
blok.w = sirina;
blok.h = visina;
return blok;
}
</code></pre>
<p>Define starting direction of the ball:</p>
<pre><code>void randomPocetniSmjer() {
//reset ball
rectLoptica.x = lopticaPocetniX;
rectLoptica.y = lopticaPocetniY;
//reset paddle
rectSplav.x = splavPocetniX;
rectSplav.y = splavPocetniY;
int smjerKretanja = (rand() % 2 + 1);
int kutGibanjaX1 = -1;
int kutGibanjaY1 = 1;
switch (smjerKretanja)
{
case 1:
lopticaTrenutniX = -kutGibanjaX1;
lopticaTrenutniY = -kutGibanjaY1;
break;
case 2:
lopticaTrenutniX = kutGibanjaX1;
lopticaTrenutniY = -kutGibanjaY1;
break;
default:
break;
}
}
</code></pre>
<p>Next in code is collision:</p>
<pre><code>bool tocnaUnutarSplavi(int objektX, int objektY, SDL_Rect loptica) {
if ((objektX + sirinaSplavi >= loptica.x && objektY >= loptica.y) && (objektX <= loptica.x + visinaLoptice && objektY <= loptica.y + visinaLoptice)) {
return true;
}
else
return false;
}
bool tocnaUnutarBloka(int objektX, int objektY, SDL_Rect loptica) {
if ((objektX + sirinaBloka >= loptica.x && objektY >= loptica.y) && (objektX <= loptica.x + sirinaLoptice && objektY <= loptica.y + visinaLoptice)) {
return true;
}
else
return false;
}
bool provjeraKolizijeSplavi(SDL_Rect splav, SDL_Rect r2) {
//when ball hits paddle for direction DOWNLEFT
if (tocnaUnutarSplavi(splav.x, splav.y, r2) == true) {
cout << "KOLIZIJA: Splav[" << rectSplav.x << "," << rectSplav.y << "]" << endl;
return true;
}
//when ball hits paddle for direction DOWNRIGHT
else if (tocnaUnutarSplavi(splav.x, splav.y + splav.h, r2) == true) {
return true;
}
else
return false;
}
bool provjeraKolizijeBloka(int x, int y, int brojUdaraca, SDL_Rect r2) {
//when ball hits block from direction UPLEFT
if (tocnaUnutarBloka(x, y, r2) == true) {
return true;
}
//when ball hits block from direction UPRIGHT
else if (tocnaUnutarBloka(x, y + visinaBloka, r2) == true) {
return true;
}
else
return false;
}
</code></pre>
<p>If someone could give me some direction to start with because im just confused how to even convert it into OOP .</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-10-10T19:39:49.607",
"Id": "396141",
"Score": "0",
"body": "I don't know if it suits your needs but I made [this breakout clone](https://github.com/ThanosRestas/Breakout-SDL) using SDL in the past It's from my noob days into programming, ... | [
{
"body": "<p>This is really not that bad. Despite the variable names not being in English, I'm able to get the gist of it. Here are some useful things that I think would improve the situation.</p>\n\n<h1>Avoid Globals</h1>\n\n<p>Your first header is mainly a list of global variables. Globals are difficult to w... | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-10-10T19:20:21.067",
"Id": "205324",
"Score": "2",
"Tags": [
"c++",
"object-oriented",
"game",
"collision",
"sdl"
],
"Title": "C++ Breakout game using SDL"
} | 205324 |
<p>I'm looking for feedback on a way to avoid massive code duplication on unit tests of a generic interface. It is expected that the interface will have several dozen implementations with common constraints.</p>
<p>Consider the following simple builder interface:</p>
<pre><code>public interface IBuilder<in TInput, out TOutput>
{
TOutput Build(TInput input);
}
</code></pre>
<p>Now consider the fact that each implementation of this interface needs proper unit tests written for them, and that I always want to make sure the following rule is never violated:</p>
<blockquote>
<p>If the input is null, an <code>ArgumentNullException</code> should be thrown</p>
</blockquote>
<p>As a liskov substitution best practice, I don't want to allow implementors to "decide" if they are going to throw or not. They should always throw if it is <code>null</code>. Without code contracts, this is not possible to enforce directly on the interface though of course.</p>
<p>At the same time, I also don't want to restrict the interface to reference types. In other words, this is allowed:</p>
<pre><code>public class ValueTypeBuilder : IBuilder<DateTime, int>
{
int IBuilder<DateTime, int>.Build(DateTime input)
{
return input.Hour;
}
}
</code></pre>
<p>Notice how in this particular case, it is impossible for <code>input</code> to be <code>null</code>, as it is a value type. Throwing an <code>ArgumentNullException</code> would thus not make sense in this particular implementation, and it should not be tested for it.</p>
<p>We can also have other implementations like:</p>
<pre><code>public class ReferenceTypeBuilder : IBuilder<object, int>
{
int IBuilder<object, int>.Build(object input)
{
if (input == null)
throw new ArgumentNullException(nameof(input)));
return input.GetHashCode();
}
}
</code></pre>
<p>And a more complex example with interface dependencies:</p>
<pre><code>public class ComplexBuilder : IBuilder<object, int>
{
private readonly IHashCodeProvider hashCodeProvider;
public ComplexBuilder(IHashCodeProvider hashCodeProvider)
{
this.hashCodeProvider = hashCodeProvider;
}
int IBuilder<object, int>.Build(object input)
{
if (input == null)
throw new ArgumentNullException(nameof(input));
return this.hashCodeProvider.GetHashCode(input);
}
}
public interface IHashCodeProvider
{
int GetHashCode<T>(T instance);
}
</code></pre>
<p>With the above in mind, this is my proposal to have centralized test logic for the <code>null</code> checking exception throwing rule.</p>
<hr>
<p>First, I created a generic abstract test class:</p>
<pre><code>public abstract class CustomBuilderTestsBase<TBuilder, TInput, TOutput>
where TBuilder : IBuilder<TInput, TOutput>
where TInput : class
{
[TestMethod]
public void BuildingFromNullSourceShouldThrowArgumentNullException()
{
var builder = CreateBuilder();
Assert.ThrowsException<ArgumentNullException>(() => builder.Build(default(TInput)));
}
protected abstract TBuilder CreateBuilder();
}
</code></pre>
<p>This base class enforces the exception rule by having a single general purpose unit test that validates it. Consumers can simply inherit from it for any given builder to have the rule enforced, and can optionally add other unit tests covering the actual logic inside the builder.</p>
<p>This would be the a valid unit test class for the "complex" scenario:</p>
<pre><code>[TestClass]
public sealed class ComplexBuilderTests : CustomBuilderTestsBase<ComplexBuilder, object, int>
{
private IHashCodeProvider hashCodeProvider;
[TestInitialize]
public void Initialize()
{
hashCodeProvider = Mock.Of<IHashCodeProvider>();
}
[TestMethod]
public void ShouldReturnCorrectHashCode()
{
var input = new object();
var expectedHashCode = 10;
Mock.Get(hashCodeProvider)
.Setup(m => m.GetHashCode(input))
.Returns(expectedHashCode);
IBuilder<object, int> builder = CreateBuilder();
var actualHashCode = builder.Build(input);
Assert.AreEqual(expectedHashCode, actualHashCode);
}
protected override ComplexBuilder CreateBuilder()
{
return new ComplexBuilder(hashCodeProvider);
}
}
</code></pre>
<p><a href="https://i.stack.imgur.com/m6PiN.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/m6PiN.png" alt="Base test + specific test"></a></p>
<p>Then I realized that in a lot of cases, the builder has no dependencies, so it would make sense to provide a class that knew how to create the instances:</p>
<pre><code>public abstract class BuilderTestsBase<TBuilder, TInput, TOutput> : CustomBuilderTestsBase<TBuilder, TInput, TOutput>
where TBuilder : IBuilder<TInput, TOutput>, new()
where TInput : class
{
protected sealed override TBuilder CreateBuilder()
{
return new TBuilder();
}
}
</code></pre>
<p>Notice how this one relies on the other abstract class to share the single test, but due to the additional generic constraint, doesn't need to force consumers to override the creation method.</p>
<p>This leads to test classes like this:</p>
<pre><code>[TestClass]
public sealed class ReferenceTypeBuilderTests : BuilderTestsBase<ReferenceTypeBuilder, object, int>
{
}
</code></pre>
<hr>
<p>Now for the questions:</p>
<ol>
<li><p><strong>Redundancy in generic arguments</strong></p>
<p>To restrict the abstract classes only to "reference type inputs", I had to declare the class with 3 generic arguments: one for the builder, and the other 2 to represent the input and output. To the caller, this seems unnecessary, since you are already providing the mapper type. Do you see any way to avoid that and make callers a bit simpler?</p>
<p>I think I could add a non-generic version of <code>IBuilder</code> as a kind of marker interface to enable a generic constraint like <code>where T : IBuilder</code>, but then there would be no way of verifying that <code>TInput</code> is a reference type anymore.</p>
<p>.</p></li>
<li><p><strong>On multiple abstract classes</strong></p>
<p>To make the life of consumers a little bit easier, I added the second abstract class. That was the only way I could come up with to have the same constraints with the additional <code>new()</code> one. Unfortunately, they cannot have the same "name" (there is no such thing as "class overload" in C#), which can make it harder to discover. Do you see another option that would result in the same behavior? I'm starting to think it might not be worth it providing this second version, since in cases of a simple constructor, it is straightforward enough to override the method. Still, I was wondering if there would be a way to make this work.</p>
<p>.</p></li>
<li><p><strong><code>abstract</code> method to create the builder</strong></p>
<p>My approach was to expose an abstract method so that each inherited class is able to customize the actual creation of the object. This can lead to potentially confusing code as above, where we have a <code>TestInitialize</code> method generating the dependencies, and then these dependencies are used inside the factory method. Do you see any immediate issues on that front, or is it intuitive enough for you? Any other suggestions for a pattern on creating complex builders? I'm not a fan of using the <code>[TestInitialize]</code> myself but in that particular case it made the most sense to me. I guess I could get rid of it and create the mock inside the <code>CreateBuilder</code> method as well in that case?</p>
<p>.</p></li>
<li><p><strong><code>sealed</code> <code>CreateBuilder</code> override</strong></p>
<p>I made the overriden <code>CreateBuilder</code> method <code>sealed</code> in the class which creates the instances automatically. I felt like it would not make sense to ever want to override this method on that particular class, and <a href="https://blogs.msdn.microsoft.com/ericlippert/2004/01/22/why-are-so-many-of-the-framework-classes-sealed/" rel="nofollow noreferrer">I also tend to favor <code>sealed</code>-by-default on everything I write</a>. Do you agree with that decision, or do you see a case where it would still make sense to override the <code>CreateBuilder</code> method there?</p></li>
</ol>
<p>I'd also appreciate if you could share your general thoughts on this idea, as there is a high chance that it could be extended for any kind of generic interface with lots of implementations. Maybe you think this is too clever and you'd replicate the exact same unit test across the few dozen unit test classes?</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-10-10T21:48:40.743",
"Id": "396140",
"Score": "0",
"body": "At a quick glance, seems sane, but do you have a corresponding abstract base class for value types or will value type implementers simply use the interface?"
},
{
"Conten... | [
{
"body": "<p>I think this solution is way too complex because it requires abstract classes and inheriting from them. This is a lot to do and the simple test case does not justify this effort. Also creating instances of the builder, which is the <em>arrange</em> part could be complex too, so I doubt it's possib... | {
"AcceptedAnswerId": null,
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-10-10T19:59:07.803",
"Id": "205327",
"Score": "4",
"Tags": [
"c#",
"unit-testing",
"generics"
],
"Title": "Unit testing a generic interface: proposal to avoid test duplication for different generic types"
} | 205327 |
<p>I was recently asked the following interview question over the phone:</p>
<blockquote>
<p>Given an array of integers, produce an array whose values are the
product of every other integer excluding the current index.</p>
<p>Example:</p>
<p>[4, 3, 2, 8] -> [3*2*8, 4*2*8, 4*3*8, 4*3*2] -> [48, 64, 96, 24]</p>
</blockquote>
<p>I came up with below code:</p>
<pre><code> public static BigInteger[] calcArray(int[] input) throws Exception {
if (input == null) {
throw new IllegalArgumentException("input is null");
}
BigInteger result[] = new BigInteger[input.length];
for (int i = 0; i < input.length; i++) {
result[i] = calculateProduct(input, i);
}
return result;
}
private static BigInteger calculateProduct(int[] input, int exceptIndex) {
BigInteger result = BigInteger.ONE;
for (int i = 0; i < input.length; i++) {
if (i == exceptIndex) {
continue;
}
result = result.multiply(BigInteger.valueOf(input[i]));
}
return result;
}
</code></pre>
<p>Complexity:</p>
<pre><code>Time Complexity: O(n)
Space Complexity: O(n)
</code></pre>
<p>Is there any better or efficient way to do this apart from what I have so that complexity can be reduced?</p>
| [] | [
{
"body": "<p>The Time Complexity is indeed: <span class=\"math-container\">\\$\\mathcal{O}(n^2)\\$</span>.</p>\n\n<p>You can optimize it to <span class=\"math-container\">\\$\\mathcal{O}(n)\\$</span> by calculating the total product of all elements in the source array, and then looping over the array and divid... | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-10-10T23:00:04.030",
"Id": "205338",
"Score": "2",
"Tags": [
"java",
"algorithm"
],
"Title": "Given an array of numbers, return array of products of all other numbers"
} | 205338 |
<p>I've wrapped an imported function (a promise) and attempted to write unit tests that bring my codebase to 100% coverage.</p>
<pre><code>import { Auth } from 'aws-amplify';
import signIn from './shared';
describe('signIn', () => {
afterEach(() => {
jest.restoreAllMocks();
});
it('invokes the success callback on success', (done) => {
const mockUser = { username: 'jon', password: 'snow' };
jest
.spyOn(Auth, 'signIn')
.mockImplementation(() => Promise.resolve(mockUser));
const mockSuccessCb = (user) => {
expect(user).toBe(mockUser);
done();
};
const mockErrorCb = (err) => {
done(err);
};
signIn('jon', 'snow', mockSuccessCb, mockErrorCb);
});
it('invokes the error callback on err', (done) => {
const mockUser = { username: 'jon', password: 'snow' };
jest
.spyOn(Auth, 'signIn')
.mockImplementation(() => Promise.reject(mockUser));
const mockSuccessCb = (user) => {
expect(Auth.signIn).toHaveBeenCalledWith('jon', 'snow');
expect(user).toBe(mockUser);
done();
};
const mockErrorCb = () => {
expect(Auth.signIn).toHaveBeenCalledWith('bob', 'tom');
done();
};
signIn('bob', 'tom', mockSuccessCb, mockErrorCb);
});
});
</code></pre>
<p>Auth is the imported object that is getting wrapped. In my first test, I attempt verify a successful login by returning a resolved promise. In the second test, I reject the promise. I got my 100% coverage, but since I tell my promise how to resolve itself, I can't help but feel like I'm setting myself up for false positives. Is this a good test? How can it be improved?</p>
<p>Edit: Added the original wrapper function for detail:</p>
<pre><code>import { Auth } from 'aws-amplify';
const signIn = (
username,
password,
successCallback,
errorCallback,
) => {
Auth.signIn(username, password)
.then(user => successCallback(user))
.catch(err => errorCallback(err));
};
export default signIn;
</code></pre>
| [] | [
{
"body": "<p>I think the test is ok. Remember what you're testing is this</p>\n\n<pre><code>const signIn = (\n username,\n password,\n successCallback,\n errorCallback,\n) => {\n Auth.signIn(username, password)\n .then(user => successCallback(user))\n .catch(err => errorCallback(err));\n};\... | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-10-11T02:01:11.560",
"Id": "205341",
"Score": "6",
"Tags": [
"javascript",
"unit-testing",
"ecmascript-6",
"promise",
"mocks"
],
"Title": "Jest unit test that handles a wrapped Promise"
} | 205341 |
<p>I wrote this C++ code for Tic-tac-toe for an interview (The basic skeleton was pre-provided) and got rejected because the code was too complex and inefficient. I'm not an expert programmer so I'd like some ideas about how to better my code to make it more efficient. The code is as follows:</p>
<pre><code>#include <iostream>
const int N = 3; // Square NxN board, win with N consecutive
int board[N][N];
class TicTacToe {
public:
int MakeMove(int player, int row_location, int col_location){
if(player == 1){
if(board[row_location][col_location]==0){
board[row_location][col_location]=1;
/*std::cout << "Player: "<< player << "\nCurrent board:\n";
for(int i=0;i<N;i++){
for(int j=0;j<N;j++){
std::cout << board[i][j];
}
}*/
}
else{
std::cout<<"Invalid entry\n";
}
}
else if(player == 2){
if(board[row_location][col_location]==0){
board[row_location][col_location]=2;
/*std::cout << "Player: "<< player << "\nCurrent board:\n";
for(int i=0;i<N;i++){
for(int j=0;j<N;j++){
std::cout << board[i][j];
}
}*/
}
else{
std::cout<<"Invalid entry\n";
}
}
int result = check_board(board);
//std::cout << "\nResult of checkboard is: " << result << std::endl;
return result;
}
private:
int check_board(int board[N][N]){
bool flag = 0;
//std::cout << "\nInside checkboard function: \n";
if(flag==0)
{
for(int i=0;i<N;i++){ //Horizontal check
for(int j=1;j<N-1;j++){
if(board[i][j-1]==1 && board[i][j]==1 && board[i][j+1]==1){
return 1;
flag=1;
break;
}
else if(board[i][j-1]==2 && board[i][j]==2 && board[i][j+1]==2){
return 2;
flag=1;
break;
}
}
}
}
if(flag==0)
{
for(int j=0;j<N;j++){ //Vertical check
for(int i=1;i<N-1;i++){
if(board[i-1][j]==1 && board[i][j]==1 && board[i+1][j]==1){
return 1;
flag=1;
break;
}
else if(board[i-1][j]==2 && board[i][j]==2 && board[i+1][j]==2){
return 2;
flag=1;
break;
}
}
}
}
if(flag==0){
for(int i=1;i<N-1;i++){ //Leading diagonal check
for(int j=i;j<N-1;j++){
if(board[i-1][j-1]==1 && board[i][j]==1 && board[i+1][j+1]==1){
return 1;
flag=1;
break;
}
else if(board[i-1][j-1]==2 && board[i][j]==2 && board[i+1][j+1]==2){
return 2;
flag=1;
break;
}
}
}
}
if(flag==0){
for(int i=N-1;i>1;i--){ //Opposite diagonal check
for(int j=1;j<N-1;j++){
//std::cout<<"In opposite diagonal loop\n "<<board[i+1][j-1]<<board[i][j]<<board[i-1][j+1];
if(board[i+1][j-1]==1 && board[i][j]==1 && board[i-1][j+1]==1){
return 1;
flag=1;
break;
}
else if(board[i+1][j-1]==2 && board[i][j]==2 && board[i-1][j+1]==2){
return 2;
flag=1;
break;
}
}
}
}
return 0;
}
};
int main(int argc, char** argv) {
int result;
TicTacToe ttt;
std::cout << "Starting test!" << std::endl;
result = ttt.MakeMove(1,1,0);
result = ttt.MakeMove(1,1,1);
result = ttt.MakeMove(1,1,2);
std::cout << "Winning Player is: " << result << std::endl;
return 0;
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-10-11T02:29:31.217",
"Id": "396153",
"Score": "2",
"body": "You really should at least make the effort of properly formatting your code. There *are* tools automating that, even."
}
] | [
{
"body": "<p>I see a number of things that may help you improve your code.</p>\n\n<h2>Format your code</h2>\n\n<p>This code is messy and difficult to read. It has inconsistent indentation, and very little whitespace, making it hard to read and understand. There are abundant examples here of C++ code that is ... | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-10-11T02:12:23.660",
"Id": "205342",
"Score": "1",
"Tags": [
"c++",
"object-oriented",
"programming-challenge",
"array",
"tic-tac-toe"
],
"Title": "Tic tac toe game using C++"
} | 205342 |
<p>This question is the second follow-up of: <a href="https://codereview.stackexchange.com/q/182381/104270">Shell POSIX OpenSSL file decryption script</a></p>
<p>The first follow-up was: <a href="https://codereview.stackexchange.com/q/185367/104270">Shell POSIX OpenSSL file decryption script follow-up #1</a></p>
<p>Both of which have proven very useful and sped up my learning curve of shell scripting.</p>
<p>You should probably look at them, but as I made so many changes, I feel it is not necessary.</p>
<p>All reviews are welcome, feel free to also comment in case of minor points.</p>
<hr>
<pre><code>#!/bin/sh
###############################################################################
## OpenSSL file decryption POSIX shell script ##
## revision: 0.9 ##
## GitHub: https://git.io/fxslm ##
###############################################################################
# shellcheck disable=SC2016
# disable shellcheck information SC2016 globally for the script
# link to wiki: https://github.com/koalaman/shellcheck/wiki/SC2016
# reason: the script's main parts use constructs like that
# treat unset variables as an error when substituting
set -o nounset
# pipe will be considered successful only if all the commands involved are executed without errors
# ERROR: Illegal option -o pipefail. This likely works in Bash and alike only.
#set -o pipefail
#------------------------------------------------------------------------------
print_error_and_exit()
# expected arguments:
# $1 = exit code
# $2 = error origin (usually function name)
# $3 = error message
{
# redirect all output of this function to standard error stream
exec 1>&2
# check if exactly 3 arguments have been passed
# if not, print out an internal error without colors
if [ "${#}" -ne 3 ]
then
printf 'print_error_and_exit internal error\n\n\tWrong number of arguments has been passed: %b!\n\tExpected the following 3:\n\t\t$1 - exit code\n\t\t$2 - error origin\n\t\t$3 - error message\n\nexit code = 1\n' "${#}"
exit 1
fi
# check if the first argument is a number
# if not, print out an internal error without colors
if ! [ "${1}" -eq "${1}" ] 2> /dev/null
then
printf 'print_error_and_exit internal error\n\n\tThe first argument is not a number: %b!\n\tExpected an exit code from the script.\n\nexit code = 1\n' "${1}"
exit 1
fi
# check if we have color support
if command -v tput > /dev/null 2>&1 && tput setaf 1 > /dev/null 2>&1
then
# color definitions
readonly bold=$(tput bold)
readonly red=$(tput setaf 1)
readonly yellow=$(tput setaf 3)
readonly nocolor=$(tput sgr0)
# here we do have color support, so we highlight the error origin and the exit code
printf '%b%b\n\n\t%b%b%b\n\nexit code = %b%b\n' \
"${bold}${yellow}" "${2}" "${nocolor}" \
"${3}" \
"${bold}${red}" "${1}" "${nocolor}"
exit "${1}"
else
# here we do not have color support
printf '%b\n\n\t%b\n\nexit code = %b\n' \
"${2}" "${3}" "${1}"
exit "${1}"
fi
}
#------------------------------------------------------------------------------
# in this function, the SC2120 warning is irrelevant and safe to ignore
# link to wiki: https://github.com/koalaman/shellcheck/wiki/SC2120
# shellcheck disable=SC2120
am_i_root()
# expected arguments: none
{
# check if no argument has been passed
[ "${#}" -eq 0 ] || print_error_and_exit 1 "am_i_root" "Some arguments have been passed to the function!\\n\\tNo arguments expected.\\n\\tPassed: ${*}"
# check if the user is root
# this will return an exit code of the command itself directly
[ "$(id -u)" -eq 0 ]
}
# check if the user had by any chance run the script with root privileges
# if you need to run it as root, feel free to comment out the line below
# in this function call, the SC2119 information is irrelevant and safe to ignore
# link to wiki: https://github.com/koalaman/shellcheck/wiki/SC2119
# shellcheck disable=SC2119
am_i_root && print_error_and_exit 1 "am_i_root" "Running this script with root privileges is discouraged!\\n\\tQuiting to shell."
#------------------------------------------------------------------------------
check_for_prerequisite()
# expected arguments:
# $1 = command / program name
{
# check if exactly one argument has been passed
[ "${#}" -eq 1 ] || print_error_and_exit 1 "check_for_prerequisite" "Exactly one argument has not been passed to the function!\\n\\tOne command to test expected.\\n\\tPassed: ${*}"
# check if the argument is a program which is installed
command -v "${1}" > /dev/null 2>&1 || print_error_and_exit 1 "check_for_prerequisite" "This script requires '${1}' but it is not installed or available on this system!\\n\\tPlease install the corresponding package manually."
}
check_for_prerequisite 'openssl'
check_for_prerequisite 'pv'
check_for_prerequisite 'file'
check_for_prerequisite 'grep'
#------------------------------------------------------------------------------
is_number()
# expected arguments:
# $1 = variable or literal
{
# check if exactly one argument has been passed
[ "${#}" -eq 1 ] || print_error_and_exit 1 "is_number" "Exactly one argument has not been passed to the function!\\n\\tOne variable or literal to test expected.\\n\\tPassed: ${*}"
# check if the argument is an integer number
# this will return an exit code of the command itself directly
[ "${1}" -eq "${1}" ] 2> /dev/null
}
#------------------------------------------------------------------------------
print_usage_and_exit()
{
# check if exactly one argument has been passed
[ "${#}" -eq 1 ] || print_error_and_exit 1 "print_usage_and_exit" "Exactly one argument has not been passed to the function!\\n\\tPassed: ${*}"
# check if the argument is a number
is_number "${1}" || print_error_and_exit 1 "print_usage_and_exit" "The argument is not a number!\\n\\Expected an exit code from the script.\\n\\tPassed: ${1}"
# in case of non-zero exit code given, redirect all output to stderr
[ "${1}" -ne 0 ] && exec 1>&2
echo "Usage: ${0} [-o directory] file"
echo
echo " -o directory: Write the output file into the given directory;"
echo " Optional and must be given before the file."
echo
echo " file: Regular file to decrypt."
exit "${1}"
}
#------------------------------------------------------------------------------
given_output_directory=
while getopts ":ho:" option
do
case "${option}" in
o)
given_output_directory="${OPTARG}"
;;
h)
print_usage_and_exit 0
;;
*)
print_usage_and_exit 1
;;
esac
done
shift $(( OPTIND - 1 ))
#------------------------------------------------------------------------------
[ "${#}" -eq 0 ] && print_usage_and_exit 1
#------------------------------------------------------------------------------
[ "${#}" -gt 1 ] && print_error_and_exit 1 '[ "${#}" -gt 1 ]' "You have passed ${#} arguments to the script!\\n\\tOnly one file expected.\\n\\tPassed: ${*}"
#------------------------------------------------------------------------------
[ -f "${1}" ] || print_error_and_exit 1 '[ -f "${1}" ]' "The given argument is not an existing regular file!\\n\\tPassed: ${1}"
#------------------------------------------------------------------------------
input_file="${1}"
[ -r "${input_file}" ] || print_error_and_exit 1 '[ -r "${input_file}" ]' "Input file is not readable by you!\\n\\tPassed: ${input_file}"
#------------------------------------------------------------------------------
is_file_encrypted_using_openssl()
{
# check if exactly one argument has been passed
[ "${#}" -eq 1 ] || print_error_and_exit 1 "is_file_encrypted_using_openssl" "Exactly one argument has not been passed to the function!\\n\\tPassed: ${*}"
# check if the argument is a file
[ -f "${1}" ] || print_error_and_exit 1 "is_file_encrypted_using_openssl" "The provided argument is not a regular file!\\n\\tPassed: ${1}"
# check if the provided file has been encrypted using openssl
# this will return an exit code of the command itself directly
file "${1}" | grep --ignore-case 'openssl' > /dev/null 2>&1
}
is_file_encrypted_using_openssl "${input_file}" || print_error_and_exit 1 "is_file_encrypted_using_openssl" "Input file does not seem to have been encrypted using OpenSSL!\\n\\tPassed: ${input_file}"
#------------------------------------------------------------------------------
# parameter substitution with - modifier will cause the output_directory
# variable to to get dirname ... in case given_output_directory is empty
output_directory="${given_output_directory:-$(dirname "${input_file}")}"
[ -d "${output_directory}" ] || print_error_and_exit 1 '[ -d "${output_directory}" ]' "Destination:\\n\\t\\t${output_directory}\\n\\tis not a directory!"
[ -w "${output_directory}" ] || print_error_and_exit 1 '[ -w "${output_directory}" ]' "Destination directory:\\n\\t\\t${output_directory}\\n\\tis not writable by you!"
#------------------------------------------------------------------------------
filename_extracted_from_path=$(basename "${input_file}")
filename_without_enc_extension="${filename_extracted_from_path%.enc}"
if [ "${filename_extracted_from_path}" = "${filename_without_enc_extension}" ]
then
# the file has a different than .enc extension or no extension at all
# what we do now, is that we append .dec extention to the file name
output_file="${output_directory}/${filename_extracted_from_path}.dec"
else
# the file has the .enc extension
# what we do now, is that we use the file name without .enc extension
output_file="${output_directory}/${filename_without_enc_extension}"
fi
#------------------------------------------------------------------------------
# -e FILE: True if file exists. Any type of file!
[ -e "${output_file}" ] && print_error_and_exit 1 '[ -e "${output_file}" ]' "Destination file:\\n\\t\\t${output_file}\\n\\talready exists!"
#------------------------------------------------------------------------------
# here comes the core part - decryption of the given file
if ! pv --wait "${input_file}" | openssl enc -aes-256-cbc -md sha256 -salt -out "${output_file}" -d 2> /dev/null
then
[ -f "${output_file}" ] && rm "${output_file}"
echo
print_error_and_exit 1 'pv --wait "${input_file}" | openssl enc -aes-256-cbc -md sha256 -salt -out "${output_file}" -d' "Decryption failed!"
else
echo
echo "Decryption successful."
# scripts exit with 0 exit code by default, in case of success,
# so this just more explicit for readers
exit 0
fi
</code></pre>
<hr>
<p>The project is uploaded on GitHub: <a href="https://git.io/fxslm" rel="nofollow noreferrer">https://git.io/fxslm</a></p>
<p>But not this revision. I will learn from answers and make the first release afterwards.</p>
<hr>
<h2>EDIT1</h2>
<p>I now realized I should check for free space, so I added this:</p>
<pre><code>file_size=$(du --bytes "${input_file}" | awk '{ print $1 }')
free_space=$(df "${output_directory}" | tail --lines=1 | awk '{ print $4 }')
[ "${free_space}" -gt "${file_size}" ] || print_error_and_exit 1 '[ "${free_space}" -gt "${file_size}" ]' "There is not enough free space in the destination directory!\\n\\t\\tFile size: ${file_size}\\n\\t\\tFree space: ${free_space}"
</code></pre>
<hr>
<h2>EDIT2</h2>
<p>I have fixed an issue with getting free space in bytes by adding <code>-B1</code> to <code>df</code>:</p>
<pre><code>free_space=$(df -B1 "${output_directory}" | tail --lines=1 | awk '{ print $4 }')
</code></pre>
| [] | [
{
"body": "<h1>POSIX</h1>\n\n<p>The script is a strange mixture of POSIX and non-POSIX. On the one hand, <code>openssl</code> definitely isn't POSIX, but it's essential since that's what the entire script is about. On the other hand, many of the options used here for POSIX utilities aren't standard, and <code>p... | {
"AcceptedAnswerId": "205579",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-10-11T05:03:46.950",
"Id": "205348",
"Score": "0",
"Tags": [
"linux",
"aes",
"sh",
"posix",
"openssl"
],
"Title": "Shell POSIX OpenSSL file decryption script follow-up #2"
} | 205348 |
<p>This program is an implementation of the classic puzzle <a href="http://www.towerofhanoi.org/" rel="noreferrer">Tower of Hanoi</a>! This is my first mostly recursive Assembly program. Any advice and all topical comments on code optimization and conventions is appreciated!</p>
<hr>
<p>Compiled as follows using <code>VS2017 x64 Native Tools Command Prompt</code>:</p>
<blockquote>
<pre><code>> nasm -g -fwin64 hanoi.asm
> cl /Zi hanoi.obj msvcrt.lib legacy_stdio_definitions.lib
</code></pre>
</blockquote>
<p><strong>hanoi.asm</strong></p>
<pre><code>;; bits 64
default rel
extern printf, scanf
section .text
global main
global hanoi
main:
sub rsp, 56
lea rcx, [prompt]
call printf
lea rdx, [rsp+32]
lea rcx, [scan_fmt]
call scanf
cmp eax, 1
jz .call_hanoi
lea rcx, [scan_fail]
call printf
mov eax, 1 ; return 1
.end:
add rsp, 56
ret
.call_hanoi:
mov ecx, dword [rsp+32] ; ecx = num_disks
mov r9d, 3 ; r9d = tmp
mov r8d, 2 ; r8d = dst
mov edx, 1 ; edx = src
call hanoi ; hanoi(num_disks, src, dst, tmp)
xor eax, eax ; return 0
jmp .end
hanoi:
push r12
mov r12d, r8d ; r12d = r8d = dst
push rbp
push rdi
push rsi
mov esi, edx ; esi = edx = src
push rbx
sub rsp, 40
cmp ecx, 1 ; if num_disks == 1
jz .skip_recursive_move
mov ebx, ecx
mov edi, r9d ; edi = r9d = tmp
.move_disk:
lea ebp, [rbx-1H] ; ebp = num_disks - 1
mov r9d, r12d ; r9d = r12d = dst
mov r8d, edi ; r8d = edi = tmp
mov edx, esi ; edx = esi = src
mov ecx, ebp ; ecx = edp = num_disks - 1
call hanoi ; tmp & dst are swapped for this call
mov edx, ebx ; edx = ebx = num_disks
mov r9d, r12d ; update r9d after hanoi call
mov r8d, esi ; update r8d after hanoi call
lea rcx, [prompt_move_disk]
mov ebx, ebp ; ebx = ebp = num_disks - 1
call printf
cmp ebp, 1 ; if num_disks == 1
jz .move_one_disk
mov eax, esi
mov esi, edi
mov edi, eax ; swaps tmp and src (esi and edi)
jmp .move_disk
.skip_recursive_move:
mov edi, edx ; edi = edx = src
.move_one_disk:
add rsp, 40
mov r8d, r12d
mov edx, edi
pop rbx
lea rcx, [prompt_move_one_disk]
pop rsi
pop rdi
pop rbp
pop r12
jmp printf
%macro str 2
%2: db %1, 0
%endmacro
section .rdata
str "How many disks do you want to play with? ", prompt
str "%u", scan_fmt
str {"Uh-oh, I couldn't understand that... No towers of Hanoi for you!", 10}, scan_fail
str {"Move disk 1 from %d to %d", 10}, prompt_move_one_disk
str {"Move disk %d from %d to %d", 10}, prompt_move_disk
</code></pre>
<p><strong>Sample output</strong></p>
<img src="https://i.imgur.com/lL9np1r.png"/></p>
| [] | [
{
"body": "\n\n<h2>Observations.</h2>\n\n<blockquote>\n<pre class=\"lang-none prettyprint-override\"><code>Move disk 1 from 1 to 3\nMove disk 2 from 1 to 2\n</code></pre>\n</blockquote>\n\n<p>I think these messages would be more descriptive (less ambiguous) if you included the word <em>peg</em>:</p>\n\n<p><em>M... | {
"AcceptedAnswerId": "205996",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-10-11T05:07:09.293",
"Id": "205350",
"Score": "7",
"Tags": [
"game",
"recursion",
"windows",
"assembly",
"nasm"
],
"Title": "Tower of Hanoi in NASM Win64 Assembly"
} | 205350 |
<p>Made a project to generate TypeScript classes from database tables, and I'm looking for input if the code is reasonable. <code>pg</code> and <code>mysql</code> are not hard dependencies - that's why they're <code>@ts-ignore</code>d.</p>
<p>This would be my first package to be published in npm.</p>
<p>Goals were to have as little as possible dependencies and maximum flexibility. I'm planning to add support for callback mutators to different parts of the generator.</p>
<pre><code>import {parse as urlParse} from 'url';
export enum DialectType
{
PostgreSQL = 'postgres',
MySQL = 'mysql'
}
enum ForceCase
{
None = 'none',
Camel = 'camel',
Snake = 'snake',
Pascal = 'pascal',
}
export interface Options
{
excludeTables?: Array<string>
schema?: string
extends?: string | object
dialect?: DialectType
exportKeyword?: string
attribute?: string
indent?: string
forceMemberCase?: ForceCase
forceTypeCase?: ForceCase
prepend?: string
append?: string
lineFeed?: string
header?: boolean
connectionData?: ConnectionData
additional_info: any
}
let defaultOptions =
{
excludeTables: [],
schema: 'public',
extends: '',
dialect: DialectType.PostgreSQL,
exportKeyword: 'class',
attribute: '',
indent: ' ',
forceMemberCase: ForceCase.None,
forceTypeCase: ForceCase.None,
prepend: '',
append: '',
lineFeed: '\n',
header: true,
additional_info: {},
} as Options;
export interface Column
{
name: string
type: string
nullable: boolean
}
export interface Table
{
name: string
columns: Array<Column>
}
export interface ConnectionDataObject
{
user?: string;
database?: string;
password?: string;
port?: number;
host?: string;
connectionString?: string;
}
type ConnectionData = string | ConnectionDataObject;
type DBColumn = { column_name, data_type, is_nullable };
type ITransformColumn = ((column: DBColumn) => Column);
type QueryResult = { rows: Array<any>, error: any };
interface IClient
{
query: ((string) => Promise<QueryResult>)
options: Options
}
class Dialect
{
connectionData: ConnectionData;
options: Options;
constructor(connectionData, options)
{
this.connectionData = connectionData;
this.options = options;
}
protected client: IClient;
protected real_client: any;
//abstract transformColumn(column: DBColumn): Column;
getClient(): Promise<IClient>
{
return null;
}
getMapping(): { [type: string]: Array<string>; }
{
return null
}
mapColumn(column_type: string): string
{
let type = 'any';
let mapping = this.getMapping();
for (let t in mapping)
{
if ((mapping[t] as Array<string>).indexOf(column_type) !== -1)
{
type = t;
break;
}
}
return type;
}
transformColumn(column: DBColumn): Column
{
let name = column.column_name;
name = Generator.camelCase(name);
return {
name: name,
type: this.mapColumn(column.data_type),
nullable: column.is_nullable === 'YES',
}
}
async getTableNames()
{
let client = await this.getClient();
return (await client.query(`
select distinct table_name
from information_schema.columns
where table_schema = '${this.options.schema}'
`)).rows.map(row => row.table_name);
};
}
export class PostgresDialect extends Dialect
{
async getClient()
{
if (this.client) return this.client;
// @ts-ignore
let pg = await import('pg');
let client = this.real_client = new pg.Client(this.connectionData);
await client.connect();
this.options.additional_info.ip = (client as any).connection.stream.remoteAddress;
return this.client = {
async query(statement)
{
let res = (await client.query(statement));
return {
rows: res.rows,
error: res.errno
};
}
} as IClient;
}
getMapping()
{
return {
number: ['int2', 'int4', 'int8', 'float4', 'float8', 'numeric', 'money', 'oid'],
string: ['bpchar', 'char', 'varchar', 'text', 'citext', 'uuid', 'bytea', 'inet', 'time', 'timetz', 'interval', 'name'],
boolean: ['bool'],
Object: ['json', 'jsonb'],
Date: ['date', 'timestamp', 'timestampz'],
};
}
}
export class MySQLDialect extends Dialect
{
async getClient()
{
if (this.client) return this.client;
// @ts-ignore
let mysql = await import('mysql');
let client = mysql.createConnection(this.connectionData);
await new Promise<void>( resolve => { client.connect(resolve) });
this.options.additional_info.ip = (client as any)._socket.remoteAddress;
let query = function promise_query(q) {
return new Promise((resolve) => {
client.query(q, ((err, results) => {
resolve({
rows: results,
error: err
})
}))
})
};
if (typeof this.connectionData === 'string')
{
this.options.schema = urlParse(this.connectionData).pathname.substr(1)
}
return this.client = {
query: query
} as IClient;
}
getMapping()
{
return {
number: ['integer', 'int', 'smallint', 'mediumint', 'bigint', 'double', 'decimal', 'numeric', 'float', 'year'],
string: ['char', 'varchar', 'text', 'tinytext', 'mediumtext', 'longtext', 'time', 'geometry', 'set', 'enum'],
boolean: ['tinyint'],
Object: ['json'],
Date: ['date', 'datetime', 'timestamp'],
Buffer: ['tinyblob', 'mediumblob', 'longblob', 'blob', 'binary', 'varbinary', 'bit'],
};
}
}
class Generator
{
protected static indent = ' ';
options: Options;
constructor(options: Options)
{
this.options = options;
}
static camelCase(text: string)
{
return text.split(/[^a-z]/i).filter(x => x).map( (v, i) => {
return i ? v.charAt(0).toUpperCase() + v.substr(1) : v;
}).join('');
}
protected getHost()
{
if(this.options.connectionData)
{
if(typeof this.options.connectionData === 'string')
{
return urlParse(this.options.connectionData).host
}
else
{
return this.options.connectionData.host;
}
}
return '';
}
generateType(column: Column)
{
return column.type + (column.nullable ? ' | null' : '');
}
generateClass(table: Table)
{
let o = this.options;
let lf = o.lineFeed;
let output = '';
let inheritance = o.extends ? ` extends ${o.extends}` : '';
let attribute = o.attribute ? o.indent + o.attribute + lf : '';
output += `export ${this.options.exportKeyword} ${table.name}${inheritance}${lf}{${lf}`;
table.columns.map(column => {
output += attribute;
output += `${o.indent}${column.name}: ${this.generateType(column)};${lf}`;
});
output += '}';
return output;
}
generateTables(tables: Table[])
{
let o = this.options;
let lf = o.lineFeed;
let lflf = lf + lf;
let output = '';
if(o.header)
{
let cleanOptions = Object.assign({}, o);
delete cleanOptions['connectionData'];
let header = [
`Generated on ${(new Date()).toISOString()}`,
'Host: ' + this.getHost(),
//'Tables: ' + tables.map(t => t.name).join(', '),
'Options used:'
].concat(JSON.stringify(cleanOptions, null, o.indent).replace('*/', '*//*').split('\n'));
output += '/**\n * ' + header.join(lf + ' * ') + lf + ' * ' + lf + ' */' + lflf;
}
if(o.prepend)
{
output += o.prepend + lflf;
}
output += tables.map(table => this.generateClass(table)).join(lflf);
if(o.append)
{
output += lflf + o.append;
}
return output;
}
}
export async function grease(connectionString: string | ConnectionData, options: Options = null, generatorClass: typeof Generator = Generator)
{
options = Object.assign(defaultOptions, options || {});
let CurrentDialect: typeof Dialect;
switch (options.dialect)
{
case DialectType.PostgreSQL:
CurrentDialect = PostgresDialect;
break;
case DialectType.MySQL:
CurrentDialect = MySQLDialect;
break;
default:
throw new Error('No dialect specified');
}
let dialect = new CurrentDialect(connectionString, options);
let client = await dialect.getClient();
async function columns(table: string)
{
if (options.dialect == DialectType.MySQL)
{
return (await client.query(`
select column_name, data_type, is_nullable
from information_schema.columns
where table_schema = '${options.schema}' and table_name = '${table}'
`));
}
else
{
return (await client.query(`
select column_name, udt_name as data_type, is_nullable
from information_schema.columns
where table_schema = '${options.schema}' and table_name = '${table}'
`));
}
}
let table_names = await dialect.getTableNames();
let table_promises = [];
let tables: any = [];
for (let i in table_names)
{
let promise = columns(table_names[i]);
table_promises.push(promise);
promise.then(result => {
tables.push({
name: table_names[i],
raw_columns: (result.rows as Array<DBColumn>),
columns: (result.rows as Array<DBColumn>).map(col => dialect.transformColumn(col))
})
});
}
await Promise.all(table_promises);
let generator = new generatorClass(options);
let all = generator.generateTables(tables);
return all;
}
</code></pre>
<p>Used like this:</p>
<pre><code>#! /usr/bin/env node
import {parse as urlParse} from 'url';
import {grease} from "../src/elbowgrease";
import * as fs from 'fs'
let connectionData = process.argv.slice(-2, -1)[0];
let output = process.argv.slice(-1)[0];
let args = process.argv.slice(2, -2);
let options = {} as any;
let config = 'elbowgrease.json';
args.map(arg => {
let option = /--([a-zA-Z]+)=(.*)/.exec(arg);
if (option[1] === 'config')
{
config = option[2];
}
else
{
options[option[1]] = option[2];
}
});
if (fs.existsSync(config))
{
options = Object.assign(JSON.parse(fs.readFileSync(config, 'utf8')), options);
}
if('connectionData' in options)
{
connectionData = options.connectionData;
}
if('output' in options)
{
output = options.output;
}
if(typeof connectionData === 'string')
{
options.dialect = urlParse(connectionData).protocol.slice(0,-1);
}
grease(connectionData, options).then(outputCode => {
fs.writeFileSync(output, outputCode);
process.exit();
});
</code></pre>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-10-11T06:07:36.633",
"Id": "205352",
"Score": "4",
"Tags": [
"mysql",
"node.js",
"typescript",
"postgresql"
],
"Title": "Automatically generate TypeScript classes from database tables"
} | 205352 |
<p>Part 2: <a href="https://codereview.stackexchange.com/q/205355/507">JSON Test Harness: Part 2</a><br>
Part 3: <a href="https://codereview.stackexchange.com/q/205356/507">JSON Test Harness: Part 3</a><br>
Part 4: <a href="https://codereview.stackexchange.com/q/205357/507">JSON Test Harness: Part 4</a> </p>
<p>Time to review some test harness code I have written.</p>
<p><a href="https://github.com/Loki-Astari/JsonBenchmark" rel="nofollow noreferrer">https://github.com/Loki-Astari/JsonBenchmark</a></p>
<p>I wrote a C++ JSON parser/serializer and wanted to compare performance against other JSON parsers. This was originally written by somebody else (credit were credit is due (see README)) but has been highly modified to use better C++ idioms (I hope).</p>
<p>This review is for the test harness than handles all the different JSON parsers. Each implementation of a test harness (one for each JSON parser) is supposed to:</p>
<ul>
<li>include <code>test.h</code> and derive their own class from of <code>TestBase</code> implementing the virtual functions.</li>
<li>In their own source declare <code>REGISTER_TEST(<YourClass>);</code> to create an instance of an object of their class.</li>
<li>In test.cpp add <code>REGISTER_TEST_OBJECT(<YourClass>);</code> to link it together.</li>
</ul>
<p><a href="https://github.com/Loki-Astari/JsonBenchmark/tree/master/src/ThirdParty" rel="nofollow noreferrer">https://github.com/Loki-Astari/JsonBenchmark/tree/master/src/ThirdParty</a></p>
<h3>TestManager.h</h3>
<pre><code>#ifndef THORS_ANVIL_BENCHMARK_TEST_MANAGER_H
#define THORS_ANVIL_BENCHMARK_TEST_MANAGER_H
#include <vector>
#include <string.h>
#include <tuple>
#include <algorithm>
class TestBase;
using ParsrList = std::vector<const TestBase*>;
class TestManager
{
public:
static TestManager& instance();
void addTest(const TestBase* test);
const ParsrList& getTests() const;
private:
ParsrList mTests;
};
#endif
</code></pre>
<h3>TestManager.cpp</h3>
<pre><code>#include "TestManager.h"
#include <memory>
TestManager& TestManager::instance()
{
static TestManager singleton;
return singleton;
}
void TestManager::addTest(const TestBase* test)
{
mTests.push_back(test);
}
const ParsrList& TestManager::getTests() const
{
return mTests;
}
</code></pre>
<h3>test.h</h3>
<pre><code>#ifndef THORS_ANVIL_BENCHMARK_TEST_H
#define THORS_ANVIL_BENCHMARK_TEST_H
#include <cstddef>
#include <string>
class ParseResultBase
{
public:
virtual ~ParseResultBase() {}
};
class StringResultBase
{
public:
virtual ~StringResultBase() {}
virtual const char* c_str() const = 0;
};
struct Stat
{
std::size_t objectCount;
std::size_t arrayCount;
std::size_t numberCount;
std::size_t stringCount;
std::size_t trueCount;
std::size_t falseCount;
std::size_t nullCount;
std::size_t memberCount; // Number of members in all objects
std::size_t elementCount; // Number of elements in all arrays
std::size_t stringLength; // Number of code units in all strings
bool operator==(Stat const& rhs) const;
bool operator!=(Stat const& rhs) const;
};
class TestBase
{
public:
virtual ~TestBase() {}
bool operator<(const TestBase& rhs) const;
virtual const char* GetName() const = 0;
virtual const char* GetFilename() const = 0;
// For each operation, call SetUp() before and TearDown() after.
// It is mainly for libraries require huge initialize time (e.g. Creating Isolate in V8).
virtual void SetUp() const {}
virtual void TearDown() const {}
virtual void SetUp(char const*) const {SetUp();}
virtual void TearDown(char const*) const {TearDown();}
virtual bool ParseDouble(const char* /*json*/, double* /*d*/) const { return false; }
virtual bool ParseString(const char* /*json*/, std::string& /*s*/) const { return false; }
virtual ParseResultBase* Parse(const char* /*json*/, std::size_t /*length*/) const { return nullptr; }
virtual StringResultBase* Stringify(const ParseResultBase* /*parseResult*/) const { return nullptr; }
virtual StringResultBase* Prettify(const ParseResultBase* /*parseResult*/) const { return nullptr; }
virtual StringResultBase* SaxRoundtrip(const char* /*json*/, std::size_t /*length*/) const { return nullptr; }
virtual bool Statistics(const ParseResultBase* /*parseResult*/, Stat* /*stat*/) const { return false; }
virtual bool SaxStatistics(const char* /*json*/, std::size_t /*length*/, Stat* /*stat*/) const { return false; }
virtual bool SaxStatisticsUTF16(const char* /*json*/, std::size_t /*length*/, Stat* /*stat*/) const { return false; }
};
#define REGISTER_TEST(cls) std::unique_ptr<TestBase> get ## cls() { return std::make_unique<cls>(); }static_assert(true)
#endif
</code></pre>
<h3>test.cpp</h3>
<pre><code>#include "test.h"
#include "TestManager.h"
#include <memory>
bool Stat::operator!=(Stat const& rhs) const
{
return !operator==(rhs);
}
bool TestBase::operator<(const TestBase& rhs) const
{
return strcmp(GetName(), rhs.GetName()) < 0;
}
bool Stat::operator==(Stat const& rhs) const
{
return std::forward_as_tuple(objectCount, arrayCount, numberCount,
stringCount, trueCount, falseCount,
nullCount, memberCount, elementCount,
stringLength)
==
std::forward_as_tuple(rhs.objectCount, rhs.arrayCount, rhs.numberCount,
rhs.stringCount, rhs.trueCount, rhs.falseCount,
rhs.nullCount, rhs.memberCount, rhs.elementCount,
rhs.stringLength);
}
class TestRunner: public TestBase
{
std::unique_ptr<TestBase> pimpl;
public:
TestRunner(std::unique_ptr<TestBase>&& src)
: pimpl(std::move(src))
{
TestManager::instance().addTest(this);
}
virtual const char* GetName() const override {return pimpl->GetName();}
virtual const char* GetFilename() const override {return pimpl->GetFilename();}
virtual void SetUp(char const* test) const override {return pimpl->SetUp(test);}
virtual void TearDown(char const* test) const override {return pimpl->TearDown(test);}
virtual bool ParseDouble(const char* json, double* d) const override {return pimpl->ParseDouble(json, d);}
virtual bool ParseString(const char* json, std::string& s) const override {return pimpl->ParseString(json, s);}
virtual ParseResultBase* Parse(const char* json, size_t length) const override {return pimpl->Parse(json, length);}
virtual StringResultBase* Stringify(const ParseResultBase* parseResult) const override {return pimpl->Stringify(parseResult);}
virtual StringResultBase* Prettify(const ParseResultBase* parseResult) const override {return pimpl->Prettify(parseResult);}
virtual StringResultBase* SaxRoundtrip(const char* json, size_t length) const override {return pimpl->SaxRoundtrip(json, length);}
virtual bool Statistics(const ParseResultBase* parseResult, Stat* stat) const override {return pimpl->Statistics(parseResult, stat);}
virtual bool SaxStatistics(const char* json, size_t length, Stat* stat) const override {return pimpl->SaxStatistics(json, length, stat);}
virtual bool SaxStatisticsUTF16(const char* json, size_t length, Stat* stat) const override {return pimpl->SaxStatisticsUTF16(json, length, stat);}
};
#define REGISTER_TEST_OBJECT(cls) std::unique_ptr<TestBase> get ## cls();TestRunner gRegister ## cls(get ## cls())
REGISTER_TEST_OBJECT(ThorsSerializerTest);
REGISTER_TEST_OBJECT(ArduinojsonTest);
REGISTER_TEST_OBJECT(CajunTest);
REGISTER_TEST_OBJECT(ConfiguruTest);
REGISTER_TEST_OBJECT(FastjsonTest);
REGISTER_TEST_OBJECT(JeayesonTest);
REGISTER_TEST_OBJECT(JsonboxTest);
REGISTER_TEST_OBJECT(JsonconsTest);
REGISTER_TEST_OBJECT(JsoncppTest);
REGISTER_TEST_OBJECT(VoorheesTest);
REGISTER_TEST_OBJECT(JsonxxTest);
REGISTER_TEST_OBJECT(JvarTest);
REGISTER_TEST_OBJECT(JzonTest);
REGISTER_TEST_OBJECT(NlohmannTest);
REGISTER_TEST_OBJECT(PicojsonTest);
REGISTER_TEST_OBJECT(RapidjsonTest);
REGISTER_TEST_OBJECT(RapidjsonFullPrecTest);
REGISTER_TEST_OBJECT(RapidjsonInsituTest);
REGISTER_TEST_OBJECT(RapidjsonIterativeTest);
REGISTER_TEST_OBJECT(RapidjsonAutoUTFTest);
REGISTER_TEST_OBJECT(GasonTest);
REGISTER_TEST_OBJECT(SajsonTest);
REGISTER_TEST_OBJECT(UjsonTest);
REGISTER_TEST_OBJECT(Ujson4cTest);
REGISTER_TEST_OBJECT(PJsonTest);
REGISTER_TEST_OBJECT(UdbTest);
REGISTER_TEST_OBJECT(JusonTest);
REGISTER_TEST_OBJECT(CcanTest);
REGISTER_TEST_OBJECT(CjsonTest);
REGISTER_TEST_OBJECT(VinenthzTest);
REGISTER_TEST_OBJECT(YajlTest);
REGISTER_TEST_OBJECT(JsoncTest);
REGISTER_TEST_OBJECT(JsmnTest);
</code></pre>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-10-11T06:31:36.620",
"Id": "205353",
"Score": "4",
"Tags": [
"c++",
"json",
"integration-testing"
],
"Title": "JSON Test Harness: Part 1"
} | 205353 |
<p>Part 1: <a href="https://codereview.stackexchange.com/q/205353/507">JSON Test Harness: Part 1</a><br>
Part 3: <a href="https://codereview.stackexchange.com/q/205356/507">JSON Test Harness: Part 3</a><br>
Part 4: <a href="https://codereview.stackexchange.com/q/205357/507">JSON Test Harness: Part 4</a> </p>
<p>Time to review some test harness code I have written.</p>
<p><a href="https://github.com/Loki-Astari/JsonBenchmark" rel="nofollow noreferrer">https://github.com/Loki-Astari/JsonBenchmark</a></p>
<p>I wrote a C++ JSON parser/serializer and wanted to compare performance against other JSON parsers. This was originally written by somebody else (credit were credit is due (see README)) but has been highly modified to use better C++ idioms (I hope).</p>
<p>This review is for the test suite. I tried to design this so others could easily add new tests to the existing test suites and also add additional test suites.</p>
<p><a href="https://github.com/Loki-Astari/JsonBenchmark/tree/master/src/benchmark" rel="nofollow noreferrer">https://github.com/Loki-Astari/JsonBenchmark/tree/master/src/benchmark</a></p>
<h3>TestSuite.h</h3>
<pre><code>#ifndef THORS_ANVIL_BENCHMARK_BENCHMARK_H
#define THORS_ANVIL_BENCHMARK_BENCHMARK_H
#include "filesystem.h"
#include "ThirdParty/test.h"
#include "ThirdParty/TestManager.h"
#include <string>
#include <vector>
#include <fstream>
namespace ThorsAnvil
{
namespace Benchmark
{
struct Options
{
std::string testFilter =R"([^/]*/[^/]*)";
std::string parserFilter = "";
std::ofstream conformance;
std::ofstream performance;
};
class Test
{
public:
FileSystem::Path path;
std::string input;
std::string output;
Test(FileSystem::Path const& path);
void clear();
friend std::ostream& operator<<(std::ostream& str, Test const& test);
};
enum State {NotImplemented, Pass, Fail};
class TestSetUp
{
TestBase const& parser;
std::string name;
bool callFuncs;
public:
TestSetUp(TestBase const& parser, std::string const& name, bool callFuncs);
~TestSetUp();
};
class TestSuite
{
using Cont = std::vector<Test>;
protected:
Options& options;
Cont tests;
public:
TestSuite(Options& options);
void executeTestOnAllParsers(ParsrList const& parsrList);
virtual void executeTest(TestBase const& parser);
virtual State executeTest(TestBase const& parser, Test const& test) = 0;
/* Interface for the range based for() */
using iterator = Cont::iterator;
iterator begin() {return tests.begin();}
iterator end() {return tests.end();}
void emplace_back(FileSystem::Path const& path) {tests.emplace_back(path);}
virtual std::string getDir() const = 0;
private:
struct DataLoader
{
TestSuite& benchmark;
DataLoader(TestSuite& benchmark):benchmark(benchmark) {benchmark.preload();}
~DataLoader() {benchmark.clear();}
};
void preload();
void clear();
/* Used by preload() */
virtual void preloadData(Test&) = 0;
/* used in executeTest() to init TestSetUp() */
virtual std::string setupName(Test const&) = 0;
virtual bool useSetUp() const {return true;}
/* used executeTest() */
virtual void generateConPerData(TestBase const& parser, Test const& test, State state) = 0;
virtual void printResults(TestBase const& parser, int (&count)[3], std::vector<Test const*>& failed);
};
}
}
#endif
</code></pre>
<h3>TestSuite.cpp</h3>
<pre><code>#include "TestSuite.h"
using namespace ThorsAnvil::Benchmark;
Test::Test(FileSystem::Path const& path)
: path(path)
{}
void Test::clear()
{
std::string().swap(output); // Shrink to default size
std::string().swap(input); // Shrink to default size
}
namespace ThorsAnvil
{
namespace Benchmark
{
std::ostream& operator<<(std::ostream& str, Test const& test)
{
return str << test.path.str();
}
}
}
TestSetUp::TestSetUp(TestBase const& parser, std::string const& name, bool callFuncs)
: parser(parser)
, name(name)
, callFuncs(callFuncs)
{
if (callFuncs)
{ parser.SetUp(name.c_str());
}
}
TestSetUp::~TestSetUp()
{
if (callFuncs)
{ parser.TearDown(name.c_str());
}
}
TestSuite::TestSuite(Options& options)
: options(options)
{}
void TestSuite::executeTestOnAllParsers(ParsrList const& parsrList)
{
std::cerr << "BenchMark: " << getDir() << "\n";
if (!tests.empty())
{
DataLoader loadData(*this);
for (auto const& parser: parsrList)
{
executeTest(*parser);
}
}
}
void TestSuite::executeTest(TestBase const& parser)
{
int count[3] = {0, 0, 0};
std::vector<Test const*> failed;
for (auto const& test: tests)
{
TestSetUp testSetUp(parser, setupName(test), useSetUp());
State state = executeTest(parser, test);
generateConPerData(parser, test, state);
++count[static_cast<int>(state)];
if (state == Fail)
{
failed.push_back(&test);
}
}
printResults(parser, count, failed);
}
void TestSuite::printResults(TestBase const& parser, int (&count)[3], std::vector<Test const*>& failed)
{
std::cerr << "\tParser: " << parser.GetName();
if (count[0] == 0 && count[2] == 0)
{
std::cerr << " Perfect\n";
}
else
{
std::cerr << "\n";
if (count[0] != 0)
{
std::cerr << "\t\tNot Implemented: " << count[0] << "\n";
}
std::cerr << "\t\tPass: " << count[1] << "\n";
std::cerr << "\t\tFail: " << count[2] << "\n";
for (auto const& fail: failed)
{
std::cerr << "\t\t\tFailed: " << *fail << "\n";
}
}
}
void TestSuite::preload()
{
for (auto& test: tests)
{
preloadData(test);
}
}
void TestSuite::clear()
{
for (auto& test: tests)
{
test.clear();
}
}
</code></pre>
<h3>benchmark.cpp</h3>
<pre><code>#include "benchmarkConfig.h"
#include "TestSuite.h"
#include "ValidateString.h"
#include "ValidateFloat.h"
#include "PassChecker.h"
#include "FailChecker.h"
#include "RoundTripChecker.h"
#include "PerformanceChecker.h"
#include <list>
#include <regex>
namespace BM = ThorsAnvil::Benchmark;
using DirIter = ThorsAnvil::FileSystem::DirectoryIterator;
using TestSuiteList = std::list<BM::TestSuite*>;
BM::Options getOptions(int argc, char* argv[]);
void displayOptions();
void getTestSuiteList(std::string const& testFilter, TestSuiteList& tSuiteList);
ParsrList getParsrList(std::string const& parserFilter);
int main(int argc, char* argv[])
{
BM::Options options = getOptions(argc, argv);
options.conformance << "Type,Library,Test,Result\n";
options.performance << "Type,Library,Filename,Time (ms),Memory (byte),MemoryPeak (byte),AllocCount,LeakedBytes,LeakCount,FileSize (byte)\n";
ParsrList parsrList = getParsrList(options.parserFilter);
BM::PassChecker jsoncheckerPass(options);
BM::FailChecker jsoncheckerFail(options);
BM::PerformanceChecker performance(options);
BM::RoundTripChecker roundtrip(options);
BM::ValidateFloat validate_float(options);
BM::ValidateString validate_string(options);
TestSuiteList tSuiteList = {&jsoncheckerPass,
&jsoncheckerFail,
&performance,
&roundtrip,
&validate_float,
&validate_string
};
getTestSuiteList(options.testFilter, tSuiteList);
for (auto const& test: tSuiteList)
{
test->executeTestOnAllParsers(parsrList);
}
}
BM::Options getOptions(int argc, char* argv[])
{
BM::Options result;
int loop = 1;
for (; loop < argc; ++loop)
{
if (strncmp(argv[loop], "--filter=", 9) == 0)
{
result.testFilter = argv[loop] + 9;
}
else if (strncmp(argv[loop], "--parser=", 9) == 0)
{
result.parserFilter = argv[loop] + 9;
}
else if (strcmp(argv[loop], "--help") == 0)
{
displayOptions();
exit(0);
}
else if (strcmp(argv[loop], "--") == 0)
{
break;
}
else
{
if (argv[loop][0] != '-')
{
break;
}
std::cerr << "Invalid option: " << argv[loop] << "\n";
displayOptions();
exit(1);
}
}
if (loop + 2 != argc)
{
std::cerr << "Invalid Options: Need two output file names\n";
displayOptions();
exit(1);
}
result.conformance.open(argv[loop]);
if (!result.conformance)
{
std::cerr << "Failed to open 'conformance file'\n";
exit(1);
}
result.performance.open(argv[loop + 1]);
if (!result.performance)
{
std::cerr << "Failed to open 'performance file'\n";
exit(1);
}
return result;
}
void displayOptions()
{
#pragma vera-pushoff
std::cout << R"(
benchmark [--filter=<filter>] [--parser=<parser>] [--help] <conformance file> <performance file>
filter: Default value [^/]*/[^/]*
This option is used as a regular expression to decide what tests to perform.
The first part decides what family of tests jsonchecker/performance/roundtrip.
The second part specifies a test name.
parser:
If unused this will will run all the parsers.
If specified it will run the specified parser only. It choose the parser
by comparing the value given against the result of GetName() method of each parser.
conformance file:
File conformance data is written to.
performance file:
File performance data is written to.
)";
#pragma vera-pop
}
void getTestSuiteList(std::string const& testFilter, TestSuiteList& suiteList)
{
for (auto const& dir: DirIter(QUOTE(DATA_DIR)))
{
if (!dir.isNormalDir())
{ continue;
}
for (auto const& file: DirIter(dir.path()))
{
if (!file.isNormalFile())
{ continue;
}
std::string testName = dir.name() + "/" + file.name();
if (testName.find("EXCLUDE") != std::string::npos)
{ continue;
}
std::regex expression(testFilter + R"(\.json$)");
if (!regex_search(testName, expression))
{ continue;
}
auto find = std::find_if(std::begin(suiteList), std::end(suiteList),
[&dir](BM::TestSuite const* test){return test->getDir() == dir.name();}
);
if (find != std::end(suiteList))
{
(*find)->emplace_back(file.path());
}
}
}
}
ParsrList getParsrList(std::string const& parserFilter)
{
ParsrList result = TestManager::instance().getTests();
if (parserFilter != "")
{
result.erase(std::remove_if(std::begin(result),
std::end(result),
[&parserFilter](TestBase const* parser){return parser->GetName() != parserFilter;}
),
std::end(result)
);
}
return result;
}
</code></pre>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-10-11T06:37:29.593",
"Id": "205355",
"Score": "4",
"Tags": [
"c++",
"json",
"integration-testing"
],
"Title": "JSON Test Harness: Part 2"
} | 205355 |
<p>Part 1: <a href="https://codereview.stackexchange.com/q/205353/507">JSON Test Harness: Part 1</a><br>
Part 2: <a href="https://codereview.stackexchange.com/q/205355/507">JSON Test Harness: Part 2</a><br>
Part 4: <a href="https://codereview.stackexchange.com/q/205357/507">JSON Test Harness: Part 4</a></p>
<p>Time to review some test harness code I have written.</p>
<p><a href="https://github.com/Loki-Astari/JsonBenchmark" rel="nofollow noreferrer">https://github.com/Loki-Astari/JsonBenchmark</a></p>
<p>I wrote a C++ JSON parser/serializer and wanted to compare performance against other JSON parsers. This was originally written by somebody else (credit were credit is due (see README)) but has been highly modified to use better C++ idioms (I hope).</p>
<p>This questions covers the simpler tests. These are all part of the "Conformance" tests. Results found here: <a href="https://lokiastari.com/Json/Conformance.linux.html" rel="nofollow noreferrer">https://lokiastari.com/Json/Conformance.linux.html</a></p>
<h3>PassChecker.h</h3>
<pre><code>#ifndef THORS_ANVIL_BENCHMARK_PASS_CHECKER_H
#define THORS_ANVIL_BENCHMARK_PASS_CHECKER_H
#include "CommonReader.h"
#include <memory>
namespace ThorsAnvil
{
namespace Benchmark
{
class PassChecker: public CommonReader
{
public:
using CommonReader::CommonReader;
virtual std::string getDir() const override
{
return "jsonchecker_pass";
}
virtual State executeTest(TestBase const& parser, Test const& test) override
{
std::unique_ptr<ParseResultBase> result(parser.Parse(test.input.c_str(), test.input.size()));
return result != nullptr ? Pass : Fail;
}
virtual void generateConPerData(TestBase const& parser, Test const& test, State state) override
{
std::size_t begin = test.path.str().rfind('/') + 1;
std::size_t end = test.path.str().rfind('.');
std::string fileName = test.path.str().substr(begin, (end - begin));
options.conformance << "1. Parse Validation,"
<< parser.GetName() << ","
<< fileName << ","
<< (state == Pass ? "true" : "false")
<< "\n";
}
};
}
}
#endif
</code></pre>
<h3>FailChecker.h</h3>
<pre><code>#ifndef THORS_ANVIL_BENCHMARK_FAIL_CHECKER_H
#define THORS_ANVIL_BENCHMARK_FAIL_CHECKER_H
#include "CommonReader.h"
#include <memory>
namespace ThorsAnvil
{
namespace Benchmark
{
class FailChecker: public CommonReader
{
public:
using CommonReader::CommonReader;
virtual std::string getDir() const override
{
return "jsonchecker_fail";
}
virtual State executeTest(TestBase const& parser, Test const& test) override
{
std::unique_ptr<ParseResultBase> result(parser.Parse(test.input.c_str(), test.input.size()));
return result == nullptr ? Pass : Fail;
}
virtual void generateConPerData(TestBase const& parser, Test const& test, State state) override
{
std::size_t begin = test.path.str().rfind('/') + 1;
std::size_t end = test.path.str().rfind('.');
std::string fileName = test.path.str().substr(begin, (end - begin));
options.conformance << "1. Parse Validation,"
<< parser.GetName() << ","
<< fileName << ","
<< (state == Pass ? "true" : "false")
<< "\n";
}
};
}
}
#endif
</code></pre>
<h3>RoundTripChecker.h</h3>
<pre><code>#ifndef THORS_ANVIL_BENCHMARK_ROUNDTRIP_CHECKER_H
#define THORS_ANVIL_BENCHMARK_ROUNDTRIP_CHECKER_H
#include "CommonReader.h"
#include <string>
#include <memory>
#include <cctype>
namespace ThorsAnvil
{
namespace Benchmark
{
class RoundTripChecker: public CommonReader
{
public:
using CommonReader::CommonReader;
virtual void preloadData(Test& test) override
{
CommonReader::preloadData(test);
test.output = stripSpace(test.input);
}
virtual State executeTest(TestBase const& parser, Test const& test) override
{
std::unique_ptr<ParseResultBase> result(parser.Parse(test.input.c_str(), test.input.size()));
if (!result)
{
return NotImplemented;
}
std::unique_ptr<StringResultBase> stringify(parser.Stringify(result.get()));
std::string output;
if (stringify)
{
output = stringify->c_str();
}
return test.output == stripSpace(output) ? Pass : Fail;
}
virtual std::string getDir() const override
{
return "roundtrip";
}
private:
std::string stripSpace(std::string const from)
{
std::string result;
std::copy_if(std::begin(from), std::end(from),
std::back_inserter(result),
[inString = false, lastChar = ' '](char next) mutable
{
if (next == '"' && lastChar != '\\')
{
inString = !inString;
}
lastChar = next;
return !inString && std::isspace(next);
}
);
return result;
}
virtual void generateConPerData(TestBase const& parser, Test const& test, State state) override
{
std::size_t begin = test.path.str().rfind('/') + 1;
std::size_t end = test.path.str().rfind('.');
std::string fileName = test.path.str().substr(begin, (end - begin));
options.conformance << "4. Roundtrip,"
<< parser.GetName() << ","
<< fileName << ","
<< (state == Pass ? "true" : "false")
<< "\n";
}
};
}
}
#endif
</code></pre>
<h3>ValidFloatChecker.h</h3>
<pre><code>#ifndef THORS_ANVIL_BENCHMARK_VALIDATE_FLOAT_H
#define THORS_ANVIL_BENCHMARK_VALIDATE_FLOAT_H
#include "TestSuite.h"
#include <fstream>
#include <string>
#include <limits>
#include <cstdlib>
namespace ThorsAnvil
{
namespace Benchmark
{
class ValidateFloat: public TestSuite
{
public:
using TestSuite::TestSuite;
virtual std::string setupName(Test const&) override
{
return "vector-double";
}
virtual std::string getDir() const override
{
return "validate_float";
}
virtual void preloadData(Test& test) override
{
std::ifstream input(test.path.str());
std::getline(input, test.input, '<');
input.ignore(std::numeric_limits<std::streamsize>::max(), '>');
std::getline(input, test.output, '<');
}
virtual State executeTest(TestBase const& parser, Test const& test) override
{
double output;
char *end;
double expected = std::strtod(test.output.c_str(), &end);
bool result = parser.ParseDouble(test.input.c_str(), &output);
return !result ? NotImplemented : output == expected ? Pass: Fail;
}
virtual void generateConPerData(TestBase const& parser, Test const& test, State state) override
{
std::size_t begin = test.path.str().rfind('/') + 1;
std::size_t end = test.path.str().rfind('.');
std::string fileName = test.path.str().substr(begin, (end - begin));
options.conformance << "2. Parse Double,"
<< parser.GetName() << ","
<< fileName << ","
<< (state == Pass ? "true" : "false")
<< "\n";
}
};
}
}
#endif
</code></pre>
<h3>ValidStringChecker.h</h3>
<pre><code>#ifndef THORS_ANVIL_BENCHMARK_VALIDATE_STRING_H
#define THORS_ANVIL_BENCHMARK_VALIDATE_STRING_H
#include "TestSuite.h"
#include <fstream>
#include <string>
namespace ThorsAnvil
{
namespace Benchmark
{
class ValidateString: public TestSuite
{
public:
using TestSuite::TestSuite;
virtual std::string setupName(Test const&) override
{
return "vector-string";
}
virtual std::string getDir() const override
{
return "validate_string";
}
virtual void preloadData(Test& test) override
{
std::ifstream input(test.path.str());
std::getline(input, test.input, '<');
input.ignore(std::numeric_limits<std::streamsize>::max(), '>');
std::getline(input, test.output, '<');
}
virtual State executeTest(TestBase const& parser, Test const& test) override
{
std::string output;
bool result = parser.ParseString(test.input.c_str(), output);
return !result ? NotImplemented : output == test.output ? Pass: Fail;
}
virtual void generateConPerData(TestBase const& parser, Test const& test, State state) override
{
std::size_t begin = test.path.str().rfind('/') + 1;
std::size_t end = test.path.str().rfind('.');
std::string fileName = test.path.str().substr(begin, (end - begin));
options.conformance << "3. Parse String,"
<< parser.GetName() << ","
<< fileName << ","
<< (state == Pass ? "true" : "false")
<< "\n";
}
};
}
}
#endif
</code></pre>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-10-11T06:43:06.353",
"Id": "205356",
"Score": "2",
"Tags": [
"c++",
"json",
"integration-testing"
],
"Title": "JSON Test Harness: Part 3"
} | 205356 |
<p>Part 1: <a href="https://codereview.stackexchange.com/q/205353/507">JSON Test Harness: Part 1</a><br>
Part 2: <a href="https://codereview.stackexchange.com/q/205355/507">JSON Test Harness: Part 2</a><br>
Part 3: <a href="https://codereview.stackexchange.com/q/205356/507">JSON Test Harness: Part 3</a> </p>
<p>Time to review some test harness code I have written.</p>
<p><a href="https://github.com/Loki-Astari/JsonBenchmark" rel="nofollow noreferrer">https://github.com/Loki-Astari/JsonBenchmark</a></p>
<p>I wrote a C++ JSON parser/serializer and wanted to compare performance against other JSON parsers. This was originally written by somebody else (credit were credit is due (see README)) but has been highly modified to use better C++ idioms (I hope).</p>
<p>This questions covers the biggest test. These are for the "Performance" tests. Results found here: <a href="https://lokiastari.com/Json/Performance.linux.html" rel="nofollow noreferrer">https://lokiastari.com/Json/Performance.linux.html</a> (Sadly, but not unexpectedly my code is not the fastest :-( )</p>
<h3>PerformanceChecker.h</h3>
<pre><code>#ifndef THORS_ANVIL_BENCHMARK_PERFORMANCE_CHECKER_H
#define THORS_ANVIL_BENCHMARK_PERFORMANCE_CHECKER_H
#include "CommonReader.h"
#include <map>
#include <chrono>
namespace ThorsAnvil
{
namespace Benchmark
{
class PerformanceChecker: public CommonReader
{
static std::map<std::string, Stat const*> const validator;
static const int loopCount = 10;
public:
using CommonReader::CommonReader;
virtual void executeTest(TestBase const& parser) override;
virtual State executeTest(TestBase const& parser, Test const& test) override;
virtual std::string getDir() const override
{
return "performance";
}
private:
virtual bool useSetUp() const override {return false;}
virtual void generateConPerData(TestBase const& parser, Test const& test, State state) override;
virtual void printResults(TestBase const&, int (&)[3], std::vector<Test const*>&) override{}
private:
void getCodeSize(TestBase const& parser);
void validatePerformance(TestBase const& parser);
class Output
{
Options& options;
TestBase const& parser;
Test const& test;
std::string const name;
std::string const action;
double& minDuration;
bool fail;
public:
Output(Options& options, TestBase const& parser_, Test const& test_, std::string const& name_, std::string const& action_, double& minDuration_);
~Output();
void setPass();
void validateMemory();
void readoutput(int fd, std::ostream& output);
};
template<typename F>
double timeExecution(F&& action);
void executeParse(TestBase const& parser, Test const& test);
void executeStringify(TestBase const& parser, Test const& test);
void executePrettify(TestBase const& parser, Test const& test);
void executeStatistics(TestBase const& parser, Test const& test);
void executeSaxRoundtrip(TestBase const& parser, Test const& test);
void executeSaxStatistics(TestBase const& parser, Test const& test);
};
template<typename F>
double PerformanceChecker::timeExecution(F&& action)
{
auto start = std::chrono::high_resolution_clock::now();
action();
auto end = std::chrono::high_resolution_clock::now();
std::chrono::duration<double> duration = end-start;
return duration.count();
}
}
}
#endif
</code></pre>
<h3>PerformanceChecker.cpp</h3>
<pre><code>#include "PerformanceChecker.h"
#include <memory>
#include <chrono>
#include <iomanip>
#include <algorithm>
#include <unistd.h>
#include <sys/wait.h>
#include <stdlib.h>
using namespace ThorsAnvil::Benchmark;
#pragma vera-pushoff
using namespace std::string_literals;
#pragma vera-pop
static Stat constexpr canada =
{
/*objectCount:*/ 4,
/*arrayCount:*/ 56045,
/*numberCount:*/ 111126,
/*stringCount:*/ 12,
/*trueCount:*/ 0,
/*falseCount:*/ 0,
/*nullCount:*/ 0,
/*memberCount:*/ 8,
/*elementCount:*/ 167170,
/*stringLength:*/ 90
};
static Stat constexpr citm_catalog
{
/*objectCount:*/ 10937,
/*arrayCount:*/ 10451,
/*numberCount:*/ 14392,
/*stringCount:*/ 26604,
/*trueCount:*/ 0,
/*falseCount:*/ 0,
/*nullCount:*/ 1263,
/*memberCou:nt*/ 25869,
/*elementCount:*/ 11908,
/*stringLength:*/ 221379
};
static Stat constexpr twitter =
{
/*objectCount:*/ 1264,
/*arrayCount:*/ 1050,
/*numberCount:*/ 2109,
/*stringCount:*/ 18099,
/*trueCount:*/ 345,
/*falseCount:*/ 2446,
/*nullCount:*/ 1946,
/*memberCou:nt*/ 13345,
/*elementCount:*/ 568,
/*stringLength:*/ 367917
};
std::map<std::string, Stat const*> const PerformanceChecker::validator
{
{"canada.json"s, &canada},
{"citm_catalog.json"s, &citm_catalog},
{"twitter.json"s, &twitter}
};
void PerformanceChecker::executeTest(TestBase const& parser)
{
std::cerr << "\t" << parser.GetName() << "\n";
validatePerformance(parser);
CommonReader::executeTest(parser);
getCodeSize(parser);
}
State PerformanceChecker::executeTest(TestBase const& parser, Test const& test)
{
executeParse(parser, test);
executeStringify(parser, test);
executePrettify(parser, test);
executeStatistics(parser, test);
executeSaxRoundtrip(parser, test);
executeSaxStatistics(parser, test);
return Pass;
}
void PerformanceChecker::generateConPerData(TestBase const& /*parser*/, Test const& /*test*/, State /*state*/)
{}
void PerformanceChecker::getCodeSize(TestBase const& parser)
{
std::string path = QUOTE(THORSANVIL_ROOT) "/build/lib/";
std::string fileName = std::string(parser.GetName());
std::size_t endOfName = fileName.find(' ');
fileName = fileName.substr(0, endOfName);
std::string fullPath = path + "lib" + fileName + "Test" + QUOTE(LIBEXT);
std::ifstream obj(fullPath);
obj.seekg(0, std::ios_base::end);
std::size_t size = obj.tellg();
options.performance << "7. Code size," << parser.GetName() << ",XXX,0,0,0,0,0,0," << size << "\n";
}
void PerformanceChecker::validatePerformance(TestBase const& parser)
{
for (auto const& test: tests)
{
std::string fileName = test.path.str().substr(test.path.str().rfind('/') + 1);
TestSetUp testSetUp(parser, setupName(test), true);
std::unique_ptr<ParseResultBase> dom(parser.Parse(test.input.c_str(), test.input.size()));
Stat stats {};
bool result = parser.Statistics(dom.get(), &stats);
std::cerr << "\t\t" << std::setw(15) << std::left << "Validate:"
<< std::setw(20) << std::left << fileName
<< std::right << std::flush;
if (!result)
{
std::cerr << " Not Implemented\n";
}
else
{
auto find = validator.find(fileName);
if (find == validator.end())
{
std::cerr << " New Test! No comparison\n";
continue;
}
bool ok = stats == *find->second;
std::cerr << (ok ? " Pass" : " Fail") << "\n";
if (!ok)
{
std::cerr << "\t\t\tobjectCount " << std::setw(8) << find->second->objectCount << " : " << std::setw(8) << stats.objectCount << (find->second->objectCount == stats.objectCount ? "" : " BAD") << "\n"
<< "\t\t\tarrayCount " << std::setw(8) << find->second->arrayCount << " : " << std::setw(8) << stats.arrayCount << (find->second->arrayCount == stats.arrayCount ? "" : " BAD") << "\n"
<< "\t\t\tnumberCount " << std::setw(8) << find->second->numberCount << " : " << std::setw(8) << stats.numberCount << (find->second->numberCount == stats.numberCount ? "" : " BAD") << "\n"
<< "\t\t\tstringCount " << std::setw(8) << find->second->stringCount << " : " << std::setw(8) << stats.stringCount << (find->second->stringCount == stats.stringCount ? "" : " BAD") << "\n"
<< "\t\t\ttrueCount " << std::setw(8) << find->second->trueCount << " : " << std::setw(8) << stats.trueCount << (find->second->trueCount == stats.trueCount ? "" : " BAD") << "\n"
<< "\t\t\tfalseCount " << std::setw(8) << find->second->falseCount << " : " << std::setw(8) << stats.falseCount << (find->second->falseCount == stats.falseCount ? "" : " BAD") << "\n"
<< "\t\t\tnullCount " << std::setw(8) << find->second->nullCount << " : " << std::setw(8) << stats.nullCount << (find->second->nullCount == stats.nullCount ? "" : " BAD") << "\n"
<< "\t\t\tmemberCount " << std::setw(8) << find->second->memberCount << " : " << std::setw(8) << stats.memberCount << (find->second->memberCount == stats.memberCount ? "" : " BAD") << "\n"
<< "\t\t\telementCount " << std::setw(8) << find->second->elementCount << " : " << std::setw(8) << stats.elementCount << (find->second->elementCount == stats.elementCount? "" : " BAD") << "\n"
<< "\t\t\tstringLength " << std::setw(8) << find->second->stringLength << " : " << std::setw(8) << stats.stringLength << (find->second->stringLength == stats.stringLength? "" : " BAD") << "\n";
}
}
}
}
void PerformanceChecker::executeParse(TestBase const& parser, Test const& test)
{
double minDuration = std::chrono::duration<double>::max().count();
Output generator(options, parser, test, "Parse", "1", minDuration);
for (int loop = 0; loop < loopCount; ++loop)
{
TestSetUp testSetUp(parser, setupName(test), true);
std::unique_ptr<ParseResultBase> result;
double duration = timeExecution([&parser, &test, &result]()
{ result.reset(parser.Parse(test.input.c_str(), test.input.size()));});
if (!result)
{
return;
}
minDuration = std::min(minDuration, duration);
}
generator.setPass();
}
void PerformanceChecker::executeStringify(TestBase const& parser, Test const& test)
{
double minDuration = std::chrono::duration<double>::max().count();
Output generator(options, parser, test, "Stringify", "2", minDuration);
TestSetUp testSetUp(parser, setupName(test), true);
std::unique_ptr<ParseResultBase> dom(parser.Parse(test.input.c_str(), test.input.size()));
for (int loop = 0; loop < loopCount; ++loop)
{
std::unique_ptr<StringResultBase> result;
double duration = timeExecution([&parser, &result, &dom]()
{ result.reset(parser.Stringify(dom.get()));});
if (!result)
{
return;
}
minDuration = std::min(minDuration, duration);
}
generator.setPass();
}
void PerformanceChecker::executePrettify(TestBase const& parser, Test const& test)
{
double minDuration = std::chrono::duration<double>::max().count();
Output generator(options, parser, test, "Prettify", "3", minDuration);
TestSetUp testSetUp(parser, setupName(test), true);
std::unique_ptr<ParseResultBase> dom(parser.Parse(test.input.c_str(), test.input.size()));
for (int loop = 0; loop < loopCount; ++loop)
{
std::unique_ptr<StringResultBase> result;
double duration = timeExecution([&parser, &result, &dom]()
{ result.reset(parser.Prettify(dom.get()));});
if (!result)
{
return;
}
minDuration = std::min(minDuration, duration);
}
generator.setPass();
}
void PerformanceChecker::executeStatistics(TestBase const& parser, Test const& test)
{
double minDuration = std::chrono::duration<double>::max().count();
Output generator(options, parser, test, "Statistics", "4", minDuration);
TestSetUp testSetUp(parser, setupName(test), true);
std::unique_ptr<ParseResultBase> dom(parser.Parse(test.input.c_str(), test.input.size()));
for (int loop = 0; loop < loopCount; ++loop)
{
Stat stats {};
bool result;
double duration = timeExecution([&parser, &result, &stats, &dom]()
{ result = parser.Statistics(dom.get(), &stats);});
if (!result)
{
return;
}
minDuration = std::min(minDuration, duration);
}
generator.setPass();
}
void PerformanceChecker::executeSaxRoundtrip(TestBase const& parser, Test const& test)
{
double minDuration = std::chrono::duration<double>::max().count();
Output generator(options, parser, test, "SaxRoundtrip", "5", minDuration);
for (int loop = 0; loop < loopCount; ++loop)
{
TestSetUp testSetUp(parser, setupName(test), true);
std::unique_ptr<StringResultBase> result;
double duration = timeExecution([&parser, &test, &result]()
{ result.reset(parser.SaxRoundtrip(test.input.c_str(), test.input.size()));});
if (!result)
{
return;
}
minDuration = std::min(minDuration, duration);
}
generator.setPass();
}
void PerformanceChecker::executeSaxStatistics(TestBase const& parser, Test const& test)
{
double minDuration = std::chrono::duration<double>::max().count();
Output generator(options, parser, test, "SaxStatistics", "6", minDuration);
for (int loop = 0; loop < loopCount; ++loop)
{
TestSetUp testSetUp(parser, setupName(test), true);
Stat stats {};
bool result;
double duration = timeExecution([&parser, &test, &result, &stats]()
{ result = parser.SaxStatistics(test.input.c_str(), test.input.size(), &stats);});
if (!result)
{
return;
}
minDuration = std::min(minDuration, duration);
}
generator.setPass();
}
</code></pre>
<h3>PerformanceChecker.cpp (PerformanceChecker::Output)</h3>
<pre><code>PerformanceChecker::Output::Output(Options& options, TestBase const& parser_, Test const& test_, std::string const& name_, std::string const& action_, double& minDuration_)
: options(options)
, parser(parser_)
, test(test_)
, name(name_)
, action(action_)
, minDuration(minDuration_)
, fail(true)
{
((void)parser);
std::string fileName = test.path.str().substr(test.path.str().rfind('/') + 1);
std::cerr << "\t\t" << std::setw(15) << std::left << name
<< std::setw(20) << std::left << fileName << " ... "
<< std::right << std::flush;
}
PerformanceChecker::Output::~Output()
{
if (!fail)
{
double throughput = test.input.size() / (1024.0 * 1024.0) / minDuration;
std::cerr << std::setw(6) << std::setprecision(3) << (minDuration * 1000) << " ms "
<< std::setw(3) << std::setprecision(3) << throughput << " MB/s\n"
<< std::flush;
options.performance << action << ". "
<< name << ","
<< parser.GetName() << ","
<< test.path.str().substr(test.path.str().rfind('/') + 1) << ","
<< (minDuration * 1000) << ",";
validateMemory();
options.performance << "0\n";
}
else
{
std::cerr << "\t\tNot support\n" << std::flush;
}
}
void PerformanceChecker::Output::setPass() {fail = false;}
void PerformanceChecker::Output::validateMemory()
{
int stdoutPipe[2];
int stderrPipe[2];
if (pipe(stdoutPipe) < 0)
{
std::cerr << "Failed to Create Pipe: Stdout";
exit(1);
}
if (pipe(stderrPipe) < 0)
{
std::cerr << "Failed to Create Pipe: Stderr";
exit(1);
}
pid_t pid = fork();
if (pid < 0)
{
std::cerr << "Failed to Fork Memory App";
exit(1);
}
if (pid == 0)
{
dup2(stdoutPipe[1], fileno(stdout));
dup2(stderrPipe[1], fileno(stderr));
close(stdoutPipe[0]);
close(stdoutPipe[1]);
close(stderrPipe[0]);
close(stderrPipe[1]);
std::string fileName = test.path.str().substr(test.path.str().rfind('/') + 1);
std::string pName = parser.GetName();
std::string memoryApp= QUOTE(THORSANVIL_ROOT) "/build/bin/memory17";
setenv("DYLD_LIBRARY_PATH", QUOTE(THORSANVIL_ROOT) "/build/lib/", 1);
setenv("DYLD_INSERT_LIBRARIES", QUOTE(THORSANVIL_ROOT) "/build/lib/libMemory17.dylib", 1);
setenv("DYLD_FORCE_FLAT_NAMESPACE", "1", 1);
execl(memoryApp.c_str(), memoryApp.c_str(), pName.c_str(), fileName.c_str(), action.c_str(), nullptr);//, envp);
exit(0);
}
close(stdoutPipe[1]);
close(stderrPipe[1]);
readoutput(stdoutPipe[0], std::cout);
readoutput(stderrPipe[0], options.performance);
int stat_loc;
pid_t child = wait4(pid, &stat_loc, 0, nullptr);
if (child != pid)
{
std::cerr << "Processes wait error\n";
exit(1);
}
close(stdoutPipe[0]);
close(stderrPipe[0]);
}
void PerformanceChecker::Output::readoutput(int fd, std::ostream& output)
{
char buffer[4096];
int nbytes;
while ((nbytes = ::read(fd, buffer, sizeof(buffer))) != 0)
{
if (nbytes == -1)
{
switch (errno)
{
case EAGAIN: continue;
case EINTR: continue;
case EBADF: std::cerr << "EBADF\n"; break;
case EFAULT: std::cerr << "EFAULT\n"; break;
case EINVAL: std::cerr << "EINVAL\n"; break;
case EIO: std::cerr << "EIO\n"; break;
case EISDIR: std::cerr << "EISDIR\n"; break;
case ENOBUFS: std::cerr << "ENOBUFS\n"; break;
case ENOMEM: std::cerr << "ENOMEM\n"; break;
case ENXIO: std::cerr << "ENXIO\n"; break;
case ESPIPE: std::cerr << "ESPIPE\n"; break;
case ECONNRESET:std::cerr << "ECONNRESET\n";break;
case ENOTCONN: std::cerr << "ENOTCONN\n"; break;
case ETIMEDOUT: std::cerr << "ETIMEDOUT\n"; break;
default:
std::cerr << "Unknown: " << errno << "\n";
break;
}
std::cerr << "Read from socket failed\n";
exit(1);
}
output.write(buffer, nbytes);
}
}
</code></pre>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-10-11T06:49:17.167",
"Id": "205357",
"Score": "3",
"Tags": [
"c++",
"json",
"integration-testing"
],
"Title": "JSON Test Harness: Part 4"
} | 205357 |
<p>The reason I created this is because the Material UI way of doing a simple 'menu that opens below the button' <a href="https://material-ui.com/demos/menus/#menulist-composition" rel="nofollow noreferrer">is convoluted as hell</a> (see the 'toggle menu grow' example, and check the code out. I've basically copied the code for that, and put it in one nice wrapper.</p>
<p><a href="https://codesandbox.io/s/j384pln0l5" rel="nofollow noreferrer">Codepen</a></p>
<p>Here's the usage of the component: </p>
<pre><code><NavDropdownMenu
buttonProps={{
variant: "contained",
color: "secondary"
}}
buttonChildren={"foo bar"}
>
<MenuItem onClick={this.handleA}>Profile</MenuItem>
<MenuItem onClick={this.handleB}>My account</MenuItem>
<MenuItem>Logout</MenuItem>
</NavDropdownMenu>
</code></pre>
<p>Notes: </p>
<ul>
<li>We can pass through whatever material props to the button.</li>
<li>We can put whatever content we like inside the button. (e.g. icons, avatars).</li>
<li>We put whatever we like as menu items, and bind our own onclick events to them.</li>
</ul>
<p>Under the hood, in order to both trigger the close menu functionality, as well as allow the user to bind their own click events to the menu items, I have this code that uses <a href="https://reactjs.org/docs/react-api.html#cloneelement" rel="nofollow noreferrer"><code>React.cloneElement</code></a>:</p>
<pre><code> <MenuList>
{children.map((child, i) => {
return React.cloneElement(child, {
...child.props,
...{
onClick: this.generateOnClick(child.props.onClick),
key: `${menuId}${i}`
}
});
})}
</MenuList>
</code></pre>
<p>And that function: </p>
<pre><code> generateOnClick = fn => {
if (fn)
return () => {
fn();
this.handleMenuClose();
};
else {
return this.handleMenuClose;
}
};
</code></pre>
<p>Now, I haven't put in PropTypes; I have to confess I'm not in the habit of using them. And there's probably some more extensibility I could add - (e.g. configuring the placement of the menu). </p>
<p>But other than that, are there glaring issue with this code that make it a bad idea? </p>
| [] | [
{
"body": "<p>As a general sentiment, I can't spot any glaring issues with the code just the one section and a few minor things (you did say you basically copied it; I'd imagine the Material UI team have some idea what they're doing)</p>\n\n<hr>\n\n<blockquote>\n<pre><code>{children.map((child, i) => {\n re... | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-10-11T07:08:52.280",
"Id": "205359",
"Score": "0",
"Tags": [
"javascript",
"react.js"
],
"Title": "Material UI menu drop down component"
} | 205359 |
<h3>Objective:</h3>
<p>I want to loop through a bitarray and store subsets of that bitarray in a table.</p>
<h3>Context:</h3>
<p>I have a bitarray with 48 elements where each element represent one hour. I want to look back 24 hours from the start of the second day and retrieve the intervals where the last bit is 1.</p>
<p>I was able to achieve this but want to know if someone can provide a better solution :)</p>
<p>I have a table called [Numbers] that has 5000 rows that was created in accordance to this link <a href="https://www.mssqltips.com/sqlservertip/4176/the-sql-server-numbers-table-explained--part-1/" rel="nofollow noreferrer">https://www.mssqltips.com/sqlservertip/4176/the-sql-server-numbers-table-explained--part-1/</a> .</p>
<h3>SCRIPT:</h3>
<pre><code>DECLARE @Ba NVARCHAR(48) = '000011110000000001110000000011111111000011110000'
DECLARE @numberOfIntervals INT = 24;
DECLARE @intervals TABLE(
SequenceId INT,
[Periods] NVARCHAR(24)
)
INSERT INTO @intervals
SELECT number-1 AS [SequenceId], SUBSTRING(@Ba, number, @numberOfIntervals) AS [Values]
FROM [dbo].[Numbers]
WHERE number > 1 AND number <= (LEN(@Ba)-(@numberOfIntervals-1)) AND RIGHT(SUBSTRING(@Ba, number, @numberOfIntervals), 1) = '1'
SELECT * FROM @intervals
</code></pre>
<h3>RESULTS:</h3>
<pre><code>[SequenceId] [Values]
_________________________
5 111000000000111000000001
6 110000000001110000000011
7 100000000011100000000111
8 000000000111000000001111
9 000000001110000000011111
10 000000011100000000111111
11 000000111000000001111111
12 000001110000000011111111
17 111000000001111111100001
18 110000000011111111000011
19 100000000111111110000111
20 000000001111111100001111
</code></pre>
| [] | [
{
"body": "<p>You're definitely on the right track by using a \"Numbers\" table, rather than a loop or cursor. Given the small size and the fact that you know up front that you only need 24 rows, there's no need to calculate it. You can also save a bit my creating the numbers table on the fly.</p>\n\n<p>What yo... | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-10-11T08:45:36.287",
"Id": "205366",
"Score": "3",
"Tags": [
"sql",
"sql-server",
"t-sql"
],
"Title": "Loop Through bitarray to retrieve subsets of that bitarray"
} | 205366 |
<p>I've started a course about the MVC pattern applied to the web. I want to improve my PHP programming skills so I've decided to write a simple boilerplate for my webapps that use the front controller pattern. The code is working fine, but I think maybe it can be improved. Any suggestion about will be appreciated. </p>
<p>Front controller routing class</p>
<pre><code><?php
class Router{
private $controller;
private $model;
private $path;
public function __construct(Model $model, $tpl, Controller $controller){
$this->model = $model;
$this->tpl = $tpl;
$this->controller = $controller;
}
public function route(){
if(isset($_SERVER['PATH_INFO'])){
$this->path = $_SERVER['PATH_INFO'];
$this->pathSplit = explode('/', ltrim($this->path));
}else{
$this->pathSplit = '/';
}
if($this->pathSplit == '/'){
echo $this->controller->index();
}
else{
$req_ctr = ucfirst($this->pathSplit[1]).'Controller';
$req_action = $this->pathSplit[2];
if(file_exists($req_ctr.'.php')){
$controller = new $req_ctr($this->model, $this->tpl);
if(method_exists($controller ,$req_action)){
echo $controller->$req_action();
}
#else{}
}
#else{}
}
}
}
?>
</code></pre>
<p>.htaccess</p>
<pre><code>RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.+)$ index.php/$1 [L]
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-10-13T09:40:22.587",
"Id": "396403",
"Score": "0",
"body": "Personally I dislike abbreviated variables names. It becomes a guessing game. Might 'tpl' stand for 'topleague', 'tadpole' or 'template'? 'req_ctr' is, if I understand the code c... | [] | {
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-10-11T09:33:19.717",
"Id": "205368",
"Score": "1",
"Tags": [
"php",
"object-oriented",
".htaccess"
],
"Title": "PHP OOP front controller pattern"
} | 205368 |
<p>I am learning algorithms. And my current algorithm is create a single list, and try to remove all duplicated elements in a <strong>sorted</strong> list.
Ex:
given Input: 1 -> 1 -> 1 -> 2 -> 2 -> 3 -> 5 -> 5 -> 7
Expected Output: 3 -> 7</p>
<p>My bellow solution worked well:</p>
<pre><code>//Definition for singly-linked list.
public class ListNode
{
public int val;
public ListNode next;
public ListNode(int x)
{
val = x;
next = null;
}
}
public ListNode deleteAllDuplicates(ListNode list)
{
if (list == null)
{
return null;
}
var start = list;
var isStart = true;
var pre = start;
var tmp = list.val;
while (list?.next != null)
{
if (tmp == list.next.val)
{
while (list?.val == tmp)
{
list = list.next;
}
if (isStart)
{
start = list;
pre = start;
}
else
{
pre.next = list;
}
if (list == null)
{
return start;
}
tmp = list.val;
}
else
{
pre = list;
list = list.next;
tmp = list.val;
isStart = false;
}
}
return start;
}
</code></pre>
<p>My question is: What should I do to improve the solution?
Any help are appriciate!</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-10-11T10:13:42.777",
"Id": "396189",
"Score": "2",
"body": "`A` is really a terrible variable name. I'm sure you can think of something more meaningful."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-10-11T10:38... | [
{
"body": "<p>All in all it looks OK to me. I would maybe call the variables something else:</p>\n\n<pre><code>list -> root\ntmp -> currentValue\nstart -> result\netc.\n</code></pre>\n\n<hr>\n\n<p>In the <code>ListNode</code> class it's common practice in C# to name public members in CamelCase:</p>\n\n... | {
"AcceptedAnswerId": "205453",
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-10-11T10:08:04.530",
"Id": "205369",
"Score": "2",
"Tags": [
"c#",
"algorithm"
],
"Title": "Remove all duplicated elements in a single list"
} | 205369 |
<p>I wrote a Python program that can take as argument either a string or a filename, with these options being mutually exclusive:</p>
<pre><code>#!/usr/bin/env python
import argparse
import sys
def parse_command_line():
parser = argparse.ArgumentParser()
parser.add_argument('-t', '--text', dest = 'input_text', help = 'Text')
parser.add_argument('-f', '--file', dest = 'input_file', help = 'File containing the text')
return parser
if __name__ == '__main__':
parser = parse_command_line()
args = parser.parse_args()
if args.input_text is not None and args.input_file is None:
text = args.input_text
elif args.input_file is not None and args.input_text is None:
text = open(args.input_file, 'r').read()
else:
parser.print_help()
sys.exit()
# Program continues ...
</code></pre>
<p>The mutually exclusive check is not optimal and will become very ugly in case of three, four, ... options. How can I improve this code? </p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-10-11T10:26:59.377",
"Id": "396191",
"Score": "0",
"body": "Hi, we're a little different from SO by not answering specific questions. Could you also make your code one code block. Thanks."
},
{
"ContentLicense": "CC BY-SA 4.0",
... | [
{
"body": "<p>What you are looking for is <a href=\"https://docs.python.org/3/library/argparse.html#mutual-exclusion\" rel=\"noreferrer\"><code>add_mutually_exclusive_group</code></a>. It allows you to define options that are mutually exclusive as well as specifying if selecting one of these options is a requir... | {
"AcceptedAnswerId": "205377",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-10-11T10:22:22.060",
"Id": "205372",
"Score": "3",
"Tags": [
"python"
],
"Title": "Mutually exclusive options for argparse"
} | 205372 |
<p>I would like to know how to make this faster. It's okay for 100 rows but 1k, 10k, 100k is different.</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>let array = {
"PageOption": {
"rowperpage": "10",
"rowtotal": "235",
"currentPage": "1",
"divheight": "250"
},
"header": [
{
"visible": true,
"label": "rownum",
"fontweight": "normal",
"footer": "Sum"
},
{
"visible": true,
"label": "subpkid",
"fontweight": "normal",
"footer": "Sum"
},
{
"visible": true,
"label": "destsubpkid",
"fontweight": "normal",
"footer": "Sum"
},
{
"visible": true,
"label": "jrlpkid",
"fontweight": "normal",
"footer": "max"
},
{
"visible": true,
"label": "jrltype",
"fontweight": "normal",
"footer": "Sum"
},
{
"visible": true,
"label": "invtype",
"fontweight": "normal",
"footer": "Sum"
},
{
"visible": true,
"label": "accountid",
"fontweight": "normal",
"footer": "Sum"
},
{
"visible": true,
"label": "expID",
"fontweight": "normal",
"footer": "Sum"
},
{
"visible": true,
"label": "invdate",
"fontweight": "normal",
"footer": "Sum"
},
{
"visible": true,
"label": "invno",
"fontweight": "normal",
"footer": "Sum"
},
{
"visible": true,
"label": "invdesc",
"fontweight": "normal",
"footer": "Sum"
},
{
"visible": true,
"label": "dtamt",
"fontweight": "normal",
"footer": "Sum"
},
{
"visible": true,
"label": "currate",
"fontweight": "normal",
"footer": "Sum"
},
{
"visible": true,
"label": "dtamtf",
"fontweight": "normal",
"footer": "Sum"
},
{
"visible": true,
"label": "isdebit",
"fontweight": "normal",
"footer": "Sum"
},
{
"visible": true,
"label": "cusid",
"fontweight": "normal",
"footer": "Sum"
}
],
"rows": [
{
"rownum": "1",
"currate": "2",
"invtype": "3",
"invdesc": "BEGIN GOOD",
"invdate": "1900/01/01",
"destsubpkid": "0",
"dtamt": "INS",
"cusid": "2014/03/22 13:35:02",
"dtamtf": "20000",
"jrltype": "MOD",
"jrlpkid": "526",
"subpkid": "190001011011003632",
"isdebit": "123213",
"expid": "1900/01/01",
"invno": "0",
"accountid": "20120608101100001"
},
{
"rownum": "1",
"currate": "2",
"invtype": "3",
"invdesc": "BEGIN GOOD",
"invdate": "1900/01/01",
"destsubpkid": "0",
"dtamt": "INS",
"cusid": "2014/03/22 13:35:02",
"dtamtf": "1003764",
"jrltype": "OD",
"jrlpkid": "895",
"subpkid": "190001011011003633",
"isdebit": "123213",
"expid": "1900/01/01",
"invno": "0",
"accountid": "20101023101100273"
},
{
"rownum": "1",
"currate": "2",
"invtype": "3",
"invdesc": "BEGIN GOOD",
"invdate": "1900/01/01",
"destsubpkid": "0",
"dtamt": "INS",
"cusid": "2014/03/22 13:35:02",
"dtamtf": "1003764",
"jrltype": "OD",
"jrlpkid": "895",
"subpkid": "190001011011003633",
"isdebit": "123213",
"expid": "1900/01/01",
"invno": "0",
"accountid": "20101023101100273"
},
{
"rownum": "1",
"currate": "2",
"invtype": "3",
"invdesc": "BEGIN GOOD",
"invdate": "1900/01/01",
"destsubpkid": "0",
"dtamt": "INS",
"cusid": "2014/03/22 13:35:02",
"dtamtf": "1003764",
"jrltype": "OD",
"jrlpkid": "895",
"subpkid": "190001011011003633",
"isdebit": "123213",
"expid": "1900/01/01",
"invno": "0",
"accountid": "20101023101100273"
},
{
"rownum": "1",
"currate": "2",
"invtype": "3",
"invdesc": "BEGIN GOOD",
"invdate": "1900/01/01",
"destsubpkid": "0",
"dtamt": "INS",
"cusid": "2014/03/22 13:35:02",
"dtamtf": "1003764",
"jrltype": "OD",
"jrlpkid": "895",
"subpkid": "190001011011003633",
"isdebit": "123213",
"expid": "1900/01/01",
"invno": "0",
"accountid": "20101023101100273"
},
{
"rownum": "1",
"currate": "2",
"invtype": "3",
"invdesc": "BEGIN GOOD",
"invdate": "1900/01/01",
"destsubpkid": "0",
"dtamt": "INS",
"cusid": "2014/03/22 13:35:02",
"dtamtf": "1003764",
"jrltype": "OD",
"jrlpkid": "895",
"subpkid": "190001011011003633",
"isdebit": "123213",
"expid": "1900/01/01",
"invno": "0",
"accountid": "20101023101100273"
},
{
"rownum": "1",
"currate": "2",
"invtype": "3",
"invdesc": "BEGIN GOOD",
"invdate": "1900/01/01",
"destsubpkid": "0",
"dtamt": "INS",
"cusid": "2014/03/22 13:35:02",
"dtamtf": "1003764",
"jrltype": "OD",
"jrlpkid": "895",
"subpkid": "190001011011003633",
"isdebit": "123213",
"expid": "1900/01/01",
"invno": "0",
"accountid": "20101023101100273"
},
{
"rownum": "1",
"currate": "2",
"invtype": "3",
"invdesc": "BEGIN GOOD",
"invdate": "1900/01/01",
"destsubpkid": "0",
"dtamt": "INS",
"cusid": "2014/03/22 13:35:02",
"dtamtf": "1003764",
"jrltype": "OD",
"jrlpkid": "895",
"subpkid": "190001011011003633",
"isdebit": "123213",
"expid": "1900/01/01",
"invno": "0",
"accountid": "20101023101100273"
},
{
"rownum": "1",
"currate": "2",
"invtype": "3",
"invdesc": "BEGIN GOOD",
"invdate": "1900/01/01",
"destsubpkid": "0",
"dtamt": "INS",
"cusid": "2014/03/22 13:35:02",
"dtamtf": "1003764",
"jrltype": "OD",
"jrlpkid": "895",
"subpkid": "190001011011003633",
"isdebit": "123213",
"expid": "1900/01/01",
"invno": "0",
"accountid": "20101023101100273"
},
{
"rownum": "1",
"currate": "2",
"invtype": "3",
"invdesc": "BEGIN GOOD",
"invdate": "1900/01/01",
"destsubpkid": "0",
"dtamt": "INS",
"cusid": "2014/03/22 13:35:02",
"dtamtf": "0",
"jrltype": "KOD",
"jrlpkid": "453",
"subpkid": "190001011011003634",
"isdebit": "123213",
"expid": "1900/01/01",
"invno": "0",
"accountid": "20101202101100001"
},
{
"rownum": "1",
"currate": "2",
"invtype": "3",
"invdesc": "BEGIN GOOD",
"invdate": "1900/01/01",
"destsubpkid": "0",
"dtamt": "INS",
"cusid": "2014/03/22 13:35:02",
"dtamtf": "124000",
"jrltype": "DON",
"jrlpkid": "1562",
"subpkid": "190001011011003635",
"isdebit": "123213",
"expid": "1900/01/01",
"invno": "0",
"accountid": "20130124101100002"
},
{
"rownum": "1",
"currate": "2",
"invtype": "3",
"invdesc": "BEGIN GOOD",
"invdate": "1900/01/01",
"destsubpkid": "0",
"dtamt": "INS",
"cusid": "2014/03/22 13:35:02",
"dtamtf": "319090.59",
"jrltype": "HOD",
"jrlpkid": "1562",
"subpkid": "190001011011003636",
"isdebit": "123213",
"expid": "1900/01/01",
"invno": "0",
"accountid": "20101023101100050"
},
{
"rownum": "1",
"currate": "2",
"invtype": "3",
"invdesc": "BEGIN GOOD",
"invdate": "1900/01/01",
"destsubpkid": "0",
"dtamt": "INS",
"cusid": "2014/03/22 13:35:02",
"dtamtf": "0",
"jrltype": "YOSH",
"jrlpkid": "1562",
"subpkid": "190001011011003637",
"isdebit": "123213",
"expid": "1900/01/01",
"invno": "0",
"accountid": "20101023101100270"
},
{
"rownum": "1",
"currate": "2",
"invtype": "3",
"invdesc": "BEGIN GOOD",
"invdate": "1900/01/01",
"destsubpkid": "0",
"dtamt": "INS",
"cusid": "2014/03/22 13:35:02",
"dtamtf": "0",
"jrltype": "ZOD",
"jrlpkid": "1562",
"subpkid": "190001011011003638",
"isdebit": "123213",
"expid": "1900/01/01",
"invno": "0",
"accountid": "20101023101100265"
},
{
"rownum": "1",
"currate": "2",
"invtype": "3",
"invdesc": "BEGIN GOOD",
"invdate": "1900/01/01",
"destsubpkid": "0",
"dtamt": "INS",
"cusid": "2014/03/22 13:35:02",
"dtamtf": "0",
"jrltype": "GOD",
"jrlpkid": "1562",
"subpkid": "190001011011003639",
"isdebit": "1232131231231",
"expid": "1900/01/01",
"invno": "0",
"accountid": "20101023101100263"
},
{
"rownum": "2",
"currate": "2",
"invtype": "3",
"invdesc": "BEGIN GOOD",
"invdate": "1900/01/01",
"destsubpkid": "0",
"dtamt": "INS",
"cusid": "2014/03/22 13:35:02",
"dtamtf": "0",
"jrltype": "GOD",
"jrlpkid": "1562",
"subpkid": "190001011011003640",
"isdebit": "123213",
"expid": "1900/01/01",
"invno": "0",
"accountid": "20101023101100051"
}
]
};
let counter=0;
let cont = $('.cont');
function header(array){
let div = $("<div></div>");
let extraheader = $('<div></div>').addClass('extraFixedHeader');
$(cont).find('table').parent().before(div.clone().addClass('fixedheaderHolder'))
$.each(array.header,function(key,value){
let main = $(cont).find('table').find('thead').children('tr');
let mainfooter = $(cont).find('table').find('tfoot').children('tr');
var html = $("<th></th>");
let styleClass=' ';
let checkbox = $('<input type="checkbox" />').on('click',function(e){
e.stopPropagation();
});
let span = $('<span></span>')
let sorttrigger = $('<i></i>').addClass('fas fa-sort').addClass('sortTrigger text-secondary').attr('data-sorted','none');
let icon = sorttrigger.clone();
let label = $('<label></label>');
let itemShow = label.clone();
itemShow.off('click');
itemShow.on('click',function(){
if(!$(this).find('input').is(':checked')){
}
let direction=$(this).find('span').attr('data-freeze-column');
let colindex=$(this).parents('th').attr('data-column-index');
let table = main.parents('table');
let width = $(this).parents('table').find('tbody tr td[data-column-index="'+colindex+'"]').outerWidth()+6;
let height = $(this).parents('table').find('tbody tr td').outerHeight();
let headerheight = $(this).parents('th').outerHeight();
switch(direction){
case 'left':
table.find('tbody tr[data-row="true"]').each(function(){
$(this).find('td').eq(colindex).removeClass('freezeRight freezeLeft').addClass('freezeLeft').css({
'width':width,
'height':height
});
});
$(this).parents('th').removeClass('freezeRight freezeLeft').addClass('freezeLeft').css({
'width':width,
});
break;
case 'right':
table.find('tbody tr[data-row="true"]').each(function(){
console.log($(this).find('td').eq(colindex).outerHeight());
$(this).find('td').eq(colindex).removeClass('freezeRight freezeLeft').addClass('freezeRight').css({
'width':width,
});
});
$(this).parents('th').removeClass('freezeRight freezeLeft').addClass('freezeRight');
break;
default:
table.find('tbody tr[data-row="true"]').find('td:nth-child('+(+colindex+1)+')').removeClass('freezeRight freezeLeft');
$(this).parents('th').removeClass('freezeRight freezeLeft');
break;
}
})
icon.click(function(){
let sortdir = $(this).attr('data-sorted');
var table = $(this).parents('table');
var col = $(this).parents('th').attr('data-column-index');
icon.closest('tr').find('.sortTrigger').attr('data-sorted','none');
icon.closest('tr').find('.sortTrigger').addClass('fa-sort').removeClass('fa-sort-up fa-sort-down');
var rows = table.find('tbody tr[data-row="true"]').toArray().sort(comparer($(this).parents('th').index()))
switch (sortdir){
case 'none':
$(this).attr('data-sorted','asc');
$(this).removeClass('fa-sort').addClass('fa-sort-up');
this.asc = true;
break;
case 'asc':
$(this).attr('data-sorted','desc');
$(this).removeClass('fa-sort-up').addClass('fa-sort-down');
this.asc = false;
break;
case 'desc':
$(this).attr('data-sorted','none');
this.asc = 'none';
$(this).removeClass('fa-sort-down').addClass('fa-sort');
break;
}
if($(cont).find('.rowOrder ').children().length > 0){
return false;
}
if (!this.asc){
rows = rows.reverse()
}
if(this.asc != 'none'){
for (var i = 0; i < rows.length; i++){
table.append(rows[i])
}
}
});
let resizeable = div.clone().append(icon,span.clone().addClass('headerName').html(value.label)).addClass('resizeHeader');
let dropdowntrigger = $('<i></i>').addClass('fas fa-bars headerdroptriger').attr({
"data-toggle":"dropdown",
"aria-haspopup":"true",
});
let dropdown = div.clone().addClass('dropdown-menu').css({
'width':'100px',
})
let item = $('<a></a>').addClass('dropdown-item');
// dropdown.append(item.clone().append(itemShow.clone(true).append(checkbox.clone(true),span.clone().text('To right').attr('data-freeze-column','right'))));
// dropdown.append(item.clone().append(itemShow.clone(true).append(checkbox.clone(true),span.clone().text('To left').attr('data-freeze-column','left'))));
// dropdown.append(item.clone().append(itemShow.clone(true).append(checkbox.clone(true),span.clone().text('None').attr('data-freeze-column','none'))));
html.append(resizeable,div.clone().html('&nbsp;').addClass('resizeHandler')).attr('data-column-index',counter).attr({
'data-height':html.outerHeight(),
'data-width':html.outerWidth()
}).hide();
extraheader.append(div.clone().append(resizeable.clone(true).attr('data-column-index',counter)).addClass('fixedItem').css({
})).attr('data-column-index',counter);
switch(value.visible){
case true:
styleClass+='table-th-show ';
break;
case false:
styleClass+='table-th-hide ';
break;
}
switch(value.fontweight.toLowerCase()){
case 'lighter':
styleClass+='table-font-weight-light ';
break;
case 'normal':
styleClass+='table-font-weight-normal ';
break;
case 'heavy':
styleClass+='table-font-weight-heavy ';
break;
case 'bold':
styleClass+='table-font-weight-bold ';
break;
}
switch(value.footer.toLowerCase()){
case 'sum':
styleClass+='table-footer-data-sum ';
break;
case 'avg':
styleClass+='table-footer-data-avg ';
break;
case 'min':
styleClass+='table-footer-data-min ';
break;
case 'max':
styleClass+='table-footer-data-max ';
break;
default:
styleClass+=''
break;
}
html.addClass(styleClass);
main.append(html);
mainfooter.append(html.clone().text(''));
counter++;
});
$(cont).find('.fixedheaderHolder').append(div.clone().addClass('fixedrow').append(extraheader.children()));
};
header(array);
function body(array){
let i=0;
$.each(array.rows, function(key,value){
let main = $(cont).find('table').find('tbody');
let row=$('<tr></tr>').attr({
'data-row':'true',
'role':'row',
});
let td='';
if(i==0){
row.addClass('RowSelected');
}
let k = 0;
let currentrow=array.rows[i];
let countercolindex = 0;
$.each(currentrow,function(key,value){
let headerProp=array.header[k].label.toLowerCase();
td=$("<td></td>").attr('data-column-index',countercolindex);
td.text(currentrow[headerProp]);
td.on('click',function(){
if(main.find('.RowSelected').length > 0){
main.find('.RowSelected').removeClass('RowSelected');
main.find($(this)).closest('tr').addClass('RowSelected');
}
else{
main.find($(this)).closest('tr').addClass('RowSelected');
}
})
row.append(td);
countercolindex++;
k++;
});
main.append(row);
row='';
i++;
});
}
body(array);
$('table tbody tr')</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='cont'>
<table>
<thead>
</thead>
<tbody>
</tbody>
</table>
</div></code></pre>
</div>
</div>
</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-10-11T12:51:17.333",
"Id": "396219",
"Score": "1",
"body": "For a high number of rows, the performance cost will be high no matter how you do it."
}
] | [
{
"body": "<blockquote>\n <p>but 1k, 10k, 100k is different</p>\n</blockquote>\n\n<p>If you take a step back from code and look at the bigger picture, nobody actually reads 100k table rows in one session. It would be 100 rows at best, then people start skimming. At that point, all the effort of rendering is fo... | {
"AcceptedAnswerId": "205460",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-10-11T10:56:05.623",
"Id": "205373",
"Score": "-1",
"Tags": [
"javascript",
"performance",
"jquery"
],
"Title": "Creating dynamic table rows"
} | 205373 |
<p>I'm looking for a code review of this python I wrote - this code reads the zipcode column value from a CSV file and calls an API to retrieve lat, long, state and city info.</p>
<p>It works fine and gives me the correct results, but I'm looking for ways to improve the code/my approach and exception handling. I am pretty sure there are better ways to write this long code.</p>
<p>All comments and suggestions as brutal as may be are mostly appreciated.</p>
<pre><code>import requests
import pandas as pd
import time
from ratelimiter import RateLimiter
API_KEY = "some_key"
zip_code_col_name = "zipcode"
RETURN_FULL_RESULTS = False
excel_data = pd.read_csv("Downloads/test_order.csv", encoding='utf8')
if zip_code_col_name not in excel_data.columns:
raise ValueError("Missing zipcode column")
# This will put all zipcodes from column to list including duplicates , hence avoiding it.
#zipcodes = excel_data[zip_code_col_name].tolist()
zipcodes =[]
for i in excel_data.zipcode:
if i not in zipcodes:
zipcodes.append(i)
def get_geo_info(zipcode, API_KEY, return_full_response=False):
init_url = "some_url"
if API_KEY is not None:
url = init_url+API_KEY+"/info.json/"+format(zipcode)+"/degrees"
# Ping site for the reuslts:
r= requests.get(url)
if r.status_code != 200:
#this will print error code to but in reuslt set it will be empty
print("error is" + str(r.status_code))
data = r.json()
output = {
"zipcode" : data.get('zip_code'),
"lat" : data.get('lat'),
"lng" : data.get('lng'),
"city" : data.get('city'),
"state" : data.get('state')
}
return output
def limited(until):
duration = int(round(until - time.time()))
print('Rate limited, sleeping for {:d} seconds'.format(duration))
results = []
### Putting max call to 49 for 1 hour, we can paramterized it also
rate_limiter = RateLimiter(max_calls=49, period=3600, callback=limited)
for zipcode in zipcodes:
with rate_limiter:
geocode_result = get_geo_info(zipcode, API_KEY, return_full_response=RETURN_FULL_RESULTS)
results.append(geocode_result)
#print(results)
ddf = pd.DataFrame(results)
### This is to put the geo_info into same file however I would prefer it to write it to antoher file load it int staging table. to keep it for future refrence purposes.
""""df = pd.read_csv("Downloads/test_order.csv")
df['state'] = ddf.state
df['city'] = ddf.city
df['lattitude'] = ddf.lat
df['Longitude'] = ddf.lng
df['api_zip'] = ddf.zipcode
df.to_csv('Downloads/test_order.csv',index = False)"""
### This is to create a new file with the results
ddf.to_csv('Downloads/geo_info.csv',index = False)
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-10-11T16:02:25.373",
"Id": "396266",
"Score": "0",
"body": "Also, is `ratelimiter` the package available on PyPI (https://pypi.org/project/ratelimiter/), or something else?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate... | [
{
"body": "<p>Let's start with the zipcode data imported from the CSV file. This should probably be contained in its own method:</p>\n\n<pre><code>def get_zipcodes(zip_code_col_name, file_name=\"Downloads/test_order.csv\"):\n excel_data = pd.read_csv(file_name, encoding='utf8')\n if zip_code_col_name not ... | {
"AcceptedAnswerId": "205435",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-10-11T11:35:56.363",
"Id": "205376",
"Score": "5",
"Tags": [
"python",
"error-handling",
"geospatial"
],
"Title": "Rate-limited geographic data lookup"
} | 205376 |
<p>I have a task in which I want to handle error occurred in FTP downloading, For which I used the <code>wget</code> command to download a file via FTP and once the download is complete, compare downloaded filesize with FTP file size.</p>
<p>For that, I have the code as follows. My question: is this the correct method?</p>
<pre><code># fetch file details from the server and extract only number from the return value
FileSizeOnServer=curl --max-time 10 -u $FTP_USER:$FTP_PASSWORD --head $FTP_Path 2>&1 | grep "Content-Length:"
echo "Present File Size Details:" $FileSizeOnServer
FTP_File_Size=${FileSizeOnServer#*: }
echo "FTP_File_Size:$FTP_File_Size"
# fetch only size of local file size
DownloadedFileSize=`stat -c %s /home/pi/Desktop/ABCD.txt`
echo "DownloadedFileSize:$DownloadedFileSize"
# compare local and ftp file size
if [ "$DownloadedFileSize" -eq "$FTP_File_Size" ]; then
echo "Size matched"
else
echo "File Size doesn't match Start Downloading again"
fi
</code></pre>
| [] | [
{
"body": "<p>You definitely need more quoting of parameter expansions. Notably, <code>$FTP_PASSWORD</code> may well contain characters that are meaningful to the shell:</p>\n\n<pre><code>FileSizeOnServer=$(curl --max-time 10 -u \"$FTP_USER:$FTP_PASSWORD\" \\\n --head \"$FTP_Path\" 2>&... | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-10-11T11:51:01.883",
"Id": "205378",
"Score": "3",
"Tags": [
"bash",
"shell",
"ftp"
],
"Title": "Check that file is fully downloaded by FTP"
} | 205378 |
<p>Here is a simplified version of my JSON.</p>
<pre><code>{
"Relations": [
{
"Type": "A",
"Categories": [
{ "Name": "Identity" }
]
},
{
"Type": "B",
"Categories": [
{ "Name": "Identity" },
{
"Name": "Contact Information",
"Type": "Phone"
},
{ "Name": "Addresses" },
{ "Name": "Bank Accounts" }
]
},
{
"Type": "C",
"Categories": [
{ "Name": "Identity" },
{ "Name": "Contact Information" },
{ "Name": "Service Fields" }
]
}
]
}
</code></pre>
<p>My code generates an <code>IEnumerable</code> (<code>List</code>, but I am open to suggestions if there is a more compatible option) that holds all distinct categories, meaning, when joining its values (using <code>string.Join("\n", collection)</code>) it contains the following JSON:</p>
<pre><code>{ "Name": "Identity" }
{
"Name": "Contact Information"
"Type": "Phone"
}
{ "Name": "Addresses" }
{ "Name": "Bank Accounts" }
{ "Name": "Contact Information" }
{ "Name": "ServiceFields" }
</code></pre>
<p>This is the code:</p>
<pre><code>List<dynamic> Method()
{
string jString = File.ReadAllText(@"file.json");
dynamic jObject = JsonConvert.DeserializeObject<dynamic>(jString);
// The variable in questions
var categories = new List<dynamic>();
foreach (dynamic relation in jObject.Relations)
{
foreach (dynamic category in relation.Categories)
{
if (!CollectionContainsItem(categories, category))
{
categories.Add(category);
}
}
}
return categories;
bool CollectionContainsItem(IEnumerable<dynamic> collection, JToken searchedItem)
{
foreach (var item in collection)
{
if (JToken.DeepEquals(item, searchedItem))
{
return true;
}
}
return false;
}
}
</code></pre>
<p>How to improve my code? It seems very cumbersome to me, especially the local method.</p>
<p><strong>Note:</strong> I need a dynamic approach. I do not want to create C# classes for the JSON data.</p>
<p>Thanks!</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-10-11T14:12:51.180",
"Id": "396231",
"Score": "1",
"body": "Is it necessary that your result is in JSON? Couldn't you want a list of categories without json? Like : `[\"Identity\",\"Contact Information\",...]`"
},
{
"ContentLicens... | [
{
"body": "<p>Maybe try a two step process:</p>\n\n<p>First, convert the Json to XML. Various libraries can do the conversion.\nSecond, use LINQ to query the XML. LINQ documentation has examples.</p>\n\n<p>Expanding upon this answer. The original poster wanted less cumbersome code. Well, why reinvent the wheel?... | {
"AcceptedAnswerId": null,
"CommentCount": "10",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-10-11T13:51:39.567",
"Id": "205388",
"Score": "1",
"Tags": [
"c#",
"json",
"json.net"
],
"Title": "Extracting information from JSON"
} | 205388 |
<p>I've implemented a simple calculator in C# that takes in the left operand, the operator, and the right operand. Once the calculate button is clicked, I use four methods to validate the inputs:
1. The input is present
2. The operands are decimals
3. The operands are within the range 1-1000000
4. The operator is valid.</p>
<p>Right now all of these work <em>except</em> for #4, the operator validation. Where did I go wrong?</p>
<pre><code>namespace SimpleCalculator
{
public partial class SimpleCalculator : Form
{
public SimpleCalculator()
{
InitializeComponent();
}
//click event with private method Calculate
private void calcButton_Click(object sender, EventArgs e)
{
//validation for operands
try
{
if (IsValidData())
{
decimal operand1 = Convert.ToDecimal(operandTextBox1.Text);
string operator1 = operandTextBox1.Text;
decimal operand2 = Convert.ToDecimal(operand2TextBox.Text);
Calculate(operand1, operand2);
}
}
catch(FormatException)
{
MessageBox.Show("A format exception has occurred. Please check all entries.", "Entry Error");
}
catch (OverflowException)
{
MessageBox.Show("An overflow exception has occurred. Please enter smaller values.", "Entry Error");
}
catch (DivideByZeroException)
{
MessageBox.Show("Dividing by zero is not allowed. Please check operand entries.", "Entry Error");
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
}
// methods for IsPresent, IsDecimal, IsWithinRange, and IsOperator
public bool IsPresent(TextBox textBox, string name)
{
if(textBox.Text == "")
{
MessageBox.Show(name + " is a required field.", "Entry Error.");
textBox.Focus();
return false;
}
return true;
}
public bool IsDecimal(TextBox textBox, string name)
{
decimal number = 0m;
if(Decimal.TryParse(textBox.Text, out number))
{
return true;
}
else
{
MessageBox.Show(name + " must be a decimal value.", "Entry Error");
textBox.Focus();
return false;
}
}
public bool IsWithinRange(TextBox textBox, string name, decimal min, decimal max)
{
decimal number = Convert.ToDecimal(textBox.Text);
if(number < min || number > max)
{
MessageBox.Show(name + " must be between " + min.ToString() + " and " + max.ToString() + ".", "Entry Error");
textBox.Focus();
return false;
}
return true;
}
// this is the method that is returning false every time
public bool IsOperator(TextBox textBox, string name, string add, string subtract, string multiply, string divide)
{
string symbol = Convert.ToString(textBox.Text);
if(symbol != add || symbol != subtract || symbol != multiply || symbol != divide)
{
MessageBox.Show(name + " must be +, -, *, or /.", "Entry Error");
textBox.Focus();
return false;
}
return true;
}
//public method that that uses created methods to check validity
public bool IsValidData()
{
return
//validate operand 1
IsPresent(operandTextBox1, "Operand 1") &&
IsDecimal(operandTextBox1, "Operand 1") &&
IsWithinRange(operandTextBox1, "Operand 1", 1, 1000000) &&
//validate operand 2
IsPresent(operand2TextBox, "Operand 2") &&
IsDecimal(operand2TextBox, "Operand 2") &&
IsWithinRange(operand2TextBox, "Operand 2", 1, 1000000) &&
//validate operator
IsOperator(operatorTextBox, "Operator", "+", "-", "*", "/");
}
//private method that does the calculations
private void Calculate(decimal operand1, decimal operand2)
{
//switch statement that used the operator to perform calculations
//also displays error message if wrong operator is used
switch (operatorTextBox.Text)
{
case "+":
resultTextBox.Text = (operand1 + operand2).ToString("f4");
break;
case "-":
resultTextBox.Text = (operand1 - operand2).ToString("f4");
break;
case "*":
resultTextBox.Text = (operand1 * operand2).ToString("f4");
break;
case "/":
resultTextBox.Text = (operand1 / operand2).ToString("f4");
break;
default:
MessageBox.Show("You can only use +, -, *, or /");
break;
}
operandTextBox1.Focus();
}
private void exitButton_Click(object sender, EventArgs e)
{
this.Close();
}
private void clearResult(object sender, EventArgs e)
{
resultTextBox.Text = "";
}
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-10-11T15:02:08.583",
"Id": "396249",
"Score": "0",
"body": "operator validation when wrong in what case? could you please given an example for that? because your code look OK with the logic."
},
{
"ContentLicense": "CC BY-SA 4.0",... | [
{
"body": "<h2>1. About your question( validation operator is wrong):</h2>\n\n<p>From your condition:</p>\n\n<blockquote>\n <p>if(symbol != add || symbol != subtract || symbol != multiply || symbol\n != divide)</p>\n</blockquote>\n\n<p>you are checking if the symbol is not 1 of 4 operators then it will return... | {
"AcceptedAnswerId": "205398",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-10-11T14:47:25.917",
"Id": "205395",
"Score": "-2",
"Tags": [
"c#",
"validation",
"calculator"
],
"Title": "Simple calculator with validation"
} | 205395 |
<p>So I've been following the discussions around VBA as an OOP language and the applicability of various design patterns, such as MVP or MVC. Excellent postings on these topics are extremely informative and have caused me to rethink my implementation approach for my projects (past and present). Change and growth is always a good thing :)</p>
<ul>
<li><a href="https://stackoverflow.com/a/101561/4717755">What are MVP and MVC and what is the difference?</a></li>
<li><a href="https://rubberduckvba.wordpress.com/2017/10/25/userform1-show/" rel="nofollow noreferrer">UserForm1.Show</a></li>
<li><a href="https://codereview.stackexchange.com/questions/205263/responding-to-events-of-dynamically-added-controls">Responding to Events of Dynamically added Controls</a></li>
<li><a href="https://rubberduckvba.wordpress.com/2018/08/29/vbaoop-what-when-why/" rel="nofollow noreferrer">VBA+OOP: What, When, and Why</a></li>
<li>plus many of the posts here on Code Review (especially the <a href="https://codereview.stackexchange.com/questions/204982/web-battleship-the-unofficial-battleship-ui">Battleship</a> implementation) </li>
</ul>
<p>What I'm looking for is a discussion along these lines on the applicability of the MVC/MVP design pattern when then the "view" is not a userform, but is the worksheet itself. I think this is a common implementation technique for many developers, both new and experienced. This especially includes worksheets that hold the data to be manipulated and use embedded form controls. I'll contribute an example of my own approach to add to the discussion for critique and comment.</p>
<p><strong>Design Thoughts</strong></p>
<p>Most of the clean examples discussed about an MVP or MVC design pattern present the user interface as a userform. The userform is an easily accessible object with the class VBA code written largely by the developer. Controls are added, often <code>WithEvents</code>, and <code>Interface</code> classes can be designed for the userform to <code>Implement</code>. The data presented and/or used on the userform most often is derived or directly sourced from data on a worksheet. But what if the worksheet IS both the datastore and the "view with controls"?</p>
<p>I toyed with creating a persistent object that would be always available (<code>VB_PredeclaredId = True</code>), but discarded that idea because there already is a persistent data store: the worksheet object itself. The basic idea is an MVC design pattern.</p>
<p>After many different iterations, I arrived at a design where a data model is created only when needed, i.e. when activity on the worksheet occurs. The "view" aspect of the pattern is handled directly by the formatted data on the worksheet. The "controller" part of the pattern are functional <code>Sub</code> and <code>Function</code> calls tied directly to worksheet or control events.</p>
<p><em>(The whole reason for this post and my interest in a discussion is to find out if this is a "preferred" way of achieving the goals of the application. Clearly, my approach works. But I'm always on a quest for improvement!)</em></p>
<p><strong>The Application</strong></p>
<p>This is one part of an overall application that's needed to import a variety of data from external sources. The original configuration interface was set up on a worksheet with a (relatively) static number of possible entries. Each entry row is selectable and the user can click a button to bring up the file selection dialog to choose a file. Two of the fields are user-editable. (Optional access to this application in my <a href="https://github.com/pmtutko/ConfigureView" rel="nofollow noreferrer">GitHub</a>)</p>
<p><a href="https://i.stack.imgur.com/SEbPp.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/SEbPp.png" alt="enter image description here"></a></p>
<p><em>If you choose, there is a module below (<code>CreateProjectSheet</code>) that should create the "Configure" worksheet, format the "view" and create the controls. Obviously, run the top-level routine once to set up the worksheet.</em></p>
<p><strong>The Code - ConfigureView Project</strong></p>
<p>The code breaks down into a combination of the data model (<code>ProjectsModel</code> with a <code>ProjectInfo</code> collection) and the "controller" code (several code modules that respond to the worksheet and control events.</p>
<p><a href="https://i.stack.imgur.com/O8e4C.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/O8e4C.png" alt="enter image description here"></a></p>
<p>Starting in the <code>ProjectGlobal</code> module, there is a set of helper functions that give quick access to relevant areas of the "view". Additionally, I've established an enumeration that provides access to the correct data column within the "view".</p>
<p>Module: <code>ProjectGlobal</code></p>
<pre><code>Option Explicit
Public Enum ProjectInfoColumns
[_First] = 1 'columns numbers are relative to the anchor cell
ProjectNumber = 1
SelectCheckBox = 2
DBName = 3
FullPath = 4
BrowseButton = 5
FileTimestamp = 6
SelectedCellLink = 7
[_Last] = 7
End Enum
Public Enum ProjectApp_Errors
NoProjectArea = vbObject + 600
IndexOutOfBounds
End Enum
Public Const DEFAULT_PROJECT_ROWS As Long = 15
Public Const ROW_ONE_ANCHOR As String = "A3"
Public Function ConnectToModel() As ProjectsModel
Dim anchor As Range
Dim projectArea As Range
Set anchor = ThisWorkbook.Sheets("Configure").Range(ROW_ONE_ANCHOR)
Set projectArea = anchor.Resize(DEFAULT_PROJECT_ROWS, ProjectInfoColumns.[_Last])
Dim pvm As ProjectsModel
Set pvm = New ProjectsModel
pvm.Connect projectArea
Set ConnectToModel = pvm
End Function
Public Function ProjectEditableArea() As Range
Dim anchor As Range
Dim projectArea As Range
Set anchor = ThisWorkbook.Sheets("Configure").Range(ROW_ONE_ANCHOR)
Set projectArea = anchor.Resize(DEFAULT_PROJECT_ROWS, ProjectInfoColumns.[_Last])
Set ProjectEditableArea = Application.Union(projectArea.Columns(ProjectInfoColumns.DBName), _
projectArea.Columns(ProjectInfoColumns.FullPath))
End Function
Public Function ProjectSelectAllCell() As Range
Dim anchor As Range
Set anchor = ThisWorkbook.Sheets("Configure").Range(ROW_ONE_ANCHOR)
Set ProjectSelectAllCell = anchor.Offset(-1, ProjectInfoColumns.SelectedCellLink - 1)
End Function
Public Function ProjectInfoColumnsName(ByVal index As Long) As String
ProjectInfoColumnsName = vbNullString
If (index >= ProjectInfoColumns.[_First]) Or _
(index <= ProjectInfoColumns.[_Last]) Then
Dim names() As String
names = Split(",Name in DB,MS Excel Path,," & _
"MS Excel File Timestamp,,", _
",", , vbTextCompare)
ProjectInfoColumnsName = names(index - 1)
End If
End Function
Public Function ProjectRowIndex(ByVal wsRowIndex As Long) As Long
'--- given the worksheet row number, this returns the project
' index row into the group of projects
Dim anchor As Range
Set anchor = ThisWorkbook.Sheets("Configure").Range(ROW_ONE_ANCHOR)
ProjectRowIndex = wsRowIndex - anchor.Row + 1
End Function
</code></pre>
<p>In particular, notice the <code>ConnectToModel</code> function that creates the data model giving quick and abstracted access to the underlying data. All data access should go through this model.</p>
<p>Class: <code>ProjectsModel</code></p>
<pre><code>Option Explicit
Private Type InternalData
storage As Range
projects As Collection 'collection of ProjectInfo objects
End Type
Private this As InternalData
Public Property Get IsConnected() As Boolean
IsConnected = (Not this.projects Is Nothing)
End Property
Public Property Get ProjectCount() As Long
If Not this.projects Is Nothing Then
ProjectCount = this.projects.Count
Else
ProjectCount = 0
End If
End Property
Public Property Get GetProject(ByVal index As Long) As ProjectInfo
If Not this.projects Is Nothing Then
If index > 0 And index <= this.projects.Count Then
Set GetProject = this.projects(index)
Else
Err.Raise ProjectApp_Errors.IndexOutOfBounds, _
"ProjectsModel::GetProject", _
"Project index out of bounds"
End If
Else
Set GetProject = Nothing
End If
End Property
Public Sub Connect(ByRef projectArea As Range)
If this.storage Is Nothing Then
If Not projectArea Is Nothing Then
Set this.storage = projectArea
Else
Err.Raise ProjectApp_Errors.NoProjectArea, _
"ProjectsModel::Load", _
"Missing project area"
End If
ElseIf Not this.storage = projectArea Then
'--- we've got a new table, so dump the old one and reload
Set this.storage = Nothing
Set this.storage = projectArea
End If
Set this.projects = Nothing
Set this.projects = New Collection
Dim projectRow As Range
Set projectRow = this.storage.Resize(1, ProjectInfoColumns.[_Last])
Dim i As Long
Dim newInfo As ProjectInfo
For i = 1 To projectArea.Rows.Count
Set newInfo = New ProjectInfo
newInfo.Connect projectRow
this.projects.Add newInfo
Set projectRow = projectRow.Offset(1, 0)
Next i
End Sub
Public Function GetSelectedProjects() As Collection
Dim selectedCollection As Collection
Dim projectRow As Variant
For Each projectRow In this.projects
If projectRow.IsSelected Then
If selectedCollection Is Nothing Then
Set selectedCollection = New Collection
End If
selectedCollection.Add projectRow
End If
Next projectRow
Set GetSelectedProjects = selectedCollection
End Function
Private Sub Class_Initialize()
End Sub
</code></pre>
<p>There's an interesting aspect to the <code>ProjectInfo</code> class below. Because each "view" row has a checkbox (and a button), expected UX behavior would present the checkbox as "unselectable" if the row is empty of data. So each of the <code>ProjectInfo</code> objects must "connect" to the appropriate checkbox located on its row, and then enable/disable as appropriate.</p>
<p>Class: <code>ProjectInfo</code></p>
<pre><code>Option Explicit
Private Type InternalData
projectRow As Range
selectBox As CheckBox
End Type
Private this As InternalData
Public Property Let IsSelected(ByVal newState As Boolean)
'--- can only be selected if there is a valid filename
If Len(this.projectRow.Cells(1, ProjectInfoColumns.FullPath)) > 0 Then
this.projectRow.Cells(1, ProjectInfoColumns.SelectedCellLink).Value = newState
End If
End Property
Public Property Get IsSelected() As Boolean
IsSelected = this.projectRow.Cells(1, ProjectInfoColumns.SelectedCellLink).Value
End Property
Public Property Let NameInDB(ByVal newName As String)
'--- disable events because this area is watched by a
' Worksheet_Change event
Application.EnableEvents = False
this.projectRow.Cells(1, ProjectInfoColumns.DBName).Value = newName
Application.EnableEvents = True
End Property
Public Property Get NameInDB() As String
NameInDB = this.projectRow.Cells(1, ProjectInfoColumns.DBName).Value
End Property
Public Property Let FullPath(ByVal newPath As String)
'--- disable events because this area is watched by a
' Worksheet_Change event
Application.EnableEvents = False
If Len(newPath) > 0 Then
this.projectRow.Cells(1, ProjectInfoColumns.FullPath).Value = newPath
On Error GoTo TimestampError
Me.FileTimestamp = FileDateTime(newPath)
Else
'--- clear all the data if the user deleted the name
this.projectRow.Cells(1, ProjectInfoColumns.DBName).Value = vbNullString
this.projectRow.Cells(1, ProjectInfoColumns.FullPath).Value = vbNullString
this.projectRow.Cells(1, ProjectInfoColumns.FileTimestamp).Value = vbNullString
End If
NormalExit:
SetCheckBoxState
Application.EnableEvents = True
Exit Property
TimestampError:
If Err.Number = 53 Then
MsgBox "The filename you entered is not valid. Please enter " & _
"a valid filename.", vbCritical + vbOKOnly, _
"Error In Filename"
this.projectRow.Cells(1, ProjectInfoColumns.FullPath).Value = vbNullString
End If
GoTo NormalExit
End Property
Public Property Get FullPath() As String
FullPath = this.projectRow.Cells(1, ProjectInfoColumns.FullPath)
End Property
Public Property Get PathOnly() As String
'--- returns ONLY the path part of the full path
PathOnly = vbNullString
If Len(Me.FullPath) = 0 Then
Exit Property
End If
Dim pos1 As Long
pos1 = InStrRev(Me.FullPath, "\", , vbTextCompare)
If pos1 > 0 Then
PathOnly = left$(Me.FullPath, pos1 - 1)
Else
PathOnly = Me.FullPath
End If
End Property
Public Property Get Filename() As String
'--- returns ONLY the filename part of the full path
Filename = vbNullString
If Len(Me.FullPath) = 0 Then
Exit Property
End If
Dim pos1 As Long
pos1 = InStrRev(Me.FullPath, "\", , vbTextCompare)
If pos1 > 0 Then
Filename = Right$(Me.FullPath, Len(Me.FullPath) - pos1)
Else
Filename = Me.FullPath
End If
End Property
Public Property Let FileTimestamp(ByVal newDate As Date)
this.projectRow.Cells(1, ProjectInfoColumns.FileTimestamp).Value = newDate
End Property
Public Property Get FileTimestamp() As Date
FileTimestamp = this.projectRow.Cells(1, ProjectInfoColumns.FileTimestamp).Value
End Property
Public Sub Connect(ByRef dataRow As Range)
'--- establishes the connection of this object to the given worksheet
' row of project data
Set this.projectRow = dataRow
FindMyCheckBox
SetCheckBoxState
End Sub
Private Sub Class_Initialize()
End Sub
Private Sub FindMyCheckBox()
'--- quickly loop through all the checkboxes on the worksheet and find the
' one that is located in this assigned row. there can only be one
Dim cb As CheckBox
Dim ws As Worksheet
Set ws = this.projectRow.Parent
For Each cb In ws.CheckBoxes
If (cb.top >= this.projectRow.top) And _
(cb.top < (this.projectRow.top + this.projectRow.height)) Then
Set this.selectBox = cb
Exit For
End If
Next cb
End Sub
Private Sub SetCheckBoxState()
'--- the checkbox is enabled if there is a valid filename
If Not this.selectBox Is Nothing Then
If Len(Me.FullPath) > 0 Then
this.selectBox.Enabled = True
Else
this.selectBox.Value = False
this.selectBox.Enabled = False
End If
End If
End Sub
</code></pre>
<p>So executing the <code>ConnectToModel</code> function will create the model above.</p>
<p>Start interacting with the "view" by clicking any of the file browse buttons and choosing a file. The file path and timestamp are filled in. The "Name in DB" is optional and less important in this example. You can also manually enter a filename if you choose which will be picked up by the <code>Worksheet_Change</code> event in the worksheet object.</p>
<p>Module: <code>ProjectBrowse</code></p>
<pre><code>Option Explicit
Public Sub UserFileSelect()
'--- connected to the "..." button on the Configure worksheet to select
' an MS Project file for that row
Dim wsRow As Long
Dim projectIndex As Long
wsRow = ThisWorkbook.Sheets("Configure").Shapes(Application.Caller).TopLeftCell.Row
projectIndex = ProjectRowIndex(wsRow)
Dim pvm As ProjectsModel
Set pvm = ConnectToModel()
Dim projInfo As ProjectInfo
Set projInfo = pvm.GetProject(projectIndex)
Dim filePicker As Office.FileDialog
Set filePicker = Application.FileDialog(MsoFileDialogType.msoFileDialogOpen)
With filePicker
.Title = "Select an MS Excel File to Add..."
.Filters.Add "MS Project", "*.xlsx", 1
.AllowMultiSelect = False
If Len(projInfo.FullPath) > 0 Then
.InitialFileName = projInfo.FullPath
Else
.InitialFileName = ThisWorkbook.path
End If
If .Show Then
projInfo.FullPath = .SelectedItems(1)
End If
End With
End Sub
</code></pre>
<p>Worksheet Object: `Sheet2 (Configure)</p>
<pre><code>Option Explicit
Private Sub Worksheet_Change(ByVal Target As Range)
Dim editArea As Range
Dim dbNameArea As Range
Dim selectAllBox As Range
Set editArea = ProjectGlobal.ProjectEditableArea().Columns(2)
Set dbNameArea = ProjectGlobal.ProjectEditableArea().Columns(1)
Set selectAllBox = ProjectGlobal.ProjectSelectAllCell()
Dim i As Long
Dim pvm As ProjectsModel
Dim projectIndex As Long
Dim projInfo As ProjectInfo
If Not Union(editArea, Target) Is Nothing Then
Set pvm = ProjectGlobal.ConnectToModel()
For i = 1 To Target.Rows.Count
projectIndex = ProjectGlobal.ProjectRowIndex(Target.Rows(i).Row)
Set projInfo = pvm.GetProject(projectIndex)
'--- this was just edited by the user, but re-apply the edit
' through the Info object for validation
projInfo.FullPath = Target.Rows(i).Value
Next i
ElseIf Not Union(dbNameArea, Target) Is Nothing Then
Set pvm = ProjectGlobal.ConnectToModel()
For i = 1 To Target.Rows.Count
projectIndex = ProjectGlobal.ProjectRowIndex(Target.Rows(i).Row)
Set projInfo = pvm.GetProject(projectIndex)
'--- this was just edited by the user, but re-apply the edit
' through the Info object for validation
projInfo.NameInDB = Target.Rows(i).Value
Next i
ElseIf Not Union(selectAllBox, Target) Then
ProjectSelect.CheckUncheckAll
End If
End Sub
</code></pre>
<p>The other "view" controls are the checkboxes and the "Import" button. The code for those is below:</p>
<p>Module: <code>ProjectSelect</code></p>
<pre><code>Option Explicit
Public Sub CheckUncheckAll()
Dim selectAllBox As Range
Set selectAllBox = ProjectSelectAllCell()
Dim pvm As ProjectsModel
Dim projInfo As ProjectInfo
Set pvm = ConnectToModel()
Dim i As Long
For i = 1 To pvm.ProjectCount
Set projInfo = pvm.GetProject(i)
projInfo.IsSelected = selectAllBox
Next i
End Sub
</code></pre>
<p>Module: <code>ProjectImport</code></p>
<pre><code>Option Explicit
Public Sub ImportProjects()
Dim pvm As ProjectsModel
Set pvm = ConnectToModel()
Dim selectedProjects As Collection
Set selectedProjects = pvm.GetSelectedProjects
Dim text As String
If selectedProjects Is Nothing Then
text = "No projects selected!"
Else
Dim proj As Variant
For Each proj In selectedProjects
text = text & " -- " & proj.Filename & vbCrLf
Next proj
End If
MsgBox "You selected these projects for import:" & vbCrLf & text, _
vbInformation + vbOKOnly
End Sub
</code></pre>
<p>As promised, if you wanted to create and interact with this application, import the module below and execute <code>BuildProjectView</code></p>
<p>Module: <code>CreateProjectsSheet</code></p>
<pre><code>Option Explicit
Public Sub BuildProjectView()
'--- wipe the sheet and build it up to ensure everything is
' in the right place
Dim ws As Worksheet
On Error Resume Next
Set ws = ThisWorkbook.Sheets("Configure")
If ws Is Nothing Then
Set ws = ThisWorkbook.Sheets.Add
ws.Name = "Configure"
End If
ResetSheet ws
Dim anchor As Range
Dim projectArea As Range
Dim headerArea As Range
Dim importArea As Range
Set anchor = ws.Range(ROW_ONE_ANCHOR)
Set projectArea = anchor.Resize(DEFAULT_PROJECT_ROWS, ProjectInfoColumns.[_Last])
Set headerArea = anchor.Offset(-1, 1).Resize(1, ProjectInfoColumns.[_Last] - 2)
Set importArea = anchor.Offset(DEFAULT_PROJECT_ROWS + 1, 2)
ws.Cells.Interior.color = XlRgbColor.rgbPaleTurquoise 'overall bg color
FormatProjectArea projectArea, headerArea
CreateBrowseButtons ws, projectArea
CreateCheckboxes ws, projectArea
CreateImportButton ws, importArea
anchor.Offset(, 2).Select
End Sub
Private Sub ResetSheet(ByRef ws As Worksheet)
With ws
.Cells.Clear
.Cells.ColumnWidth = 8.14
.Cells.EntireRow.AutoFit
.Cells.Font.Name = "Calibri"
.Cells.Font.Size = 11
Do While .CheckBoxes.Count > 0
.CheckBoxes(1).Delete
Loop
Do While .Buttons.Count > 0
.Buttons(1).Delete
Loop
Do While .OLEObjects.Count > 0
.OLEObjects(1).Delete
Loop
End With
End Sub
Private Sub FormatProjectArea(ByRef projectArea As Range, _
ByRef headerArea As Range)
Dim areaWithoutNumbers As Range
Set areaWithoutNumbers = projectArea.Offset(0, 1).Resize(, ProjectInfoColumns.[_Last] - 2)
With areaWithoutNumbers.Borders
.LineStyle = xlContinuous
.color = XlRgbColor.rgbDarkGray
.Weight = xlThin
End With
'--- predefined column widths and formats
With projectArea
.Columns(ProjectInfoColumns.ProjectNumber).ColumnWidth = 3#
.Columns(ProjectInfoColumns.SelectCheckBox).ColumnWidth = 3#
.Columns(ProjectInfoColumns.DBName).ColumnWidth = 11#
.Columns(ProjectInfoColumns.FullPath).ColumnWidth = 40#
.Columns(ProjectInfoColumns.BrowseButton).ColumnWidth = 5#
.Columns(ProjectInfoColumns.FileTimestamp).ColumnWidth = 14#
.Cells(1, ProjectInfoColumns.SelectCheckBox).Resize(.Rows.Count, 1).Interior.color = rgbWhite
.Cells(1, ProjectInfoColumns.DBName).Resize(.Rows.Count, 1).Interior.color = rgbWhite
.Cells(1, ProjectInfoColumns.FullPath).Resize(.Rows.Count, 1).Interior.color = rgbWhite
.Cells(1, ProjectInfoColumns.FileTimestamp).Resize(.Rows.Count, 1).NumberFormat = "dd-mmm-yyyy"
'--- the linked cell needs to have the same font color as the background
.Cells(1, ProjectInfoColumns.SelectedCellLink).Resize(.Rows.Count, 1).Font.color = XlRgbColor.rgbPaleTurquoise
End With
With headerArea
.Cells.Interior.color = XlRgbColor.rgbDarkBlue
.Cells.Font.color = XlRgbColor.rgbWhite
.Cells.Font.Bold = True
.Borders.LineStyle = xlContinuous
.Borders.color = XlRgbColor.rgbDarkGray
.Borders.Weight = xlThin
.WrapText = True
.HorizontalAlignment = xlCenter
.EntireRow.AutoFit
Dim i As Long
'--- start at _First+1 to skip the ProjectNumber column
For i = (ProjectInfoColumns.[_First] + 1) To ProjectInfoColumns.[_Last]
.Cells(1, i).Value = ProjectInfoColumnsName(i)
Next i
'--- the linked cell needs to have the same font color as the background
.Cells(1, .Columns.Count + 1).Font.color = XlRgbColor.rgbPaleTurquoise
End With
'--- label the project indexes
With projectArea
For i = 1 To .Rows.Count
.Cells(i, ProjectInfoColumns.ProjectNumber).Value = i
Next i
.Resize(.Rows.Count, 1).Font.Size = 8
End With
End Sub
Private Sub CreateBrowseButtons(ByRef ws As Worksheet, ByRef projectArea As Range)
Dim projectRow As Range
Set projectRow = projectArea.Resize(1, ProjectInfoColumns.[_Last])
Dim left As Double
Dim top As Double
Dim height As Double
Dim width As Double
Dim i As Long
For i = 1 To DEFAULT_PROJECT_ROWS
With projectRow
height = .height - 2
width = .Cells(1, ProjectInfoColumns.BrowseButton).width - 2
top = .top + 1
left = .Cells(1, ProjectInfoColumns.BrowseButton).left + 1
Dim btn As Button
Set btn = ws.Buttons.Add(left:=left, top:=top, _
height:=height, width:=width)
btn.Caption = "..."
btn.Enabled = True
btn.OnAction = "UserFileSelect"
Set projectRow = projectRow.Offset(1, 0)
End With
Next i
End Sub
Private Sub CreateCheckboxes(ByRef ws As Worksheet, ByRef projectArea As Range)
Dim projectRow As Range
Set projectRow = projectArea.Resize(1, ProjectInfoColumns.[_Last] + 1)
Dim left As Double
Dim top As Double
Dim height As Double
Dim width As Double
Dim cb As CheckBox
Dim i As Long
For i = 1 To DEFAULT_PROJECT_ROWS
With projectRow
top = .top + 1
height = .height - 2
width = 14
With .Cells(1, ProjectInfoColumns.SelectCheckBox)
'--- centered in the column
left = .left + (.width / 2#) - (width / 2#)
End With
End With
Set cb = ws.CheckBoxes.Add(left:=left, top:=top, _
height:=height, width:=width)
cb.Caption = vbNullString
cb.LinkedCell = projectRow.Cells(1, ProjectInfoColumns.SelectedCellLink).Address
projectRow.Cells(1, ProjectInfoColumns.SelectedCellLink).Value = False
'--- sometimes the height and width don't get correctly set during
' the Add call, so set them (again) here, with other settings
cb.height = height
cb.width = width
Set projectRow = projectRow.Offset(1, 0)
Next i
'--- now add the Select All checkbox above these
' keep the same height, width, and left position, but
' recalculate the Top to set it at the botton of the cell
Set projectRow = projectArea.Offset(-1, 0).Resize(1, ProjectInfoColumns.[_Last] + 1)
top = projectRow.top + projectRow.height - height - 2
Set cb = ws.CheckBoxes.Add(left:=left, top:=top, _
height:=height, width:=width)
cb.Caption = vbNullString
cb.OnAction = "CheckUncheckAll"
cb.LinkedCell = projectRow.Cells(1, ProjectInfoColumns.SelectedCellLink).Address
projectRow.Cells(1, ProjectInfoColumns.SelectedCellLink).Value = False
End Sub
Private Sub CreateImportButton(ByRef ws As Worksheet, _
ByRef importArea As Range)
Dim left As Double
Dim top As Double
Dim height As Double
Dim width As Double
With importArea
height = .height * 2#
width = .width * 2.5
left = .left
top = .top
Dim btn As Button
Set btn = ws.Buttons.Add(left:=left, top:=top, _
height:=height, width:=width)
btn.Caption = "Import Select Projects"
btn.Enabled = True
btn.OnAction = "ImportProjects"
End With
End Sub
</code></pre>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-10-11T14:53:29.013",
"Id": "205396",
"Score": "4",
"Tags": [
"object-oriented",
"vba",
"excel"
],
"Title": "So what if the \"View\" in an MVC isn't a Userform, but is the Worksheet?"
} | 205396 |
<p>I have been studying C#, and I am trying to model the Tic Tac Toe game. Is my program reasonable or is there anything I need to improve?</p>
<pre><code> enum Result
{
None,
Win,
Draw
}
public class TicTacToe
{
static char[] board = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' };
char player = 'O';
Result result = Result.None;
public void PlayGame()
{
Intro();
do
{
Console.Clear();
Console.WriteLine("Player 1 : O Player 2 : X");
DrawBoard();
Console.WriteLine($"\nPlayer {player}'s Turn \nPlease Enter the empty number");
label:
int choice = 0;
while (!int.TryParse(Console.ReadLine(), out choice))
{
Console.WriteLine("Enter the num please");
}
if (choice >= 10)
{
Console.WriteLine("Please enter btw 1 - 9");
goto label;
}
if (board[choice] != 'X' && board[choice] != 'O')
{
board[choice] = player;
ChangeTurn();
}
CheckWin();
} while (result != Result.Draw && result != Result.Win);
Console.Clear();
DrawBoard();
GameResult();
Console.ReadKey();
}
void ChangeTurn()
{
if (player == 'X')
player = 'O';
else if (player == 'O')
player = 'X';
}
void GameResult()
{
if (result == Result.Win)
{
ChangeTurn();
Console.WriteLine("Player {0} has won", player);
}
else if(result == Result.Draw)
{
Console.WriteLine("Draw");
}
Console.ReadLine();
}
void Intro()
{
Console.WriteLine("Welcome to TieTacToe");
Console.WriteLine("Press any Key to continue");
Console.ReadKey();
Console.Clear();
}
void DrawBoard()
{
int x = 1;
Console.WriteLine();
for (int row = 0; row < 3; row++)
{
Console.Write("| ");
for (int col = 0; col < 3; col++)
{
Console.Write(board[x]);
Console.Write(" | ");
x++;
}
Console.WriteLine();
}
}
void CheckWin()
{
// horzontial
if (board[1] == board[2] && board[2] == board[3])
{
result = Result.Win;
}
else if (board[4] == board[5] && board[5] == board[6])
{
result = Result.Win;
}
else if (board[7] == board[8] && board[8] == board[9])
{
result = Result.Win;
}
// vertical
else if (board[1] == board[4] && board[4] == board[7])
{
result = Result.Win;
}
else if (board[2] == board[5] && board[5] == board[8])
{
result = Result.Win;
}
else if (board[3] == board[6] && board[6] == board[9])
{
result = Result.Win;
}
// X
else if (board[1] == board[5] && board[5] == board[9])
{
result = Result.Win;
}
else if (board[3] == board[5] && board[5] == board[7])
{
result = Result.Win;
}
else if (board[1] != '1' && board[2] != '2' && board[3] != '3' && board[4] != '4' && board[5] != '5' && board[6] != '6' && board[7] != '7' && board[8] != '8' && board[9] != '9')
{
result = Result.Draw;
}
else
{
result = Result.None;
}
}
}
</code></pre>
| [] | [
{
"body": "<p>If you want to be completely safe, I would also check the 'choice' to make sure that it was not a negative number.</p>\n\n<p><code>Goto</code>'s should be avoided. You can easily refactor your code to use a <code>while</code> loop and <code>break</code>.</p>\n\n<p>In your function <code>GameResult... | {
"AcceptedAnswerId": "205400",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-10-11T15:20:35.973",
"Id": "205397",
"Score": "1",
"Tags": [
"c#",
"tic-tac-toe"
],
"Title": "TicTacToe game in C#"
} | 205397 |
<p>I wanted to challenge myself in a new language that I am learning (C#) by doing a simple exercise: check if a "modulus 10" Luhn number is valid or not. In this case the common application if verifying credit card numbers. So I discovered that an exist implementation of this algorithm.</p>
<p>I have tested the code works with <a href="http://www.validcreditcardnumber.com/" rel="nofollow noreferrer">generated card numbers</a>)</p>
<p>How might this be improved. I saw on <a href="https://stackoverflow.com/questions/21249670/implementing-luhn-algorithm-using-c-sharp">other posts</a> that all the procedure can be done in very few lines of code compared to mine.</p>
<p><strong>Program.cs</strong></p>
<pre><code>using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CreditCardChecker
{
class Program
{
static void Main(string[] args)
{
string cardNumber = Operations.UInput();
LuhnValidator.Validator(cardNumber);
Operations.DoWork();
Console.ReadLine();
}
}
class Operations
{
static string userInput;
static string cardType = "";
public static string UInput()
{
Console.ForegroundColor = ConsoleColor.White;
Console.WriteLine("Insert credit card number");
userInput = Console.ReadLine();
return userInput;
}
public static void DoWork()
{
if (LuhnValidator.IsValid(userInput) == true)
{
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine("Valid Card");
var input = userInput.Substring(0, 1);
switch (input)
{
case "3":
Console.ForegroundColor = ConsoleColor.Cyan;
break;
case "4":
Console.ForegroundColor = ConsoleColor.Blue;
break;
case "5":
Console.ForegroundColor = ConsoleColor.Yellow;
break;
case "6":
Console.ForegroundColor = ConsoleColor.DarkYellow;
break;
default:
Console.WriteLine("Card type unidentified");
break;
}
cardType = ConfigurationManager.AppSettings[input];
Console.WriteLine(cardType);
}
else
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("Invalid Card");
}
}
}
}
</code></pre>
<p><strong>LuhnValidator.cs</strong></p>
<pre><code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CreditCardChecker
{
// TODO: refactoring
//CheckDigit included
class LuhnValidator
{
static string invertedCardNumber = "";
static string noCheckDigit = "";
static List<int> numbersArray = new List<int>();
static List<int> listEvenPosition = new List<int>();
static List<int> listOddPosition = new List<int>();
static List<int> evenNumbers = new List<int>();
static List<int> notSumEvenNumbers = new List<int>();
static int sumDoubleEvenNumbers;
static int sumOfAll;
static int magicNumber = 0;
static int checkDigit = 0;
public static void Validator(string cardNumber)
{
Inverser(cardNumber);
AddToList(invertedCardNumber);
EvenOddLists();
Multiply();
Sums();
IsValid(cardNumber);
}
public static void Inverser(string cardNumber)
{
try
{
cardNumber = cardNumber.Replace(" ", string.Empty);
switch (cardNumber.Length)
{
case 16:
noCheckDigit = cardNumber.Substring(0, 15);
break;
case 15:
noCheckDigit = cardNumber.Substring(0, 14);
break;
default:
Console.WriteLine("Insert a valid number");
break;
}
// Invert card number so I can operate from left to right
for (int i = noCheckDigit.Length - 1; i >= 0; i--)
{
invertedCardNumber = invertedCardNumber + cardNumber[i];
}
}
catch (Exception)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("Number too short");
}
}
public static void AddToList(string noCheckDigit)
{
// Convert the numbers from char to int and add them to array
numbersArray = invertedCardNumber.Substring(0, invertedCardNumber.Length).Select(c => c - '0').ToList();
}
public static void EvenOddLists()
{
// Separate Even and Odd numbers into two lists
listEvenPosition = numbersArray.Where((item, index) => index % 2 == 0).ToList();
listOddPosition = numbersArray.Where((item, index) => index % 2 != 0).ToList();
}
public static void Multiply()
{
foreach (var digit in listEvenPosition)
{
int sum = digit * 2;
if (sum > 9)
{
var digits = sum.ToString().Select(x => int.Parse(x.ToString()));
evenNumbers.Add(digits.Sum());
}
if (sum < 9)
{
notSumEvenNumbers.Add(sum);
}
}
sumDoubleEvenNumbers = evenNumbers.Sum();
}
public static void Sums()
{
int a = listOddPosition.Sum();
int b = notSumEvenNumbers.Sum();
sumOfAll = a + b + sumDoubleEvenNumbers;
checkDigit = Convert.ToInt32((sumOfAll * 9).ToString().AsEnumerable().Last().ToString());
if (invertedCardNumber.Length < 16)
{
magicNumber = sumOfAll + checkDigit;
}
if (invertedCardNumber.Length >= 16)
{
magicNumber = sumOfAll;
}
}
public static bool IsValid(string cardNumber)
{
bool status = true;
if (magicNumber % 10 == 0 & cardNumber.EndsWith(checkDigit.ToString()))
{
status = true;
}
else
{
status = false;
}
return status;
}
}
}
</code></pre>
<p>Where the code can be improved ? It's a very basic version, did just to see if it works (in fact, I wrote this code two times before having a working version, this one).
Can I get rid of all that lists at the beggining?</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-10-11T17:14:59.770",
"Id": "396284",
"Score": "0",
"body": "We need a better title for it... this is anything else but _simple_ ;-)"
}
] | [
{
"body": "<p>First of all, I really acknowledge your efforts, and secondly it seems that the code does what it is expected to do.</p>\n\n<p>You split the code into some meaningful methods and the naming is easy to understand in the context.</p>\n\n<p>There's a lot to comment and I can not cover it all so here ... | {
"AcceptedAnswerId": "205459",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-10-11T16:46:26.123",
"Id": "205401",
"Score": "1",
"Tags": [
"c#",
"beginner",
"algorithm",
".net",
"checksum"
],
"Title": "Luhn Algorithm \"modulus 10\" checksum"
} | 205401 |
<p>I wrote a tool that takes a domain name and a password, concatenates them, hashes the result with sha512, and returns the result encoded in base64 truncated to 32 characters. The main idea behind this is to prevent an abusive server owner from getting my password by storing my password in plain text and using that password on other accounts, or if the developer forgot to remove the password from logs and a hacker got into them.</p>
<p>A lot of my code was already written and used in another application. The base64 encoder was taken from <a href="https://github.com/superwills/NibbleAndAHalf" rel="nofollow noreferrer">https://github.com/superwills/NibbleAndAHalf</a> and slightly modified. <code>makeSyscallError</code> used to throw a <code>std::system_error</code> but to keep things simple I just made it call <code>std::perror</code> and exit in this code.</p>
<p>My main question is, is this a secure way to protect my password? I know I should really be keeping a database of randomly generated passwords and encrypt it with my master password, but I don't want to lose that database and I don't want to put the encrypted database in the cloud.</p>
<p>here's <code>mpass.cpp</code>:</p>
<pre><code>#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <signal.h>
#include <termios.h>
#include <unistd.h>
#include "hash.hpp"
#include "base64.h"
struct termios newTerm, oldTerm;
void setEcho(bool echo, bool icanon){
if(echo) newTerm.c_lflag |= ECHO;
else newTerm.c_lflag &= ~ECHO;
if(icanon) newTerm.c_lflag |= ICANON;
else newTerm.c_lflag &= ~ICANON;
if(tcsetattr(0, TCSANOW, &newTerm) == -1){
std::perror("tcsetattr");
std::exit(1);
}
}
//I hate it so much when my program crashes on a signal and my terminal gets screwed up, so
void cleanUp(int sn, siginfo_t *info, void *ctx){
tcsetattr(0, TCSANOW, &oldTerm);
if(sn != SIGINT) psiginfo(info, NULL);
signal(sn, SIG_DFL);
raise(sn);
std::exit(-1); //if raise some reason didn't kill
}
//A list of signals to clean up on
const int signalsToCatch[] = {
SIGINT, SIGQUIT, SIGILL, SIGABRT, SIGFPE, SIGSEGV, SIGPIPE, SIGALRM,
SIGTERM, SIGUSR1, SIGUSR2, SIGBUS, SIGIO, SIGPROF, SIGSYS, SIGTRAP,
SIGVTALRM, SIGXCPU, SIGXFSZ, SIGPWR, 0
}
/*This struct is defined in an external C file as
struct sigaction sa = {
.sa_flags = SA_SIGINFO
};
Now sa is already filled with 0s, except for sa_flags. I wish C++ included this feature.
*/
extern struct sigaction sa;
int main(){
if(tcgetattr(0, &oldTerm) == -1){
std::perror("tcgetattr");
return 1;
}
std::memcpy(&newTerm, &oldTerm, sizeof(struct termios));
sa.sa_sigaction = cleanUp;
for(int i = 0; signalsToCatch[i] != 0; ++i){
if(sigaction(signalsToCatch[i], &sa, NULL) == -1){
std::perror("sigaction");
return 1;
}
}
std::string dom, pass;
(std::cout << "Enter domain: ").flush();
std::getline(std::cin, dom);
(std::cout << "Enter password: ").flush();
setEcho(false, true);
std::getline(std::cin, pass);
setEcho(true, true);
(std::cout << "\nPassword for " << dom << ": ").flush();
dom += pass;
char buf[64];
sha512sum(dom.c_str(), dom.length(), buf);
int useless;
char *ret = base64(buf, 64, &useless);
if(ret == NULL){ //Almost forgot to include this so if someone posts about this while I make this edit, don't look at them like they're stupid.
perror("malloc");
return 1;
}
ret[32] = '\n'; //I'm just gonna put the newline here
if(write(1, ret, 33) == -1){
std::perror("write");
return 1;
}
//I could std::free(ret), but it will get freed anyway by the program exit.
return 0;
}
//Must be defined for hash.cpp, but I wont be catching exceptions for sha512sum
//I don't want to edit hash.cpp either, as it is the same file used in another application
void makeSyscallError(const char *what){
std::perror(what);
std::exit(1);
}
</code></pre>
<p>Here's hash.hpp:</p>
<pre><code>#ifndef HASH_HPP
#define HASH_HPP
#include <stddef.h>
//Args: input buffer, input buffer length, output buffer (output buffer must always be 64 bytes or more)
void sha512sum(const void *, size_t, void *);
#endif
</code></pre>
<p>Here's hash.cpp:</p>
<pre><code>#include <sys/types.h>
#include <sys/socket.h>
#include <unistd.h>
#include <sys/ioctl.h>
#include <linux/if_alg.h>
#include <cerrno>
#include <cstring>
//I won't show misc.hpp, it's just a definition for makeSyscallError(const char *msg);
#include "misc.hpp"
static int cryptoFd = -1;
extern "C"{
extern const struct sockaddr_alg sha512addr;
/*This is also defined in the C file:
const struct sockaddr_alg sha512addr = {
.salg_family = AF_ALG,
.salg_type = "hash",
.salg_name = "sha512"
};
*/
}
//This function checks if cryptoFd is equal to -1, and if it is, it will create it
static void checkCryptoFd(){
if(cryptoFd != -1) return;
int bindFd = socket(AF_ALG, SOCK_SEQPACKET, 0);
if(bindFd == -1)
makeSyscallError("Failed to create AF_ALG socket");
if(bind(bindFd, (struct sockaddr *) &sha512addr, sizeof(struct sockaddr_alg))){
close(bindFd);
makeSyscallError("Failed to bind AF_ALG socket");
}
cryptoFd = accept(bindFd, 0, 0);
close(bindFd);
if(cryptoFd == -1)
makeSyscallError("Failed to create sha512 socket");
}
//Now, I am using linux AF_ALG not for speed (I believe this usage of it would actually be slower due to syscall overhead,
//but simply because it's there and its the only interface I actually learned how to use. I'm not looking at portability in any way, and if I were, I'd rewrite this as a browser extension
void sha512sum(const void *toHash, size_t len, void *result){
checkCryptoFd();
for(;;){
if(len < 128){ //Last 128 bytes to write
if(write(cryptoFd, toHash, len) == -1)
makeSyscallError("(odd) Failed to write to sha512 socket");
if(read(cryptoFd, result, 64) == -1) //Get result
makeSyscallError("(odd) Failed to read from sha512 socket");
return; //All done!
}
if(send(cryptoFd, toHash, 128, MSG_MORE)){
makeSyscallError("(odd) Failed to write to sha512 socket");
}
toHash += 128;
len -= 128;
}
}
</code></pre>
<p>base64.c:</p>
<pre><code>#include <stdlib.h>
const static char* b64="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/" ;
// Converts binary data of length=len to base64 characters.
// Length of the resultant string is stored in flen
// (you must pass pointer flen).
//I did modify this
char* base64( const void* binaryData, int len, int *flen )
{
const unsigned char* bin = (const unsigned char*) binaryData ;
char* res ;
int rc = 0 ; // result counter
int byteNo ; // I need this after the loop
int modulusLen = len % 3 ;
int pad = ((modulusLen&1)<<1) + ((modulusLen&2)>>1) ; // 2 gives 1 and 1 gives 2, but 0 gives 0.
*flen = 4*(len + pad)/3 ;
res = (char*) malloc( *flen + 1 ) ; // and one for the null
//Here's the modfifcations I made
/* if( !res )
{
puts( "ERROR: base64 could not allocate enough memory." ) ;
puts( "I must stop because I could not get enough" ) ;
return 0;
}*/
if(!res) return NULL; //Much better
for( byteNo = 0 ; byteNo <= len-3 ; byteNo+=3 )
{
unsigned char BYTE0=bin[byteNo];
unsigned char BYTE1=bin[byteNo+1];
unsigned char BYTE2=bin[byteNo+2];
res[rc++] = b64[ BYTE0 >> 2 ] ;
res[rc++] = b64[ ((0x3&BYTE0)<<4) + (BYTE1 >> 4) ] ;
res[rc++] = b64[ ((0x0f&BYTE1)<<2) + (BYTE2>>6) ] ;
res[rc++] = b64[ 0x3f&BYTE2 ] ;
}
if( pad==2 )
{
res[rc++] = b64[ bin[byteNo] >> 2 ] ;
res[rc++] = b64[ (0x3&bin[byteNo])<<4 ] ;
res[rc++] = '=';
res[rc++] = '=';
}
else if( pad==1 )
{
res[rc++] = b64[ bin[byteNo] >> 2 ] ;
res[rc++] = b64[ ((0x3&bin[byteNo])<<4) + (bin[byteNo+1] >> 4) ] ;
res[rc++] = b64[ (0x0f&bin[byteNo+1])<<2 ] ;
res[rc++] = '=';
}
res[rc]=0; // NULL TERMINATOR! ;)
return res ;
}
//I removed the decoder
</code></pre>
<p>The base64 encoder came as a header library. I moved it to a .c file and added this .h file (base64.h):</p>
<pre><code>#ifndef BASE64_H
#define BASE64_H
#ifdef __cplusplus
#define MYEXTERN extern "C"
#else
#define MYEXTERN
#endif
//To encode, length, returned length
MYEXTERN char *base64(const void *, int, int *);
#undef MYEXTERN
#endif
</code></pre>
<p>I'm sure many will ask, here's the original definition of makeSyscallError(const char *):</p>
<pre><code>void makeSyscallError(const char *what){
throw std::system_error(std::make_error_code(std::errc(errno)), what);
}
</code></pre>
<p>Edit: forgot to mention, this code is mainly for my personal use. I will rewrite it and release it if things look good.</p>
| [] | [
{
"body": "<p>Looks pretty good. I have no experience with <code>AF_ALG</code> sockets, so can't comment on the usage there (but it's a relief not to have to review home-implemented crypto, so kudos for avoiding that trap!)</p>\n\n<p>Most of my suggestions are somewhat style orientated, so don't feel that ther... | {
"AcceptedAnswerId": "205416",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-10-11T17:37:58.517",
"Id": "205404",
"Score": "2",
"Tags": [
"c++",
"linux",
"hashcode"
],
"Title": "Password encrypting tool"
} | 205404 |
<p>Am teaching myself about sorting techniques and trying my hand at a <a href="https://en.wikipedia.org/wiki/Quicksort" rel="nofollow noreferrer">quicksort</a> implementation. I found a lot of examples based on recursion but didn't want to go that route in a language that doesn't support tail-call optimization.</p>
<pre><code>public static class ListExtensions
{
public static void InsertionSort<T>(this IList<T> values, int startIndex, int endIndex, IComparer<T> comparer) {
var left = startIndex;
var right = 0;
var temp = default(T);
while (left < endIndex) {
right = left;
temp = values[++left];
while ((right >= startIndex) && (0 < comparer.Compare(values[right], temp))) {
values[(right + 1)] = values[right--];
}
values[(right + 1)] = temp;
}
}
public static void InsertionSort<T>(this IList<T> values, IComparer<T> comparer) {
InsertionSort(values, 0, (values.Count - 1), comparer);
}
public static void InsertionSort<T>(this IList<T> values) {
InsertionSort(values, Comparer<T>.Default);
}
public static void QuickSort<T>(this IList<T> values, int startIndex, int endIndex, IComparer<T> comparer, IRandomNumberGenerator randomNumberGenerator) {
var range = (startIndex, endIndex);
var stack = new Stack<(int, int)>();
do {
startIndex = range.startIndex;
endIndex = range.endIndex;
if ((endIndex - startIndex + 1) < 31) {
values.InsertionSort(startIndex, endIndex, comparer);
continue;
}
var pivot = values.SampleMedian(startIndex, endIndex, comparer, randomNumberGenerator);
var left = startIndex;
var right = endIndex;
while (left <= right) {
while (0 > comparer.Compare(values[left], pivot)) { left++; }
while (0 > comparer.Compare(pivot, values[right])) { right--; }
if (left <= right) {
values.Swap(left++, right--);
}
}
if (startIndex < right) {
stack.Push((startIndex, right));
}
if (left < endIndex) {
stack.Push((left, endIndex));
}
}
while (stack.TryPop(out range));
}
public static void QuickSort<T>(this IList<T> values, IComparer<T> comparer, IRandomNumberGenerator randomNumberGenerator) {
QuickSort(values, 0, (values.Count - 1), comparer, randomNumberGenerator);
}
public static void QuickSort<T>(this IList<T> values) {
QuickSort(values, Comparer<T>.Default, FastRandom.Default);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static T SampleMedian<T>(this IList<T> values, int startIndex, int endIndex, IComparer<T> comparer, IRandomNumberGenerator randomNumberGenerator) {
var left = randomNumberGenerator.NextInt32(startIndex, endIndex);
var middle = randomNumberGenerator.NextInt32(startIndex, endIndex);
var right = randomNumberGenerator.NextInt32(startIndex, endIndex);
if (0 > comparer.Compare(values[right], values[left])) {
Swap(values, right, left);
}
if (0 > comparer.Compare(values[middle], values[left])) {
Swap(values, middle, left);
}
if (0 > comparer.Compare(values[right], values[middle])) {
Swap(values, right, middle);
}
return values[middle];
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static void Swap<T>(this IList<T> values, int xIndex, int yIndex) {
var temp = values[xIndex];
values[xIndex] = values[yIndex];
values[yIndex] = temp;
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-10-11T17:56:27.890",
"Id": "396291",
"Score": "0",
"body": "What IDE are you using? The code formatting is very non-C#-ish. It looks more like JavaScript ;-]"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-10-11T... | [
{
"body": "<p>All in all there is not much to comment. I like the iterative mechanism with the stack. Trying other collections (linked list, dictionary, hashset etc.) doesn't seem to improve the performance.</p>\n\n<p>One could argue that it would be nice to have the partition part in a dedicated function to im... | {
"AcceptedAnswerId": null,
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-10-11T17:55:11.877",
"Id": "205407",
"Score": "2",
"Tags": [
"c#",
"algorithm",
"sorting"
],
"Title": "Quicksort Without Recursion"
} | 205407 |
<p>I made this implementation of a stack in Swift that stores its elements as a linked list. It seems to work perfectly well, but I’m wondering how I can improve it to follow the best practices of the language.</p>
<p></p>
<pre><code>struct StackList<T> : CustomStringConvertible {
private var first: StackNode? = nil // The topmost node in the stack
/// Add a new element to the top of the stack
/// - parameter newElement: the new element to be added
mutating func push(_ newElement: T) {
let newElement = StackNode(newElement);
newElement.next = first;
first = newElement;
}
/// Remove and return the topmost element from the stack
/// - returns: Optional containing the removed element, or nil if the stack was empty
mutating func pop() -> T? {
guard let first = first else { return nil }
let poppedElement = first.element
self.first = first.next
return poppedElement
}
/// The number of elements in the stack
var size: Int {
var count = 0
var current = first
// Traverse the list
while current != nil {
count += 1
current = current!.next
}
return count
}
/// Textual representation of the stack
var description: String {
var output = ""
// Traverse the list
var currentNode = first;
while let thisNode = currentNode {
if output != "" { output += ", " } // Add commas between elements
output += String(describing: thisNode.element)
currentNode = thisNode.next
}
return "[\(output)]"
}
private class StackNode {
var next: StackNode? = nil
var element: T
init(_ element: T) {
self.element = element
}
}
}
</code></pre>
| [] | [
{
"body": "<p>That looks already quite good and clean. Here are my remarks:</p>\n\n<blockquote>\n<pre><code>private var first: StackNode? = nil // The topmost node in the stack\n</code></pre>\n</blockquote>\n\n<p>An optional value is initalized to <code>nil</code> by default, so</p>\n\n<pre><code>private var fi... | {
"AcceptedAnswerId": "205413",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-10-11T18:57:57.287",
"Id": "205411",
"Score": "2",
"Tags": [
"beginner",
"linked-list",
"swift",
"stack"
],
"Title": "Stack using Linked List in Swift"
} | 205411 |
<p>I have a fast producer thread and a slow consumer thread. The consumer processes as many objects as it can and simply ignores the rest in order to not slow down the producer. Therefore, I used a one-element wait-free single-producer single-consumer queue for passing objects to the consumer in a thread-safe manner. After taking one out, it should be filled back in by the producer before the consumer finishes processing the element. I was wondering about how to simplify this one-element edge case and came up with the following.</p>
<p>The <code>spsc_object</code> class reserves storage for a single object and achieves thread safety for a single writer and a single reader. It's inspired by <code>boost::lockfree::spsc_queue</code> and supports move semantics.</p>
<pre><code>#ifndef SPSC_OBJECT_HH
#define SPSC_OBJECT_HH
#include <type_traits>
#include <new>
#include <atomic>
template<typename T>
class spsc_object {
using storage_t = typename std::aligned_storage<sizeof(T), alignof(T)>::type;
storage_t storage_;
std::atomic_bool occupied_;
public:
bool write(const T& object)
{
const bool occupied = occupied_.load(std::memory_order_acquire);
if (!occupied) {
new (&storage_) T(object); // copy
occupied_.store(true, std::memory_order_release);
return true;
}
return false;
}
bool write(T&& object)
{
const bool occupied = occupied_.load(std::memory_order_acquire);
if (!occupied) {
new (&storage_) T(std::move(object)); // move
occupied_.store(true, std::memory_order_release);
return true;
}
return false;
}
template<typename Functor>
bool read(Functor& functor)
{
const bool occupied = occupied_.load(std::memory_order_acquire);
if (!occupied)
return false;
T& object = reinterpret_cast<T&>(storage_);
functor(object);
object.~T();
occupied_.store(false, std::memory_order_release);
return true;
}
template<typename Functor>
bool read(const Functor& functor)
{
const bool occupied = occupied_.load(std::memory_order_acquire);
if (!occupied)
return false;
T& object = reinterpret_cast<T&>(storage_);
functor(object);
object.~T();
occupied_.store(false, std::memory_order_release);
return true;
}
};
#endif
</code></pre>
<p>It seems to work in a small test case I wrote but correctness is hard to verify. Considering performance, <code>boost::lockfree::spsc_queue</code> uses a read index and a write index (placed in different cache lines!) and one additional queue element to distinguish an empty queue from a full one. My container only uses an <code>std::atomic_bool</code> in addition to the object storage space, so it is definitely smaller and hopefully faster. I am not certain whether there could be a faster alternative to the <code>std::atomic_bool</code>. Maybe a processor-word sized variable is faster? Would two separate flags be useful to reduce contention? Did I miss anything else?</p>
<p>Edit: Here's my test case (<a href="https://coliru.stacked-crooked.com/a/107a121d36bbe3a7" rel="nofollow noreferrer">see Coliru</a>) that produces dummy objects and outputs which of those could be consumed. For some reason, there will be major gaps, i.e. large numbers of subsequent objects are not consumed. I guess that happens whenever <code>std::cout</code>'s buffer is flushed.</p>
<pre><code>#include "spsc_object.hpp"
#include <cassert>
#include <atomic>
#include <future>
#include <iostream>
struct test_t {
int x, y;
test_t(int x) : x(x), y(1) {}
~test_t() {
y = 0;
}
};
const int to_produce = 10000000;
spsc_object<test_t> object;
std::atomic_bool stop_consuming;
int producer()
{
int written = 0;
for (int i = 0; i < to_produce; i++) {
if (object.write(test_t(i)))
written++;
}
return written;
}
int consumer()
{
int read = 0;
for (;;) {
test_t mytest(3);
if (object.read([&mytest](const test_t& test) {
mytest = test;
})) {
read++;
// Here go expensive calculations
std::cout << mytest.x << '\n';
assert(mytest.y != 0);
} else if (stop_consuming) {
return read;
} else {
// Should not happen unless only a single hardware thread is
// available for both producer and consumer, as seems to be the case
// on Coliru for example.
std::cout << "Oh boy, the producer was too slow!\n";
}
}
}
int main()
{
stop_consuming = false;
auto t1 = std::async(std::launch::async, producer);
auto t2 = std::async(std::launch::async, consumer);
int written = t1.get();
stop_consuming = true;
int read = t2.get();
std::cout << "produced = " << to_produce << "\n"
"written = " << written << "\n"
"read = consumed = " << read << '\n';
}
</code></pre>
<p>Sample output:</p>
<pre><code>...
9908795
9908803
9908812
9908822
9908832
9908842
9908852
9908861
9908872
9908881
9908891
9908898
9908907
9908917
9908928
9908938
9908948
produced = 10000000
written = 37374
read = consumed = 37374
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-10-12T09:09:11.177",
"Id": "396337",
"Score": "0",
"body": "Your question might be valid as is, but you should really provide a minimal complete working program, and not just your class."
},
{
"ContentLicense": "CC BY-SA 4.0",
... | [
{
"body": "<h2>Build on top of the standard library, not along</h2>\n\n<p>You didn't specify which version of the standard you target. If it is the most recent one, then you have in <a href=\"https://en.cppreference.com/w/cpp/utility/optional\" rel=\"nofollow noreferrer\">std::optional</a> the tool to avoid exp... | {
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-10-11T21:28:06.300",
"Id": "205418",
"Score": "6",
"Tags": [
"c++",
"multithreading",
"queue",
"lock-free"
],
"Title": "Single producer single consumer wait-free object container"
} | 205418 |
<p>The way I've written this feels clunky. Particularly, it feels like I shouldn't need to have both a 'dateToCheck' and 'selectedDate' variables.</p>
<p>The objective is to find the Date in a list that is the closest to today (inclusive), with a preference for dates in the future.</p>
<p>The list is guaranteed to be passed in, in descending order.</p>
<p>The list can contain dates in the future...all the way to anytime in the past. Or just dates in the future. Or just today. Or just dates in the past. Anything...</p>
<p>Here is my working version:</p>
<pre><code>Public Shared Function GetClosetDateToToday(lstOrderedDates As List(Of Date)) As Date
' Select the closest Delivery date to TODAY (inclusive) from the list of Ordered dates
If lstOrderedDates.Count > 1 Then
Dim dateToCheck = lstOrderedDates.ElementAt(1)
Dim selectedDate = lstOrderedDates.ElementAt(0)
For i = 1 To lstOrderedDates.Count - 1
If dateToCheck < Date.Now.Date Then
Exit For
End If
If dateToCheck >= Date.Now.Date Then
selectedDate = dateToCheck
End If
If i + 1 < lstOrderedDates.Count Then
dateToCheck = lstOrderedDates.ElementAt(i + 1)
End If
Next i
Return selectedDate
ElseIf lstOrderedDates.Count = 1 Then
Return lstOrderedDates.First()
End If
Return Nothing
End Function
</code></pre>
<p>Is there a better way?</p>
| [] | [
{
"body": "<p>Because this method is <code>Public</code> you should check if <code>lstOrderedDates</code> is <code>Nothing</code> and you should't believe that the passed List really is ordered. </p>\n\n<p>Doing the check on lstOrderedDates.Count for <code>0</code> and <code>1</code> first will save one indent... | {
"AcceptedAnswerId": "205444",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-10-12T03:58:55.973",
"Id": "205423",
"Score": "1",
"Tags": [
"vb.net"
],
"Title": "Function to return the closest Date to Today (inclusive) from Ordered list"
} | 205423 |
<p>I have a vector <span class="math-container">\$X_k\$</span> and a matrix <span class="math-container">\$Y_{k,j}\$</span>, where <span class="math-container">\$k \in \{1,\dots,K\}\$</span> and <span class="math-container">\$j \in \{1, \dots, J\}\$</span>. They are circular, meaning that <span class="math-container">$$\eqalign{X_{k+K} &= X_k \\ Y_{k+K,j} &= Y_{k,j} \\ Y_{k,j+J} &= Y_{k,j}}$$</span> </p>
<p>I want to compute a <span class="math-container">\$ZX\$</span> vector and <span class="math-container">\$ZY\$</span> matrix according to the equations <span class="math-container">$$\eqalign{ZX_k &= -X_{k-1}(X_{K-2}-X_{K+1})-X_k \\ ZY_{k,j} &= -Y_{k,j+1}(Y_{k,j+2}-Y_{k,j-1})-Y_{k,j}+X_k}$$</span></p>
<p>Currently, I'm doing this through a loop, where first I compute the edge cases (for <span class="math-container">\$ZX\$</span>, <span class="math-container">\$k = 1, 2, K\$</span>; for <span class="math-container">\$ZY\$</span>, <span class="math-container">\$j = 1, J, J-1\$</span>). And for the others, I use the equations above.</p>
<p>I'm wondering if this calculation can be vectorized. Here is the example code. </p>
<pre><code>import numpy as np
np.random.seed(10)
K = 20
J = 10
# initial state (equilibrium)
x = np.random.uniform(size=K)
y = np.random.uniform(size=(K*J))
y = y.reshape(K,J)
# zy
zy = np.zeros((K*J))
zy = zy.reshape(K,J)
# Edge case of Y
for k in range(K):
zy[k,0] = -y[k,1]*(y[k,2]-y[k,J-1])-y[k,0]+ x[k]
zy[k,J-1] = -y[k,0]*(y[k,1]-y[k,J-2])-y[k,J-1]+ x[k]
zy[k,J-2] = -y[k,J-1]*(y[k,0]-y[k,J-3])-y[k,J-2]+ x[k]
# General Case of Y
for j in range(1,J-2):
zy[k,j] = -y[k,j+1]*(y[k,j+2]-y[k,j-1])-y[k,j]+ x[k]
# zx
zx = np.zeros(K)
# first the 3 edge cases: k = 1, 2, K
zx[0] = -x[K-1]*(-x[1] + x[K-2]) - x[0]
zx[1] = - x[0]*(-x[2] + x[K-1])- x[1]
zx[K-1] = -x[K-2]*(-x[0] + x[K-3]) - x[K-1]
# then the general case for X
for k in range(2, K-1)
zx[k] = -x[k-1]*(-x[k+1] + x[k-2]) - x[k]
print(zx)
print(zy)
</code></pre>
<p>I suspect that is possible to optimize with matrix operations but not sure if it is possible without the loops (at least for the edge cases).</p>
<p>Any suggestion of how to improve the performance?</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-10-12T06:29:00.147",
"Id": "396319",
"Score": "2",
"body": "Can you explain the purpose of this code? What do \\$X\\$, \\$Y\\$, \\$ZX\\$, \\$ZY\\$ represent? Can you check the mathematics in the post — in particular, the post says \\$ZX_k... | [
{
"body": "<p>This is easy using <a href=\"https://docs.scipy.org/doc/numpy/reference/generated/numpy.roll.html\" rel=\"noreferrer\"><code>numpy.roll</code></a>, for example:</p>\n\n<pre><code>zx = np.roll(x, 1) * (np.roll(x, 2) + np.roll(x, -1)) - x\n</code></pre>\n",
"comments": [
{
"Content... | {
"AcceptedAnswerId": "205426",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-10-12T05:57:51.753",
"Id": "205424",
"Score": "3",
"Tags": [
"python",
"performance",
"matrix",
"vectorization"
],
"Title": "Vectorizing matrix operation instead of for loop in circular matrices"
} | 205424 |
<p><em>I already posted this on Stack Overflow, but someone suggested to post it to Code Review instead.</em></p>
<p>I am creating an Android app that draws to the <code>canvas</code>. For this, I have defined rectangular screenareas that I want to draw to the canvas. As I am always drawing a fixed set of screenareas, I was thinking of using <code>Enum</code> (as <code>Enum</code> is designed for fixed sets).</p>
<p>Here is my <code>enum</code>:</p>
<pre><code>public enum LayoutEnum {
FULLSCREEN(
new ScreenArea(
new Rect(
0,
0,
MainActivity.getDevice().getWidth(),
MainActivity.getDevice().getHeight()),
Attributes.BG_PAINT)),
LOGO_AREA(
new ScreenArea (
new Rect(
(int) (0.3 * FULLSCREEN.getScreenArea().getArea().width()),
(int) (0.3 * FULLSCREEN.getScreenArea().getArea().width()),
(int) (FULLSCREEN.getScreenArea().getArea().width() - 0.3 * FULLSCREEN.getScreenArea().getArea().width()),
(int) (0.7 * FULLSCREEN.getScreenArea().getArea().width())),
Attributes.BG_PAINT)
);
private ScreenArea screenArea;
LayoutEnum(ScreenArea screenArea) {
this.screenArea = screenArea;
}
public ScreenArea getScreenArea() {
return screenArea;
}
}
</code></pre>
<p><code>ScreenArea</code> is a simple class that holds a <code>Rect</code> and a <code>Paint</code> and contains a <code>draw</code> method (and some getters and setters).</p>
<p>The question I have, is: is this a good approach? On one hand I am working with a fixed set of variables. On the other hand, these variables are mutable and I can change their attributes (e.g., using the getters and setters). For example, I can call <code>FULLSCREEN.getScreenArea().getPaint().setColor(Color.BLUE)</code></p>
<p>When you look at <code>Enum</code> it says it is </p>
<blockquote>
<p>a special data type that enables for a variable to be a set of
predefined constant</p>
</blockquote>
<p>So I do have a fixed set, it is predefined, but not necessarily constant.</p>
<p>My original approach was to define a class called <code>Layout</code> which contained a <code>HashMap</code> of <code>Screenarea</code>'s. In that case, I was using e.g., <code>Layout.get("fullscreen").draw(canvas)</code> to draw the screenarea to the canvas. In this new approach I am using e.g., <code>FULLSCREEN.getScreenArea().draw(canvas)</code>.</p>
<p>One of the reasons I would like to switch is to introduce a typesafe solution. Of course, it would also be possible to switch from a <code>HashMap</code> to an <code>EnumMap</code> and store the names of my screenareas in an <code>Enum</code>.</p>
<p>Hope you can point me in the right direction: a direction that not only works (the above is already working) but is also acceptable and doesn't smell.</p>
| [] | [
{
"body": "<p>Enums are meant to be immutable. I'd go with the EnumMap.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-10-12T11:54:06.377",
"Id": "396351",
"Score": "0",
"body": "That is what I am working on right now :)"
... | {
"AcceptedAnswerId": "205449",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-10-12T07:28:36.810",
"Id": "205430",
"Score": "1",
"Tags": [
"java",
"android",
"enum"
],
"Title": "Using Enum in java to store a fixed set of mutable objects"
} | 205430 |
<p>I am solving <a href="https://leetcode.com/problems/word-break-ii/description/" rel="nofollow noreferrer">Word Break II from leetcode</a>:</p>
<blockquote>
<p>Given a non-empty string <code>s</code> and a dictionary <code>wordDict</code> containing a list of non-empty words, add spaces in <code>s</code> to construct a sentence where each word is a valid dictionary word. Return all such possible sentences.</p>
<p>Note:</p>
<p>The same word in the dictionary may be reused multiple times in the segmentation.
You may assume the dictionary does not contain duplicate words.</p>
<p>Input:</p>
<pre><code>s = "pineapplepenapple"
wordDict = ["apple", "pen", "applepen", "pine", "pineapple"] Output:
[
"pine apple pen apple",
"pineapple pen apple",
"pine applepen apple"
]
</code></pre>
<p>Explanation: Note that you are allowed to reuse a dictionary word.</p>
</blockquote>
<p>I think my Python has improved since I posted island problem last. Your input is appreciated. </p>
<p>Here are the two solutions:</p>
<pre><code>def inverse_iterative(s, wdict):
st = []
ans = []
for w in wdict:
if s.startswith(w):
if len(s) == len(w):
ans.append(w)
return ans
st.append((w, 0, [w]))
while st:
cur_w, cur_idx, cur_list = st.pop()
cur_start = cur_idx + len(cur_w)
for w in wdict:
if not s[cur_start:].startswith(w):
continue
if len(w) == len(s[cur_start:]):
ans.append(' '.join(cur_list+[w]))
else:
st.append((w, cur_start, cur_list+[w]))
return ans
</code></pre>
<pre><code>def inverse_helper(s, wdict, memo):
if s in memo:
return memo[s]
if not s:
return []
res = []
for word in wdict:
if not s.startswith(word):
continue
if len(word) == len(s):
res.append(word)
else:
result_of_rest = helper(s[len(word):], wordDict, memo)
for r in result_of_rest:
r = word + ' ' + r
res.append(r)
memo[s] = res
return res
</code></pre>
<pre><code>ans_iterative = inverse_iterative(s, wdict)
ans_recursive = inverse_helper(s, wdict, {})
</code></pre>
| [] | [
{
"body": "<h3>The first solution</h3>\n\n<p>There's a bug in the first loop:</p>\n\n<blockquote>\n<pre><code> for w in wdict:\n if s.startswith(w):\n if len(s) == len(w):\n ans.append(w)\n return ans\n ^^^^^^^^^^ should not do this!\n ... | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-10-12T09:01:48.230",
"Id": "205436",
"Score": "4",
"Tags": [
"python",
"programming-challenge",
"depth-first-search",
"backtracking"
],
"Title": "Two versions of Word Break II - exhaustive combinations"
} | 205436 |
<p>I am willing to see how to write readable and efficient <strong>continuations on the heap in c++</strong>. I am not quite satisfied. </p>
<p>The following is just an exercise: it is coded for fun. I post the code here because I am not really satisfied. I am looking for suggestions.
I picked up the simplest algorithm: measuring the length of a list and I wrote few recursive implementations. The plain one is <code>len()</code>. </p>
<p>Then I wrote <code>lenK()</code> i.e. len() in CPS. This is quite straightforward, I think this code is fine. Isn't it? </p>
<p>When it comes to Kontinuations on the heap, I had to write the continuation K as a class (fine) but I had to use virtuality to let the compiler understand what I wanted (if I use templates the compiler cannot understand that my program eventually terminates and for each call create a new type). I have the strong impression that my solution is not elegant and is not efficient. Is there a better way to implement CPS on the heap? </p>
<pre><code>#include <iostream>
#include <functional>
#include <memory>
struct List;
bool isEnd(const List& l);
double getHead(const List& l);
List* getTail(const List& l);
</code></pre>
<p>//////////////////////////////////////////////////////////////////////////////</p>
<pre><code>int len(const List& l, int val=0){
if (isEnd(l))
return val;
return len(*getTail(l),
++val);
}
//////////////////////////////////////////////////////////////////////////////
double lenK(const List& l, std::function<int(int)> k){
if (isEnd(l))
return k(0);
return lenK(*getTail(l), [k](int a){return k(a+1);} );
}
//////////////////////////////////////////////////////////////////////////////
class IntInt{
public:
virtual ~IntInt()=default;
virtual int operator()(int)=0;
};
using funcPtr = std::unique_ptr<IntInt>;
class IntID : public IntInt{
public:
int operator()(int a){ return a;}
};
class K : public IntInt{
public:
K( funcPtr&& k) : k_(std::move(k)){}
int operator()(int a){ return (*k_)(a+1);}
private:
funcPtr k_;
};
//////////////////////////////////////////////////////////////////////////////
double lenKheap(const List& l, funcPtr&& k){
if (isEnd(l))
return (*k)(0);
List* myTail = getTail(l);
funcPtr myK = std::make_unique<K>(std::move(k));
// Without tail call optimization we run out of stack space as for lenK and len.
return lenKheap(*myTail,
std::move(myK));
}
void checkLenFunctions(const List& myL){
std::cout << len(myL) << std::endl;
auto intId = [](int x){return x;};
std::cout << lenK(myL, intId ) << std::endl;
std::cout << lenKheap(myL, std::make_unique<IntID>()) << std::endl;
}
</code></pre>
<p>If you want to experiment without bothering with the task of implementing the List class and functions, I provide you with an implementation of it. But this is not part of the review: </p>
<pre><code>struct List{
List(double d, List* l) : d_(d), l_(l){}
List() : d_(0.0), l_(this){}
double d_;
List* l_;
};
bool isEnd(const List& l){
if (l.l_ == &l)
return true;
return false;
}
double getHead(const List& l){
if (!isEnd(l))
return l.d_;
throw "EndOfList";
}
List* getTail(const List& l){
if (!isEnd(l))
return l.l_;
throw "EndOfList";
}
int main(){
List myL;
List myL1 = List(1.0, &myL);
List myL2 = List(2.0, &myL1);
List myL3 = List(3.0, &myL2);
List myL4 = List(4.0, &myL3);
checkLenFunctions(myL4);
return 0;
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-10-12T14:30:52.060",
"Id": "396355",
"Score": "0",
"body": "It's continuation *passing* style"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-10-12T14:36:03.270",
"Id": "396356",
"Score": "0",
"body":... | [
{
"body": "<h2>Code Review</h2>\n\n<ul>\n<li>Use standard library data structures! In this case <code>std::list</code>.</li>\n<li>Iterators are the usual way of traversing a C++ container, so use those too (they also allow us to not care which data structure is being used).</li>\n<li>Use <code>std::size_t</code... | {
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-10-12T09:07:10.090",
"Id": "205437",
"Score": "1",
"Tags": [
"c++",
"recursion",
"functional-programming",
"c++14",
"heap"
],
"Title": "C++ heap CPS: Continuation Passing Style with Recursion"
} | 205437 |
<p>This is a game for two users who roll 2 dice 5 times. If the total of dice is even, the player gains 10 points; if it is odd, they lose 5.</p>
<p>If there is a tie after the five rounds, then the users have to roll one die to determine the winner.</p>
<pre><code>###### IMPORTING RANDOM AND TIME & DEFINING VARIABLES ######
import random
import time
i = 0
Player1Points = 0
Player2Points = 0
Player1Tiebreaker = 0
Player2Tiebreaker = 0
Winner_Points = 0
###### LOGIN CODE ######
### This Sets logged in to false, and then makes sure the username and password is correct before allowing them to continue ###
logged_in1 = False
logged_in2 = False
while logged_in1 == False:
username = input('What is your username? ')
password = input('What is your password? ')
if username == 'User1' or username == 'User2' or username == 'User3' or username == 'User4' or username == 'User5':
if password == 'password':
print('Welcome, ',username,' you have been successfully logged in.')
logged_in1 = True
user1 = username
else:
print('Incorrect password, try again')
else:
print('Incorrect username, try again')
while logged_in2 == False:
username = input('What is your username? ')
password = input('What is your password? ')
if username == 'User1' or username == 'User2' or username == 'User3' or username == 'User4' or username == 'User5':
if password == 'password':
print('Welcome, ',username,' you have been successfully logged in.')
logged_in2 = True
user2 = username
else:
print('Incorrect password, try again')
else:
print('Incorrect username, try again')
###### DEFINING ROLL ######
### Makes the dice roll for the player and works out the total for that roll ###
def roll():
points = 0
die1 = random.randint(1,6)
die2 = random.randint(1,6)
dietotal = die1 + die2
points = points + dietotal
if dietotal % 2 == 0:
points = points + 10
else:
points = points - 5
if die1 == die2:
die3 = random.randint(1,6)
points = points +die3
return(points)
###### DICE ROLL ######
### This rolls the dice 5 times for the players, and then adds up the total. If the scores are equal, it starts a tie breaker and determines the winner off that ###
for i in range(1,5):
Player1Points += roll()
print('After this round ',user1, 'you now have: ',Player1Points,' Points')
time.sleep(1)
Player2Points += roll()
print('After this round ',user2, 'you now have: ',Player2Points,' Points')
time.sleep(1)
if Player1Points == Player2Points:
while Player1Tiebreaker == Player2Tiebreaker:
Player1Tiebreaker = random.randint(1,6)
Player2Tiebreaker = random.randint(1,6)
if Player1Tiebreaker > Player2Tiebreaker:
Player2Points = 0
elif Player2Tiebreaker > Player1Tiebreaker:
Player1Points = 0
###### WORKING OUT THE WINNER ######
### This checks which score is bigger, then creates a tuple for my leaderboard code ( Gotton of stack overflow ) ###
if Player1Points>Player2Points:
Winner_Points = Player1Points
winner_User = user1
winner = (Winner_Points, user1)
elif Player2Points>Player1Points:
Winner_Points = Player2Points
winner = (Winner_Points, user2)
winner_User = user2
print('Well done, ', winner_User,' you won with ',Winner_Points,' Points')
###### CODE TO UPLOAD ALL SCORES TO A FILE ######
### This will store the winners username and score in a text file ###
winner = (Winner_Points,',',winner_User)
f = open('Winner.txt', 'a')
f.write(''.join(winner))
f.write('\n')
f.close()
###### CODE TO LOAD, UPDATE AND SORT LEADERBOARD ######
### This loads the leaderboard into an array, then compares the scores just gotton and replaces it ###
f = open('Leaderboard.txt', 'r')
leaderboard = [line.replace('\n','') for line in f.readlines()]
f.close()
for idx, item in enumerate(leaderboard):
if item.split(', ')[1] == winner[1] and int(item.split(', ')[0]) < int(winner[0]):
leaderboard[idx] = '{}, {}'.format(winner[0], winner[1])
else:
pass
### This sorts the leaderboard in reverse, and then rewrites it ###
leaderboard.sort(reverse=True)
with open('Leaderboard.txt', 'w') as f:
for item in leaderboard:
f.write("%s\n" % item)
</code></pre>
<p>This was for my NEA task in computer science, which I have now finished; if anyone has any suggestions on how I could have made it better they will be greatly appreciated. So, please suggest how I can improve it!</p>
| [] | [
{
"body": "<h2>Login</h2>\n\n<ol>\n<li>Make a function <code>login</code> and move all the code to do with <code>logged_in1</code> into it.</li>\n<li>Use <code>while not logged_in1</code> rather than <code>while logged_in1 == False</code>.</li>\n<li>Rather than using <code>val == 'a' or val == 'b'</code> you ca... | {
"AcceptedAnswerId": "205445",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-10-12T09:41:43.577",
"Id": "205440",
"Score": "4",
"Tags": [
"python",
"python-3.x",
"game",
"dice"
],
"Title": "2-player dice game"
} | 205440 |
<p>I'm writing a Kotlin app that uses Exposed (<a href="https://github.com/JetBrains/Exposed" rel="nofollow noreferrer">https://github.com/JetBrains/Exposed</a>) as a SQL wrapper to write and read objects from databases. The problem I'm facing is that I end up with 3 classes featuring the same variables. For example:</p>
<pre><code>package database
import hashLength
import org.jetbrains.exposed.dao.EntityID
import org.jetbrains.exposed.dao.IntEntity
import org.jetbrains.exposed.dao.IntEntityClass
import org.jetbrains.exposed.dao.IntIdTable
import org.jetbrains.exposed.sql.Table
object LogEntries : IntIdTable() {
val logId = binary("id", hashLength).primaryKey()
val prev = binary("prev", hashLength).index()
val owner = varchar("owner", 32).index()
val timestamp = long("timestamp").index()
val action = integer("action")
val proof = text("proof")
val nonce = binary("nonce", 8)
val signature = binary("signature", 32)
}
class LogEntry(id: EntityID<Int>) : IntEntity(id) {
companion object : IntEntityClass<LogEntry>(LogEntries)
var logId by LogEntries.logId
var prev by LogEntries.prev
var owner by LogEntries.owner
var timestamp by LogEntries.timestamp
var action by LogEntries.action
var proof by LogEntries.proof
var nonce by LogEntries.nonce
var signature by LogEntries.signature
}
data class LogEntryHolder(
var logId: ByteArray,
val prev: ByteArray,
val owner: String,
val timestamp: Long,
val action: Int,
val proof: String,
val nonce: ByteArray,
val signature: ByteArray
)
</code></pre>
<p>The first is the Exposed DAO class (I don't use that directly), the second is a wrapper (companion class) to where I add more functions, this is where I do my CRUD operations on. The third is an in-memory class that I use to 'create' the object before storing it in the database. There are 2 reasons for that:</p>
<p>1: I now can edit the object before persisting it in the database (otherwise if I create a new <code>LogEntry</code> it's immediately saved in the database and I have to edit the log again directly after storing it, which seems counter-intuitive.</p>
<p>2: When processing through a function, I just have to supply the <code>LogEntryHolder</code> instead of passing all the values of the object individually.</p>
<p>Is there are way to reduce the amount of classes needed, so that the final code is less error-prone and redundant? Thanks a lot!</p>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-10-12T10:20:35.020",
"Id": "205443",
"Score": "2",
"Tags": [
"object-oriented",
"sql",
"kotlin"
],
"Title": "Kotlin DAO with Exposed: How to reduce redundancy in classes?"
} | 205443 |
<blockquote>
<p>Problem Statement: <a href="https://www.spoj.com/problems/FOXLINGS/" rel="nofollow noreferrer">FOXLINGS</a></p>
<p>It’s Christmas time in the forest, and both the Fox and the Wolf
families are celebrating. The rather large Fox family consists of two
parents as well as <span class="math-container">\$N\$</span> (<span class="math-container">\$1 \leq N \leq 10^9\$</span>) little Foxlings. The
parents have decided to give their children a special treat this year
– crackers! After all, it’s a well-known fact that Foxen love
crackers.</p>
<p>With such a big family, the parents can’t afford that many crackers.
As such, they wish to minimize how many they give out, but still
insure that each Foxling gets at least a bit. The parents can only
give out entire crackers, which can then be divided and passed around.</p>
<p>With this many children, not all of them know one another all that
well. The Foxlings have names, of course, but their parents are
computer scientists, so they have also conveniently numbered them from
<span class="math-container">\$1\$</span> to <span class="math-container">\$N\$</span>. There are <span class="math-container">\$M\$</span> (<span class="math-container">\$1 \leq M \leq 10^5\$</span>) unique two-way
friendships among the Foxlings, where relationship <span class="math-container">\$i\$</span> is described by
the distinct integers <span class="math-container">\$A_i\$</span> and <span class="math-container">\$B_i\$</span> (<span class="math-container">\$1 \leq A_i,B_i \leq N\$</span>),
indicating that Foxling <span class="math-container">\$A_i\$</span> is friends with Foxling <span class="math-container">\$B_i\$</span>, and vice
versa. When a Foxling is given a cracker, he can use his tail to
precisely split it into as many pieces as he wants (the tails of Foxen
have many fascinating uses). He can then pass these pieces around to
his friends, who can repeat this process themselves.</p>
<p>Input</p>
<p>Line 1: 2 integers, <span class="math-container">\$N\$</span> and <span class="math-container">\$M\$</span></p>
<p>Next <span class="math-container">\$M\$</span> lines: 2 integers, <span class="math-container">\$A_i\$</span> and <span class="math-container">\$B_i\$</span>, for <span class="math-container">\$i=1\ldots M\$</span></p>
<p>Output</p>
<p>A single integer – the minimum number crackers must be given out, such
that each Foxling ends up with at least a small part of a cracker.</p>
</blockquote>
<p>From the question I attempted with disjoint sets. I applied union by size along with path compression. But the constraints are very high and I could not think how to optimize this further. Offcourse I am getting TLE with solution upon submitting. So can anyone tell me any trick or idea regarding optimization?</p>
<pre><code>public static void main(String[] argh) throws Exception{
// BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
Reader br= new Reader();
int n= br.nextInt();
int m= br.nextInt();
int[] dj= new int[n+1];
int[] size= new int[n+1];
for(int i=1; i<=n; i++){
dj[i]= i;
size[i]= 1;
}
HashMap<Integer, Integer> map= new HashMap<>();
int count=0;
for(int i=0; i<m; i++){
int n1= br.nextInt();
int n2= br.nextInt();
union(dj, size, n1, n2);
}
for(int i=1; i<=n; i++){
findParent(dj, i);
}
for(int i=1; i<=n; i++){
if(!map.containsKey(dj[i])){
count++;
map.put(dj[i], 1);
}
}
System.out.println(count);
}
private static int findParent(int[] arr, int pos){
if(arr[pos] == pos) return pos;
return arr[pos]= findParent(arr, arr[pos]);
}
private static void union(int[] arr, int[] size, int pos1, int pos2){
int posP1= findParent(arr, pos1);
int posP2= findParent(arr, pos2);
if(posP1 != posP2){
if(size[posP1] < size[posP2]){
int temp= posP1;
posP1= posP2;
posP2= temp;
}
arr[posP2]= posP1;
size[posP1] += size[posP2];
}
}
</code></pre>
<blockquote>
<p>Note: Reader is just another fast inputting</p>
</blockquote>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-10-12T11:01:16.227",
"Id": "396345",
"Score": "0",
"body": "One who negates . Pls do mention reason."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-10-12T17:31:52.267",
"Id": "396377",
"Score": "0",
... | [
{
"body": "<pre><code>for(int i=1; i<=n; i++){\n findParent(dj, i);\n}\n\nfor(int i=1; i<=n; i++){\n if(!map.containsKey(dj[i])){\n count++;\n map.put(dj[i], 1);\n }\n}\n</code></pre>\n\n<p>This part is slow and unnecessary - you can count how many times you did union instead. </p>\n... | {
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-10-12T10:48:03.000",
"Id": "205446",
"Score": "0",
"Tags": [
"java",
"programming-challenge",
"time-limit-exceeded"
],
"Title": "TLE in FOXLINGS SPOJ"
} | 205446 |
<p>I am relatively new in making (invocable)callouts. My main concern is if I should be using smaller parts for example for the body and using a query only once in this case. Any suggestions would be appreciated.</p>
<p>Class:</p>
<pre><code>public class or_service {
@InvocableMethod
public static void InvocePostProperty(List<ID> pIds) {
for (Id pId : pIds) {
PostProperty(pId);
}
}
@future(callout=true)
public static void PostProperty(Id pId) {
List<Orbirental_Service__c> os = null;
List<Property__c> prop = null;
Http http = new Http();
HttpRequest request = new HttpRequest();
try {
os = [SELECT Url__c, ApiKey__c, agencyUid__c FROM Orbirental_Service__c LIMIT 1];
prop = [SELECT id, Name__c, BaseGuests__c, maximumGuests__c, baseDailyRate__c, city__c, state__c, acceptInstantBook__c, isActive__c ,uid__c
FROM Property__c WHERE id =:pId LIMIT 1];
}catch(QueryException ex) {
os = null;
prop = null;
}
request.setEndpoint(os[0].Url__c +'v1/properties/');
request.setMethod('POST');
request.setHeader('Content-Type', 'application/json');
request.setHeader('X-ORBIRENTAL-APIKEY', os[0].ApiKey__c);
// Set the body as a JSON object
request.setBody('{"type": "HOUSE"'+
',"name":' + prop[0].Name__c +
',"agencyUid":' + os[0].agencyUid__c +
',"baseGuests":' + prop[0].BaseGuests__c +
',"maximumGuests":' + prop[0].maximumGuests__c +
',"baseDailyRate":' + prop[0].baseDailyRate__c +
',"city":' + prop[0].city__c +
',"state":'+ prop[0].state__c +
',"acceptInstantBook":'+ prop[0].acceptInstantBook__c +
',"isActive":'+ prop[0].isActive__c+
'}');
HttpResponse response = http.send(request);
// Parse the JSON response
if (response.getStatusCode() != 200) {
System.debug('The status code returned was not expected: ' +
response.getStatusCode() + ' ' + response.getStatus());
} else {
System.debug(response.getBody());
updateProperty(response.getBody(),pId);
}
}
public static void updateProperty(string jsonString, Id pId) {
List<Property__c> prop = null;
or_propertyJSON propClass = or_propertyJSON.parse(jsonString);
System.debug('myClass.uid '+ propClass.uid);
try {
prop = [SELECT id, Name__c, BaseGuests__c, maximumGuests__c, baseDailyRate__c, city__c, state__c, acceptInstantBook__c, isActive__c ,uid__c
FROM Property__c WHERE id =:pId LIMIT 1];
}catch(QueryException ex) {
prop = null;
}
prop[0].uid__c = propClass.uid;
update prop;
}
}
</code></pre>
| [] | [
{
"body": "<p>From a practical viewpoint, I think the methods that you have right now are splitting the responsibilities of your overall code fairly appropriately. You <em>could</em> further split things up, but the question to ask is <em>what purpose would this serve?</em></p>\n\n<p>The more methods and classe... | {
"AcceptedAnswerId": "205473",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-10-12T10:53:34.490",
"Id": "205447",
"Score": "0",
"Tags": [
"beginner",
"design-patterns",
"serialization",
"salesforce-apex"
],
"Title": "Invocable callout(Post) from processbuilder"
} | 205447 |
<p>Trivial utility program meant to go through the list of (small) files and report file offset of the first difference between them. The goal of the code is simplicity. </p>
<p>Any recommendations are useful. Be brutal. I'm collecting go experience :)</p>
<pre class="lang-golang prettyprint-override"><code>package main
import (
"fmt"
"io/ioutil"
"os"
)
func main() {
if len(os.Args) < 3 {
fmt.Println("expecting at least 2 arguments")
return
}
nfi := len(os.Args) - 1
bufs := make([][]byte, nfi)
// read in the files
for i, fn := range os.Args[1:] {
fi, err := os.Open(fn)
if err != nil {
fmt.Printf("error opening file %s: %v", fn, err)
return
}
defer fi.Close()
bufs[i], err = ioutil.ReadAll(fi)
if err != nil {
fmt.Printf("error reading from file %s: %v", fn, err)
}
}
// get a minimum len of all the buffers
min := len(bufs[0])
for _, b := range bufs[1:] {
l := len(b)
if l < min {
min = l
}
}
// compare values one by one
for i := 0; i < min; i++ { // loop over offset
v := bufs[0][i] // a byte from first file
for j := 1; j < nfi; j++ { // loop over the rest of files
if v != bufs[j][i] {
fmt.Printf("first difference at offset %d = 0x%x\n", i, i)
return
}
}
}
fmt.Println("no differences found")
}
</code></pre>
| [] | [
{
"body": "<p>To understand your program better, I cleaned up up your code.</p>\n\n<p><code>diff.go</code>:</p>\n\n<pre><code>package main\n\nimport (\n \"fmt\"\n \"io/ioutil\"\n \"os\"\n)\n\nfunc main() {\n files := os.Args[1:]\n if len(files) < 2 {\n fmt.Fprintln(os.Stderr, \"expectin... | {
"AcceptedAnswerId": "205464",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-10-12T12:58:03.847",
"Id": "205451",
"Score": "6",
"Tags": [
"file",
"go"
],
"Title": "Small program to get binary diff offset between two small files"
} | 205451 |
<p>I've written a script in python to grab different <code>title</code> and <code>address</code> from different pages of a website. Firstly the script will collect all the property links from the landing page and then go one layer deep to collect the <code>title</code> and <code>address</code>. When I run my script, I get the results accordingly. </p>
<p>Should it not be a better approach If I call a single function and the rest of the functions work like a chain to produce the same results? If so, what is the right way to do so?</p>
<p><strong><em><a href="https://www.booking.com/searchresults.en-gb.html?aid=304142;label=gen173nr-1FCAEoggJCAlhYSDNYBGhpiAEBmAExuAEHyAEM2AEB6AEB-AECkgIBeagCAw;sid=0e2f8c4950c75fa71414020ccd4091ff;class_interval=1&dest_id=102&dest_type=country&from_sf=1&group_adults=2&group_children=0&label_click=undef&no_rooms=1&offset=0&raw_dest_type=country&room1=A%2CA&sb_price_type=total&search_selected=1&slp_r_match=0&src=index&src_elem=sb&ss=Ireland&ss_raw=ireland&ssb=empty&sshis=0&" rel="nofollow noreferrer">This is the link to that site</a></em></strong></p>
<p>Here is the working script:</p>
<pre><code>import requests
from urllib.parse import urljoin
from bs4 import BeautifulSoup
url = 'https://www.booking.com/searchresults.html?aid=304142;label=gen173nr-1FCAEoggJCAlhYSDNYBGhpiAEBmAExuAEHyAEM2AEB6AEB-AECkgIBeagCAw;sid=7abf6bf275d09e8d4f617d51f4d6c803;class_interval=1;dest_id=102;dest_type=country;dtdisc=0;from_sf=1;group_adults=2;group_children=0;inac=0;index_postcard=0;label_click=undef;no_rooms=1;offset=0;postcard=0;raw_dest_type=country;room1=A%2CA;sb_price_type=total;search_selected=1;slp_r_match=0;src=index;src_elem=sb;srpvid=134253d18d97017e;ss=Ireland;ss_all=0;ss_raw=ireland;ssb=empty;sshis=0&'
headers = {"User-Agent":"Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36"}
def get_token(): #getting csrf_token
r = requests.get(url)
soup = BeautifulSoup(r.text,"lxml")
item = soup.select_one("[name='bhc_csrf_token']")['value']
payload = {
'bhc_csrf_token': item,
'logout': 1
}
return payload
def make_post(payload): #making a post http request with the payload and parsing target page links
res = requests.post(url,data=payload,headers=headers)
sauce = BeautifulSoup(res.text,"lxml")
linklist = []
for elem in sauce.select(".sr_property_block a.hotel_name_link"):
linklist.append(urljoin(url,elem.get("href").strip()))
return linklist
def get_info(link): #scraping title and address by using each of the links
response = requests.get(link,headers=headers)
soupobj = BeautifulSoup(response.text,"lxml")
name = soupobj.select_one("h2#hp_hotel_name").get_text(strip=True)
addr = soupobj.select_one(".hp_address_subtitle").get_text(strip=True)
print(f'{name}\n{addr}\n')
if __name__ == '__main__':
for link in make_post(get_token()):
get_info(link)
</code></pre>
| [] | [
{
"body": "<p>Perhaps I misunderstand you. But it looks as though you've already written the functions to call one another: <code>get_info()</code> calls <code>make_post()</code> internally, and <code>make_post()</code> then delegates getting the token to <code>get_token()</code> by calling it internally to its... | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-10-12T16:16:16.793",
"Id": "205458",
"Score": "2",
"Tags": [
"python",
"python-3.x",
"web-scraping",
"beautifulsoup"
],
"Title": "Sourcing content from a webpage in an organized manner"
} | 205458 |
<p>What is the recommended (standard, cleaner, more elegant, etc.) method in Python to get a string with all the alphabet letters?</p>
<p>Here's three versions of code to generate a dictionary with keys as letters and 0 as all values. The aim is to parse a text and count how often a letter appears.</p>
<hr>
<pre><code>from string import ascii_lowercase
frequency = {letter: 0 for letter in ascii_lowercase}
</code></pre>
<p>A downside of this method is that the constant shows up in the <code>pydoc</code> output for the module in which it is imported.</p>
<hr>
<pre><code>frequency = {chr(letter): 0 for letter in range(ord('a'), ord('z')+1)}
</code></pre>
<hr>
<pre><code>frequency = {letter: 0 for letter in 'abcdefghijklmnopqrstuvwxyz'}
</code></pre>
<hr>
<p>This is the snippet of code where it is used:</p>
<pre><code>frequency = {chr(letter): 0 for letter in range(ord('a'), ord('z')+1)}
# The 'text' variable is taken from somewhere else, we define it here for example's sake
text = 'StackExchange Code Review'
for c in text.lower():
if c in frequency.keys():
frequency[c] += 1
total += 1
output = OrderedDict(sorted(frequency.items(), key = lambda x: x[0]))
for l in output.keys():
print(l + ':' + '{:>8}'.format(output[l]) + '{:9.2f}'.format(100 * output[l] / (total if total > 0 else 1)) + ' %')
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-10-12T18:32:39.483",
"Id": "396382",
"Score": "1",
"body": "What are you _really_ trying to accomplish with this code? Please provide the context. See [ask]."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-10-12T... | [
{
"body": "<p>If your real problem is...</p>\n\n<blockquote>\n <p>A downside of this method is that the constant shows up in the pydoc\n output for the module in which it is imported.</p>\n</blockquote>\n\n<p>... then change the name of the import:</p>\n\n<pre><code>from string import ascii_lowercase as _lowe... | {
"AcceptedAnswerId": "205472",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-10-12T18:31:41.433",
"Id": "205466",
"Score": "2",
"Tags": [
"python",
"strings",
"comparative-review",
"statistics"
],
"Title": "Printing a table of letter frequencies using Python"
} | 205466 |
<p>I was asked below question in an interview where I need to print out even and odd numbers using two threads so I came up with below code one without synchronization and other with synchronization.</p>
<pre><code>/**
* Without synchronization
*
*/
class Print {
private static final int MAX = 10;
private static int count = 1;
private boolean isOdd = true;
public void printEven() {
while (true) {
if (count > MAX)
break;
if (!isOdd) {
System.err.println(Thread.currentThread().getName() + " : " + count++);
isOdd = true;
}
}
}
public void printOdd() {
while (true) {
if (count > MAX)
break;
if (isOdd) {
System.err.println(Thread.currentThread().getName() + " : " + count++);
isOdd = false;
}
}
}
}
</code></pre>
<hr>
<pre><code>/**
* Using synchronization
*
*/
class Print2 {
private static final int MAX = 10;
private static int count = 1;
private Object obj = new Object();
public void printEven() {
while (true) {
if (count > MAX)
break;
synchronized (obj) {
System.err.println(Thread.currentThread().getName() + " : " + count++);
obj.notify();
try {
obj.wait();
} catch (InterruptedException e) {
}
}
}
}
public void printOdd() {
while (true) {
if (count > MAX)
break;
synchronized (obj) {
System.err.println(Thread.currentThread().getName() + " : " + count++);
obj.notify();
try {
obj.wait();
} catch (InterruptedException e) {
}
}
}
}
}
public class PrintEvenOddTester {
public static void main(String[] args) {
Print p = new Print();
Thread t1 = new Thread(() -> p.printEven());
t1.setName("EVEN");
Thread t2 = new Thread(() -> p.printOdd());
t2.setName("ODD");
t1.start();
t2.start();
}
}
</code></pre>
<p>I wanted to check whether there is any better or efficient way to do these kind of tasks? I ran both the code and it works fine so wanted to check if everything looks good from thread safety and synchronization perspective.</p>
<p>Since in my above code, I am using <code>while(true)</code> loop which will take some CPU's so I am not sure whether this is the best way to do it?</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-10-13T05:58:15.543",
"Id": "396398",
"Score": "0",
"body": "Your first version operates on two global variables which are manipulated without any protection from thread switches. That means, the modification of count and isOdd is not guar... | [
{
"body": "<p>In <code>Print</code> both variables <code>count</code> and <code>isOdd</code> should be marked as <code>volatile</code> then it would be thread safe, but not very efficient.</p>\n\n<p>In <code>Print2</code> you assume that no one else could wake up your thread which is incorrect as thread could b... | {
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-10-12T19:04:30.343",
"Id": "205468",
"Score": "1",
"Tags": [
"java",
"multithreading",
"interview-questions",
"thread-safety"
],
"Title": "Print odd and even numbers using two threads in Java"
} | 205468 |
<p>I created the following class for sending mail in my node.js API :</p>
<pre><code>import * as nm from 'nodemailer'
import config from '../config/environment'
class Mailer {
private mailConfig: nm.SentMessageInfo
private mailOptions: nm.SendMailOptions
private isDev: boolean = false
private devEnv: string[] = ['development', 'test', 'preproduction']
public constructor() {
if (this.devEnv.indexOf(config.env) !== -1) {
this.isDev = true
}
}
public send = (
to: string[],
subject: string,
template: string
): void | string[] => {
const dest: string = to.join(',')
const text: string = template // TODO : create and find actual template
if (this.isDev) {
this.sendDev(dest, subject, text)
} else {
this.sendProd(dest, subject, text)
}
}
private sendDev = (
dest: string,
subject: string,
text: string
): void | string[] => {
nm.createTestAccount((err: Error, account: nm.TestAccount) => {
this.mailConfig = this.setMailConfig(account)
const transporter: nm.Transporter = nm.createTransport(this.mailConfig)
this.mailOptions = this.setMailOptions(dest, subject, text)
transporter.sendMail(this.mailOptions, (error: Error, info: nm.SentMessageInfo) => {
// no empty block
})
})
}
private sendProd = (
dest: string,
subject: string,
text: string
): void | string[] => {
this.mailConfig = this.setMailConfig()
this.mailOptions = this.setMailOptions(dest, subject, text)
const transporter: nm.Transporter = nm.createTransport(this.mailConfig)
transporter.sendMail(this.mailOptions, (error: Error, info: nm.SentMessageInfo) => {
// No empty block
})
}
private setMailConfig = (
account: nm.TestAccount = null
): nm.SentMessageInfo => {
const conf: nm.SentMessageInfo = {
host: config.mail.host,
port: 587,
auth: {
user: null,
pass: null
}
}
if (this.isDev) {
conf.auth.user = account.user
conf.auth.pass = account.pass
} else {
conf.auth.user = config.mail.username
conf.auth.pass = config.mail.password
}
return conf
}
private setMailOptions = (
dest: string,
subject: string,
text: string
): nm.SendMailOptions => {
return {
from: '"Night Vision " <contact@night-vision.com>',
to: dest,
subject: subject,
html: text
}
}
}
export default new Mailer()
</code></pre>
<p>I was wondering what improvements could be made.</p>
<p>My tsconfig.json is : </p>
<pre><code>{
"compilerOptions": {
"target": "es2017",
"module": "commonjs",
"sourceMap": true,
"removeComments": true,
"outDir": "./dist/",
"pretty": true
}
}
</code></pre>
<p>And the tslint.json file (as I am unsure if this file should be included, feel free to edit the question) : </p>
<pre><code>{
"comment-format": [
true,
"check-space"
],
"extends": "tslint:latest",
"rulesDirectory": [],
"rules": {
"no-implicit-dependencies": false,
"arrow-parens": false,
"class-name": true,
"forin": true,
"deprecation": true,
"curly": true,
"eofline": true,
"indent": [
true,
"spaces",
4
],
"no-console": [
true,
"debug",
"info",
"time",
"timeEnd",
"trace",
"log"
],
"only-arrow-functions": true,
"max-line-length": [
true,
100
],
"member-ordering": [
true,
{
"order": [
"public-before-private",
"static-before-instance",
"variables-before-functions"
]
}
],
"typedef": [
true,
"call-signature",
"arrow-call-signature",
"parameter",
"arrow-parameter",
"property-declaration",
"member-variable-declaration",
"variable-declaration"
],
"no-arg": true,
"no-construct": true,
"no-duplicate-variable": true,
"no-duplicate-imports": true,
"no-unused-variable": true,
"no-non-null-assertion": true,
"no-shadowed-variable": true,
"no-string-literal": false,
"no-string-throw": true,
"no-switch-case-fall-through": true,
"no-empty": true,
"no-eval": true,
"no-namespace": false,
"no-trailing-whitespace": true,
"no-unused-expression": true,
"linebreak-style": [
true,
"LF"
],
"one-line": [
true,
"check-open-brace",
"check-catch",
"check-else",
"check-whitespace"
],
"ordered-imports": false,
"quotemark": [
true,
"single"
],
"semicolon": [
true,
"never"
],
"space-before-function-paren": false,
"object-literal-shorthand": [
true,
"never"
],
"trailing-comma": true,
"triple-equals": true,
"variable-name": [
true,
"ban-keywords"
],
"object-literal-sort-keys": false,
"cyclomatic-complexity": true,
"whitespace": [
true,
"check-branch",
"check-operator",
"check-typecast"
]
}
}
</code></pre>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-10-12T19:27:25.307",
"Id": "205469",
"Score": "1",
"Tags": [
"beginner",
"node.js",
"typescript"
],
"Title": "Nodemailer class"
} | 205469 |
<p>First time writing a "game" in a sense. Used a functions approach, it's simple, looking for a review of the way it's written and of course looking for how should it be written. Also using random for first time (I know I'm a nube).</p>
<pre><code>#Number Guess Game
import random
def gameNumber():
while True:
difficulty = input("Type: E, M, H for easy, medium, or hard number range:\n").lower()
if difficulty == 'e':
return random.randint(0,20)
elif difficulty == 'm':
return random.randint(0,50)
elif difficulty == 'h':
return random.randint(0,100)
else:
print("Incorrect input")
def numberGuessGame():
number = gameNumber()
while True:
try:
guess = int(input("Your guess: "))
if number == guess:
print("Correct guess!\n")
return numberGuessGame() if input("play again?(y/any key to exit) ").lower() == 'y' else 0
print("Too High" if number < guess else "Too Low")
except ValueError:
print("must be an integer value\n")
def main():
numberGuessGame()
if __name__ == '__main__':
main()
</code></pre>
| [] | [
{
"body": "<p>What you have is very good and it certainly functions as expected. I have just a few ideas to consider implementing (more in relation to the game than the code):</p>\n\n<ul>\n<li>Print the number ranges for each difficulty at the start, so that the user knows what range to guess in.</li>\n<li>Chec... | {
"AcceptedAnswerId": "205476",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-10-12T21:06:17.487",
"Id": "205470",
"Score": "2",
"Tags": [
"python",
"beginner",
"number-guessing-game"
],
"Title": "Number-guessing game using functions"
} | 205470 |
<p>Overall, I feel that my code is a bit verbose.</p>
<p><em>game.py</em></p>
<pre><code>#!/usr/bin/python3
import sys,os
from models import Board, GameState
"""
Game loop for the minesweeper game.
"""
class Game:
def __init__(self):
self.board = Board(rows=10, cols=10)
def play(self):
self.welcome()
while self.board.game_state in [GameState.on_going, GameState.start]:
self.board.print_board_wrapper(self.board.print_board_hook)
try:
raw = input("> ")
line = "".join(raw.split())
if line[0] == "f":
point = tuple(map(int, line[1:].split(",")))
self.board.flag_square(point[0], point[1])
else:
point = tuple(map(int, line.split(",")))
self.board.click_square(point[0], point[1])
except (IndexError, ValueError):
self.help()
except KeyboardInterrupt:
try:
sys.exit(0)
except SystemExit:
os._exit(0)
if self.board.game_state == GameState.lose:
print("\n\nYou hit a mine. :(\n")
else:
print("\n\nYou win!\n")
self.board.print_board_wrapper(self.board.print_board_end_hook)
def welcome(self):
print("\nWelcome to PySweep!")
self.help()
def help(self):
print("\nEnter coordinates")
print("> <row>,<column>")
print("> 1,1")
print("Flag and unflag coordinates")
print("> f <row>,<column>")
print("> f 1,1")
if __name__ == "__main__":
game = Game()
game.play()
</code></pre>
<p><em>models.py</em></p>
<pre><code>""" Data models for a minesweeper CLI game. """
import random
import itertools
from enum import Enum
class GameState(Enum):
start = 0
win = 1
lose = 2
on_going = 3
class Board:
""" Represents a minesweeper board with squares. """
def __init__(self, rows, cols):
self.rows = rows
self.cols = cols
self.game_state = GameState.start
self.number_of_mines = 0
self.max_mines = (cols-1)*(rows-1)
mines_percentage = (100 * self.max_mines / (rows*cols))/3
self.__create_squares(self.cols, self.rows, mines_percentage)
def flag_square(self, row, col):
if not self.__valid_square(row, col) or self.__get_square(row, col).clicked:
return
square = self.squares[row][col]
square.flag = not square.flag
def click_square(self, row, col):
"""
Click the square and click its
neighbors which don't have neighboring mines.
"""
if not self.__valid_square(row, col) or self.__get_square(row, col).clicked:
return
square = self.squares[row][col]
if self.game_state == GameState.start:
square.mine = False
for neighbor in square.neighbors():
neighbor.mine = False
self.game_state = GameState.on_going
if square.mine:
self.game_state = GameState.lose
return
square.clicked = True
if square.mine_neighbors() == 0:
for neighbor in square.neighbors():
if not neighbor.mine:
if neighbor.mine_neighbors() == 0:
self.click_square(neighbor.row, neighbor.col)
neighbor.clicked = True
if self.__win():
self.game_state = GameState.win
def print_board_wrapper(self, print_hook):
print("\n")
col_print = " "
for i in range(0, self.cols):
col_print += str(i) + " "
print(col_print + "\n")
for i,row in enumerate(self.squares):
row_print = str(i) + " "
for square in row:
row_print += print_hook(square)
print(row_print + "\n")
def print_board_hook(self, square):
"""
Prints the board. If a square is clicked,
print the number of neighboring mines.
If the square is flagged, print "f".
Else print ".".
"""
if square.clicked:
return " " + str(square.mine_neighbors()) + " "
elif square.flag:
return " f "
return " . "
def print_board_end_hook(self, square):
if square.mine:
return " x "
return self.print_board_hook(square)
def __win(self):
for row in self.squares:
for square in row:
if not square.mine and not square.clicked:
return False
return True
def __get_square(self, row, col):
""" Return the square at the given row and column."""
return self.squares[row][col]
def __valid_square(self, row, col):
return (row < self.rows and row >= 0) and (col < self.cols and col >= 0)
def __create_squares(self, cols, rows, mines_percentage):
"""
Create a grid of squares of size rows by cols.
"""
self.squares = [[Square(self, row, col, mine=self.__is_mine(mines_percentage))
for col in range(cols)] for row in range(rows)]
def __is_mine(self, mines_percentage):
""" Determine if a square is a mine while generating the board. """
is_mine = random.randrange(100) < mines_percentage
if is_mine:
if self.number_of_mines >= self.max_mines:
return False
self.number_of_mines = self.number_of_mines + 1
return True
return False
class Square:
"""
Represents a single square in the minesweeper board.
A square may have or may not have a mine, may be clicked or unclicked.
"""
def __init__(self, board, row, col, mine):
self.board = board
self.row = row
self.col = col
self.mine = mine
self.flag = False
self.clicked = False
def mine_neighbors(self):
return len(list(filter(lambda square: square.mine, [self.board.squares[point[0]][point[1]] for point in self.__point_neighbors()])))
def neighbors(self):
return [self.board.squares[point[0]][point[1]] for point in self.__point_neighbors()]
def __point_neighbors(self):
row_neighbors = list(filter(lambda val: val >= 0 and val < self.board.rows, [self.row-1, self.row, self.row+1]))
col_neighbors = list(filter(lambda val: val >= 0 and val < self.board.cols, [self.col-1, self.col, self.col+1]))
neighbor_set = set(itertools.product(row_neighbors, col_neighbors))
neighbor_set.remove((self.row, self.col))
return list(neighbor_set)
</code></pre>
<p>I think there's lots of places where my code could be made a lot more readable. The hook for the <em>print_board</em> function seems a bit suspect. The <code>__point_neighbors</code> function could probably be improved (having a lambda seems to be overkill).</p>
<p>I'm also looking to improve the mine generation algorithm. Currently, each square has an individual probability of being a mine and mine generation is stopped when max_mines is reached. So, the bottom right corner would be likely to have less mines. My solution to the "first click shouldn't be a mine" problem is I clear the space around the first click so you always get the eight spaces around the first click for free.</p>
<p>Here's a <a href="https://github.com/kdbeall/pysweep/tree/bfbdf51c87ee89339802fe1b5e195b9ec2d36311" rel="noreferrer">link</a> to the git repository.</p>
| [] | [
{
"body": "<p>Your <code>Game</code> class might not need to be a class at all. You create <code>self.board</code> in the <code>__init__()</code> method, and then only use it in the <code>play()</code> method. Since <code>play()</code> doesn't return until the game is over, <code>board</code> could simply be ... | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-10-12T21:31:54.363",
"Id": "205474",
"Score": "6",
"Tags": [
"python",
"minesweeper"
],
"Title": "Made a minesweeper game in Python"
} | 205474 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.