texts: Classic "100 doors" simulation in Clojure

texts:
I read this question about the "100 Doors" puzzle, and thought that it would make for a good quick exercise.

I ended up with two implementations. The first is more straightforward and uses a vector to store the boolean state of each door.

This is quite slow though, and having a vector of true and falses seems off, so I decided to instead try making it use a set of open doors, and just toggle membership of the set. This is much faster, although the logic is a bit more complex.

I'd like just general feedback on anything that's here. The need for oneth-range is unfortunate (as is its name), and any suggestions to avoid its use would be nice. I know this can probably be solved entirely using simple math, but I'd like suggestions on the "manual" algorithm.

; Example of set-version usage and time
(let [n 5000]
  (time
    (find-open-doors-for n n)))
"Elapsed time: 939.315276 msecs"
=> (1 4 9 16 25 36 49 64 81 100 121 144 169 196 225 256 289 324 361 400 441 484 529 576 625 676 729 784 841 900 961 1024 1089 1156 1225 1296 1369 1444 1521 1600 1681 1764 1849 1936 2025 2116 2209 2304 2401 2500 2601 2704 2809 2916 3025 3136 3249 3364 3481 3600 3721 3844 3969 4096 4225 4356 4489 4624 4761 4900)

(ns irrelevant.hundred-doors-vec)

(defn- new-doors [n-doors]
  (vec (repeat n-doors false)))

(defn- multiple-of? [n mutliple]
  (zero? (rem n mutliple)))

(defn- oneth-range
  "Returns a range without 0. Max is inclusive."
  ([] (rest (range)))
  ([max] (rest (range (inc max)))))

(defn- toggle-doors
  "Toggles the state of every nth door."
  [doors every-n]
  (mapv #(if (multiple-of? % every-n)
           (not %2)
           %2)
        (oneth-range), doors))

(defn- toggle-doors-for [doors max-n]
  (reduce toggle-doors doors (oneth-range max-n)))

(defn find-open-doors-for
  "Simulates the opening and closing of n-doors many doors, up to a maximum skip distance of n."
  [n-doors n]
  (let [doors (new-doors n-doors)
        toggled (toggle-doors-for doors n)]

    (->> toggled
         (map vector (oneth-range))
         (filter second)
         (map first))))

(ns irrelevant.hundred-doors-set)

(defrecord Doors [open n-doors])

