texts: Javascript PriorityQueue based on object property

texts:
I wrote this class which is a priority queue based on a numeric property of any object. As far as I can tell, the following code is working as intended. Are there any stylistic tendencies that I am getting wrong, or any gotchas I should look out for?

//Constants

PriorityQueue.MAX_HEAP = 0;
PriorityQueue.MIN_HEAP = 1;

/**
* This is an improved Priority Queue data type implementation that can be used to sort any object type.
* It uses a technique called a binary heap.
*
* For more on binary heaps see: http://en.wikipedia.org/wiki/Binary_heap
*
* @param criteria The criteria by which to sort the objects. This should be a property of the objects you're sorting.
* @param heapType either PriorityQueue.MAX_HEAP or PriorityQueue.MIN_HEAP.
**/
function PriorityQueue(criteria,heapType) {
    this.length = 0; //The current length of heap.
    var queue = [];
    var isMax = false;

    //Constructor
    if (heapType==PriorityQueue.MAX_HEAP) {
        isMax = true;
    } else if (heapType==PriorityQueue.MIN_HEAP) {
        isMax = false;
    } else {
        throw heapType + " not supported.";
    }

    /**
    * Inserts the value into the heap and sorts it.
    *
    * @param value The object to insert into the heap.
    **/
    this.insert = function(value) {
        if (!value.hasOwnProperty(criteria)) {
            throw "Cannot insert " + value + " because it does not have a property by the name of " + criteria + ".";
        }
        queue.push(value);
        length++;
        bubbleUp(length-1);
    }

    /**
    * Peeks at the highest priority element.
    *
    * @return the highest priority element
    **/
    this.getHighestPriorityElement = function() {
        return queue[0];
    }

    /**
    * Removes and returns the highest priority element from the queue.
    *
    * @return the highest priority element
    **/
    this.shiftHighestPriorityElement = function() {
        if (length < 0) {
            throw ("There are no more elements in your priority queue.");
        }
        var oldRoot = queue[0];
        var newRoot = _queue.pop();
        length--;
        queue[0] = newRoot;
        swapUntilQueueIsCorrect(0);
        return oldRoot;
    }

    var bubbleUp = function(index) {
        if (index==0) {
            return;
        }
        var parent = getParentOf(index);
        if (evaluate(index,parent)) {
            swap(index,parent);
            bubbleUp(parent);
        } else {
            return;
        }
    }

    var swapUntilQueueIsCorrect = function(value) {
        left = getLeftOf(value);
        right = getRightOf(value);
        if (evaluate(left,value)) {
            swap(value,left);
            swapUntilQueueIsCorrect(left);
        } else if (evaluate(right,value)) {
            swap(value,right);
            swapUntilQueueIsCorrect(right);
        } else if (value==0) {
            return;
        } else {
            swapUntilQueueIsCorrect(0);
        }
    }

    var swap = function(self,target) {
        var placeHolder = queue[self];
        queue[self] = queue[target];
        queue[target] = placeHolder;
    }

    /*
    /*Helpers
    */
    var evaluate = function(self,target) {
        if (queue[target]==null||queue[self]==null) {
            return false;
        }
        if (isMax) {
            if (queue[self][criteria] > queue[target][criteria]) {
                return true;
            } else {
                return false;
            }
        } else {
            if (queue[self][criteria] < queue[target][criteria]) {
                return true;
            } else {
                return false;
            }
        }
    }

    var getParentOf = function(index) {
        return Math.floor(index/2)-1;
    }

    var getLeftOf = function(index) {
        return index*2 + 1;
    }

    var getRightOf = function(index) {
        return index*2 + 2;
    }
}


texts:
I'm trying to get an efficient algorithm to calculate the height of a tree in Python for large datasets. The code I have works for small datasets, but takes a long time for really large ones (100,000 items) so I'm trying to figure out ways to optimize it but am getting stuck. Sorry if it seems like a really newbie question, I'm pretty new to Python.

The input is a list length and a list of values, with each list item pointing to its parent, with list item -1 indicating the root of the tree. So with an input of:

5
4 -1 4 1 1

The answer would be 3 — the tree is: ({key:1, children: [{key: 3}, {key:4, children:[{key:0, {key:2}]}] }

Here is the code that I have so far:

import sys, threading
sys.setrecursionlimit(10**7) # max depth of recursion
threading.stack_size(2**25)  # new thread will get stack of such size

class TreeHeight:
    def read(self):
        self.n = int(sys.stdin.readline())
        self.parent = list(map(int, sys.stdin.readline().split()))

    def getChildren(self, node, nodes):
        parent = {'key': node, 'children': []}
        children = [i for i, x in enumerate(nodes) if x == parent['key']]
        for child in children:
            parent['children'].append(self.getChildren(child, nodes))
        return parent

    def compute_height(self, tree):
        if len(tree['children']) == 0:
            return 0
        else:
            max_values = []
            for child in tree['children']:
                max_values.append(self.compute_height(child))
            return 1 + max(max_values)

def main():
  tree = TreeHeight()
  tree.read()
  treeChild = tree.getChildren(-1, tree.parent)
  print(tree.compute_height(treeChild))

threading.Thread(target=main).start()


texts: Given n numbers, find out the least k numbers from them

texts:
I have been solving the following problem:

  Given n numbers find out the least k numbers from them. For example, if there are 8 numbers like 5,6,3,4,7,8,9,-1. For k = 3 the result will be -1,3,4.

I implemented it in the following way:

make heap with first k numbers
traverse the rest k-n numbers

if heapMax > any of the k numbers then
swap

return heap containing k numbers

Can you please review my code and provide me with feedback?

#include <iostream>
#include <set>
#include <vector>

std::vector<int> getKLeastNumbers(std::vector<int> &nums, int k)
{
    std::vector<int> tmpNums;

    if(k<=0 || k > nums.size())
    {
        return tmpNums;
    }

    for(int i=0; i<k; i++)
    {
        tmpNums.push_back(nums.at(i));
    }
    std::make_heap(tmpNums.begin(), tmpNums.end());

    for(int i=k; i<nums.size(); i++)
    {
        if (tmpNums.front() > nums.at(i))
        {
            int tmp = nums.at(i);

            nums.at(i) = tmpNums.front();

            std::pop_heap(tmpNums.begin(),tmpNums.end());
            tmpNums.pop_back();

            tmpNums.push_back(tmp);
            std::push_heap(tmpNums.begin(), tmpNums.end());
        }
    }

    return tmpNums;
}

int main()
{
    // test codes
    std::vector<int>nums;
    nums.push_back(56);
    nums.push_back(5);
    nums.push_back(6);
    nums.push_back(60);
    nums.push_back(-6);
    nums.push_back(3);
    nums.push_back(600);

    nums = getKLeastNumbers(nums,1);

    for(int i=0; i<nums.size(); i++)
    {
        std::cout<<nums.at(i)<<std::endl;
    }

    std::vector<int>nums2;
    nums2.push_back(56);

    nums2 = getKLeastNumbers(nums2,-1);

    std::cout<<std::endl<<"Test set 2 "<<std::endl;
    for(int i=0; i<nums2.size(); i++)
    {
        std::cout<<nums2.at(i)<<std::endl;
    }
}


texts: Python simple Class with sqlite and unit testing

texts:
I am trying to learn best practices for OOP and unit testing. I have implemented a simple User class here which checks if the user exists in the database. If yes, then it loads the user data into the instance. If not, then it should create a new entry in the database.

My questions:

How should I create unit tests for the methods? For example, for check_user_exists() should I mock for conn or cursor or exists or three of them? I tried to research for this but none of the tutorials for mocking in Python really gave me any true understanding of how good mocking is done.
In each of the methods, all the database connection related codes are repeated (i.e. conn.cursor(), conn.close()). Can these be refactored away? My guess would be to create a Database class, but I'm not sure about that.
Is it weird for User class to have a database_path attribute? So far this is the best that I have come up with. Please give any suggestions on how to structure a class where it has to always query databases.

user.py

import sqlite3

class User:
    def __init__(self, username, database_path):
        self.username = username
        self.database_path = database_path

        if not self.check_user_exists():
            self.create_user()
        else:
            self.get_user()

    def check_user_exists(self):
        conn = sqlite3.connect(self.database_path)
        cursor = conn.cursor()

        cursor.execute('SELECT rowid FROM user WHERE name = ?', (self.username,))
        exists = cursor.fetchone()

        conn.close()

        if exists is None:
            return False
        else:
            return True

    def create_user(self):
        conn = sqlite3.connect(self.database_path)
        cursor = conn.cursor()

        cursor.execute("INSERT INTO user (name) VALUES (?)", (self.username,))

        conn.commit()
        conn.close()

    def get_user(self):
        conn = sqlite3.connect(self.database_path)
        cursor = conn.cursor()

        cursor.execute("SELECT data FROM user WHERE name=?", (self.username,))
        self.data = cursor.fetchone()[0]

        conn.close()


texts: Decoding a telephone number that was masked with letters from the respective keys with APL

texts:
Legend says phones used to have keyscitation needed and in those times, a person could "encode" a phone number by creating a word from the letters in the keys with the given numbers.

Below is the usual layout of the keys (that matter for my question) of a phone:

     | abc | def |
  1  |  2  |  3  |
------------------
 ghi | jkl | mno |
  4  |  5  |  6  |
------------------
pqrs | tuv | wxyz|
  7  |  8  |  9  |
------------------

I have to write a function that, given a vector of characters with uppercase letters/digits, recovers the original phone number.

For example,

'HELLO' -> 4 3 5 5 6
'IAMYY4U' -> 4 2 6 9 9 4 8
'' -> ⍬

This is the code I have written:

Telephone ← {
  ⍝ Monadic function taking an uppercase string as input.
  ⍝ Decodes the number expressed with uppercase letters,
  ⍝ e.g. '1ABCZ' gives '12229'

  ⍝ Split letters and digits according to their keys (each digit goes to itself)
  keyStarts ← 'ADGJMPTW'
  splits ← ⎕D, keyStarts
  classes ← (1 -⍨ ⍳10), 1 + ⍳8

  classes[splits ⍸ ⍵]
}

I am particularly interested in a better way to create the classes variable, that looks like this 0 1 2 3 4 5 6 7 8 9 2 3 4 5 6 7 8 9 and this ordering depends obviously on the order of splits.

This comes from a problem from an APL competition.


texts:
I just wanted to ask the following question. I have solved Kadanes algorithm using the recursive approach as shown below. The implementation works

 public class Kadane {

    public static void main(String[] args) {
        int[] arr =  {-2, -5, 6, -2, -3, 1, 5, -6};
        Kadane k = new Kadane();
        System.out.println(k.calculate(arr, 0, 0));
    }

    public int calculate(int[] arr, int pointer, int sum) {
        if(pointer >= arr.length )
            return sum;

        return Math.max(sum, Math.max(calculate(arr, pointer+1, sum+arr[pointer]), calculate(arr, pointer+1, 0)));
    }
}

My question is whether the way I am using recursion(top down) is correct or should recursion by definition should always be bottom up? Is this approach correct logically even though implementation wise it seems fine?


texts:
I'm trying to split an incoming stream of strings into cumulative tokens per line item using a function below,

def cumulativeTokenise(string: String): Array[String] = {
  val array = string.split(" +")
  var result: Array[String] = Array()
  array.map { i => (
                    result = result :+ (
                                       if (result.lastOption == None) i
                                       else result.lastOption.getOrElse("")+ " " + i
                                       )
                   )
             }
  result
}

Ex: output of cumulativeTokenise("TEST VALUE DESCRIPTION . AS") would be => Array(TEST, TEST VALUE, TEST VALUE DESCRIPTION, TEST VALUE DESCRIPTION ., TEST VALUE DESCRIPTION . AS)

Trying to figure out if there's another efficient in-built method in Scala or better ways of doing it with FP, without any mutable array. Any help is much appreciated.


texts:
Currently I'm learning OOP and meanwhile I'm trying to keep the SOLID principles. Is it right to inject dependency (GenName - generate file name) on File constructor (for example if someone else wants to write an Image class but he does not know about required dependency injection in constructor)? Does it violate open/close and single responsibility principles?

interface iUpload {
    public function getName();
}

interface iGenName {
    public function genName($file);
}

class GenName implements iGenName {
    public function genName($file)
    {
        // generate and return file name
        return 'filename.txt';
    }
}

class File implements iUpload {
    protected $genName;
    protected $file; //file obj

    public function __construct(iGenName $genName)
    {
        $this->genName = $genName;
    }

    public function getName()
    {
        return $this->genName->genName($this->file);
    }
}

class Upload {
    protected $uploadContent;

    public function __construct(iUpload $uploadContent)
    {
        $this->uploadContent = $uploadContent;
    }

    public function upload() {
        // upload file
        return save($this->uploadContent->getName(),...,...);
    }
}


texts: my constructor is doing work. Is this a code smell in this example?

texts:
I have created a queue in javascript. This queue also has blocking take(). As you all probably know this is not really true, because javascript does not have threads. It just wait until element has been added to queue. You can view to source-code at https://gist.github.com/2467432. I try to write testable code. As you can see from my code below my constructor does real work?

var EventEmitter = require('events').EventEmitter,
    Queue = module.exports = function Queue() {
    /*  Constructor is doing work..??
    */
    var _emitter    = this._emitter     = new EventEmitter(),
        _awaiting   = this._awaiting    = [],
        _queue      = this._queue       = [];

    _emitter.on('offer', function (data) {
        _awaiting.shift()(data);
    });

};

My question is if this a code smell? I think this class(object) is a leaf of application graph(value-object), so maybe it is not such a big deal. This way I think I can keep my API clean(easy to use). I think my class is still easy to test as you can hopefully see from my test class.

  Value-objects, these tend to
  have lots of getters / setters and are very easy to construct are
  never mocked, and probably don't need an interface. (Example:
  LinkedList, Map, User, EmailAddress, Email, CreditCard, etc...). (2)
  Service-objects which do the interesting work, their constructors ask
  for lots of other objects for colaboration, are good candidates for
  mocking, tend to have an interface and tend to have multiple
  implementations (Example: MailServer, CreditCardProcessor,
  UserAthenticator, AddressValidator).

If you think it is a code smell I would like to know how you would fix this(but still keep the tests pass  without any modification if possible?)


texts: Count distinct records in a JOINed SQL query

texts:
I have two tables with a 1-many relationship, Device and TestResult.

My application has a filter builder front-end that allows a user to retrieve TestResults based on whatever filters they specify. This generates queries similar to this:

SELECT d.id,
       d.serialNumber,
       d.createdAt,
       r.id,
       r.testBlockId,
       r.deviceId,
       r.type,
       r.fieldResponses,
       r.stationName,
       r.summary,
       r.createdAt
FROM Device AS d
INNER JOIN TestResult AS r ON r.deviceId = d.id
WHERE d.id IN
    (SELECT id
     FROM Device
     WHERE serialNumber BETWEEN '000000001000' AND '000000002020'
     ORDER BY serialNumber ASC
     LIMIT 570, 10)
  AND r.createdAt BETWEEN '2020-03-27T11:54:43.100Z' AND '2020-04-01 09:21:02.362768'
ORDER BY serialNumber ASC;

This query limits the number of Devices returned, which handles paging on the front-end. I'm also generating a query that counts the total number of Devices that match the filters, without the OFFSET and LIMIT values. This is used to tell the front-end how many pages of records there are.

If I simply run the above query but change the SELECT statement to SELECT COUNT(DISTINCT d.id) as totalDevices and remove the LIMIT, it's very slow. So instead I'm generating this query to find the count:

SELECT COUNT(DISTINCT d.id) AS totalDevices
FROM Device AS d
INNER JOIN TestResult AS r ON r.deviceId = d.id
WHERE serialNumber BETWEEN '000000001000' AND '000000002020'
  AND r.createdAt BETWEEN '2020-03-27T11:54:43.100Z' AND '2020-04-01 09:21:02.362768';

This query runs faster, but it still isn't fast. I'm wondering if there is a better way to retrieve a count of the distinct Device records that would be returned from this query.

This query shows the following execution time with 1,000,000 records:

Run Time: real 8.090 user 1.562500 sys 6.500000


texts: Unit testing static method that imports environment file

texts:
I'm (very) new to writing unit tests and I'm wondering how I should approach testing a static method that constructs our API endpoints based on what the properties are set to in our environment.ts file.

The environment.ts file changes with the environment, so I'm curious how I would accommodate for that in my test.

Does my method need to be refactored to make this easier to test? For example, instead of implicitly referencing environment.endpoint, instead pass-in environment as a argument? Would I mock the environment.ts file?

Any suggestions would be helpful.

import {environment} from '../../environments/environment';

export class Utilities {

  public static constructAPIEndpoint(): string {
    const hostname: string = environment.endpoint;
    const protocol: string = environment.local ? 'http:' : 'https:';

    return `${protocol}//${hostname}/`;
  }
}

environments.ts

export const environment = {
  production: false,
  local: false,
  hostname: 'localhost',
  showLogs: true,
  endpoint: 'foo-dev-graphapp.com',
  appInsights: {
    instrumentationKey: '123'
  }
};

jasmine test:

  import {environment} from '../../environments/environment';

  it('constructAPIEndpoint() it should construct an endpoint based on environment.ts', () => {
    const endpoint: string = Utilities.constructAPIEndpoint();

    /// THIS DOESN'T SEEM - having to recreate logic inside constructAPIEndpoint()
    const protocol: string = environment.local ? 'http:' : 'https';

        expect(endpoint).toEqual(`${protocol}//${environment.endpoint}`);

  });


texts: Iterative implementation of the Ackermann function

texts:
Here's an iterative implementation of the Ackermann function for review:

#include <stack>
#include <iostream>
#include <tuple>
#include <vector>

int Ackermann(int m, int n) {
    std::stack<int> s;
    s.push(m);
    while (!s.empty()) {
        m = s.top();
        s.pop();
        if (m == 0 || n == 0)
            n += m + 1;
        else {
            s.push(m - 1);
            s.push(m);
            n--;
        }
    }
    return n;
}

int main() {
    std::vector<std::tuple<int, int, int>> tests{
        { 0, 0, 1},
        { 1, 0, 2},
        { 1, 1, 3},
        { 2, 1, 5}
    };

    for (auto const &test : tests) {
        using std::get;

        auto result = Ackermann(get<0>(test), get<1>(test));
        if (result == get<2>(test)) {
            std::cout << "Ackermann("
                       << get<0>(test) << ", "
                       << get<1>(test) << ") == "
                       << result << ": passed\n";
        }
        else {
            std::cerr << "Error: Ackermann("
                      << get<0>(test) << ", "
                      << get<1>(test)
                      << ": expected" << get<2>(test)
                      << ", but got: " << result << "\n";
        }
    }
}

Any comments appreciated.


texts:
I have an app that user submit the log in form , when it sent the data to server app create a connection for its account.

In this connection i have an integer field named as state.
the state value is : 1 for connecting, 2 for connected and 0 for failed.

I show a dialog to user display  Connecting ... and then check the state of connection. if its return 0 or 2 dismiss the dialog and show the related message else if it doesn't change after 15 sec dismiss dialog and change the state to 0 !
I do the logic in this way :

final AsyncTask<IImConnection, Void, Boolean> task = new CheckSignInTask();
timeOut = new TimeOut(task);
handler.postDelayed(timeOut, 60 * 1000);
task.execute(conn);

CheckSignInTask class :

 private class CheckSignInTask extends AsyncTask<IImConnection, Void, Boolean> {

        private IImConnection connection;

        @Override
        protected Boolean doInBackground(IImConnection... params) {
            try {
                connection = params[0];
                if (connection != null){
                    while (connection.getState() == ImConnection.LOGGING_IN) {
                        // do nothing while connection state not change

                    }
                    return true;
                }
                else{
                    return false;
                }

            } catch (RemoteException e) {
                e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
            }
            return true;  //To change body of implemented methods use File | Settings | File Templates.
        }

        protected void onPreExecute() {
            dialog = new ProgressDialog(AccountActivity.this);
            dialog.setMessage("Signing in...");
            dialog.show();
        }

        protected void onPostExecute(final Boolean result) {
            if (dialog.isShowing()) {
                dialog.dismiss();
            }
            if (result) {
                try {
                    if (connection.getState() == ImConnection.LOGGED_IN) {
                        isSignedIn = true;
                        setResult(RESULT_OK);
                        finish();
                    } else {
                        isSignedIn = false;
                        deleteAccount();
                        displayLoginError("Login failed ! maybe your username/password is incorrect");
                    }
                } catch (RemoteException e) {
                    e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
                }
            }
            else{
                recreate();
            }
        }

        @Override
        protected void onCancelled() {
            if (dialog.isShowing()) {
                dialog.dismiss();
            }
            super.onCancelled();
        }
    }

TimeOut class :

 public class TimeOut implements Runnable {
        private AsyncTask task;

        public TimeOut(AsyncTask task) {
            this.task = task;
        }

        @Override
        public void run() {
            if (task.getStatus() == AsyncTask.Status.RUNNING) {
                task.cancel(true);
                deleteAccount();
                try {
                    if (dialog != null && dialog.isShowing()) {
                        dialog.dismiss();
                    }
                } catch (java.lang.IllegalArgumentException iae) {
                    //dialog may not be attached to window if Activity was closed
                }
                displayLoginError("Login failed ! check your internet connetction or maybe your username/password is incorrect");
            }
        }
    }

Its work ! but im not sure is it a good approach ?


texts: Function wrapper like std::function that uses "small buffer" allocation

texts:
My Function class is similar to std::function with the small-buffer optimization. However, it always uses  a small buffer and static asserts if the required size exceeds it.

I would like a review for:

correct use of the low-level features
general class design and interoperability with standard library

Here is my code:

#include <cassert>
#include <functional>
#include <iostream>
#include <new>
#include <utility>
#include <array>

template<typename Signature>
struct Function;

template<typename R, typename ...Args>
struct Function<R(Args...)>
{
    Function() : storage()
    {}

    template<typename F>
    Function(const F& f)
    {
        static_assert(alignof(F) <= alignof(Function), "");
        static_assert(sizeof(f) <= sizeof(storage), "");

        new (storage.data()) Impl<F>(f);
    }

    Function(const Function& rhs) :
        storage(rhs.storage)
    {
        if (rhs.valid())
        {
            rhs.getImpl().clone(data());
        }
    }

    Function(Function&& rhs) noexcept :
        storage(rhs.storage)
    {
        rhs.storage = Storage();
    }

    Function& operator=(Function rhs) noexcept
    {
        std::swap(storage, rhs.storage); // not sure if safe
        return *this;
    }

    ~Function()
    {
        if (valid())
        {
            getImpl().~Base();
        }
    }

    R operator()(Args&& ...args) const
    {
        if (!valid())
        {
            throw std::bad_function_call();
        }
        return getImpl().call(std::forward<Args>(args)...);
    }

private:
    struct Base
    {
        virtual ~Base() {}
        virtual R call(Args&& ...args) const = 0;
        virtual void clone(void* where) const = 0;
    };

    template<typename F>
    struct Impl : Base
    {
        Impl(const F& f) : f(f) {}

        R call(Args&& ...args) const override final
        { return f(std::forward<Args>(args)...); }

        void clone(void* where) const override final
        { new (where) Impl<F>(*this); }

        F f;
    };

    // convenience methods
    bool valid() const
    { return storage != Storage(); }

    const void* data() const
    { return static_cast<const void*>(storage.data()); }

    void* data()
    { return static_cast<void*>(storage.data()); }

    const Base& getImpl() const
    { assert(valid()); return *static_cast<const Base*>(data()); }

    Base& getImpl()
    { assert(valid()); return *static_cast<Base*>(data()); }

    typedef std::array<long, 4> Storage; // long is probably max-align
    Storage storage;
};

int main()
{
    Function<int(int)> increment = [](int n) {
        return n + 1;
    };
    Function<int(int)> decrement = [](int n) {
        return n - 1;
    };

    std::cout << increment(3) << std::endl;
    std::cout << decrement(3) << std::endl;

    increment = std::move(decrement);
    std::cout << increment(3) << std::endl;

    // calling the moved-from decrement
    try
    {
        decrement(3);
        assert(false);
    }
    catch (std::bad_function_call& e)
    {
        std::cout << e.what() << std::endl;
    }
}


texts: Transfer of data instead of copy.paste.clear used

texts:
I am using this code in a worksheet to check the condition, and based on the condition, copying the entire row of values in a different range of particular condition if true.

For copying I am clearing the destination range each time and copying the same data with updated information on the same destination. This makes the code running longer. Can I make the code to copy only the updated cells and merge onto the destination ranges where the old data exists?

Private Sub Worksheet_Change(ByVal Target As Range)
Application.ScreenUpdating = False
If (Target.Row >= 120 And Target.Row < 1400) And (Target.Column >= 1 And Target.Column <= 4) Then
    Dim rngSinglecell As Range
    Dim rngQuantityCells As Range
    Dim intCount As Integer

    Sheets("CE1 Data").Range("K2:S1400").Clear

    Set rngQuantityCells = Sheets("CE1 Data").Range("B120", Range("B120").End(xlDown))

    For Each rngSinglecell In rngQuantityCells

    If rngSinglecell.Value = "Primary" Then

    Range(Range("A" & rngSinglecell.Row), Range("D" & rngSinglecell.Row)).Copy Range("K" & Rows.Count).End(xlUp).Offset(1)

    ElseIf rngSinglecell.Value = "Backup" Then

    Range(Range("A" & rngSinglecell.Row), Range("D" & rngSinglecell.Row)).Copy Range("P" & Rows.Count).End(xlUp).Offset(1)

    End If
Next

End If

Application.ScreenUpdating = True
Application.CutCopyMode = False
End Sub


texts: Logging the name of recipes using ingredients

texts:
Given two objects with some food data, log the name of the recipe and ingredients names separated by conjunction "and". Please run the code I have attached to see the expected output.

condition - match RECIPES.rules.id with INGREDIENT.id and use INGREDIENT.name in the final output.

I was wondering if my solution can be improved? The fact that I am looping array inside an existing array loop makes me think this solution is not good.

const INGREDIENTS = [
  {
    id: 'chocolate',
    name: 'Chocolate Ice Cream',
    type: 'ice_cream',
    contains: ['cream', 'milk_chocolate']
  },
  {
    id: 'm_and_ms',
    name: 'M&Ms',
    type: 'topping',
    contains: ['milk_chocolate']
  },
  {
    id: 'lemon',
    name: 'Lemon Ice Cream',
    type: 'ice_cream',
    contains: ['cream', 'lemon']
  },
  {
    id: 'peanuts',
    name: 'Peanuts',
    type: 'topping',
    contains: ['peanuts']
  },
  {
    id: 'vanilla',
    name: 'Vanilla Ice Cream',
    type: 'ice_cream',
    contains: ['cream', 'vanilla_extract']
  },
  {
    id: 'strawberry',
    name: 'Strawberry Ice Cream',
    type: 'ice_cream',
    contains: ['cream', 'strawberries']
  },
  {
    id: 'caramel',
    name: 'Caramel Sauce',
    type: 'topping',
    contains: ['caramel']
  },
  {
    id: 'raspberry',
    name: 'Raspberry Sauce',
    type: 'topping',
    contains: ['raspberries']
  }
];

// DOCSTRING
const RECIPES = [
  {
    id: 'the_basic',
    name: 'The Basic',
    rules: ['chocolate', 'vanilla']
  },
  {
    id: 'chocolate_lovers',
    name: 'Chocolate Lovers',
    rules: ['chocolate', 'm_and_ms', 'caramel']
  },
  {
    id: 'tooty_fruity',
    name: 'Tooty Fruity',
    rules: ['strawberry', 'raspberry', 'm_and_ms']
  }
];

const printRecipe = () => {
  RECIPES.forEach(recipe => {
    let recipeName = recipe.name;

    let listOfItems = recipe.rules.reduce((acc, currentIngredient, index) => {
      let result;
      let items = INGREDIENTS.find(ingrd => {
        return ingrd.id === currentIngredient;
      });
      if (acc.length === 0) {
        result = items.name;
      } else {
        result = `${acc} and ${items.name}`;
      }
      return result;
    }, '');
    console.log(`${recipeName} - ${listOfItems}`);
  });
};

printRecipe();


texts:
After implementing suggestions from an earlier, related question (Python: Insertion Sort), I have written this code. Could you help me to improve this code?

def get_input():
    input_str = input("Enter elements to be sorted: ")
    lst = list(map(int, input_str.split()))
    return lst

def selection_sort(thelist):
    for i in range(len(thelist)-1):
        min_idx = i

        for j in range(i+1, len(thelist)):
            if thelist[j] < thelist[min_idx]:
                 min_idx = j

        thelist[i], thelist[min_idx] = thelist[min_idx], thelist[i]

if __name__ == '__main__':
    input_list = get_input()
    selection_sort(input_list)
    print(*input_list, sep = ", ")


texts: C++ limiting a method for an rvalue caller, an expression evaluator example

texts:
There are many ways to implement a math expressions evaluator (I focus here just on the evaluator part, without any parsing).

I want to explore a certain implementation to support the following main:

int main() {
    Expression e = Sum( Sum(Number(2), Number(3)), Number(-1) );
    cout << e << "=" << e.eval() << endl;
}

The expected output is:

((2+3)+-1)=4

A basic notion: there are some temporary objects created there. We should better move them.
So I came up with the following code I would like to consult about.

BaseExpression - an abstract base for all expressions

class BaseExpression {
public:
    virtual ~BaseExpression() {}
    // what do you think about the concept of the method 'get_unique_copy()' below?
    virtual std::unique_ptr<BaseExpression> get_unique_copy() && = 0;
    virtual double eval()const = 0;
    virtual void print(ostream& out)const = 0;
};

Expression - the actual non-abstract to hold an expression

class Expression {
    std::unique_ptr<BaseExpression> _e;
public:
    Expression(nullptr_t) {}
    Expression(BaseExpression&& e)
    : _e(std::move(e).get_unique_copy()) {}
    ~Expression() {}
    Expression(Expression&& e) noexcept : _e(std::move(e._e)) {}
    Expression& operator=(Expression&& e) noexcept { std::swap(_e, e._e); return *this; }
    double eval() const { return _e->eval(); }
    friend ostream& operator<<(ostream& out, const Expression& e) {
        e._e->print(out);
        return out;
    }
};

Sum - an example of an actual expression

class Sum: public BaseExpression {
    Expression _e1{nullptr}, _e2{nullptr};
public:
    Sum(BaseExpression&& e1, BaseExpression&& e2)
        : _e1(std::move(e1)), _e2(std::move(e2)) {}
    Sum(const Sum& s) = delete;
    Sum& operator=(const Sum& s) = delete;
    Sum(Sum&& s) noexcept {
        std::swap(_e1, s._e1);
        std::swap(_e2, s._e2);
    }
    // what do you think about the implementation of 'get_unique_copy()' below? is it safe?
    virtual std::unique_ptr<BaseExpression> get_unique_copy() && {
        return std::make_unique<Sum>(std::move(*this));
    }
    virtual double eval()const override {
        return _e1.eval() + _e2.eval();
    }
    virtual void print(ostream& out)const override {
        out << '(' << _e1 << '+' << _e2 << ')';
    }
};

Number - the simplest actual expression

class Number: public BaseExpression {
    double _d;
public:
    Number(double d) : _d(d) {}
    // what do you think about the duplication of 'get_unique_copy()' in each derived?
    // is there a way to avoid the duplication, apart from ugly Macros?
    virtual std::unique_ptr<BaseExpression> get_unique_copy() && {
        return std::make_unique<Number>(std::move(*this));
    }
    virtual double eval()const override {
        return _d;
    }
    virtual void print(ostream& out)const override {
        out << _d;
    }
};

What do you think?

http://coliru.stacked-crooked.com/a/9843afbe4e9ed4d8


texts:
I call a service which returns an array of tags. The array may be empty, and if so, it just saves the tag. Otherwise, it checks if the tag is in the array. If so, then the tag is removed, otherwise it's saved.

Can this be optimized for efficiency?

function processTag(total, tag, associatedTicker) {
    var foundFlag = false;

    TagFactory.retrieveTickerTags('onlyTags').then(function(data) {
        console.log('onlyTags data',data);

        // Is there are selected Tags:
        if (data.length > 0) {
            // Search for tag in tagFactory
            for (var i=0; i<data.length; i++) {
                if (data[i].term_id === tag.term_id) {
                    foundFlag = true;
                    break;
                }
            }
            // If found, remove tag:
            if (foundFlag) {
                removeTag(tag, associatedTicker);
            }
            else {
                // Save the tag:
                if (total < 3) {
                    saveTag(tag, associatedTicker);
                }
                // 3 are already selected, display alert:
                else {
                    displayAlert('failure', 'Only 3 tags can be monitored at a time.');
                }
            }
        }
        // Else if there are no selected tags:
        else {
            saveTag(tag, associatedTicker);
        }
    });
}


texts:
I have a class:

public class EmailSender: IDisposable
{
    private SmtpClient EmailSmtpClient { get; set; }
    private MailMessage Message { get; set; }

    public override void Dispose()
    {
         EmailSmtpClient.Dispose();
         Message.Dispose();
         GC.Collect();
    }
}

This is what I currently have implemented. What is the best way to release all the resources including the attachments (that are a part of MailMessage) immediately after the email is sent? Can anyone review my Dispose method and suggest some betterment? I will be thankful :)