(defn- new-doors [n-doors]
  (->Doors #{} n-doors))

(defn- multiple-of? [n multiple]
  (zero? (rem n multiple)))

(defn- oneth-range
  "Returns a range without 0. Max is inclusive."
  ([] (rest (range)))
  ([max] (rest (range (inc max)))))

(defn- toggle-doors
  "Toggles the state of every nth door."
  [doors every-n]
  (update doors :open
    (fn [open]
      (reduce (fn [acc-set n]
                (cond
                  (not (multiple-of? n every-n)) acc-set
                  (open n) (disj acc-set n)
                  :else (conj acc-set n)))
              open
              (oneth-range (:n-doors doors))))))

(defn- toggle-doors-for [doors max-n]
  (reduce toggle-doors doors (oneth-range max-n)))

(defn find-open-doors-for
  "Simulates the opening and closing of n-doors many doors, up to a maximum skip distance of n."
  [n-doors n]
  (let [doors (new-doors n-doors)
        toggled (toggle-doors-for doors n)]

    (-> toggled
        (:open)
        (sort))))


texts:
A Fenwick Tree, or a Binary Indexed tree, is an interesting data structure that can efficiently update its elements. You can read more about it in this paper.

Here is a generic implementation of a Fenwick Tree, which could take any two reversible operations:

class FenwickTree<T> {

    private let count   : Int
    private let neutral : T
    private let forward : (T,T) -> T
    private let reverse : (T,T) -> T

    private var data    : [T]
    private var tree    : [T]

    init(
        count: Int,
        neutralElement: T,
        forward: @escaping (T,T) -> T,
        reverse: @escaping (T,T) -> T
        ) {
        self.count = count
        self.neutral = neutralElement
        self.forward = forward
        self.reverse = reverse
        self.data = Array(repeating: neutralElement, count: count)
        self.tree = Array(repeating: neutralElement, count: count + 1)
    }

    func update(index: Int, with newValue: T) {
        let oldValue = data[index];
        let delta = reverse(newValue, oldValue)
        data[index] = newValue
        var treeIndex = index + 1
        while treeIndex <= count {
            tree[treeIndex] = forward(tree[treeIndex], delta)
            treeIndex += treeIndex & -treeIndex
        }
    }

    func accumulated(at index: Int) -> T {
        var sum = neutral
        var treeIndex = index + 1
        while 0 < treeIndex {
            sum = forward(tree[treeIndex], sum)
            treeIndex -= treeIndex & -treeIndex
        }
        return sum
    }

    func accumulated(in range: Range<Int>) -> T {
        let low = range.lowerBound, high = range.upperBound - 1
        let cumulatedLow = low == 0 ? neutral : accumulated(at: low - 1)
        let cumulatedHigh = accumulated(at: high)
        return low == high ? data[low] : reverse(cumulatedHigh,cumulatedLow)
    }
}

Here are some example usecases:

let n = 10

let additiveTree = FenwickTree(count: n, neutralElement: 0, forward: +, reverse: -)

for i in 0..<n { additiveTree.update(index: i, with: i + 1) }

additiveTree.accumulated(at: 5)
additiveTree.accumulated(at: 9)
additiveTree.accumulated(in: 8..<10)

let multiplicativeTree = FenwickTree(count: n, neutralElement: 1, forward: *, reverse: /)

for i in 0..<n { multiplicativeTree.update(index: i, with: i + 1) }

multiplicativeTree.accumulated(at: 5)
multiplicativeTree.accumulated(at: 9)
multiplicativeTree.accumulated(in: 8..<10)

I am mainly concerned about the naming of functions and variables:

neutral: This is the neutral element for forward and reverse
forward and reverse should be transitive verbs since they have side effects. Preferably, the names should have the same number of letters.
accumulated(at:) is an unusual name, more familiar would be foldLeft from Scala, or foldl from Haskell.
accumulated(at:) and accumulated(in:) have too similar names.

I can see some possible improvements:

Performance: accumulated(in:) could have better time complexity at the expense of some auxiliary space;
Enforcing the reversibility of forward and reverse in code;

Other areas of improvement are welcome.


texts: Variable creation and returning Boolean values

texts:
Out of a challenge for myself, I created this little program in which you can create "variables", test those "variable" values, test regular values, or clear all the "variables".

from operator import *

oper = {
    "==": eq,
    ">": gt,
    "<": lt,
    "<=": le,
    ">=": ge,
    "!=": one,}

var = []

def println(stringint):
    print stringint

def clearvars():
    del var[:]

def createvar(value):
    var.append(value)

def returnbool(value1, testvalue, value2):
    print testvalue(value1, value2)

Here's an example of an interpreter session. If you're curious, pcl is the filename.

>>> import pcl
>>> pcl.createvar(1)
>>> pcl.createvar(3)
>>> pcl.println(pcl.var)
[1, 3]
>>> pcl.returnbool(pcl.var[0], pcl.oper["!="], pcl.var[1])
True
>>> pcl.clearvars()
>>> pcl.println(pcl.var)
[]

All I'm really looking for are places where I could improve on, and how I can make this compatible with Python2 & Python3.


texts: Shared Pointer based Object Pool Implementation with fixed object count

texts:
I'm implementing a object pool with shared_ptr to access with multiple thread.
Any suggestions to improve my implementation

template <typename T>
class Section : public std::enable_shared_from_this<Section<T>>
{
public:

template <typename... E>
Section(std::size_t size, E... args)
    : std::enable_shared_from_this<Section<T>>()
    , m_mem(size,T(args...))
{
    for(auto& itr: m_mem)
    {
        destroy(&itr);
        m_objs.push(&itr);
    }
}
virtual ~Section() = default;

void isEmpty() const
{
    std::unique_lock<std::mutex> lk(m_lock);
    return m_objs.empty();
}
template <typename... E>
std::shared_ptr<T> create(E... args)
{
    T* obj = getObject();
    if(obj != nullptr)
    {
        new (obj) T(args...);
    }
    return std::shared_ptr<T>(obj,[this](T* ptr)->void
    {
        destroy(ptr);
        std::unique_lock<std::mutex> lk(m_lock);
        m_objs.push(ptr);
    });
}

private:
std::list<T> m_mem;
std::queue<T*> m_objs;
mutable std::mutex m_lock;

T* getObject()
{
    std::unique_lock<std::mutex> lk(m_lock);
    if (!m_objs.empty())
    {
        T* obj = m_objs.front();
        m_objs.pop();
        return obj;
    }
    return nullptr;
}

void destroy(T* obj)
{
    obj->~T();
}
};


texts:
Is this code clean and optimized? When taking memory snapshots, it seems a bit high.
Anything I have done wrong or can do to optimize it?
#pragma once
#include <iostream>
#include <windows.h>
#include <sstream>
#include <Psapi.h>

// Author: https://github.com/TheRacc2
// Other Help: https://github.com/dgoguerra/, for the bytes_to_size function (modified from the "humanSize" function found in https://gist.github.com/dgoguerra/7194777)
// Repository: https://github.com/TheRacc2/error_handler/
// Report issues here: https://github.com/TheRacc2/error_handler/issues

constexpr const char* name = "Error Handler";

namespace helpers {
    // Convert bytes into readable sizes, E.G: 1024B -> 1KB, 1024000B -> 1MB
    //
    // call as such:
    // const char* sign = bytes_to_size(1024);
    const char* bytes_to_size(int bytes) {
        const char* units[] = { "B", "KB", "MB", "GB", "TB" };
        const int size = sizeof(units) / sizeof(units[0]) - 1;

        int i = 0;
        double outside_bytes = bytes;

        if (bytes > 1024)
            for (; (bytes / 1024) > 0 && i < size; i++, bytes /= 1024)
                outside_bytes = bytes / 1024;

        static char final[12];
        snprintf(final, 12, "%.01f %s", outside_bytes, units[i]);
        return final;
    }
}

namespace error_handler {
    // Use this in a "try, catch" situation, the send to developers function doesn't need to be provided.
    //
    // call as such:
    // try {
    //     your_function_or_code();
    // } CATCH(send_log_to_developer(ex))
    #define CATCH(send_to_developers_function) \
    catch (const std::exception& ex) { \
        std::stringstream error; \
        error << ex.what(); \
        error << "\n\n"; \
        error << "Would you like to report this to the developers? Should your request be seen, this crash may be prevented."; \
        \
        if (MessageBoxA(nullptr, error.str().c_str(), name, MB_YESNO) == IDYES) { \
            send_to_developers_function; \
            MessageBoxA(nullptr, "Thank you for reporting this!", name, MB_OK); \
        } \
    }

    // Call this when something needs to go wrong, formatted like "printf". The second argument doesn't need to be provided.
    //
    // call as such:
    // THROW("You didn't use this right! You used this like: %s", "throw()")
    //
    // output:
    // "You didnt use this right! You used this like: throw()"
    #define THROW(text, ...) \
    error_handler::throw_ex(text, __FILE__, __FUNCTION__, __LINE__, __VA_ARGS__);

    // You shouldn't manually call this function, as you have to provide the file, function and line.
    // Use the "THROW" macro instead.
    template <typename... Args>
    void throw_ex(const char* text, const char* file, const char* function, const int& line, Args... args) {
        char message[128];
        snprintf(message, 128, text, args...);

        std::stringstream stream;
        stream << message << "\n\n";

        PROCESS_MEMORY_COUNTERS_EX pmc;
        K32GetProcessMemoryInfo(GetCurrentProcess(), reinterpret_cast<PROCESS_MEMORY_COUNTERS*>(&pmc), sizeof(pmc));

        stream <<
            "{\n" <<
            "    File: \"" << file << "\",\n"
            "    Function: \"" << function << "\",\n"
            "    Line: " << line << ",\n"
            "    Memory: \"" << helpers::bytes_to_size(pmc.PrivateUsage) << "\"\n"
            "}"
        ;

        throw std::exception(stream.str().c_str());
    }
}


texts: pass argument to jQuery .on() event handler callback

texts:
In my web application, a user will click a button which will call a function that triggers an AJAX call.  That function accepts a single argument.  I would like to be able to put that function in place of the anonymous function in the jQuery event handler.  I suspect that this is a scoping issue...

Here is my working code:

(function () {
 'use strict';

  var postId;

  function userAddFlagToPost (userId) {
    return $.ajax({
      type: 'POST',
      timeout: 1000 * 3;,
      url: '/someApi/postId',
      data: {
        userId: userId
      },
    }).done(onFlagSubmitDone)
      .fail(onFlagSubmitDone);
  }

  function onLoggedIn() {
    var userId = getCookie('some_user_auth') || null;

    $(SELECTORS.POST_FLAG).on('click', function() {
      postId = $(this).data('postId');
    });

    $(SELECTORS.SUBMIT_BUTTON).on('click', function() {
      userAddFlagToPost(userId);
    });
  }

  function init() {
    eventQ.register(onLoggedIn);
  }

  init();
})();

I would like to be able to do:

$(SELECTORS.SUBMIT_BUTTON).on('click', userAddFlagToPost(userId));

I'd appreciate any info or advice on how to go about refactoring this code, thanks!


texts: Memory management for matrices built with dynamic arrays

texts:
I am working on C++ code which builds matrices (3D and 4D) using dynamic arrays.
I am using arrays instead of std::vector; as in the future, I might extend this code to some kind of multithreading or parallel process (e.g. CUDA).

In my code, I often initialize and define the source matrix in main.cpp.

Then I have a function (sometimes it may belong to a class) which inputs the matrix along with other variable and I need to return the modified matrix. Which is subsequently used in main.

This is what I usually work with in my code:

    #include <iostream>
    #include <stdio.h>
    #include <stdlib.h>
    using namespace std;

    float ***matFunc ( ***mat3D, int n);

    int main()
    {
      // define dimensions of the matrix
      int M , N, S = 3;

     //define and initialize the matrix
      float ***myMat = new float **[M];
         for (int i = 0; i< M; i++ ) {
              myMat[i] = new float *[N];
              for ( int j = 0; j < N; j++ ) {
                 myMat[i][j] = new float [S];
                    for (int k = 0; k < S; k++ ) {
                      myMat[i][j[k] = someValue obtained or calculated
                          }
                   }
              }

         // here I call my member function to perform addition
         // This is also used if I have more than one matrices

        float ***newMat = matFunc( myMat, int n ); //returns modified matrix

         //deleting the original myMat

         for (int i = 0; i < M; i++) {
             for (int j = 0; j < N; j++) {
               delete[]myMat[i][j];
        }
            delete[] myMat[i];
      }
   delete[]myMat;

      return 0;
     }

     //function definition for matFunc

      float***matFunc(float ***mat, int n ){

       int p, q, r;
       int M, N, S = 3;

           float ***modifiedMat = new float **[M];
                for ( p = 0, p < M; p++ ) {
                   modifiedMat[p] = new float *[N];
                     for ( q = 0; q < n; q++ ) {
                         modifiedmat[p][q] = new float [S];
                          for (r  =0; r < S; r++ ) {
                          modifiedMat[p][q][r] = mat[p][q][r] * do something
                         }
                        }
                      }

           return modifiedMat;
        }

As you can observe, I am always defining and initializing new matrices with help of dynamic arrays. This becomes more troublesome if matrix dimensions are to be increased. I use dynamic arrays due to their faster operations as compared to vectors. But I think there might be some memory management issues with code.  As I have observed it consumes more RAM and sometimes my IDE/compiler will complain lack of index or space for integer type.

Could you please suggest how I can improve on this code?


texts:
I've been working on learning React, and so like most people do when they get started on something new. I created an arbitrary simple project to get a bit more familiar with the concepts.

It's so simple that it shouldn't really require any explanation. Here's the React code.

var TestInput = React.createClass({
    propTypes: {
        id: React.PropTypes.string.isRequired,
        label: React.PropTypes.string.isRequired,
        placeholder: React.PropTypes.string
    },
    getDefaultProps: function() {
        return {
            type: 'text'
        }
    },
    render: function() {

        var {label, id} = this.props;
        var other = _.omit(this.props, 'label');

        return (

                {label}
                <input className="form-control" {...other}/>

        );
    }
});

var TestOutput = React.createClass({
    propTypes: {
        name: React.PropTypes.string.isRequired
    },
    render: function() {
        return (

Hello {this.props.name}!

        );
    }
});

var TestBox = React.createClass({
    getInitialState: function() {
        return {
            firstName: '',
            lastName: ''
        }
    },
    handleInput: function(event) {
        var newState = {};
        newState[event.target.id] = event.target.value;
        this.setState(newState);
    },
    createName: function() {
        var nameParts = [];

        if (this.state.firstName.length == 0 && this.state.lastName.length != 0) {
            nameParts.push('Mr.');
        }
        if (this.state.firstName.length != 0) {
            nameParts.push(this.state.firstName);
        }
        if (this.state.lastName.length != 0) {
            nameParts.push(this.state.lastName);
        }
        if (nameParts.length == 0) {
            nameParts.push('Anonymous');
        }

        return nameParts.join(' ');
    },
    render: function() {
        return (

                <TestInput id="firstName" label="First Name" placeholder="John" onKeyUp={this.handleInput}/>
                <TestInput id="lastName" label="Last Name" placeholder="Smith" onKeyUp={this.handleInput}/>
                <TestOutput name={this.createName()} />

        );
    }
});

React.render(
    <TestBox/>,
    document.getElementById('container')
);

It works, but it seems like I had to do way too much to get it to work. Not that it was difficult to write, but it just seems like a lot of data transfer and boilerplate to do very little. Maybe this is just because my example is simple and contrived? I'm just thinking that with jQuery I could write a single event handler which works on both input's keyUp and update the H3's text based on the current values.

What am I doing wrong? Or am I doing it right?


texts:
I have developed some Python code which revolves around two custom classes - a 'Library' class (Lib) which contains a Python list of several objects based on a 'Cas' class. I've not posted the code for either of these classes here, but all you really need to know to understand my question is that the 'Library' object contains a Python list and the 'Cas' objects contain various attributes, some of which are strings and some are values.

One of the objectives of the code is to manipulate the Python list in the Library class and return a sub-set of the 'Cas' objects based on some user driven criteria. For example, return Cas objects where a particular attribute is equal to a given string or greater than a given value.

For this purpose, I have written the following generic method filterLibrarySingle to allow me to filter the Python list in the library class (self.Lib) based on various methods (filterMethod), attributes (filterField) and values (filterValue). Within the method I'm achieving this using list comprehensions.

On profiling my code, it would appear that this method can be quite a bit of a bottle neck! Does any one have an idea of how I could speed it up?

def filterLibrarySingle(self, filterField, filterMethod, filterValue1, filterValue2=None):
    if filterMethod == 'eq':
        self.Lib = [cas for cas in self.Lib if getattr(cas, filterField) == filterValue1]

    elif filterMethod == 'lt':
        self.Lib = [cas for cas in self.Lib if getattr(cas, filterField) < filterValue1]

    elif filterMethod == 'gt':
        self.Lib = [cas for cas in self.Lib if getattr(cas, filterField) > filterValue1]

    elif filterMethod == 'le':
        self.Lib = [cas for cas in self.Lib if getattr(cas, filterField) <= filterValue1]

    elif filterMethod == 'ge':
        self.Lib = [cas for cas in self.Lib if getattr(cas, filterField) >= filterValue1]

    elif filterMethod == 'gelt':
        self.Lib = [cas for cas in self.Lib if  getattr(cas, filterField) >= filterValue1 and getattr(cas, filterField) < filterValue2]

    elif filterMethod == 'gele':
        self.Lib = [cas for cas in self.Lib if  getattr(cas, filterField) >= filterValue1 and getattr(cas, filterField) <= filterValue2]

I've wracked my brains for days on this to try and speed it up but I guess my Python knowledge simply isn't good enough!


texts:
I have a method which checks some preconditions and if everything is fine returns a success response object, otherwise fail with an appropriate error message.

My problem is that I have a bunch of if-elses which are checking some specific condition and if it fails return a fail object with a message.

Here is an example code:

public Response sendFirstInquiryEmail(long itemId) {

        Item item = itemService.findById(itemId);

        if (item == null) {
            return Response.fail().withComment("Can't find item");
        }

        if (State.NEW != item.getState()) {
            return Response.fail().withComment("Can't send first inquiry to customer for items not in 'NEW' state");
        }

        if (!item.hasNumber()) {
            return Response.fail().withComment("Can't find ticket in OTRS");
        }

        if (!item.isActive()) {
            return Response.fail().withComment("Item is not active anymore");
        }

        if (!item.isReady()) {
            return Response.fail().withComment("Item is not finalized, first inquiry can be send only for processed items");
        }

        send(item);

        return Response.success();

}

And here is my response:

public class Response {

    private       String  comment;
    private final boolean successful;

    private Response(boolean successful) {
        this.successful = successful;
    }

    public static Response success() {
        return new Response(true);
    }

    public static Response fail() {
        return new Response(false);
    }

    Response withComment(String comment) {
        this.comment = comment;
        return this;
    }

    public String comment() {
        return comment;
    }

    public boolean isSuccessful() {
        return successful;
    }

}

Those conditions are getting more and more, and do not like these bunch of if. Is there a better way to achieve the same? I was thinking if it is possible somehow to map this conditions with errors, so that I can call some validate() which can return the response with a message.


texts:
I have this block of code which clearly looks like duplicate, but I don't know how to refactor.

    float offsetDifference;
            nfloat newLogoHeight;
            nfloat newHeaderHeight;
            nfloat newLogoWidth;

            if (offset > _previousOffset)
            {
                offsetDifference = offset - _previousOffset;

                newHeaderHeight = (HeaderViewHeightConstraint.Constant - offsetDifference);
                newLogoHeight = (LogoImageViewHeightConstraint.Constant - offsetDifference);
                newLogoWidth = (LogoImageViewWidthConstraint.Constant - offsetDifference);

                HeaderViewHeightConstraint.Constant = newHeaderHeight < headerViewMinHeight ? headerViewMinHeight : newHeaderHeight;
                LogoImageViewHeightConstraint.Constant = newLogoHeight < logoViewMinHeight ? logoViewMinHeight : newLogoHeight;
                LogoImageViewWidthConstraint.Constant = newLogoWidth < logoViewMinWidth ? logoViewMinWidth : newLogoWidth;
            }
            else
            {
                offsetDifference = _previousOffset - offset;

                newHeaderHeight = (HeaderViewHeightConstraint.Constant + offsetDifference);
                newLogoHeight = (LogoImageViewHeightConstraint.Constant + offsetDifference);
                newLogoWidth = (LogoImageViewWidthConstraint.Constant + offsetDifference);

                HeaderViewHeightConstraint.Constant = newHeaderHeight > headerViewMaxHeight ? headerViewMaxHeight : newHeaderHeight;
                LogoImageViewHeightConstraint.Constant = newLogoHeight > logoViewMaxHeight ? logoViewMaxHeight : newLogoHeight;
                LogoImageViewWidthConstraint.Constant = newLogoWidth > logoViewMaxWidth ? logoViewMaxWidth : newLogoWidth;
            }

            //HeaderViewHeightConstraint.Constant = (headerViewMaxHeight - offset) < logoViewMaxHeight ? logoViewMaxHeight : (headerViewMaxHeight - offset);
            //LogoImageViewHeightConstraint.Constant = (logoViewMaxHeight - offset) < 0 ? 0 : (logoViewMaxHeight - offset);
            _previousOffset = offset;

Basically, I receive an offset, and according to the previous offset (wether is smaller or bigger), I reorganize some other values.

The thing is, the calculation is almost the same, and I'd love a method that just does the calculation in which I can pass the parameters, but I don't know how to write the "common code" since all the calculations varies in the + and -, or < and >.

Anyway, you're seeing this as well as I am, but you probably know how to refactor it better than I do. How would you do it ? :)

Note : I've rewritten most of this from my phone, sry for the terrible code formatting, it's really impractical. Feel free to edit


texts:
In my task I have to pass some data from one model to another, where each model contains lists:

List<VisualProcess> vProcesses = new ArrayList<VisualProcess>();
    for (Process process : processList) {
                VisualProcess vProcess = new VisualProcess();
                vProcess.setId(process.getId());
                List<VisualProcessStep> steps = new ArrayList<VisualProcessStep>();
                List<VisualProcessStepConnection> connections = new ArrayList<VisualProcessStepConnection>();
                for(ProcessStep processStep : process.getSteps()){
                    VisualProcessStep vps = new VisualProcessStep();
                    vps.setActivityId(processStep.getActivityId());
                    vps.setDefinition(processStep.getDefinition());
                    vps.setId(processStep.getId());
                    vps.setParameters(processStep.getParameters());
                    vps.setStatus(processStep.getStatus());
                    for (Activity activity : process.getActivities()) {
                        if (activity.getId().equals(vps.getActivityId())){
                            vps.setActivityName(activity.getName());
                            vps.setActivityRealization(activity.getRealization());
                            break;
                        }
                    }
                    steps.add(vps);
                    for (ProcessStep nextProcessStep : processStep.getNextSteps()) {
                        VisualProcessStepConnection vpsc = new VisualProcessStepConnection();
                        vpsc.setFrom(processStep.getId());
                        vpsc.setTo(nextProcessStep.getId());
                        connections.add(vpsc);
                    }
                }
                vProcess.setSteps(steps);
                vProcess.setConnections(connections);
                vProcesses.add(vProcess);
            }

However, while I think it looks awful, I don't have any other ideas as to making it more elegant. Another issue is about the size of the method: Would it be better to split it into several, smaller methods?


texts: Vector addition and Pythagorean Theorem code

texts:
I would like to share my code that is meant to help me add 2 vectors together. It is very simple and I would like to kindly ask you whether you could review my code. Also, I decided to keep separate variable for angle in degrees % 90. Do you think that was a good idea?

import math

def pythagorean_theorem(a,b, c=None):
    if (None is not a and None is not b) and None is c:
        return math.sqrt(float(a) ** 2 + float(b) ** 2)
    elif (a is None or b is None) and c is not None:
        if a is None:
            return math.sqrt(float(c)**2 - float(b)**2)
        else:
            return math.sqrt(float(c)**2 - float(a)**2)
    else:
        return -1

def find_x_component(vector1):
    alpha = math.radians(vector1[1] % 90)

    if vector1[1] > 0 and vector1[1] < 90:
        return (math.cos(alpha)) * vector1[0]
    elif vector1[1] > 90 and vector1[1] < 180:
        return 0 - ((math.sin(alpha)) * vector1[0])
    elif vector1[1] > 180 and vector1[1] < 270:
        return 0 - ((math.cos(alpha)) * vector1[0])
    elif vector1[1] > 270 and vector1[1] < 360:
        return (math.sin(alpha)) * vector1[0]
    elif vector1[1] == 180:
        return 0 - vector1[0]
    elif vector1[1] == 0:
        return vector1[0]
    else:
        return 0

def find_y_component(vector1):
    alpha = math.radians(vector1[1] % 90)

    if vector1[1] > 0 and vector1[1] < 90:
        return (math.sin(alpha)) * vector1[0]
    elif vector1[1] > 90 and vector1[1] < 180:
        return (math.cos(alpha)) * vector1[0]
    elif vector1[1] > 180 and vector1[1] < 270:
        return 0 - ((math.sin(alpha)) * vector1[0])
    elif vector1[1] > 270 and vector1[1] < 360:
        return 0 - (math.cos(alpha)) * vector1[0]
    elif vector1[1] == 270:
        return 0 - vector1[0]
    elif vector1[1] == 90:
        return vector1[0]
    else:
        return 0

def vector_addition(vector1, vector2):

    # Calculating X and Y components
    vector1X = find_x_component(vector1)
    vector1Y = find_y_component(vector1)

    vector2X = find_x_component(vector2)
    vector2Y = find_y_component(vector2)

    return [vector1X + vector2X, vector1Y + vector2Y, pythagorean_theorem(vector1X + vector2X,vector1Y + vector2Y)]

vectorA = [2, 45]
vectorB = [6, 73.5]
print(f'Coordinates of the endpoint of your vector are {vector_addition(vectorA, vectorB)[0:2]} and its magnitude is {vector_addition(vectorA, vectorB)[2]}.')


texts: URLIfy a character array using Python - follow-up

texts:
This is a follow up to my last code review:

URLify a string using Python

This problem has been reviewed in other languages, but I tried to solve this without looking at those answers.

I am hoping that I achieved \$O(n)\$ time and \$O(1)\$ space as was explained in my last review.  I would also appreciate any tips on improving clarity and/or making the code more pythonic without sacrificing time/space complexity.

def count_spaces(in_char_array):
   num_spaces = sum(1 for char in in_char_array if char == ' ')
   return  num_spaces

def urlify(in_char_array, true_length):
   num_spaces = count_spaces(in_char_array[:true_length])
   urlified_length = true_length + 2*num_spaces

   urlified_pos = urlified_length - 1
   for in_char in reversed(in_char_array[:true_length]):
       if in_char == ' ':
           in_char_array[urlified_pos-2:urlified_pos+1] = '%20'
           urlified_pos -= 3
       else:
           in_char_array[urlified_pos] = in_char
           urlified_pos -= 1
    return in_char_array

I tested this as follows -

urlified_string = urlify(list('Mr John Smith    '), 13)

print(urlified_string)
print(''.join(urlified_string))

The output was:

['M', 'r', '%', '2', '0', 'J', 'o', 'h', 'n', '%', '2', '0', 'S', 'm', 'i', 't', 'h']

Mr%20John%20Smith


texts: Mapping properties between two Objects of different structure

texts:
Something I've found myself having to do reasonably often is map properties from an Object (usually a heavily nested MongoDB document) to a different 'shape' to then pass it to a function call or API endpoint etc. Combine this with a development environment in which these 'shapes' are prone to change and it felt messy to do the mapping manually each time (though learning object destructuring often made it much neater!).

I've written this code to accept two arrays containing key names, an object and a delimiter option. The function then returns an object containing the properties pointed to by the keys in the input array, but with the key names as specified in the output array.

const transposeObjectByArraysOfPairs = (input, output, object, delimiter = '.') => {
    const toReturn = {};

    input.map((keyString, idx) => {
        const keysIn = keyString.split(delimiter);

        // copy object to avoid mutating original
        let _currentProp = Object.assign({}, object);

        for (let i = 0; i < keysIn.length; i++) {
            _currentProp = _currentProp[keysIn[i]];
        }

        const keysOut = output[idx].split(delimiter);

        let len = keysOut.length;

        let _obj = {[keysOut[len - 1]]: _currentProp};

        for (let j = len - 2 ; j >= 0; --j) {
            _obj = {[keysOut[j]]: _obj};
        }

        Object.assign(toReturn, _obj);
    });

    return toReturn;
};

const object = {a : {b: { c: 10, d: 30 }}};

const input = ['a.b.c', 'a.b.d'];
const output = ['A.B', 'B.C'];

console.log(misc.transposeObjectByArraysOfPairs(input, output, object));
// { A: { B: 10 }, B: { C: 30 } }

Whilst this function has neatened up chunks of my code significantly, I can't help but feel there's a neater way to do this. Iterating through an array of keys to get to the desired property feels quite hacky in particular.

In a perfect world I think I'd essentially have a function that mapped from one object schema to another and then I could simply maintain schema and know that if I made changes, I wouldn't need to modify the code that did the mapping.


texts: Game Engine :: Entity Component Design - Handling Input

texts:
I am currently creating a game engine for educational purposes.

ECS Design Pattern

The first design pattern I've included is the Entity/Component/System pattern. Therefore I've got a base singleton class called cEngine, which contains all systems (PhysicsSystem, GraphicsSystem, etc.) so it can update them on each frame.

void cEngine::Run()
{
    while( m_Run )
    {
        m_Timer.Update();
        for(int i = 0; i < m_Systems.size(); ++i)
            m_Systems.at(i)->Update();
            //NOTE: I will add a SystemManager to update them in the proper order
    }
}

Also, I can create new entities (actually just IDs) and add different components (position, velocity, renderable, ...), which then get saved in the right system. So for example, the position and the velocity components will be saved in the physics system, as this one is responsible for modifying those values. Other systems, however, may have a pointer to those components, because they may need those values (the graphic system for example needs the positional information, but won't modify it).

State Design Pattern

The second design pattern I use is a state system:

class iState
{
    virtual void Init() {}
    virtual void Quit() {}
    virtual void Update() {}
    virtual void UpdatePause() {}
    virtual void Obscuring() {} //call when another state gets pushed
    virtual void Revealed() {} //call when upper state gets poped
private:
    bool m_isActive; //true, when it is at the top of the state stack
};

The user will be able to create customizable states (overwrite the virtual functions), which then get pushed onto the StateStack. Those functions will be called properly for every state by the StateManager class.

class cStateManager
{
    void Init();
    void Update();
    void Quit();

    void PushState( iState* state );
    void PopState();
    void ChangeState( iState* state );
private:
    std::vector<iState*> m_stateStack;
};

Questions

Is this the right choice? In my opinion this design is pretty good, as it is easy for the user and it should have good performance. However, I appreciate suggestions!
This is related to Input Handling. My design would've been a singleton Input class.

class cInput
{
    void Update();

    bool wasKeyPressed(int key);
    bool wasKeyReleased(int key);

    bool isKeyDown(int key);
    bool isKeyUp()int key);

private:
    //...
}

Once again, the engine class would Update() this class every frame, so it would always have the right key information. The huge benefit by not handling this class as a system, but as a segregated singleton class is, that the user simply can create a new state, create some entities in it, and easily handle input in the virtual Update() function of that state.

Something like this:

//overwriting virtual state functions
void Init(){
    id = cEngine->AddEntity();
}

void Update(){
    //add some components, bla bla...

    //simple input handling
    if(cInput->IsKeyDown(KEY_W)){
        //do something...
    }

    if(cInput->WasKeyPressed(KEY_A)){
        //do something
    }
}

As I've already said, in my opinion this "hybrid" design, which does not see the Input as another ECS system, but as a "independent" class is better and much more comfortable for the user than a "input component". However, I haven't seen this pattern on the Internet, which makes me a little bit insecure.

Did I miss one huge benefit of an input component or a huge disadvantage with this approach?


texts: Loader animation using Custom View in Android

texts:
I created a loader animation for an Android app: a simple 3 dots loader.

Is this the correct way to animate by using TimerTask?

public class ThreeDotsLoader extends View {

    Paint dot1;
    Paint dot2;
    Paint dot3;

    int defaultColor;
    int highlightColor;

    boolean animationStarted = false;

    TimerTask task;
    Timer timer;

    int count = 1;

    public ThreeDotsLoader(Context context, AttributeSet attrs) {
        super(context, attrs);
        defaultColor = Color.rgb(44, 78, 82);
        highlightColor = Color.WHITE;

        initPaint();
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        Log.d("custom", "ondraw");
        canvas.drawCircle(50, 50, 15, dot1);
        canvas.drawCircle(100, 50, 15, dot2);
        canvas.drawCircle(150, 50, 15, dot3);
    }

    private void initPaint(){
        dot1 = new Paint();
        dot1.setColor(defaultColor);
        dot1.setStyle(Paint.Style.FILL);
        dot1.setAntiAlias(true);

        dot2 = new Paint();
        dot2.setColor(defaultColor);
        dot2.setStyle(Paint.Style.FILL);
        dot2.setAntiAlias(true);

        dot3 = new Paint();
        dot3.setColor(defaultColor);
        dot3.setStyle(Paint.Style.FILL);
        dot3.setAntiAlias(true);
    }

    public void startLoading(){
        task = new TimerTask() {

            @Override
            public void run() {

                switch(count){
                case 1:
                    dot1.setColor(highlightColor);
                    dot2.setColor(defaultColor);
                    dot3.setColor(defaultColor);
                    count++;
                    break;
                case 2:
                    dot1.setColor(defaultColor);
                    dot2.setColor(highlightColor);
                    dot3.setColor(defaultColor);
                    count++;
                    break;
                case 3:
                    dot1.setColor(defaultColor);
                    dot2.setColor(defaultColor);
                    dot3.setColor(highlightColor);
                    count = 1;
                    break;
                }
                animationStarted = true;
                postInvalidate();
            }
        };
        timer = new Timer();
        timer.schedule(task, 0, 300);

    }

    public void stopLoading(){
        animationStarted = false;
        timer.cancel();
    }
}


texts: Find smallest prime number greater than given n

texts:
I need to write a program which will find a prime number, greater than the given n.

Can it be done simpler?

#include <stdio.h>

int isPrime(int n)
{
    int i,j=0;
    for(i=1; i<=n; i++)
    {
        if(n%i == 0)
            j++;
    }
    if(j == 2)
        return 1;
    else if(j > 2)
        return 0;
}

int fun(unsigned int n)
{
    int i=n+1;
    while(1)
    {
        if(isPrime(i))
            break;
        i++;
    }
    return i;
}

int main(int argc, char **argv)
{
    printf("%d\n", fun(19));
    return 0;
}


texts:
public void AddClient(Client obj){
  try{
      using(System.Data.SQLite.SQLiteConnection conn = stock.db.SqlLiteConnection.getSQLLiteConnection()){
      System.Data.SQLite.SQLiteCommand cmd = conn.CreateCommand();
      string sql="insert into Client (email,firstName,lastName,telephone,address,city,state,zip,web) values(@email,@firstName,@lastName,@telephone,@address,@city,@state,@zip,@web)";
      cmd.CommandText = sql;
      cmd.Parameters.AddWithValue("@email", obj.Email);
      cmd.Parameters.AddWithValue("@firstName", obj.FirstName);
      cmd.Parameters.AddWithValue("@lastName", obj.LastName);
      cmd.Parameters.AddWithValue("@telephone", obj.Telephone);
      cmd.Parameters.AddWithValue("@address", obj.Address);
      cmd.Parameters.AddWithValue("@city", obj.City);
      cmd.Parameters.AddWithValue("@state", obj.State);
      cmd.Parameters.AddWithValue("@zip", obj.Zip);
      cmd.Parameters.AddWithValue("@web", obj.Web);
      cmd.ExecuteNonQuery();
    }

  }catch (Exception ex){}
}

I have couple of questions for the above code

Do I have to close connection manually?
Do I need to dispose Command object?
If exception occurs, do I have to close connection and command
How do I enhance this code further?


texts: Consistent way to handle transient timeouts with WCF calls (timeouts, unreliable network, server load, etc)

texts:
I'm currently using the following code to manage calls to WCF services that are unreliable, and or suffer performance load issues due to contention.

Right now this code is limited to solving issue with types that return void. It exponentially backs off from a subsequent call from the server, preventing unhelpful "hammering" of the server.

Question

Is there any possible way I can abstract this into something more generic for varying return types?
Have I caught all the appropriate exceptions worthy of a retry?
What is the most appropriate way I can communicate to the calling process what is going on with this code, perhaps offering an opportunity to cancel early?
Any other enhancements you may think of...

Usage Example:

Service<IOrderService>.Use(orderService=>
{
  orderService.PlaceOrder(request);
}

Source code

public delegate void UseServiceDelegate<T>(T proxy);

public static class Service<T>
{
    public static ChannelFactory<T> _channelFactory = new ChannelFactory<T>("");

    public static void Use(UseServiceDelegate<T> codeBlock)
    {
        IClientChannel proxy = (IClientChannel)_channelFactory.CreateChannel();
        bool success = false;

       Exception mostRecentEx = null;
       int millsecondsToSleep = 1000;

       for(int i=0; i<5; i++)  // Attempt a maximum of 5 times
       {
           try
           {
               codeBlock((T)proxy);
               proxy.Close();
               success = true;
               break;
           }

           // The following is typically thrown on the client when a channel is terminated due to the server closing the connection.
           catch (ChannelTerminatedException cte)
           {
              mostRecentEx = cte;
               proxy.Abort();
               //  delay (backoff) and retry
               Thread.Sleep(millsecondsToSleep  * (i + 1));
           }

           // The following is thrown when a remote endpoint could not be found or reached.  The endpoint may not be found or
           // reachable because the remote endpoint is down, the remote endpoint is unreachable, or because the remote network is unreachable.
           catch (EndpointNotFoundException enfe)
           {
              mostRecentEx = enfe;
               proxy.Abort();
               //  delay (backoff) and retry
               Thread.Sleep(millsecondsToSleep * (i + 1));
           }

           // The following exception that is thrown when a server is too busy to accept a message.
           catch (ServerTooBusyException stbe)
           {
              mostRecentEx = stbe;
               proxy.Abort();

               //  delay (backoff) and retry
               Thread.Sleep(millsecondsToSleep * (i + 1));
           }
           catch (TimeoutException timeoutEx)
           {
               mostRecentEx = timeoutEx;
               proxy.Abort();

               //  delay (backoff) and retry
               Thread.Sleep(millsecondsToSleep * (i + 1));
           }
           catch (CommunicationException comException)
           {
               mostRecentEx = comException;
               proxy.Abort();

               //  delay (backoff) and retry
               Thread.Sleep(millsecondsToSleep * (i + 1));
           }
           catch(Exception )
           {
                // rethrow any other exception not defined here
                // You may want to define a custom Exception class to pass information such as failure count, and failure type
                proxy.Abort();
                throw ;
           }
       }
       if (success == false && mostRecentEx != null)
       {
           proxy.Abort();
           throw new Exception("WCF call failed after 5 retries.", mostRecentEx );
       }

    }
}


texts:
I have class that handles HTTP requests:

public final class RestHttpClient {

    /*there is no fields*/

    /**
     * @param mhttp - HTTP request that need to send
     * @return HttpResponse, that contains information about server response
     */
    public HttpResponse sendRequest(final HttpRequestBase mhttp) throws IOException {
        /*do stuff and get response from server*/

        return response;
    }

    /*there a few more helpful methods*/
}

For the one hand - there is no need in instance of class, so I can use static methods. But for another hand singleton looks more reusable. So, I'm not sure which way to choose.

What is more readable and reusable? Static or singleton? Or should I just don't care about it and allow user to create instance of class?


texts:
Below is some code I've put together to contol a siren for a fire service.

It works by webscraping a paging feed and looks for set triggers.

Is there a better way of doing my code or is this "pythonic" enough or can it be improved?

Im python self taught.

"""PYTHON SCRIPT TO CONTROL SIREN

This script will webscape a paging feed and
in turn activate a siren on set incidents

siren should only sound for 30secconds between 0800 -2000 hrs

this has been made so the siren only goes off for some incidents not all

by s.rees (c) 2016
"""
from scraper import Scraper
import sys
import requests
from clint.textui import puts, colored
import RPi.GPIO as GPIO
from time import sleep
import time

time = datetime.datetime.now()

print "Starting"
print "Monitoring"

#Set GPIO siren is attached too
GPIO.setmode(GPIO.BOARD)
GPIO.setup(7, GPIO.OUT)

def siren ():
 GPIO.output(7, GPIO.HIGH)
 sleep(30)
 GPIO.output(7, GPIO.LOW)

if __name__ == "__main__":
# Load webscraper module
    scraper = Scraper(5, recent_messages=True)
    @scraper.register_handler
    def handler(msg):
# get msg from scraper and make it readable
        puts(colored.yellow(msg.channel), newline=False)
        puts(" [", newline=False)
        puts(colored.green(msg.datetime), newline=False)
        puts("] ", newline=False)
        if msg.response:
            puts(colored.red(msg.text))
        else:
            puts(msg.text)
# set agency
        if 'MFS' in msg.channel:
#set unit
         if 'Station' in msg.channel:
          print "Brigade Found"
#set response type
                 if 'RESPOND RUBBISH OR WASTE' in msg.text:
                  print "Trigger found"
                  if (time > datetime.time(8) and time < datetime.time(20)):
                    print "Activate Siren"
                    siren ()
                    print 'done'
                    return
                  else:
                    print "out of time restrictions"
                    return
                if 'RESPOND GRASS FIRE' in msg.text:
                  print "Trigger found"
                  if (time > datetime.time(8) and time < datetime.time(20)):
                    print "Activate Siren"
                    siren ()
                    print 'done'
                    return
                  else:
                    print "out of time restrictions"
                    return
            else:
                    print "Brigade found but no trigger"
                    return
            else:
                return
 scraper.run()
 GPIO.cleanup()


texts: Estimating the number of tanks based on a sample of serial numbers

texts:
I created code that was supposed to determine how well my system of guessing is.

The scenario is that there are n amount of tanks. Each tank is uniquely numbered 1 to n. Seven of these tanks are captured so we only know their serial number (This is done by getting a random number from 1 to n for each of the seven tanks).

I am supposed to predict n based on those serial numbers. My method (the one I have to code) was to first find the max number in the list and the number three standard deviations above the mean of the list. Then, I get my own random numbers from 1 to n where n ranges from the max number and the three standard deviations number.

During this time, I calculate the standard deviation for each of the seven serial numbers generated and after all of the standard deviations are calculated, I find which one is closest to the standard deviation of the original list. Whichever one is the closest to the standard deviation would constitute as my guess for n. I repeat this process as many times as necessary (the more times the more accurate results) to generate a list of guesses. My final guess then would be the mean of that list.

import random
import statistics

chosenNum = 429 #n is given only to check how well our process works
numRuns = 100 #number of guesses - my teacher wants at least 100
numCorrect = 0
numGuessN = []
guesses = []
percentErrors = []
for x in range(numRuns):
  randNum = [random.randint(1,chosenNum + 1),random.randint(1,chosenNum + 1),random.randint(1,chosenNum + 1),random.randint(1,chosenNum + 1),random.randint(1,chosenNum + 1),random.randint(1,chosenNum + 1),random.randint(1,chosenNum + 1)] #generates the seven serial numbers.
  NumSTD = statistics.stdev(randNum) #standard deviation
  maxNumSTD = statistics.mean(randNum)+(3*(statistics.stdev(randNum))) #three standard deviations above the mean
  maxNum = max(randNum) #max number in list
  #print (NumSTD)
  #print (maxNumSTD)
  #print (maxNum)
  #print (randNum)
  for x in range(200): #the greater the range, the more accurate the results
    STDarray = []
    if (maxNum - maxNumSTD < 0):
      for y in range(maxNum,int(maxNumSTD)): #n is max number to max number from Standard Deviation
        randNumZwei =  [random.randint(1,y),random.randint(1,y),random.randint(1,y),random.randint(1,y),random.randint(1,y),random.randint(1,y),random.randint(1,y)] #my simulated serial numbers
        testNumSTD = statistics.stdev(randNumZwei)
        STDarray.append(testNumSTD)
    else:
      for y in range(int(maxNumSTD),maxNum):
        randNumZwei =  [random.randint(1,y),random.randint(1,y),random.randint(1,y),random.randint(1,y),random.randint(1,y),random.randint(1,y),random.randint(1,y)]
        testNumSTD = statistics.stdev(randNumZwei)
        STDarray.append(testNumSTD)
    for z in range((len(STDarray) - 1)):
      if((min(STDarray, key=lambda x:abs(x-NumSTD))) == STDarray[z]): #find closest number to original standard deviation
        numGuessed = z + maxNum
    numGuessN.append(numGuessed) #make a list of all the guessed numbers
  guess = int(statistics.mean(numGuessN)) #the final guess is simply mean of all the other guesses generated
  #print(guess)
  guesses.append(guess) #number of final guesses should be the same as number of trials
print ("Your guesses are: " + str(guesses))
for x in range(len(guesses) - 1):
  percentError = (abs(guesses[x] - (chosenNum))/float(chosenNum)) * 100
  percentErrors.append(percentError)
  if(guesses[x] == chosenNum):
    numCorrect = numCorrect + 1
  else:
    closestNumber = min(guesses, key=lambda x:abs(x-chosenNum))
averagePercentError = statistics.mean(percentErrors)
print ("The average Percent Error is: " + str(averagePercentError) + "%")
if (numCorrect > 0):
  print ("You got the correct number " + str(numCorrect/float(len(guesses))))
else:
  print ("Your closest number was: " + str(closestNumber))

This code works but takes way too long to give me my result. The whole point of this is to calculate accuracy but not take way too long. How can I make this code more efficient to run faster?


texts: I'm deallocating objects created but I'm unsure whether my code is leaking memory or not

texts:
I have a simple application which requires the user to input details about students and their grades. I have two different classes Student and Database. The Student class contains info about students, such as, their names and grades:

Student.h file:

#pragma once
#ifndef STUDENT_H
#define STUDENT_H
#include <string>

class Student {
private:
    std::string name;

public:
    Student(std::string name);

    const std::string getName() const;

    ~Student();
};

#endif // !STUDENT_H

Student.cpp file:

#include "student.h"
#include <string>
#include <iostream>

Student::Student(std::string name) {
    this->name = name;
}

const std::string Student::getName() const {
    return this->name;
}

Student::~Student() {
    std::cout << "Student destructor\n";
}

Database.h file:

#pragma once
#ifndef DATABASE_H
#define DATABASE_H
#include <string>
#include "student.h"
#include <vector>

class StudentDatabase {
private:
    std::vector<Student*> student_list;

public:
    void add_student(Student* stud_obj);

    ~StudentDatabase();
};

#endif // !DATABASE_H

Database.cpp file:

#include "database.h"
#include "student.h"
#include <string>
#include <iostream>
#include <vector>

void StudentDatabase::add_student(Student* stud_obj) {
    std::cout << "ADD STUDENT METHOD\n";
    StudentDatabase::student_list.push_back(stud_obj);
}

StudentDatabase::~StudentDatabase() {
    std::cout << "Database destructor\n";

    std::vector<Student*>::iterator iter;

    for (iter = student_list.begin(); iter != student_list.end(); iter++) {
        delete* iter;
    }
}

Main.cpp file:

#include <iostream>
#include <string>
#include "database.h"
#include "student.h"

int main()
{
    std::string input;
    std::string name;

    StudentDatabase* database = new StudentDatabase();

    for (;;) {
        std::cout << "0: Add student \n";

        std::cout << "Enter a number (or q to quit) and press return... \n";

        std::cin >> input;
        std::cin.ignore();

        if (input == "q") {
            break;
        }

        else if (input == "0") {
            std::cout << "Enter student's first name: ";
            std::getline(std::cin, name);

            Student* student_obj = new Student(name, surname, student_number, grade);
            database->add_student(student_obj);
        }
    }

    delete database;
    return 0;
}

My question is: am I correctly deallocating memory for Students from ~StudentDatabase()?

I know smart pointers are more appropriate but I want to make sure I understand raw pointers properly.


texts: Critique sanitized user email PHP Script

texts:
So, I have a basic 'contact us' form that i have built, and I do some jQuery checking first (that a phone number is only numbers, email address doesn't contain unneeded characters, etc), but I also wanted to do some sanitization before sending out the email.

After reading many questions on SO (such a great service!) then doing some more reading on PHP.net and seeing some 'in use' code on W3Schools this is what I came up with. Is it secure? Is there more I should be doing? Is this overkill?

It should be said that the user content lives on my server for a very short amount of time and then is sent off to email services (GMail and HostGator)

<?
$name = filter_var($_POST[name], FILTER_SANITIZE_STRING);
$email = filter_var($_POST[email], FILTER_SANITIZE_EMAIL);
$phone = filter_var($_POST[phone], FILTER_SANITIZE_NUMBER_INT);
$usermessage = filter_var($_POST[message], FILTER_SANITIZE_STRING);
$businessmessage = filter_var($_POST[businessmessage], FILTER_SANITIZE_STRING);

$to = "spokedcouriers@gmail.com, tom@spokedcouriers.com";
$subject = "Incoming from SpokedCouriers.";
$message =
"Submitted From: ".$name."
".
"Email Address: ".$email . "
" .
"Phone Number: ".$phone . "
" .
"Message: ".$usermessage . "
" .
"Possible Business Message From: ".$businessmessage."
";

$headers  = 'MIME-Version: 1.0' . "\r\n"
    .'Content-type: text/html; charset=iso-8859-1' . "\r\n"
    .'From: ' . $email . "\r\n"
    .'Reply-To: ' . $email . "\r\n";

//GO AWAY.
mail($to, $subject, $message, $headers);
?>


texts:
Let’s say we copy some file using retry strategy (it might be blocked, etc.):

class Processor
{
    public void CopyData() =>
        CopyData(Try.Slow);

    public void CopyData(Try loop) =>
        loop.Execute(() =>
            File.Copy(@"c\a.txt", @"c:\b.txt"));
}

What do you think about names chosen for the following library code identifiers? Would you name them differently?

public abstract class Try
{
    public static Try Repeat(params int[] delays) => new Repeat(delays);
    public static readonly Try Never = Repeat();
    public static readonly Try Once = Repeat(0);
    public static readonly Try Slow = Repeat(0, 500, 1500, 4500, 12000);
    public static readonly Try Fast = Repeat(0, 50, 150, 450, 1200);
    public abstract void Execute(Action action);
}

class Repeat : Try
{
    IReadOnlyList<int> Delays { get; }

    public Repeat(params int[] delays)
    {
        Delays = delays;
    }

    public override void Execute(Action action)
    {
        for(int i=0; i< Delays.Count; i++)
            try
            {
                Thread.Sleep(Delays[i]);
                action();
                return;
            }
            catch
            {
                if (i == Delays.Count - 1)
                    throw;
            }
    }
}


texts: Project Euler problem 92 - square digit chains

texts:
Link to problem.

  A number chain is created by continuously adding the square of the
  digits in a number to form a new number until it has been seen before.

  For example,

  44 -> 32 -> 13 -> 10 -> 1 -> 1

  85 -> 89 -> 145 -> 42 -> 20 -> 4 -> 16 -> 37 -> 58 -> 89

  Therefore any chain that arrives at 1 or 89 will become stuck in an
  endless loop. What is most amazing is that EVERY starting number will
  eventually arrive at 1 or 89.

  How many starting numbers below ten million will arrive at 89?

This solution to Project Euler problem 92 takes about 80 seconds. How can I reduce the time to well under 60 seconds?

def squareDigits(num):
    total = 0
    for digit in str(num):
        total += int(digit) ** 2
    return total
pastChains = [None] * 10000001
pastChains[1], pastChains[89] = False, True
for num in range(2, 10000001):
    chain = [num]
    while pastChains[chain[-1]] is None:
        chain.append(squareDigits(chain[-1]))
    for term in chain:
        if pastChains[term] is not None:
            pastChains[term] = pastChains[chain[-1]]
print pastChains.count(True)


texts: Hackerrank problem: Climbing the Leaderboard (Java)

texts:
I am solving the following Hackerrank problem: Climbing the Leaderboard.
The problem statement:
Alice is playing an arcade game and wants to climb to the top of the leaderboard and wants to track her ranking. The game uses Dense Ranking, so its leaderboard works like this:

The player with the highest score is ranked number 1 on the leaderboard.
Players who have equal scores receive the same ranking number, and the next player(s) receive the immediately following ranking number.

For example, the four players on the leaderboard have high scores of 100, 90, 90, and 80. Those players will have ranks 1, 2, 2, and 3, respectively. If Alice's scores are 70, 80 and 105, her rankings after each game are 4th, 3rd and 1st.
Function Description
Complete the climbingLeaderboard function in the editor below. It should return an integer array where each element res[j] represents Alice's rank after the jth game.
climbingLeaderboard has the following parameter(s):
scores: an array of integers that represent leaderboard scores
alice: an array of integers that represent Alice's scores
Input Format
The first line contains an integer n, the number of players on the leaderboard.
The next line contains n space-separated integers scores[i], the leaderboard scores in decreasing order.
The next line contains an integer, m, denoting the number games Alice plays.
The last line contains m space-separated integers alice[j], the game scores.
Constraints

1 <= n <= 2 * 10^5
1 <= m <= 2 * 10^5
0 <= scores[i] <= 10^9 for 0 <= i < n
0 <= alice[j] <= 10^9 for 0 <= j < m

The existing leaderboard, scores, is in descending order.
Alice's scores, alice, are in ascending order.
Subtask
For 60% of the maximum score:

1 <= n <= 200
1 <= m <= 200

Output Format
Print m integers. The jth integer should indicate Alice's rank after playing the jth  game.

My solution is failing to pass 4 test cases due to timeout. The code is as follows:
 import java.util.*;

    public class Main {
        public static void main(String[] args) {

            Scanner scanner = new Scanner(System.in);

            int totalPlayers = scanner.nextInt();
            ArrayList<Integer> playerScores = new ArrayList<>();
            for(int i = 0; i < totalPlayers; i++) {
                playerScores.add(scanner.nextInt());
            }

            int aliceTotalScores = scanner.nextInt();
            ArrayList<Integer> aliceScores = new ArrayList<>();
            for(int i = 0; i < aliceTotalScores; i++) {
                aliceScores.add(scanner.nextInt());
            }

            List<Integer> finalScores = new ArrayList<>(playerScores);
            for(int i = 0; i < aliceTotalScores; i++) {
                finalScores.add(aliceScores.get(i));
                finalScores.sort(Collections.reverseOrder());
                Set<Integer> set = new LinkedHashSet<>(finalScores);
                finalScores.clear();
                finalScores.addAll(set);
                System.out.println(finalScores.indexOf(aliceScores.get(i)) + 1);
            }
        }
    }

Any suggestions on how to improve the solution or some general direction as to where I am making a mistake would be appreciated. Thanks in advance.


texts: Finding two consecutive triangular numbers with a given target sum

texts:
I need to speed up this code so it can handle inputs in the thousands. It adds triangular numbers to a list based on input n, then it loops through to find if any two consecutive numbers squared in that list add up to n. The test cases I've been using are n = 45, which would be true and n = 6, which would be false.

Here is the code:

def Triangular(n):
    lst = []
    for i in range(1, n + 1):
        lst.append((i** 2 + i)//2)

    for i in lst:
        for j in lst:
            if i*i + j*j == n and ((lst.index(i) == lst.index(j)+1)
                               or (lst.index(i) == lst.index(j)-1)):
                return True
            else:
                continue


texts:
I recently ported a blog of mine from Python to Go (to improve speed and performance) and while all is great so far, I'd like some help optimising the Markdown function to improve the general performance, maintenance and readability of the function.

I have this function because I write my blog articles in Markdown (.md) and then use Python Go to convert the raw Markdown to HTML for output as this saves me from having to write ridiculous amounts of HTML. (which can be tedious to say the least)

The Markdown function takes one argument (raw) which is a string that contains the raw Markdown (obtained using ioutil.ReadFile).

It then splits the Markdown by \n (removing the empty lines) and converts:

Bold and italic text (***,**,*)
Strikethrough text (~~blah blah blah~~)
Underscored text (__blah blah blah__)
Links ([https://example.com](Example Link))
Blockquotes (> sample quote by an important person)
Inline code (`abcccc`)
Headings (h1-h6)

While some of the supported features aren't exactly standard, this function works and outputs the expected result without any errors but being a new Go programmer and this being my first "real" Go project I'd like to know whether or not my code could be optimised for better performance, maintainability and readability.

Here a few questions I have regarding optimisation:

Would it make a difference to performance if I reduced the amount of imports?
Would it improve readability if I put the regexp.MustCompile functions into variables above the Markdown function?
Would it improve performance if I used individual regexes to convert Markdown headings instead of using for i := 6; i >= 1; i-- {...}?
If not, is there a way to convert i (an integer) to a string without using strconv.Itoa(i) (to help reduce the amount of imports)?

Here is my code:

package parse

import (
  "regexp"
  "strings"
  "strconv"
)

func Markdown(raw string) string {
  // ignore empty lines with "string.Split(...)"
  lines := strings.FieldsFunc(raw, func(c rune) bool {
    return c == '\n'
  })
  for i, line := range lines {
    // wrap bold and italic text in "<b>" and "<i>" elements
    line = regexp.MustCompile(`\*\*\*(.*?)\*\*\*`).ReplaceAllString(line, `<b><i>$1</i></b>`)
    line = regexp.MustCompile(`\*\*(.*?)\*\*`).ReplaceAllString(line, `<b>$1</b>`)
    line = regexp.MustCompile(`\*(.*?)\*`).ReplaceAllString(line, `<i>$1</i>`)
    // wrap strikethrough text in "<s>" tags
    line = regexp.MustCompile(`\~\~(.*?)\~\~`).ReplaceAllString(line, `<s>$1</s>`)
    // wrap underscored text in "<u>" tags
    line = regexp.MustCompile(`__(.*?)__`).ReplaceAllString(line, `<u>$1</u>`)
    // convert links to anchor tags
    line = regexp.MustCompile(`\[(.*?)\]\((.*?)\)[^\)]`).ReplaceAllString(line, `<a href="$2">$1</a>`)
    // escape and wrap blockquotes in "<blockquote>" tags
    line = regexp.MustCompile(`^\>(\s|)`).ReplaceAllString(line, `&gt;`)
    line = regexp.MustCompile(`\&gt\;(.*?)$`).ReplaceAllString(line, `<blockquote>$1</blockquote>`)
    // wrap the content of backticks inside of "<code>" tags
    line = regexp.MustCompile("`(.*?)`").ReplaceAllString(line, `<code>$1</code>`)
    // convert headings
    for i := 6; i >= 1; i-- {
      size, md_header := strconv.Itoa(i), strings.Repeat("#", i)
      line = regexp.MustCompile(`^` + md_header + `(\s|)(.*?)$`).ReplaceAllString(line, `<h` + size + `>$2</h` + size + `>`)
    }
    // update the line
    lines[i] = line
  }
  // return the joined lines
  return strings.Join(lines, "\n")
}


texts: Calling lodash _.defaults() before Object.defineProperty()

texts:
In reviewing an older project of mine, I noticed that in a particular class definition I'm doing this:

var defaultOptions = { ... object of default options ... }

var SDKClient = function(options) {
    var self = this

    ...

    _.defaults(self, options, defaultOptions)

    Object.defineProperty(self, 'clientId', {
        enumerable: false
    })

    Object.defineProperty(self, 'clientSecret', {
        enumerable: false
    })
}

If I initialize the client object like this:

var client = new SDKClient({clientId: "x", clientSecret: "y"})

Should I expect there to be problems calling defineProperty after the property has already been merged in with _.defaults()? I don't see any errors or problems thrown when running tests, but this is a large project, and I can't be certain there isn't something obscuring errors. If it's not OK, why is it not OK?


texts:
Binary Search Tree, with preorder traverse. What other methods should I add? How can I improve it?

class Bst

  attr_accessor :data, :left, :right

  def initialize(data)
    self.data = data
  end

  def insert(data)
    if  self.data < data
      if (self.right )
        self.right.insert(data)
      else
        self.right = Bst.new(data)
      end
    else
      if (self.left )
        self.left.insert(data)
      else
        self.left = Bst.new(data)
      end
    end
  end

  def each(&blk)
    Bst.traverse_preorder(self,&blk)
  end

  def self.traverse_preorder(node, &blk)
    return unless node
    traverse_preorder(node.left,&blk)
    blk.call(node.data)
    traverse_preorder(node.right,&blk)
  end

end


texts: Product of all but one number in a sequence - Follow Up

texts:
This question is a follow up question to the Product of all but one number in a sequence.
I am posting a new code here with taking into consideration the suggestions of [Edward], [CiaPan], [chux], [superb rain] and others. Please advise how the code efficiency can be improved.
#include <stdio.h>
#include <stdlib.h>

//without division, with O(n) time, but extra space complexity as suggested
//return new array on the heap
int *find_product_arr(const int *nums, int arr_size)
{
    int *new_arr = (int *)malloc(sizeof(int)*arr_size);

    int mult_prefix=1; //product of prefix elements
    int mult_suffix=1; //product of suffix elements

    //left most element special handling
    new_arr[0]=1;

    //swipe up
    for(int i=1; i<arr_size; i++) {
        mult_prefix *= nums[i-1];
        new_arr[i] = mult_prefix;
    }

    //swipe down
    for(int j=arr_size-2; j>=0; j--) {
        mult_suffix *= nums[j+1];
        new_arr[j] *= mult_suffix;
    }

    return new_arr;
}

int main(void)
{
    /*Given an array of integers, return a new array such that each element at index i of the
    new array is the product of all the numbers in the original array except the one at i.
    For example, if our input was [1, 2, 3, 4, 5], the expected output would be
    [120, 60, 40, 30, 24] */
    int nums[] = {1, 2, 2, 4, 6};
    int size = sizeof(nums)/sizeof(nums[0]);

    int *products = find_product_arr(nums, size); //get a new array

    for (int i = 0; i < size; i++)
        printf("%d ", *(products+i) );

    free(products); //release heap memory

    return 0;
}


texts: Performs calculation with operators given in an unknown order

texts:
Problem Statement

Write a simple interpreter which understands "+", "-", and "*" operations. Apply the operations with the correct order of operations (i.e. multiply, then add or subtract) using command/arg pairs starting with the initial value of value. The commands will not necessarily be given in the correct order of operations.

Arguments given: int value, vector<char> operations, vector<int> args

My Solution (C++)

int simpleInterpreter(int value, vector<char> operations, vector<int> args) {
    int index = 0;

    for (char operation : operations) {
        if (operation == '*') {
            value *= args[index];
        index++;
        }
    }

    for (char operation : operations) {
        if (operation == '+') {
            value += args[index];
        index++;
        } else if (operation == '-') {
            value -= args[index];
            index++;
        }
    }

    return value;
}

Example cases:

simpleInterpreter(0, {'+', '+', '*'}, {5000000, 1, 2}) => 3
simpleInterpreter(1, {'*', '-', '*', '+'}, {-1, -1, 1, 1) => 1
simpleInterpreter(45, {'+', '*', '-'}, {2, 90, 180}) => 0
simpleInterpreter(100, {'+', '+', '*'}, {0, 5, 2}) => 7

I'm not really concerned about having safe input / I don't care about bad input. I'm mostly focused on readability and performance here.

Is this a good solution? What can be improved? Another solution I thought of would be to build a custom comparator and store the operations into a set of pairs (operator, how many times it appears), however this would increase space complexity without reducing time complexity so I didn't do that.


texts:
Is this the best way to construct a vector of 2D points for return?

I don't entirely understand new and delete so I'm concerned about any memory leaks that I might be incurring.

std::vector<Point2D> results;
results.reserve(max_results);

... inside a loop /

Point2D* point = new Point2D(x, y);
results.push_back(*point);
delete point;

It might be that I could do this without constructor.

class Point2D {
public:
    double X;
    double Y;
    Point2D();
    Point2D(double X, double Y);
    void set(double X_p, double Y_p);
    void set(Point2D* point_p);
};


texts:
Any ideas?

public override string ToString() {
    string returnValue;
    if (!string.IsNullOrWhiteSpace(Country))
        returnValue = string.Format("{0}", Country);
    else
        return returnValue;

    if (!string.IsNullOrWhiteSpace(City))
        returnValue += string.Format(", city {0}", City);
    else
        return returnValue;

    if (!string.IsNullOrWhiteSpace(Street))
        returnValue += string.Format(", street {0}", Street);
    else
        return returnValue;

    if (!string.IsNullOrWhiteSpace(Block))
        returnValue += string.Format(", block {0}", Block);
    else
        return returnValue;

    if (!string.IsNullOrWhiteSpace(Building))
        returnValue += string.Format(", building {0}", Building);

    if (!string.IsNullOrWhiteSpace(Latitude)
             && !string.IsNullOrWhiteSpace(Longitude))
    returnValue += string.Format(", coordinates {0}:{1}", Latitude, Longitude);

    return returnValue;
}


texts: Initialize various commands for the SqlDataAdapter

texts:
This is my code for my SqlDataAdapter which is similar to the code example given in the docs:

public static int CommitBirdData(DataSet pDataSet)
{
    int rowsAffected = 0;

    using (SqlConnection conn = new SqlConnection(connString))
    using (SqlDataAdapter birdDataAdapter = new SqlDataAdapter())
    {
        SqlCommand cmd = new SqlCommand(
            "INSERT INTO [dbo].[Bird] ([BirdID], [Name], [Description]) " +
            "VALUES (@BirdID, @Name, @Description)"
            , conn);

        cmd.Parameters.Add("@BirdID", SqlDbType.NVarChar, 10, "BirdID");
        cmd.Parameters.Add("@Name", SqlDbType.NVarChar, 50, "Name");
        cmd.Parameters.Add("@Description", SqlDbType.NVarChar, 200, "Description");

        birdDataAdapter.InsertCommand = cmd;

        cmd = new SqlCommand(
            "UPDATE [dbo].[Bird] " +
            "SET [BirdID] = @BirdID, [Name] = @Name, [Description] = @Description " +
            "WHERE [BirdID] = @BirdID"
            , conn);

        cmd.Parameters.Add("@BirdID", SqlDbType.NVarChar, 10, "BirdID");
        cmd.Parameters.Add("@Name", SqlDbType.NVarChar, 50, "Name");
        cmd.Parameters.Add("@Description", SqlDbType.NVarChar, 200, "Description");

        birdDataAdapter.UpdateCommand = cmd;

        cmd = new SqlCommand(
            "DELETE FROM [dbo].[BirdCount] WHERE [BirdID] = @BirdID " +
            "DELETE FROM[dbo].[Bird] WHERE[BirdID] = @BirdID"
            , conn);

        cmd.Parameters.Add("@BirdID", SqlDbType.NVarChar, 10, "BirdID");

        birdDataAdapter.DeleteCommand = cmd;

        rowsAffected = birdDataAdapter.Update(pDataSet, "Bird");

        return rowsAffected;

    }

I noticed that this code is repetitive and I was just wondering whether there is a more efficient way to initialize the commands of the SqlDataAdapter with or without the using statements.


texts:
I need a method that clean up a string considering these few rules:

Remove or not Spaces
Remove or not Special Chars
Remove or not Numbers
Descaptalize or not the string (this is don't really needed but I included it anyway).

I did some google if exists something that already do this, but found nothing, so I came up with this:

public static class StringHelper
{
    private static readonly Dictionary<char, char> _specialChars
        = new Dictionary<char, char>
    {
        { 'á', 'a' },{ 'à', 'a' },{ 'â', 'a' },{ 'ã', 'a' },{ 'ä', 'a' },
        { 'é', 'e' },{ 'è', 'e' },{ 'ê', 'e' },{ 'ë', 'e' },
        { 'í', 'i' },{ 'ì', 'i' },{ 'î', 'i' },{ 'ï', 'i' },
        { 'ó', 'o' },{ 'ò', 'o' },{ 'õ', 'o' },{ 'ö', 'o' },
        { 'ú', 'u' },{ 'ù', 'u' },{ 'û', 'u' },{ 'ü', 'u' },
        { 'ç', 'c' },{ 'ñ', 'n' }
    };

    static StringHelper()
    {
        foreach (var item in _specialChars.ToList())
        {
            _specialChars.Add(
                item.Key.ToString().ToUpper()[0],
                item.Value.ToString().ToUpper()[0]);
        }
    }

    private static readonly Regex _spaceRegex = new Regex(@"\s", RegexOptions.Compiled);
    private static readonly Regex _numericRegex = new Regex(@"\s", RegexOptions.Compiled);

    public static string Normalize(this string str, CharType normaliar = CharType.All)
    {
        if (normaliar.HasFlag(CharType.Spaces))
        {
            str = _spaceRegex.Replace(str, string.Empty);
        }

        if (normaliar.HasFlag(CharType.Special))
        {
            str = _specialChars.ToList()
                .Aggregate(str, (ac, item) => ac.Replace(item.Key, item.Value));
        }

        if (normaliar.HasFlag(CharType.Numerics))
        {
            str = _numericRegex.Replace(str, string.Empty);
        }

        if (normaliar.HasFlag(CharType.UpperCase))
        {
            str = str.ToLower();
        }

        return str;
    }
}

public enum CharType
{
    Spaces = 1,
    Special = 2,
    Numerics = 4,
    UpperCase = 8,
    All = 15,
}

I'm not considering really all special char just Portuguese, Spanish and a few more.

As far as I could, I wrote with the better performance and organization, but this was my limit.


texts:
This is my first attempt at some moderately complex Rust code. Unfortunately, it feels very clunky to me, and I feel as if I am not using all of the features properly:

use std::collections::HashMap;

fn main() {
    let mut table: Vec<HashMap<&str, Vec<&str>>> = Vec::new();
    table.push(HashMap::new());
    table[0].insert(" ", vec!["F"]);
    table[0].insert("(", vec!["-1"]);
    table[0].insert(")", vec!["-1"]);
    table[0].insert("+", vec!["-1"]);
    table[0].insert("a", vec!["a"]);

    table.push(HashMap::new());
    table[1].insert(" ", vec!["S"]);
    table[1].insert("(", vec!["(", "S", "+", "F", ")"]);
    table[1].insert(")", vec!["-1"]);
    table[1].insert("+", vec!["-1"]);
    table[1].insert("a", vec!["F"]);

    let mut input = vec!["(", "a", "+", "a", ")"];

    parse_func(&mut table, &mut input);
}

fn parse_func(table: &mut Vec<HashMap<&str, Vec<&str>>>, input: &mut Vec<&str>) {
    let mut stack: Vec<&str> = Vec::new();
    stack.push("S");
    for c in input.iter() {
        loop {
            println!("{:?}", stack);
            let rulenum: usize = match *c {
                "$" => return,
                sval if (sval == *stack.last().unwrap()) => {stack.pop(); break;},
                _ => evaluate_table(table, c, vec![stack.last().unwrap()]).expect("Bad input"),
            };
            stack.pop();
            for item in table.get(rulenum).unwrap().get(c).unwrap().iter().rev() {
                stack.push(item);
            }
        }
    }
}

fn evaluate_table(table: &Vec<HashMap<&str, Vec<&str>>>, c: &str, nterminal: Vec<&str>) -> Option<usize> {
    for (i, row) in table.iter().enumerate() {
        if *row.get(" ").unwrap() == nterminal {
            return match row.get(c).unwrap() {
                k if (*k == vec!["-1"]) => None,
                _ => Some(i),
            }
        }
    }
    None
}


texts: JavaScript functions and global variables

texts:
I have a getValue function which just grabs some numbers from an HTML page.

How can I access those variables in later functions without passing them down the entire chain of functions? As they sit within a function they are not global?

When I call the addition function, it will need to access the variables in the getValue function.

In Java, I would have used a separate class with a normal getter and setter pattern but unsure how to replicate something similar.

I feel like I am missing a key JavaScript concept here.

    function getValue() {
    var decimal = parseInt(parent.document.getElementById('CF_9813416').value);
    var a = parseFloat(parent.document.getElementById('CF_9814331').value);
    var b = parseFloat(parent.document.getElementById('CF_9814407').value);
    var c = parseFloat(parent.document.getElementById('CF_9814615').value);
    }

    function radioButtons() {

        for (var i = 0; i < parent.document.Form1.CF_9813571.length; i++) {
            if (parent.document.Form1.CF_9813571[i].checked) {
                var sign = parent.document.Form1.CF_9813571[i].value;
            }
        }
        radioResult(sign);
    }

    function radioResult(sign) {

        if (sign == '9813524') {
            addition();
        } else if (sign == '9813527') {
            subtraction();
        } else if (sign == '9813530') {
            multiplication();
        } else devision();
    }

    function addition() {

        result = a + b + c;
        writeValue(result, decimal);
    }

    function subtraction() {

        result = a - b - c;
        writeValue(result, decimal);
    }

    function multiplication() {

        result = a * b * c;
        writeValue(result, decimal);
    }

    function devision() {

        result = a / b / c;
        writeValue(result, decimal);
    }

    function writeValue(result, decimal) {
        parent.document.getElementById('CF_9814616').value = result.toFixed(0);
        parent.document.getElementById('CF_9814617').value = result.toFixed(decimal);
    }
</script>


texts: Doctrine/Symfony WHERE clause for reports

texts:
I'm trying to generate a report from two doctrine entities.

The fields to filter the report are optional. This is the code I've got now and it looks really bad to me. How can I improve this?

public function filter($accountNumber, $companyName, $branchName, $branchManager)
{
    $em = $this->managerRegistry->getManager();
    $whereClause = 'WHERE ';

    if (!empty($accountNumber)) {
        $whereClause .= ' u.accountNumber = :acc_number';
    }
    if (!empty($companyName)) {
        $whereClause .= ' AND um.companyName = :company_name';
    }
    if (!empty($branchName)) {
        $whereClause .= ' AND um.branchName = :branch_name';
    }
    if (!empty($branchManager)) {
        $whereClause .= ' AND um.branchAccountManager = :branch_manager';
    }

    $query = $em->createQuery(
        'SELECT u FROM CarbonUserBundle:User u
        JOIN CarbonUserBundle:UserMeta um WITh u.meta=um.id
       ' . $whereClause
    );

    if (!empty($accountNumber)) {
        $query->setParameter('acc_number', $accountNumber);
    }
    if (!empty($companyName)) {
        $query->setParameter('company_name', $companyName);
    }
    if (!empty($branchName)) {
        $query->setParameter('branch_name', $branchName);
    }
    if (!empty($branchManager)) {
        $query->setParameter('branch_manager', $branchManager);
    }

    return $query->getResult();
}


texts:
I'm in the process of building some templates for Joomla, and although it all works as desired, I can't help thinking that there has to be a more elegant way to do this in PHP than my current approach. For the record, I'm still reasonably new to PHP!

Using collapsible module positions, I need to assign various CSS classes to a div depending on how many modules are published on a particular row. The code I wrote is below;

    if (($footer1 != "0") && ($footer2 == "0") && ($footer3 == "0")) {
    $footerWidth = 'full';
    }
    elseif (($footer1 == "0") && ($footer2 != "0") && ($footer3 == "0")) {
    $footerWidth = 'full';
    }
    elseif (($footer1 == "0") && ($footer2 == "0") && ($footer3 != "0")) {
    $footerWidth = 'full';
    }
    elseif (($footer1 != "0") && ($footer2 != "0") && ($footer3 == "0")) {
    $footerWidth = 'one_half';
    }
    elseif (($footer1 != "0") && ($footer2 == "0") && ($footer3 != "0")) {
    $footerWidth = 'one_half';
    }
    elseif (($footer1 == "0") && ($footer2 != "0") && ($footer3 != "0")) {
    $footerWidth = 'one_half';
    }
    else {
    $footerWidth = 'one_third';
    }

I then use the following code in the template itself to check for modules published;

    <?php if ($footer1 > 0) : ?>
                <div class="<?php echo htmlspecialchars($footerWidth); ?>">
                    <jdoc:include type="modules" name="footer1" style="html5" />

    <?php endif; ?>
    <?php if ($footer2 > 0) : ?>
                <div class="<?php echo htmlspecialchars($footerWidth); ?>">
                    <jdoc:include type="modules" name="footer2" style="html5" />

    <?php endif; ?>
    <?php if ($footer3 > 0) : ?>
                <div class="<?php echo htmlspecialchars($footerWidth); ?>">
                    <jdoc:include type="modules" name="footer3" style="html5" />

    <?php endif; ?>

Can anyone suggest / recommend a better approach? It just seems like a lot of code for a simple function.


texts:
I am so new to programming. Trying to learn as I go. I made a very simple "Guess the number" game. Just wanted to get some critiques, see if I could clean it up or change anything.

# user guesses the number. Returns Yes or sorry.
import random

# Instruct user to guess a number.
number = int(input("Guess a number, see if you're right."))

rn = random.randint(1,10)

if number == rn:  # User number equals random number
    print("You got it.")

else:  # Users number is not the same as random number.
    print("sorry")


texts: Optimal custom operator with generic type constraint for numerical type

texts:
I'm implementing (for an article) two custom infix operators:

¿% - to calculate percent of total
%? - to calculate the percent that represents a segment of total

After debugging some errors and looking for information I finally found a way to get my code working:

protocol NumericType {

    static func *(lhs: Self, rhs: Self) -> Self
    static func *(lhs: Self, rhs: Int) -> Self
    static func /(lhs: Self, rhs: Self) -> Self
    static func /(lhs: Self, rhs: Int) -> Self

} // NumericType

extension Double : NumericType {

    internal static func *(lhs: Double, rhs: Int) -> Double {
        return lhs * Double(rhs)
    }

    internal static func /(lhs: Double, rhs: Int) -> Double {
        return lhs / Double(rhs)
    }

 } // extension Double : NumericType

extension Float : NumericType {

    internal static func *(lhs: Float, rhs: Int) -> Float {
        return lhs * Float(rhs)
    }

    internal static func /(lhs: Float, rhs: Int) -> Float {
        return lhs / Float(rhs)
    }

 } // extension Float : NumericType

extension Int : NumericType { }

infix operator ¿%

func ¿% <T: NumericType>(percentage: T, ofThisTotalValue: T) -> T {

    return (percentage * ofThisTotalValue) / 100

} // infix operator ¿%

infix operator %?

func %? <T: NumericType>(segment: T, ofThisTotalValue: T) -> T {

    return (segment * 100) / ofThisTotalValue

} // infix operator %?

let percentage: Double = 8
let price: Double = 45

let save = percentage ¿% price

print("\(percentage) % of \(price) $ = \(save) $")

print("\(save) $ of \(price) $ = \(save %? price) %")

The output:

8.0 % of 45.0 $ = 3.6 $
3.6 $ of 45.0 $ = 8.0 %

Do you thinks there could be a more optimal and readable approach? Could you give some advice or share an example?


texts: Fastest / most efficient random bit indexing in Python

texts:
Using Python/Cython, I am trying to construct an efficient way to index boolean values. I have been trying to use the bitarray and/or bitstring packages to construct a fast, non memory intensive way to hold a lot of booleans. My goal was for a list like object that could be sliced as such, and actually managed the bool values in real bits of data:
>>> from bitarray import bitarray
>>> array = bitarray(1000000) # creates 1000000 allocated bits
>>> array.setall(False)
>>> array[4] # holds boolean values
False
>>> from timeit import timeit
>>> timeit(setup = 'from __main__ import array',
           stmt = 'array[500000]')
0.21002184844218164
# one million iterations, making each iteration 210 ns

>>> from bitstring import BitArray
>>> array = BitArray(1000000) # just as we did in the first example
>>> array[6] # all are False by default
False
>>> from timeit import timeit
>>> timeit(setup = 'from __main__ import array',
           stmt = 'array[500000]')
2.6748261753875795
# oh no, this one is very slow, each iteration takes 2674 ns

As you can see, there are already packages that construct this binary data and allow you to index it at random. Would it be possible to get to an even lower level to the RAM myself? 210ns is fast, but I would like to get indexing below 40ns on a 1000000 bit array. How can this be done?
Edit:
Individual item assignment to the boolean array after it is created, would be nice, but it is not required.


texts: Faster way to concat dataframes with different columns vertically

texts:
I am trying to concat two huge dataframes (around 15GB) like the following:

a_df:

            A       B       C       D
2018-10-16  a16     b16     c16     d16
2018-10-17  a17     b17     c17     d17
2018-10-18  a18     b18     c18     d18
2018-10-19  a19     b19     c19     d19
2018-10-20  a20     b20     c20     d20

b_df:

            A       C       Y       Z
2018-10-21  a21     c21     y21     z21
2018-10-22  a22     c22     y22     z22

to get a final dataframe:

            A       B       C       D       Y       Z
2018-10-16  a16     b16     c16     d16
2018-10-17  a17     b17     c17     d17
2018-10-18  a18     b18     c18     d18
2018-10-19  a19     b19     c19     d19
2018-10-20  a20     b20     c20     d20
2018-10-21  a21             c21             y21     z21
2018-10-22  a22             c22             y22     z22

I am trying that code:

dfs = [a_df, b_df]

unique_columns = []
for df in dfs:
    for column in df.columns:
        unique_columns.append(column)
unique_columns = sorted(set(unique_columns))

same_columns_dfs = []
for df in dfs:
    empty_df = pd.DataFrame(np.nan, index=df.index, columns=unique_columns)
    empty_df.loc[:, df.columns] = df.values
    same_columns_dfs.append(empty_df)

final_df = pd.concat(same_columns_dfs, axis=0, sort=True)

Is there a more efficient way to do this?


texts: QVSquareLayout implementation for Qt that makes all internal items to be squared

texts:
qsquarelayout.h

#ifndef QSQUARELAYOUT_H
#define QSQUARELAYOUT_H

#include <QLayout>
#include <QLayoutItem>

class QVSquareLayout : public QLayout
{
    Q_OBJECT
public:
    QVSquareLayout(QWidget* parent=nullptr);
    ~QVSquareLayout();

// QLayoutItem interface
public:
    virtual QSize sizeHint() const;
    virtual void setGeometry(const QRect &rect);

// QLayout interface
public:
    virtual void addItem(QLayoutItem* item);
    virtual QLayoutItem* itemAt(int index) const;
    virtual QLayoutItem* takeAt(int index);
    virtual int count() const;
    virtual QSize minimumSize() const;

private:
    QList<QLayoutItem *> _items;
};

#endif // QSQUARELAYOUT_H

qsquarelayout.cpp

#include "qsquarelayout.h"

QVSquareLayout::QVSquareLayout(QWidget* parent) : QLayout (parent)
{
}

QVSquareLayout::~QVSquareLayout() {}

void QVSquareLayout::addItem(QLayoutItem* item) {
    _items.append(item);
}

QLayoutItem* QVSquareLayout::itemAt(int index) const {
    if (index < 0 || index >= count())
        return nullptr;
    return _items.at(index);
}

QLayoutItem* QVSquareLayout::takeAt(int index) {
    if (index < 0 || index >= count())
        return nullptr;
    return _items.takeAt(index);
}

int QVSquareLayout::count() const {
    return _items.count();
}

QSize QVSquareLayout::minimumSize() const {
    return QSize(10, 10);
}

QSize QVSquareLayout::sizeHint() const {
    int width = 0, height = 0, n = count();
    foreach (QLayoutItem* item, _items) {
        QSize size = item->sizeHint();
        int min = qMin(size.width(), size.height());
        width = qMax(width, min);
        height += min;
    }
    return {width, height + n * spacing()};
}

void QVSquareLayout::setGeometry(const QRect &rect) {
    int n = count();
    if (n < 1 || rect == this->geometry())
        return;

    QLayout::setGeometry(rect);
    int left, right, top, bottom;
    getContentsMargins(&left, &top, &right, &bottom);

    int min = qMin(rect.width(), rect.height() / n);
    QPoint baseLine{rect.width()/2 - min/2 + left, top};
    QSize square{min, min};
    foreach (QLayoutItem *item, _items) {
        item->setGeometry(QRect{baseLine, square});
        baseLine.ry() += min;
    }
}

Main idea is: when you need something to take square shape - just put it in this layout.


texts:
Problem Statement:
  Let A and B be two N bit numbers (MSB to the left). You are given initial values for A and B, and you have to write a program which processes three kinds of queries:

  set_a idx x: Set A[idx] to x, where \$0 \le idx < N\$, where A[idx] is idx'th least significant bit of A.
  set_b idx x: Set B[idx] to x, where \$0 \le idx < N\$, where B[idx] is idx'th least significant bit of B.
  get_c idx: Print C[idx], where \$C=A+B\$, and \$0\le idx\$

  Input Format:
  First line of input contains two integers \$N\$ and \$Q\$ consecutively (\$1 \le N \le 100000\$, \$1\le Q \le 500000\$). Second line is an \$N\$-bit binary number which denotes initial value of \$A\$, and the third line is an \$N\$-bit binary number denoting initial value of \$B\$. \$Q\$ lines follow, each containing a query as described above.

  Output Format:
  For each query of the type get_c, output a single digit \$0\$ or \$1\$. Output must be placed in a single line.

  Sample Input:

5 5
00000
11111
set_a 0 1
get_c 5
get_c 1
set_b 2 0
get_c 5

  Sample Output:

100

I solved this question and I tried to optimize by reducing the number of calculations for bit addition, but am still getting time-limit-exceeded where the time exceeds 10 seconds for Python.

n, q = map(int, raw_input().split())
A_inp = list(raw_input())
B_inp = list(raw_input())
Query_output = []

def LSB(idx, n):
    return (n - 1) - (int(idx))

def Bit_Add(a, b, n):
    length = len(a)
    output = []
    carry = 0
    for i in range(length):
        if a[i] == "1" and b[i] == "1":
            if carry == 1:
                output.append(1)
                carry = 0
            else:
                output.append(0)
                carry = 1

        elif a[i] == "1" or b[i] == "1":
            if carry == 1:
                output.append(1)
                carry = 0
            else:
                output.append(0)
        else:
            if carry == 1:
                output.append(1)
                carry = 0

    if carry == 1:
        output.append(1)
    return output[::-1]
f = 0
for i in range(q):
    query = raw_input().split()
    if query[0][0:3] == "set":
        Value = query[0][4]
        idx = LSB(int(query[1]), n)
        if Value == "a":
            A_inp[idx] = query[2]
        elif Value == "b":
            B_inp[idx] = query[2]
        f = 0
    else:
        if f == 1:
            idx = LSB(query[1], len(output))
            Query_output.append(output[idx])
        else:
            output = Bit_Add(A_inp, B_inp, n)
            idx = LSB(query[1], len(output))
            Query_output.append(output[idx])
            f = 1

print int(''.join(["%d"%x for x in Query_output]))


texts:
I am coding an Objective-C MD5 hash "decrypter". Since you cannot decrypt such a hash function, I am approaching it with a brute force algorithm, that tries every single password combination until it found the correct one or not.

I would highly appreciate any help to improve the algorithm to make it even faster. I am currently computing approx. 28,000 guesses per second on my iMac and 7,000 on an iPhone 6. I know that 7,000 guesses are quite ridiculous compared to the performance a tool like hashcat has (2.2 billion guesses per second on my iMac), nonetheless I want a mobile MD5 decryption tool on my iPhone.

-(void)brute_sequentialWithMaxLength:(int)length
{
   iterateFurther = YES;

   char * buf = malloc(length + 1);

   for (int i=1; i <= length; i++)
   {
     memset(buf, 0, length+1);
     [self brute_implWithChar:buf andIndex:0 andDepth:i];
   }

  free(buf);
}

-(void)brute_implWithChar:(char*)str andIndex:(int)index andDepth:(int)max_depth
{

 for (int i=0; i < [pm_maskArray count] && iterateFurther == YES;i++)
 {
    alph = [[pm_maskArray objectAtIndex:i] characterAtIndex:0];

    str[index] = alph;

    if (index == max_depth - 1)
    {

         if ([[self makeMD5StringFromString:[NSString stringWithFormat:@"%s",str]] isEqualToString:pm_hashString])
         {
           NSLog(@"Found");
           iterateFurther = NO;
         }

    }
    else
    {
      [self brute_implWithChar:str andIndex:index+1 andDepth:max_depth];
    }

 }
}


texts: Rotate square matrix clockwise by 90degrees

texts:
#include<stdio.h>
#include<stdlib.h>
#include<malloc.h>

void nl(void) {     //function to print new line
    printf("\n");
}

int** allocate(_size) {
    int** matrix=(int**)malloc(sizeof(int*)*_size);
    for(int i=0;i<_size;i++) {
        matrix[i]=(int*)malloc(sizeof(int)*_size);
    }
    return matrix;
}

void scanMatrix(_matrix,_size)
int** _matrix;
{
    printf("Enter the values: ");
    for(int i=0;i<_size;i++) {
        for(int j=0;j<_size;j++) {
            scanf("%d",&_matrix[i][j]);
        }
    }
}

void printMatrix(_matrix,_size)
int** _matrix;
{
    for(int i=0;i<_size;i++) {
        for(int j=0;j<_size;j++) {
            printf("%d ",_matrix[i][j]);
        }
        nl();
    }
}

void swap(num1,num2)
int* num1;
int* num2;
{
    *num1=*num1+*num2;
    *num2=*num1-*num2;
    *num1=*num1-*num2;
}

void rotateMatrix(_matrix,_size)
int** _matrix;
{
    for(int i=0;i<_size;i++) {
        for(int j=i+1;j<_size;j++) {
            swap(&_matrix[i][j],&_matrix[j][i]);
        }
    }
    for(int i=0;i<_size;i++) {
        for(int j=0;j<_size/2;j++) {
            swap(&_matrix[i][j],&_matrix[i][_size-1-j]);
        }
    }
}

main(argc,argv)
const char** argv;
{
    int size=0;
    printf("Enter the size of the square matrix: ");
    scanf("%d",&size);
    int** matrix=allocate(size);
    scanMatrix(matrix,size);
    printMatrix(matrix,size);
    nl();
    rotateMatrix(matrix,size);
    nl();
    printMatrix(matrix,size);
    return 0;
}

This code doesn't use extra memory and also uses run-time allocation using malloc. However, has a time complexity of O(n^2). How do I further optimise it?