texts: Comparing the size of tumors over time using PANDAS

texts:
I have a dataframe in pandas like this

Date         cell         tumor_size (assume it is three dimensional)
25/10/2015    113           [51, 52, 55]
22/10/2015    222           [50, 68, 22]
22/10/2015    883           [45, 23, 67]
20/10/2015    334           [35, 23, 76]

What I want to do is compare the size of the tumors detected on the different days. Let's consider the cell 222 as an example; I want to compare its size to different cells but detected on earlier days e.g. I will not compare its size with cell 883, because they were detected on the same day. Or I will not compare it with cell 113, because it was detected later on. As my dataset is too large, I have iterate over the rows. Here is my sample code:

# These will be our lists of pairs and size differences.
pairs = []
diffs = []

# Loop over all unique dates
for date in df.Date.unique():
    # Only take dates earlier then current date.
    compare_df =df.loc[df.Date < pd.Timestamp(date).to_pydatetime()].copy()
    # Loop over each cell for this date and find the minimum
    for row in df.loc[df.Date ==  pd.Timestamp(date).to_pydatetime()].itertuples():
        # If no cells earlier are available use nans.
        if compare_df.empty:
            pairs.append(float('nan'))
            diffs.append(float('nan'))
        # Take lowest absolute value and fill in otherwise
        else:
            compare_df['distance'] = compare_df['tumor_size'].map(lambda x: np.linalg.norm(x - row.tumor_size))
            row_of_interest = compare_df.loc[compare_df.distance == compare_df.distance.min()]
            cell = row.cell
            Date = row.Date
            most_similar_to = row_of_interest.cell.values[0]
            similarity = row_of_interest.distance.values[0]
            with open('final_csv', "a", newline="") as f:
                writer = csv.writer(f, dialect="excel-tab")
                writer.writerow([cell, Date, most_similar_to, similarity])

How could I improve the speed of the code? I have over one million cells.


texts:
I'm trying to write a simple python script that acts like the nc program (netcat). I've got it working on OSX (the client that is) by testing against a netcat server, but I'm unsure about the way I've implemented it.

I'd appreciate it if anyone could give me some advice and/or let me know how you would implement it as I still consider myself a beginner. Maybe I should study more on threads and sockets before taking this task on?

By the way, I chose threads over polling for the reason that files in select don't work on Windows.

import sys
import socket
import select
import time
import threading

def _stdout_write(data):
    sys.stdout.write(data)
    sys.stdout.flush()

class NetSnake(object):
    def __init__(self):
        self._close_connection = threading.Event()
        self._stdin_handler = threading.Thread(target=self._handle_stdin)
        self._stdin_handler.daemon = True

    def connect(self, rhost, rport):
        # handle connection refused...
        self._active_sock = socket.create_connection((rhost, rport))
        self._active_sock.setblocking(0)
        self._stdin_handler.start()
        self._handle_active_sock()

    def reverse(self, *args, **kwargs):
        self.connect(*args, **kwargs)

    def _handle_stdin(self):
        while True:
            line = sys.stdin.readline()
            if not line:
                # eof
                break
            self._active_sock.sendall(line)
        # let other thread know that we want to close the connection
        # because eof has been reached.
        self._close_connection.set()

    def _handle_active_sock(self):
        # NOTE: select on windows may not be interrupted by Ctrl-C
        # if not, try time.sleep or event.wait instead.
        self._close_connection.clear()
        timeout = 0.1
        try:
            while not self._close_connection.is_set()
                ready = select.select([self._active_sock], [], [], timeout)
                if ready[0]:
                    data = self._active_sock.recv(4096)
                    if not data:
                        break
                    _stdout_write(data)
        except KeyboardInterrupt:
            _stdout_write('\n')
        finally:
            self._clean_up()

    def _clean_up(self):
        self._active_sock.close()

Edit: I've now realized that I can get rid of the event that signals
the main thread that EOF has been reached and just simply close the socket and handle select's error instead.

def _handle_stdin(self):
    try:
        while True:
            line = sys.stdin.readline()
            if not line:
                # eof
                break
            self._active_sock.sendall(line)
    finally:
        self._clean_up()

def _handle_active_sock(self):
    try:
        while True:
            ready = select.select([self._active_sock], [], [])
            if ready[0]:
                data = self._active_sock.recv(4096)
                if not data:
                    break
                _stdout_write(data)
    except KeyboardInterrupt:
        _stdout_write('\n')
    except select.error:
        pass
    finally:
        self._clean_up()


texts: Image upload and thumbnail creation script using PHP GD

texts:
Ignoring my shocking use of the mysql_* extension (and any associated issues), could you take a look at my script that uploads an image, adds it to a database, creates a thumbnail of the image 578px in width, and adds that to the database too?

<?php
require_once("validate.php");

while ($hq = mysql_fetch_assoc($hash_query)) {
    $ukip_name = $hq['ukip_name'];
    $speaker_id = $hq['speaker_id'];
    $conference_id = $hq['conference_id'];
    $conf_title = $hq['conf_title'];
    $webmaster_id = $hq['webmaster_id'];
    $first_name = $hq['first_name'];
    $family_name = $hq['family_name'];
    $job_title = $hq['job_title'];
    $company_name = $hq['company_name'];
    $country = $hq['country'];
    $speaker_photo = $hq['speaker_photo']; // Default = NULL
    $company_logo = $hq['company_logo']; // Default = NULL

}
$errors   = $_FILES['file']['error'];
$tempname = $_FILES['file']['tmp_name'];
$filename = $_FILES['file']['name'];
$filetype = $_FILES['file']['type'];
$filesize = $_FILES['file']['size'];
$extensions = array("jpg", "jpeg", "JPG", "JPEG");
$expl = explode(".", $filename);
$extension = end($expl);
if ((($filetype == "image/jpg") ||
    ($filetype == "image/jpeg")) && in_array($extension, $extensions)) {
    if ($errors == 0) {
        if ($filesize <= 10485760) {
            $timestamp = date("ymd-His");
            $filename = $speaker_id . "_" . $timestamp . "_photo." . $extension;
            $db_insert = mysql_query("INSERT INTO temp_uploads
                                     SET speaker_id = $speaker_id, image_filename = '$filename', image_type = 1");
            move_uploaded_file($tempname, "uploads/" . $filename);
            // Resize JPEG
            $md = explode(".", $filename);
            if (end($md) != "eps") {
                $filedims = getimagesize("uploads/" . $filename);
                $md_width = 578;
                $md_height = ($filedims[1] / $filedims[0]) * $md_width;
                $filename_md = $md[0] . "_md." . end($md);
                $quality = 100;
                $src = "uploads/" . $filename;
                $new = imagecreatefromjpeg($src);
                $canvas = imagecreatetruecolor($md_width, $md_height);
                imagecopyresampled($canvas, $new, 0, 0, 0, 0, $md_width, $md_height, $filedims[0], $filedims[1]);
                imagejpeg($canvas, "uploads/" . $filename_md, $quality);
                $db_insert_md = mysql_query("INSERT INTO temp_uploads
                                            SET speaker_id = $speaker_id, image_filename = '$filename_md', image_type = 1");
            }
            mysql_close();
            header("Location: crop.php?hash={$hash}&file={$filename_md}");
            exit();
        } else {
            closeCon(105, "index", "&hash={$hash}");
        }
    } else {
        closeCon(104, "index", "&hash={$hash}");
    }
} else {
    closeCon(103, "index", "&hash={$hash}");
}
?>

I do checks on the filesize, so that something over 10MB is disallowed, but I have hit out-of-memory PHP errors on line 43 ($new = imagecreatefromjpeg($src);) a couple of times recently - one on an 8MB file, and one on a 3.5MB file, which is worrying. These aren't dropping me out of the script in the expected way (closeCon(105...)) but with a PHP fatal error.

I have temporarily set my initiation file to memory_limit=-1 whilst I try and resolve the error, but I was hoping someone here could look at ways of streamlining my code so as to free up as much memory as possible, as well as suggesting general improvements (again, ignoring any mysql_* related ones - I know, and I would use mysqli_* if I could).


texts:
I'm trying to optimize my code or see if there's a better way to do it. Given values for acctData and balances below, I need to return an array of accounts filtered by the user name.

const acctData = [
      {
        acctNum: "AAA - 1234",
        user: "Alice"
      },
      {
        acctNum: "AAA - 5231",
        user: "Bob"
      },
      {
        acctNum: "AAA - 9921",
        user: "Alice"
      },
      {
        acctNum: "AAA - 8191",
        user: "Alice"
      }
];

const balance = {
  "AAA - 1234": 4593.22,
  "AAA - 9921": 0,
  "AAA - 5231": 232142.5,
  "AAA - 8191": 4344
};

const combinedAccBalance = JSON.parse(JSON.stringify(acctData));

const getAccountNumbers = (filterByUser) => {
  return combinedAccBalance
    .filter(acc => {
      acc.balance = balance[acc.acctNum];
      return acc.user === filterByUser;
    }).sort((a, b) => {
      return a.balance - b.balance;
    })
    .map(fa => {
      return fa.acctNum;
    });
};

getAccountNumbers("Alice");
//Returns
["AAA - 9921", "AAA - 8191", "AAA - 1234"]


texts:
This is a simple implementation of a knapsack written in Ruby.  I've included all the relevant code here, but my question is concerning the contents setter .contents=

## item.rb
class Item
  attr_accessor :weight
  attr_accessor :data

  def initialize(weight:, data: nil)
    @weight = weight
    @data   = data
  end

end

 ## knapsack.rb
class KnapsackCapacityExceededError < StandardError; end
class KnapsackWeightExceededError < StandardError; end
class KnapsackContentError < StandardError; end

require_relative('./item')

class Knapsack
  attr_reader :capacity
  attr_reader :weight
  attr_reader :contents

  def initialize(capacity:, weight:)
    @capacity = capacity
    @weight   = weight
    @contents = Array.new(@capacity) { nil }
  end

  def contents=(new_contents)
    raise KnapsackCapacityExceededError if self.exceeds_capacity? new_contents
    raise KnapsackWeightExceededError   if self.exceeds_weight? new_contents
    raise KnapsackContentError          unless new_contents.all? { |e| e.is_a? Item }

    @contents = new_contents
  end

  def fit?(contents)
    return false if self.exceeds_weight?(contents) || self.exceeds_capacity?(contents)
    true
  end
  alias_method :fits?, :fit?

  def fits_weight?(contents)
    new_weight = contents.map { |item| item.weight }.sum
    return true if new_weight <= self.weight
    false
  end

  def exceeds_weight?(contents)
    return true if !fits_weight? contents
    false
  end

  def fits_capacity?(contents)
    return true if contents.length <= self.capacity
    false
  end

  def exceeds_capacity?(contents)
    return true if !fits_capacity? contents
    false
  end

end

# k = Knapsack.new(capacity: 10, weight: 50)

In this method there are three conditions where an exception is raised, is this a code smell?

Any other feedback also appreciated.


texts:
This is a calculator I've made in C#. Is there any way to improve it? Surely there is a way to get rid of all the ifs that are nested inside one another.

namespace CalculatorCA
{
    using System;
    using System.Collections.Generic;
    class Program
    {
        static void Main()
        {
            Dictionary<int, Func<double, double, double>> MyDict =
                new Dictionary<int, Func<double, double, double>>();
            FillDictionary(MyDict);
            bool KeepOn = true;
            while (KeepOn)
            {
                Console.WriteLine("Enter the first number!");
                double first;
                if (double.TryParse(Console.ReadLine(), out first))
                {
                    Console.WriteLine("Please choose one of the following:\n1-Add\n2-Substract\n3-Multiply\n4-Divide");
                    int choice;
                    if (int.TryParse(Console.ReadLine(), out choice))
                    {
                        if (MyDict.ContainsKey(choice))
                        {
                            Console.WriteLine("Enter the second number!");
                            double second;

                            if (double.TryParse(Console.ReadLine(), out second))
                            {
                                Console.WriteLine("The result is : {0}", MyDict[choice](first, second));
                            }
                        }
                        else
                        {
                            Console.WriteLine("Invalid operation!");
                        }
                    }
                }
                Console.WriteLine("Continue?[Y/N]");
                KeepOn = Console.ReadKey().Key == ConsoleKey.Y;
                Console.Clear();
            }
        }
        public static void FillDictionary(Dictionary<int,Func<double,double,double>> myDictionary)
        {
            myDictionary.Add(1, (x, y) => x + y);
            myDictionary.Add(2, (x, y) => x - y);
            myDictionary.Add(3, (x, y) => x * y);
            myDictionary.Add(4, (x, y) => x / y);
        }
    }
}


texts: concatenate string, with different first and last iteration

texts:
Good day. My code works but I think there is a better way to do this. Like string pattern or string manipulation. I'm not yet familiar with both terms.
The goal is to get "=A1-A2-B3-D4-WHATEVER STRING=". From array of strings.
The code is :
string[] arr = { "A1", "A2", "B3", "D4", "WHATEVER STRING"}; // can be any string value
string newString = "=";
for (int i = 0; i < arr.Length; i++) {
    if (i == arr.Length-1) {
        newString  += arr[i].ToString() + "=";
    } else {
        newString += arr[i].ToString() + "-";
    }
}


texts:
An 'abecedarian' is a word whose letters appear in alphabetical order.
  Write a program which will determine whether the given word is
  abecedarian or not and print 1 if abecedarian, 0 if not.

Input : user enter a string or word.
Output: print `1` if word is Abecedarian else `0`.

Test Cases :

abc    1
beee   1
cuanf  0

#include<stdio.h>
#include<string.h>

void main()
 {

   char str[20];

printf("\n Enter a string");

scanf("%s",str);

int len = strlen(str);

int i,flag = 1;

for(i=0;i < len - 1;i++)
 {

if(str[i+1] >= str[i])

    continue;

else
{
       flag = 0 ;
   break;
}
}

if(flag == 0)

printf("\n String is not Abecedarian ");

else

printf("\n Is abecedarian");

}


texts: what is the best order of operation for a successful project, are there any function you would add?

texts:
I'm a developer myself, I don't excel in the area of where marketing comes into play, I have a TRC, eth, BSc, what web app should be built first, I hear about voting apps, I hear about ico, Ido, I get the basic concept, but what truly is that way to go if you went in order properly, I know it's strongly based on where you live. but here's an example to help answer.
* Smart contract for token.
* pair?
* Ico? (if necessary)
* Voting app
* node
* personal block explorer for the token project?
* crowd-funding

``pragma solidity ^0.5.0;

    import "./Token.sol";

    contract EthSwap {
      string public name = "EthSwap Instant Exchange";
      Token public token;
      uint public rate = 100;

      event TokensPurchased(
        address account,
        address token,
        uint amount,
        uint rate
      );

      event TokensSold(
        address account,
        address token,
        uint amount,
        uint rate
      );

      constructor(Token _token) public {
        token = _token;
      }

      function buyTokens() public payable {
        // Calculate the number of tokens to buy
        uint tokenAmount = msg.value * rate;

        // Require that EthSwap has enough tokens
        require(token.balanceOf(address(this)) >= tokenAmount);

        // Transfer tokens to the user
        token.transfer(msg.sender, tokenAmount);

        // Emit an event
        emit TokensPurchased(msg.sender, address(token), tokenAmount, rate);
      }

      function sellTokens(uint _amount) public {
        // User can't sell more tokens than they have
        require(token.balanceOf(msg.sender) >= _amount);

        // Calculate the amount of Ether to redeem
        uint etherAmount = _amount / rate;

        // Require that EthSwap has enough Ether
        require(address(this).balance >= etherAmount);

        // Perform sale
        token.transferFrom(msg.sender, address(this), _amount);
        msg.sender.transfer(etherAmount);

        // Emit an event
        emit TokensSold(msg.sender, address(token), _amount, rate);
      }

}```


texts:
I am not sure if I am just having a brain lapse here or if there is a better way to do this:

I am trying to only add one to count in the following scenarios:

the bool excludezeros is set to false (count should be increased for iterations of the foreach)
the bool excludezeros is set to true and studentScore is not equal to 0 (count only increases when student score is not equal to 0)

Here is what I have:

foreach (var student in students)
{
    double studentScore = GetScore();
    score += studentScore;
    if (excludeZeroes && studentScore == 0)
    {
        continue;
    }
    else
    {
        count++;
    }
}


texts:
This is a basic React problem, how to handle global listener and change state in callback without attaching a listener on each rerender.

Here is a common solution:

 useEffect(() => {
        const handleScroll = () => {
            var rect = selectedRingElement.current.getBoundingClientRect();
            if(isElementInViewport(rect)) {
                console.log(`${isInViewPort} ${initialViewPortTop}`)
                if(!isInViewPort&&!initialViewPortTop) {
                    setInitialViewPortTop(rect.top)
                }
                setIsInViewport(true)
            } else {
                setIsInViewport(false)
            }
        }
        window.addEventListener('scroll', handleScroll)
        return () => {
            window.removeEventListener("scroll", handleScroll)
          }
    }, [initialViewPortTop, isInViewPort])

So it works and shouldn't create memory leaks, however I find it not nice to have to remove et add event listener all the time. Do you know a cleaner solution to this problem, or is it the best we can do?


texts: Binary Search Tree implementation using smart pointers

texts:
I have implemented below code for binary search tree implementation using shared pointer. At present, I have considered only integers. It supports insertion and deletion of values. Also, a print method is implemented for inorder traversal.

Please review and provide your suggestions.

class Bst {
    struct node {
        int val;
        shared_ptr<node> left, right;
        node(int v) : val(v), left(nullptr), right(nullptr){}
    };
    shared_ptr<node> root;
    shared_ptr<node> _insert(shared_ptr<node> curr, int val);
    shared_ptr<node> _del(shared_ptr<node> curr, int val);
    shared_ptr<node> findmin(shared_ptr<node> curr);
    void _print(shared_ptr<node> curr);

public:
    void insert(int val) { root = _insert(root, val); }
    void del(int val) { root = _del(root, val); }
    void print() { _print(root); cout << '\n'; }
};

shared_ptr<Bst::node> Bst::_insert(shared_ptr<node> curr, int val)
{
    if (curr == nullptr)
        return make_shared<node>(val);

    if (val < curr->val)
        curr->left = _insert(curr->left, val);
    else
        curr->right = _insert(curr->right, val);

    return curr;
}
shared_ptr<Bst::node> Bst::findmin(shared_ptr<node> curr)
{
    while (curr->left)
        curr = curr->left;
    return curr;
}
shared_ptr<Bst::node> Bst::_del(shared_ptr<node> curr, int val)
{
    if (val < curr->val)
        curr->left = _del(curr->left, val);
    else if (val > curr->val)
        curr->right = _del(curr->right, val);
    else {
        if (curr->right == nullptr)
            return curr->left;
        if (curr->left == nullptr)
            return curr->right;
        shared_ptr<node> temp = findmin(curr->right);
        curr->val = temp->val;
        curr->right = _del(curr->right, curr->val);
    }
    return curr;
}
void Bst::_print(shared_ptr<node> curr)
{
    if (curr == nullptr)
        return;
    _print(curr->left);
    cout << curr->val << " ";
    _print(curr->right);
}


texts:
I'm trying to build a deep proxy to observe all the changes in an object in javascript. Here is what I got so far :

function GetDeepProxy(value, config, path = 'root')
{
    var handler = function(config) {
        return {
            set: function(target, name, value) {
                if(typeof config.beforeSet === 'function')
                {
                    config.beforeSet(target, name, value, this.path);
                }

                target[name] = GetDeepProxyHelper(value, handler(config), this.path + '.' + name);

                if(typeof config.afterSet === 'function')
                {
                    config.afterSet(target, name, value, this.path);
                }
                return true;
            }
        }
    };

    var GetDeepProxyHelper = function(value, handler, path)
    {
        handler.path = path;
        if(typeof value === 'object')
        {
            for(var prop in value)
            {
                if(typeof value[prop] === 'object')
                {
                    value[prop] = GetDeepProxyHelper(value[prop], handler, path + '.' + prop);
                }
            }
            return new Proxy(value, handler);
        }
        else
        {
            return value;
        }
    }

    return GetDeepProxyHelper(value, handler(config), path);
}

You can then use it like that :

var myConfig = {
    afterSet: function(target, name, value, path)
    {
        console.log('set :', path + '.' + name + ' = ', value);
    },
    beforeSet: function(target, name, value, path)
    {
        //console.log('setting :', path + '.' + name + ' = ', value);
    }
}

var proxy = GetDeepProxy({}, myConfig, 'proxy');

proxy.test = [];
proxy.test.push('hi');
proxy.test[0] = 'abc';
proxy.test.push('def');
proxy.test = proxy.test.slice(1);
proxy.deep = {};
proxy.deep.abc = 'abc';
proxy.deep2 = { abc: { test: {} } };
proxy.deep2.abc.test.value = 'test';

console.log(proxy);
console.log(JSON.stringify(proxy));

Which print the following result

(index):160 set : root.test =  []
(index):160 set : root.test.0 =  hi
(index):160 set : root.test.length =  1
(index):160 set : root.test.0 =  abc
(index):160 set : root.test.1 =  def
(index):160 set : root.test.length =  2
(index):160 set : root.test =  ["def"]
(index):160 set : root.deep =  {}
(index):160 set : root.deep.abc =  abc
(index):160 set : root.deep2 =  {abc: Proxy}
(index):160 set : root.deep2.abc.test.value =  test
(index):180 Proxy {test: Proxy, deep: Proxy, deep2: Proxy}
(index):181 {"test":["def"],"deep":{"abc":"abc"},"deep2":{"abc":{"test":{"value":"test"}}}}

Is there any modifications that I won't be able to observe using this approach and should I structure the code differently?


texts: Code deletes unique entity that reports data later than 4 quarters, runs too slow

texts:
I have a worksheet which is filled with data from Column A to G. Each row is a unique entity and Column G represents how long ago (in quarters) the data was reported. The purpose of the code is to check if the value is more than 4 (that means the reported date was more than 4 quarters from today), and if so, the code would delete that particular row.

Currently my code takes about 3 minutes to run, and I was wondering if there's anything else that I could do/restructure my code for it to run faster.

I have about 5000++ rows as of now.

Sub Two_Keep3Quarters()
    Dim Firstrow As Long
    Dim Lastrow As Long
    Dim lRow As Long
    Dim Tbl As ListObject
    Dim rng As Range
    Dim QuarterValue As Long

    With Application
        .Calculation = xlCalculationManual
        .ScreenUpdating = False
    End With

    With Sheets("Filtered Data")
        .DisplayPageBreaks = False

        'Set the first and last row to loop through
        Firstrow = 3
        Lastrow = .Cells(.Rows.Count, "A").End(xlUp).Row

        'We loop from Lastrow to Firstrow (bottom to top)
        For lRow = Lastrow To Firstrow Step -1

        QuarterValue = .Range("G" & lRow).Value

            'We check the values in the Column G
            With .Cells(lRow, "G")

                If Not IsError(QuarterValue) Then

                    If QuarterValue > 4 Then .EntireRow.Delete
                    'This will delete each row with value of more than 4 quarters

                End If

            End With

        Next lRow

    End With

    Range("F1").Value = "Quarters"
    Range("G1").Value = "No. of Quarters"

    On Error Resume Next
    Set rng = Range(Range("A1"), Range("G1").End(xlDown)).SpecialCells(xlCellTypeBlanks)
    rng.Rows.Delete Shift:=xlShiftUp

         For Each Tbl In Sheets("Filtered Data").ListObjects
         Tbl.Unlist

    Next

        Set Tbl = ActiveSheet.ListObjects.Add(xlSrcRange, Range(Range("A1"), Range("G1").End(xlDown)), , xlYes)

    With Tbl
    .Name = "DataTable"
    .TableStyle = "TableStyleLight10"
    End With

Application.ScreenUpdating = True

End Sub


texts: Searching a maze using DFS and BFS in Python 3

texts:
I solved the problem posted from Make School Trees and Maze article, which asks me to searching a maze using DFS and BFS in Python.

Here's the final output from PyGame:

I would like to ask for code review, as I paste my code snippet below: Here's my DFS and BFS solution for solve_maze.py code review for implementation.

BFS solutino looks like this:

You can find my code for generating_maze here: https://github.com/Jeffchiucp/graph-maze-problem

import maze
import generate_maze
import sys
import random

BIT_SOLUTION = 0b0000010010010110
# Solve maze using Pre-Order DFS algorithm, terminate with solution
def solve_dfs(m):
    stack = []
    current_cell = 0
    visited_cells = 1

    while current_cell != m.total_cells -1:
        print(current_cell)
        unvisited_neighbors = m.cell_neighbors(current_cell)
        if len(unvisited_neighbors) >= 1:
            # choose random neighbor to be new cell
            new_cell_index = random.randint(0, len(unvisited_neighbors) - 1)
            new_cell, compass_index = unvisited_neighbors[new_cell_index]
            # knock down wall between it and current cell using visited_cell
            m.visit_cell(current_cell, new_cell, compass_index)
            # push current cell to stack
            stack.append(current_cell)
            # set current cell to new cell
            current_cell = new_cell
            # add 1 to visited cells
            visited_cells += 1
        else:
            m.backtrack(current_cell)
            current_cell = stack.pop()
            print("run")
        m.refresh_maze_view()
    m.state = 'idle'

# Solve maze using BFS algorithm, terminate with solution
def solve_bfs(m):
    """
    create a queue
    set current cell to 0
    set in direction to 0b0000
    set visited cells to 0
    enqueue (current cell, in direction)

    while current cell not goal and queue not empty
        dequeue to current cell, in direction
        visit current cell with bfs_visit_cell
        add 1 to visited cells
        call refresh_maze_view to update visualization

        get unvisited neighbors of current cell using cell_neighbors, add to queue

    trace solution path and update cells with solution data using reconstruct_solution

    set state to 'idle'
    """
    queue = []
    cur_cell = 0
    in_direction = 0b0000
    visited_cells = 0
    queue.insert(0, (cur_cell, in_direction))
    while not cur_cell == len(m.maze_array) - 1 and len(queue) > 0:
        cur_cell, in_direction = queue.pop()
        m.bfs_visit_cell(cur_cell, in_direction)
        visited_cells += 1
        m.refresh_maze_view()
        neighbors = m.cell_neighbors(cur_cell)
        for neighbor in neighbors:
            queue.insert(0, neighbor)
    m.reconstruct_solution(cur_cell)
    m.state = "idle"

def print_solution_array(m):
    solution = m.solution_array()
    print('Solution ({} steps): {}'.format(len(solution), solution))

def main(solver='dfs'):
    current_maze = maze.Maze('create')
    generate_maze.create_dfs(current_maze)
    if solver == 'dfs':
        solve_dfs(current_maze)
    elif solver == 'bfs':
        solve_bfs(current_maze)
    while 1:
        maze.check_for_exit()
    return

if __name__ == '__main__':
    if len(sys.argv) > 1:
        main(sys.argv[1])
    else:
        main()


texts:
I have read a lot and spent a lot of hours trying to reach the right way to set a good htaccess in order to redirect an HTTP site to HTTPS.

There are a lot of tutorials on the Internet, even on Stack Overflow, but some of them seem to be outdated and don't meet good SEO practices.

The scenario is the following one:

My site has Cloudflare enabled
My site has a valid SSL on server-side

The current htaccess of my site:

RewriteEngine On
RewriteBase /
RewriteCond %{HTTP_HOST} ^MYSITE\.cl$
RewriteRule ^(.*) http://www.MYSITE.cl/$1 [R=301]
RewriteRule ^/?find$ find.php [L]
RewriteRule ^/?do$   do.php   [L]
ErrorDocument 404 /404.html
Options -Indexes

and I want to change .htaccess in order to keep my good SEO rank on Google, use the HTTPS and keep the .WWW:

#OLD PART
RewriteEngine On
RewriteBase /

# Non-www to www (NEW PART)
RewriteCond %{HTTP_HOST} !^www\.
RewriteRule (.*) https://www.%{HTTP_HOST}/$1 [R=301,L]

# Non-SSL to SSL (NEW PART)
RewriteCond %{HTTPS} off
RewriteRule (.*) https://%{HTTP_HOST}/$1 [R=301,L]

#OLD PART AGAIN
RewriteRule ^/?find$ find.php [L]
RewriteRule ^/?do$   do.php   [L]
ErrorDocument 404 /404.html
Options -Indexes

Will this work like a charm? Do you have a better idea? Does my code have any redundancy? I think that I must set Cloudflare SSL parameters to FULL SSL (STRICT). Is that right?


texts:
I have this method that returns an array of all the hours for the past 24 hours, ex: if the current time is 3:24pm it looks like @[3pm,4pm...12am,1am...2pm,3pm];

Everything is working as it should, I was wondering if there was a more efficient (or pretty) way to do it than how I have it:

NSCalendar *calendar = [NSCalendar currentCalendar];
NSDate *today = [NSDate date];
NSDateComponents *comps = [calendar components:NSCalendarUnitHour|NSCalendarUnitDay fromDate:today];

NSMutableArray *units = [[NSMutableArray alloc] init];

int currentHour = (int)[comps hour];

for (int i = 0; i < 25; i++) {

    int hourToInsert = currentHour + i;

    NSString *insertString = @"";

    if (hourToInsert == 12 || hourToInsert == 36) {

        //special case for noon
        insertString = @"12PM";

        [units addObject:insertString];

    } else if (hourToInsert == 24) {

        //special case for midnight
        insertString = @"12AM";

        [units addObject:insertString];

    } else if (hourToInsert > 36) {

        //next day PM
        hourToInsert = hourToInsert - 36;

        insertString = [NSString stringWithFormat:@"%iPM", hourToInsert];

        [units addObject:insertString];

    } else if (hourToInsert > 24) {

        //next day
        hourToInsert = hourToInsert - 24;

        insertString = [NSString stringWithFormat:@"%iAM", hourToInsert];

        [units addObject:insertString];

    } else if (hourToInsert > 12) {

        hourToInsert = hourToInsert - 12;

        insertString = [NSString stringWithFormat:@"%iPM", hourToInsert];

        [units addObject:insertString];

    } else {

        insertString = [NSString stringWithFormat:@"%iAM", hourToInsert];

        [units addObject:insertString];

    }

}


texts:
I'm writing a ReST API Client Tester using VueJS.

I'm trying to have a really clean code, But I feel like it's too much,

Here is my store.js file, which I use it for Vuex and the application state management, all there variables I use to send a request are store here

import Vue from 'vue';
import Vuex from 'vuex';

Vue.use(Vuex);

export default new Vuex.Store({
  state: {
    globals: {
      methods: ['GET', 'POST', 'PUT', 'DELETE'],
    },
    request: {
      method: 'GET',
      url: 'http://example.com',
      body: {},
      headers: {},
    },
  },
  mutations: {

    // Change Methods
    changeMethod(state, method) {
      state.request.method = method;
    },
    changeURL(state, url) {
      state.request.url = url;
    },
    changeBody(state, body) {
      state.request.body = body;
    },
    changeHeaders(state, headers) {
      state.request.headers = headers;
    },

    // Add to Data Methods
    addToHeaders(state, payload) {
      state.request.headers[payload.key] = payload.value;
    },
    addToBody(state, payload) {
      state.request.body[payload.key] = payload.value;
    },
    // Delete from Data Methods
    deleteFromHeaders(state, key) {
      delete state.request.headers[key];
    },
    deleteFromBody(state, key) {
      delete state.request.body[key];
    },

    // Reset Methods
    resetMethod(state) {
      state.request.method = 'GET';
    },
    resetURL(state) {
      state.request.url = '';
    },
    resetBody(state) {
      state.request.body = {};
    },
    resetHeaders(state) {
      state.request.headers = {};
    },

    // Reset request Method
    resetRequest(state) {
      state.request = {
        method: 'GET',
        url: '',
        body: {},
        headers: {},
      };
    },

  },
  actions: {

  },
});

As you can see, I'm sticking to a rule which says, each function should only do one thing and nothing more, I'm not sure if I'm using it right or now, But with this amount of code, It seems a little ridiculous to me...

Let me know what you think? How can I improve this to have more readability and less LoC?

Am I doing it right or not?


texts: Find the highest unique element in an array

texts:
Here is my approach. Unique element means that element should present only once in the array.

import java.io.IOException;
import java.util.Comparator;
import java.util.Map;
import java.util.Scanner;
import java.util.TreeMap;
import java.util.Map.Entry;

public class Unique {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();

        // Used TreeMap to store data in descending order to return maximum unique value
        Map<Integer, Integer> map = new TreeMap<Integer, Integer>(
                new Comparator<Integer>() {
                    public int compare(Integer o1, Integer o2) {
                        return o2.compareTo(o1);
                    }
                });
        // Add into map if input is not present. If already present, increase count
        for (int i = 0; i < n; i++) {
            int input = sc.nextInt();
            if (map.containsKey(input))
                map.put(input, map.get(input) + 1);
            else
                map.put(input, 1);

        }

        // Check for a entry with value 1. If not present print -1 else traverse
        // the map and print first key with value 1.
        if (map.containsValue(1)) {
            for (Entry<Integer, Integer> entry : map.entrySet()) {

                if (entry.getValue() == 1) {
                    System.out.print(entry.getKey() + " ");
                    break;
                }

            }
        } else
            System.out.println(-1);

    }
}

Sample input:

n=5
9 8 8 9 5

Desired Output:

5

Please critique my approach and suggest better way to solve this problem.


texts:
Below I present to you an IQueryable LINQ to SQL query (used with NHibernate).
I have tried to simplify this query but I could not do it.
I want to run a query for searching information.

Options:

search on source or target
search with match case or not
search match exact or not

The query it seems to work but there is much if/else branching.

Is it possible to simplify it?

        if (concordanceSearchOptions.SearchInSource)
        {
            if (concordanceSearchOptions.MatchCase)
            {
                if (concordanceSearchOptions.MatchExact)
                {
                    getByQueryable = getByQueryable.Where(p => p.SourceSegment.Equals(concordanceSearchOptions.SearchText));
                }
                else
                {
                    getByQueryable = getByQueryable.Where(p => p.SourceSegment.Contains(concordanceSearchOptions.SearchText));
                }
            }
            else
            {
                if (concordanceSearchOptions.MatchExact)
                {
                    getByQueryable = getByQueryable.Where(p => p.SourceSegment.ToLower().Equals(concordanceSearchOptions.SearchText.ToLower()));
                }
                else
                {
                    getByQueryable = getByQueryable.Where(p => p.SourceSegment.ToLower().Contains(concordanceSearchOptions.SearchText.ToLower()));
                }
            }
        }
        else
        {
            if (concordanceSearchOptions.MatchCase)
            {
                if (concordanceSearchOptions.MatchExact)
                {
                    getByQueryable = getByQueryable.Where(p => p.TargetSegment.Equals(concordanceSearchOptions.SearchText));
                }
                else
                {
                    getByQueryable = getByQueryable.Where(p => p.TargetSegment.Contains(concordanceSearchOptions.SearchText));
                }
            }
            else
            {
                if (concordanceSearchOptions.MatchExact)
                {
                    getByQueryable = getByQueryable.Where(p => p.TargetSegment.ToLower().Equals(concordanceSearchOptions.SearchText.ToLower()));
                }
                else
                {
                    getByQueryable = getByQueryable.Where(p => p.TargetSegment.ToLower().Contains(concordanceSearchOptions.SearchText.ToLower()));
                }
            }
        }


texts: Converting an image from polar to cartesian coordinates

texts:
I have the following code which has too many loops inside it (almost 13 billion). This code is actually for image processing. I am first making a matrix of dimension 1024*360. This is the value of the projection data given to me. f is my image in the polar coordinate. The first loop gives me f in the polar-coordinate. f[r,phi] where r varies from 0 to 1024 and phi varies from 0 to 90. h is a filter that I have used in the first loop. In the second I am converting the image from polar coordinate to Cartesian coordinate. The image in the Cartesian coordinate is of dimension 725*725. I  have set the range of x and y as (1,726).

I doubt that it is right too. But when I had it as (0,725) earlier, it showed me error "dividing with zero" as I use atany(y/x). Hence I changed it. And after that I am converting the image to grayscale. I am new to Python and I guess my algorithm seems to slow down the execution. Is there any other way to avoid these loops? I haven't been able to display the image until now.

from __future__ import division
import scipy.io
import numpy as np
import pylab as pl
import matplotlib.pyplot as plt
import math
from math import sin
from math import pow
from math import degrees
from math import atan
import Image

q = np.zeros((1024,360))

x = scipy.io.loadmat('/home/prakriti/Project/A.mat')
A = np.array((x.values()))
q[:,0:120] = A[0][240,:,:]
del x
del A

y = scipy.io.loadmat('/home/prakriti/Project/B.mat')
B = np.array((y.values()))
q[:,120:240] = B[0][240,:,:]
del y
del B

z = scipy.io.loadmat('/home/prakriti/Project/C.mat')
C = np.array((z.values()))
q[:,240:360] = C[0][240,:,:]
del z
del C

f = np.zeros((1024,90))  #In polar co-ordinate

D = 0.28                #Source to isocenter distance
h = np.zeros(1024)
h[0:512] = np.linspace(0,1,512)
h[513:] = np.linspace(1,0,511)

for r in range(0,1024) :
  for phi in range(0,90) :
    for b in range(0,360) :
      for s in range(0,1024) :
        U = (D + r*sin(b-phi))/D
        l = math.pow(U,-2)
        k = D/(math.pow((math.pow(D,2)+math.pow(s,2)),0.5))
        f[r,phi] = 0.5*l*k*q[s,b]*h[s]

I =np.zeros((725,725))

for x in range(1,726) :
  for y in range(1,726) :
    r = math.trunc(math.pow((math.pow(x,2)+math.pow(y,2)),0.5))
    phi = math.trunc(math.degrees(math.atan(y/x)))
    I[x,y] = f[r,phi]

I8 = (((I - I.min()) / (I.max() - I.min())) * 255.9).astype(np.uint8)
img = Image.fromarray(I8)
img.save("Fanbeamreconstruction.png")
im = Image.open("Fanbeamreconstruction.png")
im.show()

Someone also pointed out that may be in looping over b and s I am overwriting f[r,phi] 360*1024 times and only the last one is used. What could this possible mean?


texts: Enhancing performance using DataParallel

texts:
I have written the following code to practice parallelizing a PyTorch code on GPUs:
import math
import torch
import pickle
import time

import numpy as np
import torch.optim as optim

from torch import nn

print('device_count()', torch.cuda.device_count())
for i in range(torch.cuda.device_count()):
    print('get_device_name', torch.cuda.get_device_name(i))

def _data(dimension, num_examples):
    num_mislabeled_examples = 20

    ground_truth_weights = np.random.normal(size=dimension) / math.sqrt(dimension)
    ground_truth_threshold = 0

    features = np.random.normal(size=(num_examples, dimension)).astype(
        np.float32) / math.sqrt(dimension)
    labels = (np.matmul(features, ground_truth_weights) >
              ground_truth_threshold).astype(np.float32)
    mislabeled_indices = np.random.choice(
        num_examples, num_mislabeled_examples, replace=False)
    labels[mislabeled_indices] = 1 - labels[mislabeled_indices]

    return torch.tensor(labels), torch.tensor(features)

class tools:
    def __init__(self):
        self.name = 'x_2'

    def SomeFunc(self, model, input_):
        print(model.first_term(input_)[0])    # change to model.module.first_term when the flag is True

class predictor(nn.Module):
    def __init__(self, dim):
        super(predictor, self).__init__()
        self.weights = torch.nn.Parameter(torch.zeros(dim, 1, requires_grad=True))
        self.threshold = torch.nn.Parameter(torch.zeros(1, 1, requires_grad=True))

    def first_term(self, features):
        return features @ self.weights

    def forward(self, features):
        return self.first_term(features) - self.threshold

class HingeLoss(nn.Module):

    def __init__(self):
        super(HingeLoss, self).__init__()
        self.relu = nn.ReLU()

    def forward(self, output, target):
        all_ones = torch.ones_like(target)
        labels = 2 * target - all_ones
        losses = all_ones - torch.mul(output.squeeze(1), labels)

        return torch.norm(self.relu(losses))

class function(object):
    def __init__(self, epochs):

        dim = 10
        N = 100
        self.target, self.features = _data(dim, N)

        self.epochs = epochs
        self.model = predictor(dim).to('cuda')
        self.optimizer = optim.SGD(self.model.parameters(), lr=1e-3)
        self.target = self.target.to('cuda')
        self.features = self.features.to('cuda')
        self.loss_function = HingeLoss().to('cuda')

        self.tools = tools()

    def train(self):

        self.model.train()
        for epoch in range(self.epochs):
            self.optimizer.zero_grad()
            output = self.model(self.features)
            # self.tools.SomeFunc(self.model, self.features)
            print(output.is_cuda)
            loss = self.loss_function(output, self.target)
            loss.backward()
            print('For epoch {}, loss is: {}.'.format(epoch, loss.item()))
            self.optimizer.step()

def main():
    model = function(1000)
    print(torch.cuda.device_count())
    if False: # This is Flag
        if torch.cuda.device_count() > 1:
            model.model = nn.DataParallel(model.model)
    t = time.time()
    model.train()
    print('elapsed: {}'.format(time.time() - t))

if __name__ == '__main__':
    main()

As far as I understand setting the flag to True should fix the thing, but my run time increases from 1 sec to 15 sec's. I was wondering how to improve the performance.


texts:
A non-empty zero-indexed array A consisting of N integers is given.
  Array A represents numbers on a tape.

  Any integer P, such that 0 < P < N, splits this tape into two
  non-empty parts: A[0], A[1], ..., A[P − 1] and A[P], A[P + 1], ...,
  A[N − 1].

  The difference between the two parts is the value of:

|(A[0] + A[1] + ... + A[P − 1]) − (A[P] + A[P + 1] + ... + A[N − 1])|

  Write a function:

int solution(int A[], int N);

  that, given a non-empty zero-indexed array A of N integers, returns
  the minimal difference that can be achieved.

  Complexity:

  expected worst-case time complexity is \$\mathcal{O}(N)\$;
  expected worst-case space complexity is \$\mathcal{O}(N)\$, beyond input storage (not counting the storage required for input arguments).

Here is my code..

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class TapeEquilibium {

    public static void main(String[] args) {
        int[] a = {3,1,2,4,3};
        System.out.println(solution(a));
    }

    public  static int solution(int[] A){

        long totalSum = 0;

        List<Holder> list = new ArrayList<TapeEquilibium.Holder>();
        for(int i=0;i<A.length;i++){
            totalSum = totalSum + A[i];
        }
        long start = A[0];
        for(int i=1;i<A.length;i++){
            Holder holder = new Holder(i,Math.abs((2*start)-totalSum));
            list.add(holder);
            start = start+A[i];
        }

        Collections.sort(list);

        return (int)(list.get(0).sum);

    }

    static class Holder implements Comparable<Holder>{

        int p;
        long sum;

        public Holder(int p, long sum){
            this.p = p;
            this.sum = sum;
        }

        public int compareTo(Holder o) {
            if(this == o) return 0;
            else{
                return new Long(this.sum).compareTo(new Long(o.sum));
            }
        }
    }
}


texts: Changing background color of HTML elements based on user input

texts:
This is jQuery code which works like this: depending on a user choice it changes the color and background of some elements in the DOM.

The behavior is ok, is doing exactly what I want.

And as you may see, there is some code repeated. What's the best way to keep a good performance by doing a function in order to avoid repeating code?

function ArticleQuiz($el){
    this.$el = $el;
    this.answer = this.$el.data('answer');
    this.answerContainer = this.$el.find('.answer-container');
    this.result = this.$el.find('.result');
    this.correctAnswer = this.$el.find('.correct-answer');
    this.incorrectAnswer = this.$el.find('.incorrect-answer');
    this.quizLogic();
    return this;
}

ArticleQuiz.prototype.quizLogic = function(){
    var THIS = this;
    var answer;

    $('.masthead-article-quiz').parent().css('background', '#eee');
    $('.quiz-cols a', this.$el).click(function(e) {
        THIS.target = $(e.target);
        e.preventDefault();
        // exit if choice already made: users can't change their pick
        if ($(this).parents('.quiz-cols').parent().find('.white-font').length) return;
        // set class according to data-answer:
        if (THIS.target.hasClass('icon-false-shape')) {
            THIS.answerContainer.show();
            $(this).addClass('background-' + ((THIS.answer === false) ? 'green' : 'red')).addClass('white-font');
            THIS.result.addClass('font-' + ((THIS.answer === false) ? 'green' : 'red'));
            answer =  THIS.answer ? THIS.incorrectAnswer.show() : THIS.correctAnswer.show();
        }
        if (THIS.target.hasClass('icon-true-shape')) {
            THIS.answerContainer.show();
            $(this).addClass('background-' + ((THIS.answer === true) ? 'green' : 'red')).addClass('white-font');
            THIS.result.addClass('font-' + ((THIS.answer === true) ? 'green' : 'red'));
            answer =  !THIS.answer ? THIS.incorrectAnswer.show() : THIS.correctAnswer.show();
        }
    });
    return THIS;
};


texts: C++ Template to implement the Factory Pattern

texts:
Design

A template class that will create a concrete instance of an interface class when given the name (as a string) of the concrete class.

This design is often seen in code, so the purpose of this class is to reduce the boilerplate code needed to write a factory class.

The template class will be used like this:

using MyFactory = factory<MyInterfaceType, MyType_1, MyType_2, MyType_3>;

int main() {
    auto ptr = MyFactory::create("MyType_1");
    ptr->doSomething();
}

There will be a static assert to check that all of the concrete types inherit from the interface type and the create method can accept an optional argument to describe the return type if no class matching the id is found.

Implementation

template<typename interface_type, typename... products>
struct factory {

    template<typename Class>
    struct LabledClass {
        std::string_view label = to_string<Class>();
        Class data;
    };

    using labled_classes = std::tuple<LabledClass<products>...>;

    static std::unique_ptr<interface_type> create(const std::string_view& id, std::unique_ptr<interface_type> default_type = nullptr) {
        std::unique_ptr<interface_type> result = std::move(default_type);

        //checl all products inherit from interface_type
        std::apply([](auto&&... tuple_elem) {
            ((static_check<decltype(tuple_elem.data)>()), ...);
        }, labled_classes{} );

        //if product matches id, return a new instance of that product
        std::apply([&result, &id](auto&&... tuple_elem) {
            (( tuple_elem.label == id ? result = std::make_unique<decltype(tuple_elem.data)>() : result ), ...);
        }, labled_classes{} );

        return result;
    }

private:
    template<typename product>
    static void static_check() {
        static_assert(std::is_base_of<interface_type, product>::value, "all products must inherit from interface_type");
    }
};

This requires the function to_string<Class>() which does not yet exist in the c++ standard, but can be implemented on GCC or Clang like so:

template<typename Class>
constexpr std::string_view to_string() {
    std::string_view str = __PRETTY_FUNCTION__;
    auto first = str.find("= ");
    std::string_view str2 = str.substr(first + 2);
    auto last = str2.find(";");
    str2.remove_suffix(str2.length() - last);
    return str2;
}

Example use

#include <iostream>
#include "factory.h"

struct Animal {
    virtual void makeNoise() const = 0;
};

struct Dog : Animal {
    virtual void makeNoise() const override{
        std::cout << "Woof" << std::endl;
    }
};

struct Cat : Animal {
    virtual void makeNoise() const override{
        std::cout << "Meow" << std::endl;
    }
};

struct Duck : Animal {
    virtual void makeNoise() const override{
        std::cout << "Quack" << std::endl;
    }
};

struct NullAnimal : Animal {
    virtual void makeNoise() const override{
        std::cout << "?" << std::endl;
    }
};

using AnimalFactory = factory<Animal, Dog, Cat, Duck>;

int main() {
    auto animal = AnimalFactory::create("Dog");
    animal->makeNoise();
}

I have tested this with GCC 9.01 and it works


texts:
This is a class representing an exponent. Its main purpose is to deal with logarithmic quantities.
template<std::floating_point Representation>
class Exponent
{
    public:
        using representation = Representation;

        struct Literal{};

        constexpr explicit Exponent(representation val, Literal):m_val{val}
        {}

        constexpr explicit Exponent(representation val):m_val{std::log2(val)}
        {}

        constexpr representation value() const
        {
            return m_val;
        }

        constexpr operator representation() const
        {
            return std::exp2(m_val);
        }

        constexpr Exponent& operator+=(Exponent other)
        {
            m_val += other.m_val;
            return *this;
        }

        constexpr Exponent& operator-=(Exponent other)
        {
            m_val -= other.m_val;
            return *this;
        }

        constexpr Exponent& operator/=(Exponent other)
        {
            m_val /= other.m_val;
            return *this;
        }

        constexpr Exponent& operator*=(Exponent other)
        {
            m_val *= other.m_val;
            return *this;
        }

        constexpr auto operator<=>(Exponent const&) const = default;

    private:
        representation m_val;
};

template<std::floating_point T>
constexpr Exponent<T> operator+(Exponent<T> a, Exponent<T> b)
{
    return a+=b;
}

//...

What I am not sure about is how to properly disambiguate between data converting casts (taking logarithm vs exponent) operations and pure value casts (simple assign).
Another question is if the API should emulate real values. With the above API:
constexpr double multiply(double a, double b)
{return Exponent{a} + Exponent{b};}

static_assert(multiply(2.0, 3.0) == 6.0);

However, if you define operator* on exponents to behave as addition, you would instead simply write:
constexpr double multiply(Exponent a, Exponent b)
{return a*b;}

static_assert(multiply(2.0, 3.0) == 6.0);


texts:
I have a JSON array or literal (passes through JSON.parse).

Requirement: an array of tasks which contains operations which are key/value pairs.

Array of tasks > Array of operations (array of operations at times will contain duplicate key/value pairs)

[
    [
          {
            resize: [1200, 1200]
          }, {
            moveTo: "dest/nick"
          }, {
            rename: "{base}-12.{ext}"
          }, {
            toWeb: true
          }, {
            rename: "{base}.{ext}"
          }
        ], [
          {
            resize: [1000, 1000]
          }, {
            rename: "{base}-10.{ext}"
          }
        ]
      ]

The code works and I simply want to know if there is a better way of doing this. I had to wrap the individual operations with {} so that the duplicate keys wouldn't overwrite each other.


texts:
For pure practice purposes, I started implementing different sorting algorithms in modern C++ in a standard library style way (i.e. using templates on iterators). This is my version of bubble sort.

I do not really have any specific criteria I would like to have the code reviewed under, but instead appreciate any hints I can get, be they on performance, coding style, expressiveness etc.

The whole implementation lives inside the file bubble_sort.h:

#pragma once

#include <utility>

template<typename Iterator, typename Comparator>
void bubble_sort(Iterator begin, Iterator end, Comparator cmp) {
    bool swapped;
    do {
        swapped = false;
        for (auto i = begin + 1; i != end; ++i) {
            auto& val0 = *i;
            auto& val1 = *(i - 1);
            if (cmp(val0, val1)) {
                std::swap(val1, val0);
                swapped = true;
            }
        }
    } while (swapped);
}

template<typename Iterator>
void bubble_sort(Iterator begin, Iterator end) {
    bubble_sort(begin, end, [] (const typename Iterator::value_type& v0,
                const typename Iterator::value_type& v1) { return v0 < v1; });
}

For reference, I also provide to you a file containing a main-method which sorts a small std::vector of random unsigneds in ascending as well as descending order:

#include <random>
#include <vector>
#include <iostream>

#include "bubble_sort.h"

int main() {
    std::vector<unsigned> vec;
    std::default_random_engine engine;
    std::uniform_int_distribution<unsigned> distribution(0, 10000);
    for (std::size_t i = 0; i < 100; ++i) {
        unsigned num = distribution(engine);
        std::cout << num  << ' ';
        vec.push_back(num);
    }
    std::cout << "\n\n";

    bubble_sort(vec.begin(), vec.end());

    for (unsigned e : vec) {
        std::cout << e << ' ';
    }
    std::cout << "\n\n";

    bubble_sort(vec.begin(), vec.end(), [] (unsigned v0, unsigned v1) {
            return v0 > v1;
        });

    for (unsigned e : vec) {
        std::cout << e << ' ';
    }
    std::cout << '\n';
}


texts: Reading properties from file during standalone application startup

texts:
I've a standalone Java application, which basically starts and manages two socket servers. I'd like to configure server ports in a .properties file using the following class.

class ApplicationConfig {

    private static final Logger     LOG            = Logger.getLogger(ApplicationConfig.class.getName());
    private static final Properties APP_PROPERTIES = new Properties();

    static int defaultEventServerPort  = 9090;
    static int defaultClientServerPort = 9099;

    static {
        try {
            APP_PROPERTIES.load(ClassLoader.class.getResourceAsStream("/app.properties"));
            String eventServerPort = APP_PROPERTIES.getProperty("server.event.port");
            String clientServerPort = APP_PROPERTIES.getProperty("server.client.port");

            if (isValidNumeric(eventServerPort)) {
                defaultEventServerPort = Integer.valueOf(eventServerPort);
            }
            if (isValidNumeric(clientServerPort)) {
                defaultClientServerPort = Integer.valueOf(clientServerPort);
            }
        } catch (IOException ex) {
            LOG.log(
                    Level.WARNING,
                    "Unable to load server ports from properties file, going to use default port {0} for event server and {1} for client server",
                    new Object[]{defaultEventServerPort, defaultClientServerPort}
            );
        }
    }

   private static boolean isValidNumeric(String v) {
        if (v == null || v.length() == 0) {
            return false;
        }
        for (int i = 0; i < v.length(); i++) {
           if (!Character.isDigit(v.charAt(i))) {
              return false;
           }
        }
        return true;
   }
}

I really hate ApplicationConfig class, the static initialization block bothers me, but I am not able to find a better idea yet. How you would suggest to modify it?

And here is my main class

public class Application {

private static final Logger LOG = Logger.getLogger(Application.class.getName());

    private Application() {}

    public static void main(String[] args) {
        try {
            ExecutorService pool = Executors.newCachedThreadPool();

            EventServer eventServer = new EventServer(new Configuration(ApplicationConfig.defaultEventServerPort));
            ClientServer clientServer = new ClientServer(new Configuration(ApplicationConfig.defaultClientServerPort));

            pool.submit(eventServer);
            pool.submit(clientServer);
        } catch (IOException e) {
            LOG.log(Level.SEVERE, "Unable to start servers", e);
        }
    }
}


texts: Follow up to Top Active Answerers on Stack Exchange site

texts:
This is a follow up to Top Active Answerers on a Stack Exchange site

Actual SEDE Query --> Top Active Answerers on site

Do I have a good understanding of the RANK function?  It seems pretty simple.

Should I separate this into 2 queries or is having 2 rank columns an acceptable thing?  If it is acceptable have I displayed it properly? or does it look messy?

--@DaysSinceActivity is the amount of days that you would like to scan for activity
--@NumberOfUsers is the number of users you want to return.

SELECT
    TOP ##NumberOfUsers:int?1000##
    Users.Id AS [User Link],
    Users.DisplayName AS UserName,
    COUNT(Posts.Id) AS [Total Answers],
    RANK() OVER (ORDER BY (COUNT(Posts.Id)) DESC) AS [Total Answer Rank],
    CAST(AVG(CAST(Score AS float)) AS NUMERIC(6,2)) AS [Average Answer Score],
    RANK() OVER (ORDER BY (CAST(AVG(CAST(Score AS float)) AS NUMERIC(6,2))) DESC) AS [Avg Score Ranking]
FROM
    Posts
INNER JOIN
    Users ON Users.Id = OwnerUserId
WHERE
    PostTypeId = 2
    AND CommunityOwnedDate IS NULL
    AND ClosedDate IS NULL
    AND Users.LastAccessDate > DATEADD(DAY, -##DaysSinceActivity:int?31##, GETDATE())
GROUP BY
    Users.Id, Users.DisplayName
HAVING
    COUNT(Posts.Id) > 10
ORDER BY
    [Average Answer Score] DESC

The Ranking on those two rows seems really redundant because they are calculated fields.

The DisplayName in the GROUP BY is because I didn't know where else to put that, when I removed it I got an error saying

  Column 'Users.DisplayName' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.

I will probably use it in the ORDER BY statement, I think I can get away with that.