Adding Reversed Numbers - ADDREV on SPOJ Today I tried solving this problem on SPOJ, in which you reverse the digits of two numbers, add them, and print the reversed digits of the sum.  (When reversing, leading zeroes in the result should be dropped, and trailing zeroes in the result shouldn't happen.)

I used C++ to write the code for this problem. My code got accepted in the first go and I was happy about it but I feel my code is way too long for a problem of this kind. I would like some suggestions on how to reduce the code and make it more readable at the same time.

#include<cstdio>
#include<string>
#include<vector>
#include<cstring>
#include<sstream>
#include<iostream>
#include<algorithm>

using namespace std;

#define ALL(C)  (C).begin(), (C).end()
#define LN(str) (int)(str).length()

// this function gets the reversed form of the input number, the function is coded assuming that the input number has both trailing and leading 0's
string getReverseNum(string& num) {

  string reversedNum = "";
  // find the index of last leading 0
  int index1 = -1;
  for(int i = 0; i < LN(num); ++i) {
     if(num[i] == '0')
        continue;
     else {
    index1 = i;
    break;
     }
  }

  // find the index of the first trailing 0
  int index2 = -1;
  for(int i = LN(num)-1; i >= 0; --i) {
    if(num[i] == '0')
     continue;
    else {
       index2 = i+1;
       break;
    }
  }

  reversedNum = num.substr(index1, index2-index1);

  if(reversedNum == "")
    return "0";
  return reversedNum;
}

// this function is used to convert an integer to a string
string convertIntToString(int num) {

  ostringstream oss;
  oss << num;
  return oss.str();
}

// this function is used to add the two input numbers and return the result as a string
string addNumbers(string& num1, string& num2) {

  int carry = 0;
  string result = "";

  for(int i = 0; i < LN(num2); ++i) {
    int dig1 = num1[i]%48;
    int dig2 = num2[i]%48;
    int temp = dig1+dig2+carry;
    carry = temp/10;
    result += convertIntToString(temp%10);
  }

  for(int i = LN(num2); i < LN(num1); ++i) {
    int dig = num1[i]%48;
    int temp = dig+carry;
    carry = temp/10;
    result += convertIntToString(temp%10);
  }

  if(carry != 0)
   result += convertIntToString(carry);

  return getReverseNum(result);
}

// this function is used to return the reversed sum of the two input numbers it receives as parameters
string getReversedSum(string& num1, string& num2) {

  // first we get the reverse of two numbers
  string reversedNum1 = getReverseNum(num1);
  string reversedNum2 = getReverseNum(num2);

  string reversedNum = "";

  int len1 = LN(reversedNum1), len2 = LN(reversedNum2);

  if(len1 < len2)
    return addNumbers(reversedNum2, reversedNum1);
  return addNumbers(reversedNum1, reversedNum2);

}

int main() {

  // this variable stores the number of test cases on which the program is run
  int N;
  cin >> N;

  // clear the input stream
  cin.ignore();

  // program execution begins here
  while(N--) {
    string num1, num2;
    cin >> num1 >> num2;
    cout << getReversedSum(num1, num2) << endl;
  }
  return 0;
}

Code is hosted here.

A few notes:

Why do you have a bunch of extra headers at the top?  This extra cruft (such as the vector class), is going to cost you a bit of extra compile time for nothing plus it adds to the length of your code.  Cut back on the stuff you don't need; I found you only needed two of the headers out of the seven you have in your code.
Here are the woes of using namespace std;.  Please try to get into the habit of not using it.
Your #define's are interesting, but I found them a bit useless really.  They somewhat obscure the readability of the program as well, and should be removed IMO.
Your getReverseNum() function really just reverses a std::string object... but there's a standard library function std::reverse() that does this task for you (it's likely that this function is more efficient as well).
In C++, you should almost never use out parameters (variables taken by reference and used to return a value from a function), you can read this excellent article by Eric Niebler. There are few cases where out parameters can make sense:

When you want your return to be fast. And even then, return value optimization and move semantics may still be faster.
When you have several output values. For example, you want to assign a value to a function and return whether it succeeded:

bool assign(int from, int& to)
{
    if (from != 0)
    {
        to = from;
        return true;
    }
    return false;
}

But even for this situation, there are better solutions such as boost:optional to return both a value and whether it succeeded or not. And if you need several error values, use exceptions. And if you need to actually return several values, you general want to pack them into a dedicated struct or a std::tuple.
Input-output parameters: sometimes, you want to take a parameter, read from it, and then write to it again. That is still a valid use case (but these are not strict out parameters anymore).

Overall, for your case it would be better to remove the reference parameters as they serve no purpose really and could be hurting performance.
Your addNumbers() function could be simplified with the use of the standard functions std::stoi, std::to_string, and std::string::erase, along with our old friend std::reverse.
Your variable N in your main() function is somewhat confusing as to what it's purpose is at first.  I found it better named as cases.

Final Code:

#include <string>
#include <iostream>

std::string getReversedSum(std::string num1, std::string num2)
{
    // first we reverse the two numbers
    std::reverse(std::begin(num1), std::end(num1));
    std::reverse(std::begin(num2), std::end(num2));

    // convert the strings to ints so we can add them, then back to a string
    std::string sum = std::to_string(std::stoi(num1) + std::stoi(num2));

    // reverse the string and erase the leading zeros
    std::reverse(std::begin(sum), std::end(sum));
    sum.erase(0, sum.find_first_not_of('0'));
    return sum;
}

int main()
{
    int cases = 0;
    std::cin >> cases;

    // clear the input stream
    std::cin.ignore();

    while(cases--)
    {
        std::string num1;
        std::string num2;
        std::cin >> num1 >> num2;
        std::cout << getReversedSum(num1, num2) << std::endl;
    }
}


Filtering JSONArray by Branding & Modelling I have a small function that takes in a list of JSON objects that has the format below. The function below that wants to see if the brand and model of car passed to it can be matched against the List parameter called jsonfiltersList. The code I have works, but being somewhat new to coding and Java I wanted to know if I can optimize the code snippet to make it more compact somehow. Any thoughts?

{
  auto_filters : [
   {
      "brand" : "Toyota"
   },
   {
      "brand" : "Honda",
      "models" : [ "Civic", "Accord" ]
   }
  ]
}

And the code:

  public static boolean filterMatch(String brand, String model, ArrayList<JSONObject> jsonFiltersList) {
    boolean brandMatch = false;
    boolean modelMatch = false;
    if ((jsonFiltersList == null) || (jsonFiltersList.size() < 1)) return true;
    try {
        for (JSONObject j : jsonFiltersList) {
                if (j.get("brand").equals(brand)) {
                    brandMatch = true;
                }
                if (brandMatch) {
                    JSONArray jArr = null;
                    if (j.has("models")) {
                        jArr = (JSONArray) j.get("models");
                    }

                        ArrayList<String> modelsArr = new ArrayList<String>();
                        if (jArr != null) {
                            for (int i = 0; i < jArr.length(); i++)
                                modelsArr.add(jArr.get(i).toString());
                        if (modelsArr.contains(model)) {
                            modelMatch = true;
                                break;
                        }
                    } else {
                        modelMatch = true;
                        break;
                    }
            }
            brandMatch = false;
        }
    } catch(Exception e) {
        e.printStackTrace();
    }
    return brandMatch && modelMatch;
}

As it happens I have been working with JSON formatted data a little bit recently. I have some ideas that will help you simplify your code.

As for the efficiency, performance wise it looks good. I don't think it can go much faster. In terms of code structure though, there's a few things that can help.

I'll put together a laundry-list of items, and then follow it up with your code restructured...

make your parameters final when you can. It helps with discipline, and occasionally performance too.
Use interfaces instead of concrete classes if you can. The input Parameter ArrayList<JSONObject> should be reduced to an interface, but, not just List, and not even Collection, but Iterable. You should have Iterable<JSONObject>.... which means pretty much anything that has an iterator() method.
jsonFiltersList.size() < 1 is better expressed as jsonFiltersList.isEmpty()
Don't use parenthesis unless they're needed:

if ((jsonFiltersList == null) || (jsonFiltersList.size() < 1))

should be:

if (jsonFiltersList == null || jsonFiltersList.isEmpty())

1-liners should be expressed with a full braced block:

if ((jsonFiltersList == null) || (jsonFiltersList.size() < 1)) return true;

should be

if (jsonFiltersList == null || jsonFiltersList.isEmpty()) {
    return true;
}

The check above shows that you know how to return early (you don't need to wait for the end to return... so, use that to your advantage. Return when you have a result.
You have redundant brandMatch checks:

if (j.get("brand").equals(brand)) {
    brandMatch = true;
}
if (brandMatch) {
    .....

can simply be:

if (j.get("brand").equals(brand)) {
    .....

There is no need to populate the full models array... you can just return if you find a match...
Don't catch Exception, catch JSONException because that's what's thrown.

Putting this all together, your code ends up like:

public static boolean filterMatch(final String brand, final String model,
        final Iterable<JSONObject> jsonFiltersList) {
    if (jsonFiltersList == null) {
        return true;
    }
    try {
        for (JSONObject j : jsonFiltersList) {
            if (j.get("brand").equals(brand)) {
                if (!j.has("models")) {
                    return true;
                }
                JSONArray jArr = (JSONArray) j.get("models");
                if (jArr == null) {
                    return true;
                }
                for (int i = 0; i < jArr.length(); i++) {
                    if (model.equals(jArr.get(i).toString())) {
                        return true;
                    }
                }
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return false;
}


Solving Project Euler challenge I wanted to consolidate solutions to disparate problems into a single program. I am worried that there is a interface, command pattern, or dictionary solution to what will become a massive switch statement here.  However, the main in this program is essentially a meta-program which would switch between the miniature programs that it links to.

static void Main(string[] args)
{
    int eulerNumber;

    Console.WriteLine("Please enter the number of the Problem you want to solve.");

    while (!int.TryParse(Console.ReadLine(), out eulerNumber))
    {
        Console.WriteLine("Please enter a valid number.");
        Console.WriteLine();
        Console.WriteLine("Please enter the number of the Problem you want to solve.");
    }
    switch (eulerNumber)
    {
        case 1:
        //solve problem 1.
        break;

        case 2:
        //solve problem 2.
        break;
        case 3:
        //solve problem 3.

        break;
        etc. etc. etc.
    }
}

This is not an elegant solution, but it seems to mirror the situation quite well, as I see it.

Should I scratch this approach?  It seems to me to violate OCP but at the same time, it isn't chaotic, and isn't that much to keep track of, - just tack one more case onto the end, create a new class, and another problem is functional.  Should I look into some other structure to make it easier to modify?

If I were to solve this, adding the new code to the switch seems to me like overkill.

I would try writing an application that uses plugins in a searchable directory.
Then you solve each problem in its own plugin and the main program just consists of the logic to find and execute the plugins.

Of course to enhance finding the plugins there some possible designs:

Naming the plugin after the solved problem

Name the plugin file by a given structure so it is obvious which problem is solved:

ep-001.dll
ep-002.dll
...

That has the problem of forbidding user defined names, however it offers efficiency in that you can directly load only the needed plugin if you know the number.

Give the plugin class a problemNumber function

The other solution is to give the plugin class (that you will need anyway for a common interface to query for the solution) a function that returns the problem number.
This allows for arbitrarily named plugins, but also for duplicates and has the disadvantage of loading all plugins that are there to see if the one containing the requested solution is there.

Since you are not that much efficiency bound on this problem I would suggest the second alternative because it has a much nicer OO interface (IMHO).


Practice extracting variables Is better to use $id_name ( Class A Method b() ) OR $id_name_2 ( Class A Method c())?

<?php

Class A {

    function a(){
        $params = array(
            'id'=> 1,
            'name' => 'b',
        );

        $id_name = $this->b($params);
        $id_name_2 = $this->c($params);
    }

    function b($params){
        $id = $params['id'];
        $name = $params['name'];
        /*******

            Some code performing operations with $name and $id

        ********/

        $str = $id . $name;
        return $str;
    }

    function c($params){

        /*******

            Some code performing operations with $params['name'] and $params['id']

        ********/

        $str = $params['name'] . $params['id'];

        return $str;
    }

}

Using method c will have an side-effect if $params is modified. This is because arrays are passed by reference, and so any changes to $params will be visible to the caller when the function returns. Use b if you need to manipulate id or name, unless you intend to return the modifications to the caller.

Example:

$params = array('id' => 1, 'name' => 'b');
$this->d($params);
echo $params['id']; // outputs 2
...

function d($params) {
    $params['id']++;
}


Implementing basic graph theory functions in APL with matrices I had to solve three problems on graph theory that I solved by implementing a utility function and 3 functions, one for each of the problems.

The problem set defines the input for all my functions as a E+1 x 2 matrix (they call this an edge list) where the first row V E contains the number of vertices V in the graph and the number E of edges. The other E rows contain the endpoints of edges, so a row a b means there's an edge between vertices a and b.

Degrees is a function that retrieves the degree of a given vertex; e.g. Graphs.Degrees 8 2 ⍴ 6 7 1 2 2 3 6 3 5 6 2 5 2 4 1 4 gives 2 4 2 2 2 2;
DoubleDegrees is a function that, given a vertex v, retrieves the sum of the degrees of the neighbours of v (i.e. the vertices connected to v by an edge); e.g. Graphs.DoubleDegrees 5 2⍴ 5 4 1 2 2 3 4 3 2 4 gives 3 5 5 5 0;
ConnectedComponents is a function that counts the number of connected components in the graph; e.g. Graphs.ConnectedComponents 14 2⍴12 13 1 2 1 5 5 9 5 10 9 10 3 4 3 7 3 8 4 8 7 11 8 11 11 12 8 12 gives 3.

The functions work as expected.

I'm particularly interested in feedback on the AdjacencyMatrix and on the ConnectedComponents functions. Also, I believe the DoubleDegrees and ConnectedComponents functions are sub-optimal since they use simple algorithms but make use of matrix multiplications and search algorithms would be faster (in other languages). Is this still efficient code for APL? Or would a search-based solution be more efficient?

:Namespace Graphs
    ⍝ This particular namespace contains functions related to graphs.
    ⍝ For this namespace, an 'EdgeList' is a (v+1)×2 integer matrix, with v≥0, that encodes an undirected graph:
    ⍝   The first row (v e) is the number of vertices and edges in the graph;
    ⍝   The remaining e rows have two integers ≤v representing the end points of an edge.

    AdjacencyMatrix ← {
        ⍝ Compute the adjacency matrix of a graph.
        ⍝ Monadic function expecting an 'EdgeList'.

        vertices ← ⊃1↑⍵
        edges ← (↓⌽⍪⊢) 1↓⍵
        mat ← 0⍴⍨ 2⍴ vertices
        (1@edges) mat
    }

    Degrees ← {
        ⍝ Compute the degree of a vertex of a graph.
        ⍝ Dyadic function expecting integer on the left and 'EdgeList' on the right.
        ⍝   If the left integer is missing, return the degrees of all vertices.

        ⍺ ← ⍬
        adj ← AdjacencyMatrix ⍵
        ⍺⊃+/adj
    }

    DoubleDegrees ← {
        ⍝ Compute the double degree of a vertex of a graph.
        ⍝ Dyadic function expecting an integer on the left and 'EdgeList' on the right.
        ⍝   If the left integer is missing, return the double degrees of all vertices.

        ⍺ ← ⍬
        adj ← AdjacencyMatrix ⍵
        ⍺⊃+/ +.×⍨ adj
    }

    ConnectedComponents ← {
        ⍝ Computes the number of connected components of a graph.
        ⍝ Monadic function expecting 'EdgeList' as argument.

        adj ← AdjacencyMatrix ⍵
        v ← ⊃⍴ adj
        (1 1⍉adj) ← v⍴1     ⍝ Assign 1s to the main diagonal to accumulate all paths.
        accum ← (+.×)⍣(v-1)⍨ adj
        ≢∪ (1@(≠∘0)) accum
    }

:EndNamespace

I believe the DoubleDegrees and ConnectedComponents functions are sub-optimal since they use simple algorithms but make use of matrix multiplications and search algorithms would be faster (in other languages). Is this still efficient code for APL? Or would a search-based solution be more efficient?

Many APL implementations, especially Dyalog's, are heavily optimized around array operations using hardware SIMD instructions and parallel processing. Matrix multiplication is one of them.

Classical algorithms say that matrix multiplication is heavy, and a search algorithm will definitely do better. However, the uniqueness of APL gives very low constant factor to matrix multiplication (possibly even cutting down a dimension with enough parallelism), while it likely gives a high cost to a recursive search (interpreting a function over and over, and digging through a nested array).

In conclusion, I'd say matrix multiplication is the preferred way to solve such a task in APL. If in doubt, you can always implement both and compare the timings.

  I'm particularly interested in feedback on the AdjacencyMatrix and on the ConnectedComponents functions.

AdjacencyMatrix

AdjacencyMatrix ← {
    ⍝ Compute the adjacency matrix of a graph.
    ⍝ Monadic function expecting an 'EdgeList'.

    vertices ← ⊃1↑⍵          ⍝ can be simplified to `vertices ← ⊃⍵`
    edges ← (↓⌽⍪⊢) 1↓⍵       ⍝ consider putting atop `↓` outside of the train
                             ⍝ to clarify the intent:
                             ⍝ edges ← ↓ (⌽⍪⊢) 1↓⍵
    mat ← 0⍴⍨ 2⍴ vertices
    (1@edges) mat            ⍝ `1@edges⊢ mat` is more common way to split
                             ⍝ right operand from right arg
}

ConnectedComponents

ConnectedComponents ← {
    ⍝ Computes the number of connected components of a graph.
    ⍝ Monadic function expecting 'EdgeList' as argument.

    adj ← AdjacencyMatrix ⍵
    v ← ⊃⍴ adj                 ⍝ can be simplified to `v ← ≢adj`
    (1 1⍉adj) ← v⍴1            ⍝ can be simplified to `(1 1⍉adj) ← 1`
    accum ← (+.×)⍣(v-1)⍨ adj   ⍝ more on two last lines below
    ≢∪ (1@(≠∘0)) accum
}

Plain \$n\$th matrix power of an adjacency matrix \$M\$ gives the count of all length-\$n\$ paths between given two vertices. Adding the 1 to the diagonal of \$M\$ has the effect of adding loops to the graph, and its power gives the count of all length-\$≤n\$ paths. To describe the inner workings: For each pair of vertices \$(p, r)\$, +.× counts the paths \$p \rightarrow q \rightarrow r\$ for every intermediate vertex \$q\$ by multiplying × paths for \$p \rightarrow q\$ and \$q \rightarrow r\$, and collects all of them by sum +.

But right now we don't need the counts, we just need to know whether such a path exists. This gives rise to the Boolean matrix product ∨.∧. Analogously to +.×, ∨.∧ checks if any path \$p \rightarrow q \rightarrow r\$ exists by ∧-ing \$p \rightarrow q\$ and \$q \rightarrow r\$, and collects them by ∨ to indicate if some path exists. This has several benefits:

Boolean arrays and operations on them are more time- and space-efficient over integer arrays.
Finding all connected pairs is easier with the fixed point ⍣≡, while it can't be done with +.×.
You don't need an extra step (1@(≠∘0), though it can be simplified to 0≠or simply ×) to extract the exists from the counts.

Finally, if we change ∨.∧⍣≡⍨ to ∨.∧⍨⍣≡, we double the number of steps instead of advancing only one step every iteration (thus reducing the number of matmul operation from \$O(n)\$ to \$O(\log{n})\$). If we were calculating precisely the \$n\$th power, we would need repeated squaring that refers to \$n\$'s bit pattern. We don't need to care about it because we'll be iterating until it converges anyway.

Now the code looks like: (the variable v is removed since it is no longer used)

ConnectedComponents ← {
    adj ← AdjacencyMatrix ⍵
    (1 1⍉adj) ← 1
    accum ← ∨.∧⍨⍣≡ adj    ⍝ (f.g)⍣≡⍨ is same as f.g⍣≡⍨ due to parsing rule
    ≢∪ accum
}


Kotlin API - endpoint for users I am writing API in Kotlin - this is my first code in this language. I implemented a very primitive 'player' endpoint. I was wondering if I am doing everything ok (please don't mind the static variables - I will put them in the database later)

import org.springframework.http.ResponseEntity
import org.springframework.web.bind.annotation.*
import pl.domain.Player
import pl.rest.dto.PlayerDto

@RestController
@RequestMapping("/player")
class PlayerController {

    var players: Map<Long, Player> = mapOf(
            1L to Player(1L, "user1", "password1"),
            2L to Player(2L, "user2", "password2"),
            3L to Player(3L, "user3", "password3")
    )

    @GetMapping("/{id}")
    fun fetchPlayer(@PathVariable id : Long): ResponseEntity<Player> =
        players[id]?.let { ResponseEntity.ok(it) } ?: ResponseEntity.notFound().build()

    @PostMapping
    fun createPlayer(@RequestParam username: String, @RequestParam password : String): ResponseEntity<Player> {
        val playerId = (players.size + 1).toLong()
        val player = Player(playerId, username, password)
        players = players.plus(player.id to player)
        return ResponseEntity.ok(player)
    }

    @PutMapping
    fun updatePlayer(@RequestBody playerDto: PlayerDto): ResponseEntity<Player> {
        return players[playerDto.id]
                ?.apply {
                    username = playerDto.username ?: username
                    password = playerDto.password ?: password
                }?.let { ResponseEntity.ok(it) } ?: ResponseEntity.badRequest().build()
    }

    @DeleteMapping("/{id}")
    fun deletePlayer(@PathVariable id: Long): ResponseEntity<Nothing> {
        players = players.minus(id)
        return ResponseEntity.noContent().build()
    }

}

PlayerDto.kt:

class PlayerDto(var id: Long? = null, var username: String? = null, var password: String? = null)

Player.kt:

data class Player(var id: Long, var username: String, var password: String)

I've two recommendations that probably have more to do with design rather than with code. The first one is to change the API path to players:

@RequestMapping("/players")

I personally like to pluralize resource path names even if it's widely discussed.

The other one is to modify your PUT endpoint in order to also accept resources to be created. That way you would have a single endpoint which accepts a list of players, where players might be new or already have an id. For the first case, the system must create them, for the second, update them. That's also a mather of disussion in the net.


A "policy-based" design for a generic CUDA kernel I am faced with a design issue that has been discussed on SO several times, the most similar question being this one.  Essentially, I want polymorphism for a CUDA kernel in the form of a "generic" kernel that can apply a "user-supplied" function to every element in an array.

In C++, one could achieve this design by using abstract base classes.  Here's a minimal example:

#include<iostream>
#include<vector>

class AbstractFunction{
    public:
        virtual double EvalFunction(double) const = 0;
        virtual std::vector<double> operator()(std::vector<double>) const;
};

std::vector<double> AbstractFunction::operator()(std::vector<double> x) const{
    std::vector<double> y;
    for(auto it=x.begin();it!=x.end();++it)
        y.push_back(EvalFunction(*it));
    return y;
}

class ConcreteFunction : public AbstractFunction{
    public:
        double EvalFunction(double x) const {return x*x;}
};

int main()
{
    ConcreteFunction f;
    std::vector<double> x(2,1);
    x[0] = 1.0; x[1] = 2.0;
    std::vector<double> y = f(x);
    for(auto it=y.begin();it!=y.end();++it)
        std::cout<<*it<<std::endl;

    return 0;
}

As it turns out, this design is nearly impossible to port to CUDA, because CUDA doesn't play nicely with abstract base classes.  Fine.  After some digging (this question and this question were very useful), I have come up with the following design, which seems to work quite well, but I'd like to hear some critiques:

#include<iostream>

// The Managed class allows us to use CUDA unified memory.
// See http://devblogs.nvidia.com/parallelforall/unified-memory-in-cuda-6/
class Managed {
public:
  void *operator new(size_t len) {
    void *ptr;
    cudaMallocManaged(&ptr, len);
    cudaDeviceSynchronize();
    return ptr;
  }
  void operator delete(void *ptr) {
    cudaDeviceSynchronize();
    cudaFree(ptr);
  }
};

// Evaluate function on GPU
template<class FunType>
__global__ void EvalKernelGPU(double* x,double* y,int N,FunType* f)
{
    unsigned int tId = blockIdx.x*blockDim.x + threadIdx.x;
    if(tId<N)
        y[tId] = (*f)(x[tId]);
}

//Evaluator class: "policy-based" template design
template<class FunType>
class Evaluator : public FunType
{
    public:
        Evaluator() {f = new FunType;}
        Evaluator(FunType* fun_in) {f = fun_in;}
        double* EvalFunGPU(double* x,int N){
            double* y;
            cudaMallocManaged(&y,N*sizeof(double));
            dim3 block(512,1);dim3 grid((N+block.x-1)/block.x,1);
            EvalKernelGPU<FunType><<<grid,block>>>(x,y,N,f);
            cudaDeviceSynchronize();
            return y;
        }
    private:
        FunType* f;
};
//"User-defined" special function, to be evaluated
struct SpecialFun : public Managed
{
    __device__ __host__ double operator()(double x){return x*x;}
};

int main()
{
    Evaluator<SpecialFun> E;
    double* x;
    cudaMallocManaged(&x,2*sizeof(double));
    x[0] = 1.0; x[1] = 2.0;
    double* y = E.EvalFunGPU(x,2);
    std::cout<<"y[0] = "<<y[0]<<"\ny[1] = "<<y[1]<<std::endl;

    return 0;
}

I have some obvious improvements lined up, but I wanted to get input on my basic design before building it out.  Thanks for your time!

Is there a good reason against using the thrust library? It seems to come with the nvcc compiler and provides that kind of functionality:

#include <iostream>
#include <thrust/transform.h>

__device__ __managed__ float x[2], y[2];

template <typename T> struct square {
    __host__ __device__ T operator()(const T& x) const {
        return x * x;
    }
};

int main(int argc, char const *argv[]) {
    x[0] = 1; x[1] = 2;
    thrust::transform(x, x + 2, y, square<float>());
    std::cout << x[0] << "**2 = " << y[0] << "\n";
    std::cout << x[1] << "**2 = " << y[1];
    return 0;
}


Build a double from a stream of chars Back in my calculator post, janos suggested I either find a better way to read a double from a StreamReader or else go the whole way and build a double from scratch.  I looked through a few streams, but the only one I found that supported reading a double was the BinaryReader.  This, unfortunately, reads exactly 8 bytes, and the data is stored as a char (or rather, as an int representation of a char), so I could enter the equation "5+5", and it would crash when it read the "+".  If you know of a better solution, I would prefer using it.

private double GetNextNumber(StreamReader dataStream)
{
    double value = 0;
    int decimalLevel = 0;

    while (true)
    {
        if (!"0123456789.".Contains((char)dataStream.Peek()))
        {
            break;
        }
        char token = (char)dataStream.Read();

        if (token == '.')
        {
            if (decimalLevel == 0)
            {
                ++decimalLevel;
                continue;
            }
            throw new InvalidDataException("Invalid number format.");
        }

        int digit = int.Parse(token.ToString());

        value = value * 10 + digit;

        if (decimalLevel != 0)
        {
            ++decimalLevel;
        }
    }

    return value / Math.Pow(10, decimalLevel - 1);  // use "- 1" because value increments just before ending loop
}

Please analyze my code as thoroughly as the compiler does.

You should avoid while (true) { … } loops wherever it is possible to do so.  Here, it's very obviously avoidable!

while ("0123456789.".Contains((char)dataStream.Peek()))
{
    …
}

This parser leaves much to be desired in terms of handling

negative numbers (or you should document the fact that they are unsupported)
e notation for powers of ten
overflow and small numbers, due to excessive multiplying and dividing by powers of ten

Personally, I would avoid the entire headache by appending all plausible-looking characters to a StringBuilder, then calling double.Parse(string).


Event Listener and Publisher This is my first attempt at creating an event system.

My plan is that upon publishing, the listener receives both a reference to the model and to the publisher. This allows the publisher class to have multiple owners, and provide a way for listeners to know exactly how they were called.

To do this I've made the base classes for the publisher/listener generic

abstract class AEventPublisher<Model, Publisher extends AEventPublisher<Model, ?>> {
    private List<IEventListener<Model, Publisher>> listeners;

    public AEventPublisher(){
        listeners = new ArrayList<IEventListener<Model, Publisher>>();
    }

    public void subscribe(IEventListener<Model, Publisher> listener) {
        listeners.add(listener);
    }

    public void unsubscribe(IEventListener<Model, Publisher> listener) {
        listeners.remove(listener);
    }

    protected void publish(Publisher publisher, Model sender) {
        for(IEventListener<Model, Publisher> listener : listeners){
            listener.actionPerformed(publisher, sender);
        }
    }

    public abstract void publish(Model sender);
}

interface IEventListener<Model, EventPublisher extends AEventPublisher<Model, ?>> {
    public void actionPerformed(EventPublisher publisher, Model sender);
}

The publish method was made protected and abstract, because I couldnt think of a way to get this in AEventPublisher to be casted as the Publisher extends AEventPublisher<Model, ?> type

Some defined event/listeners would then be:

public class GameEvents{
    public static interface IButtonEventListener extends IEventListener<MenuButton, ButtonEventPublisher>{}

    public static class ButtonEventPublisher extends AEventPublisher<MenuButton, ButtonEventPublisher> {
        @Override
        public void publish(MenuButton sender) {
            publish(this, sender);
        }
    }

    public static interface IJoystickEventListener extends IEventListener<Joystick, JoystickEventPublisher> {}

    public static class JoystickEventPublisher extends AEventPublisher<Joystick, JoystickEventPublisher> {
        @Override
        public void publish(Joystick sender) {
            publish(this, sender);
        }
    }
}

Now the listener Interfaces can be turned into anonymous classes to act as callbacks.

This would be an example usage as part of the constructor for my Player class.

joystickCallback = new IJoystickEventListener(){
    @Override
    public void actionPerformed(JoystickEventPublisher event, Joystick sender)
    {
        updatePlayerDirection(sender);
    }
};
joystick.getJoystickEventPublisher().subscribe(joystickCallback);
//Then before player is deleted, this would be called:
//joystick.getJoystickEventPublisher().unsubscribe(joystickCallback);

I've got a few small points about this code and then I have some other points regarding your design. I'll try to discuss your design in perspective to game-development (where I am completely inexperienced) and in perspective to (the more common Java area) business applications.

Names and Design choices

Your class (and interface) names seem to come from a C# dominated development perspective to me. Prefixing I to interfaces smells .NET to me. Whenever I am developing Java I try to keep interfaces without clutter and then usually suffix the implementation classes if that is required.

Next thing that somewhat bit me was the A prefix for your abstract class. I am not a great friend of abstract classes anyways. I try to avoid them wherever I can and prefer interfaces and "Default[...]"-implementations. I have been going better with that since abstract classes often end up constraining the use of the "Interface" too much.

I'd rather write a little duplicate code than creating a central abstract class that limits my possibilities when using the interface. Instead I'll create a simple, if not "minimalistic" interface. Multiple minimalistic interfaces can be combined to allow more complex uses, but since your use-case is clear ....

Anyways this is enough of abstract talk about personal preferences in regards to language constructs. Let's give your code a thorough examination.

Code Analysis:

What instantly struck me when I first saw your code was the lack of explicit visibility modifiers on your AEventPublisher and your IEventListener. Neither of these needs the other for context so much that you'd have to put them into the same classfile.

The next thing I saw was your incredibly long generics specification:

AEventPublisher<Model, Publisher extends AEventPublisher<Model, ?>>

This seems to be a lot of unnecessary work to me. Also you're needlessly restricting the possibilities you have, when using your publishing mechanism. IMO the following would be sufficient:

AEventPublisher<Model, P extends Publisher>

Then I saw how you store listeners. You have a private List<...>

You have two choices when creating an abstract class like this. Either you allow "full" access to your fields (by making them protected) or you close yourself off completely.

Following the Open/Closed principle (Open to extension, Closed to modification) I definitely suggest the latter. You did that not even bad, but I have two small nitpicks to make.

Make your "immutable" fields really immutable:

private final List<...>

is better than just a private list.
Make use of "common" language features:
You're currently initializing your List in the constructor, and (again) repeat the clunky generics definition. Save yourself from that and use the Java 7 feature: the diamond operator. It makes overly clunky generics (as java has them) easier by shortcircuiting redundancy:

private final List<IEventListener<Model, Publisher>> listeners = new ArrayList<>();

Next up is how you handle publishing. The problem you're describing when you implemented your publish method is rooted in how you restricted yourself when starting directly with an abstract class, instead of taking yourself the room of creating an interface for a Publisher. Consider the following:

public interface Publisher<E> {
    public void subscribe(IEventListener<E, Publisher<E>> listener);
    public void unsubscribe(IEventListener<E, Publisher<E>> listener);
    public void publish(E sender);
}

This greatly simplifies your generics declarations and nestings and additionally resolves the conflict you had internally.

If you'd sacrifice a little "flexibility" (which you problably won't need anyways, more later), you could even make your IEventListener much simpler and completely get rid of the second type-parameter you introduced.

In general your solution seems overengineered for the problem. Which brings me to my next point.

Design Discussion:

In general your design is somewhat over the top. You try to keep flexibility and allow substitions (which is in principle a good thing) in places where it's overly complicating your source-code and detrimental to code-readability and hurtful to your actual flexibility.

Coming from a "GameDevelopment-Perspective"

You will never need a Listener, which can listen to multiple different model classes, and if against all odds you need it, an abstract class or interface to group these model-classes is the simplest call to make. You went too far in your idealistic approach to be "open to everything". This is something you should strive to do, but not at the cost of simplicity and effectiveness.

This is true to both gamedevelopment and business applications.

In addition to that, gamedevelopment is a often heavily performance-reliant environment, and let me tell you, overcomplicated generics and backreferencing interfaces are not something to make the JVM run faster.

I also have no idea why you'd need or want the Listener to obtain a reference to the publisher. From what I see with my nonexistant experience you could "directly" subscribe to your model, which would then pass a reference to itself to it's listener. But that makes the whole Model-circus in your code moot, and defeats the point of a separate Publisher (which I don't see in the first place).

In general, separating the Publisher from the "published" is somewhat overkill and most probably sign of an underlying design mistake. I can not imagine a situation where I'd have to get a reference to a Publisher, before publishing something. You're again: overly complicating a simple matter.

Because in the end, what is this all about?

You want to bring data from one end to another, depending on certain conditions. And there's already a lot of existing solutions (beginning with Observable and ending god knows where) in the Java world for that.

Which is also what makes this model somewhat problematic from a business perspective. The simplicity of existing solutions beats your idea easily. The practical use-case is from my point of view missing.

Overall you reinvented the wheel, but not as wheel, but as a polygon. Your solution to "Get data from A to B on demand" suffers from clunkyness in use. It's a bumpy ride and I don't know how I'd make it better without landing at some place that's already polished for use.

Final overview:

When I reviewed your code I copied it to a local project in my IDE. A few changes and a little headscratching later I was at the state of code that follows.

From what your use-case seems to be, that should be completely sufficient:

public interface Publisher<E> {
    public void subscribe(IEventListener<E> listener);
    public void unsubscribe(IEventListener<E> listener);
    public void publish(E sender);
}

public interface IEventListener<E> {
    public void actionPerformed(Publisher<E> publisher, E sender);
}

public class DefaultEventPublisher<Model> implements Publisher<Model> {
    private final ArrayList<IEventListener<Model>> listeners = new ArrayList<>();

    @Override
    public void subscribe(IEventListener<Model> listener) {
        listeners.add(listener);
    }

    @Override
    public void unsubscribe(IEventListener<Model> listener) {
        listeners.remove(listener);
    }

    @Override
    public void publish(Model sender) {
        for (IEventListener listener : listeners) {
            listener.actionPerformed(this, sender);
        }
    }
}

And since you also had an example of a usecase:

public class ButtonEventPublisher
       extends DefaultEventPublisher<ButtonEventPublisher.ButtonEvent> {
    public static class ButtonEvent {}
}

This code should in essence be able to do the same things that your code can do, but is IMO much simpler. Let me know what you think ;)


Accessing a REST WebService and updating local HTML objects with Modular JS I have this code I am doing to make my code modular js:

$(function(){
    var url, settings ={};
    var language = mainSettings.getLanguage(); /* there is an object in the page called mainSettings with current language */
    function applyLanguageSettings() {
        if (language == "en") {
         settings.web = "en";

        }
        else {
         settings.web = "es";
        }
    }

    applyLanguageSettings();
    //Get element
    var pageName= location.pathname.split("/").pop();
    pageName = pageName.substring(0, pageName.indexOf('.aspx'));
    baseUrl = mainSettings.getUrl() + settings.web + "/db/items?$filter=PageName eq '"+ pageName + "'";
    var dfd = $.ajax({
    url: baseUrl,
    method: "GET",
    headers : {
        "accept": "application/json;odata=verbose"
    }
})

dfd.done(function(data, status, jqXHR){
        if(data.d && data.d.results && data.d.results.length >0){
            var results = data.d.results;
            var card = data.d.results[0];
            var obj = {};
            obj.Title = value.Title;
            obj.ImageSource = value.Img;
    $("#Img").attr("src",obj.ImageSource);
    $("#Title").text(obj.Title);

          }
    });
})

I'm trying to access a REST-based Web-Service using JavaScript, then update a couple local HTML elements with the result of the download.

I have a couple questions:

Do I have to define a namespace and put my code inside to make it modular? Do I have to make my code modular in the first place? I don't see how I can turn this straightforward code into modular code.
For the apply language settings, I am not sure if am doing the right thing by defining a function then calling the function below it. Do I need to use IIFE?
Calling the $("#Title"), do I need to get the container in HTML once, and use .find()? What's the benefit of using .find() over what I am doing here?
Is my if condition to check for the data done in the right way?

declared but never used:

url
data (it my look like it is used but it is only assigned to results and card)
results
card

used but never declared:

baseUrl
mainSettings (though there is a comment about it)
value

Unnecessary:

applyLanguageSettings
settings
obj
status
jqXHR

I had to assume card and value were the same thing or else as mentioned above data wasn't really used. Readability can be improved by giving dfd a name that would be understood by more people. I also made use the the data setting for the ajax function.

Potential rewrite:

$(function() {
    var language = mainSettings.getLanguage(); /* there is an object in the page called mainSettings with current language */
    language = language === "en" ? "en" : "es";

    var pageName = window.location.pathname.split("/").pop();
    pageName = pageName.substring(0, pageName.indexOf('.aspx'));
    var understandableName = $.ajax({
        url: mainSettings.getUrl() + language + "/db/items",
        data : { "$filter" : "PageName eq '" + pageName + "'" },
        method: "GET",
        headers: {
            "accept": "application/json;odata=verbose"
        }
    });

    understandableName.done(function(data) {
        if (!data.d)
            return;
        var results = data.d.results;
        if (results && results.length > 0) {
            var value = results[0];
            $("#Img").attr("src", value.Img);
            $("#Title").text(value.Title);
        }
    });
});


Return characters in a string in alphabetical order Problem

  Take a string and return all input characters in alphabetical order
  Assume that no numbers or punctuation will be used
  For the same character, uppercase characters should be returned before lowercase characters
  Do not use the sorted helper method
  Do not use any libraries that are not included with Python 3.6.1

For example, alphabetize(HelLo) should return eHLlo

Approach

Create a 26-element list. This list will represent the counts (uppercase
and lowercase) of the different alphabetical characters seen via a dictionary
Iterate through the characters in the input string

Get the index for each character by subtracting the int values
of the lowercase character from the int value of a
Get the existing count for that index & case from the counts
dictionary
Increment the count by 1

Initialize the return string
Iterate through each element in the list

For each dictionary / element, get the character, and get the
uppercase and lowercase counts
Add the uppercase characters to the return string
Add the lowercase characters to the return string

Return the alphabetized string

Implementation Discussion

I know the 'Pythonic' way to accomplish this is something like
''.join(sorted(myString)).

However, as somebody trying to learn Python, I wanted to use this exercise
to learn more about strings and characters in Python (for example)
vs. Googling a one-liner (not that there's anything wrong with that).

Things I'm concerned about:

Should this be a class? Or is it ok as a standalone method? (As
somebody that is more comfortable in Java, things that aren't in classes
make me irrationally uneasy.)
Speaking of which, there's a decent amount of stuff going on in this
method, should I break it up?

If I decide to break it up, what's the right way of 'showing' that
some functions are only going to be used by another function?
I think Python doesn't really have a concept of private vs.
public so do I _(some_method_name) here?

What other 'Pythonic' elements am I missing (again, aside from using
the sorted method)?

Implementation

def alphabetize(value):
    uppercase_key = 'uppercase'
    lowercase_key = 'lowercase'

    character_counts = []
    for i in range(26):
        character_counts.append({uppercase_key: 0, lowercase_key: 0}.copy())

    for character in value:
        index = ord(character.lower()) - ord('a')
        counts = character_counts[index]
        key = uppercase_key if character.isupper() else lowercase_key

        count = counts[key]
        counts[key] = count + 1

    alphabetized = ''
    for index, counts in enumerate(character_counts):
        character = chr(ord('a') + index)
        uppercase_counts = counts[uppercase_key]
        lowercase_counts = counts[lowercase_key]
        for i in range(uppercase_counts):
            alphabetized += character.upper()
        for i in range(lowercase_counts):
            alphabetized += character

    return alphabetized

What other 'Pythonic' elements am I missing (again, aside from using the sorted method)?

If you want to more heavily use the standard library, you can use a collections.Counter along with the alphabet constants string.ascii_uppercase and string.ascii_lowercase.

Things are also simpler if you store the counts in a dict (map) instead of the implicit map-by-ord()-value that you're currently using. The ordering of the counts doesn't really matter, just the order in which you output them.

from collections import Counter
from itertools import chain
import string

def alphabetize(s):
    counts = Counter(s)

    return ''.join(
        char * counts[char]
        for char in chain(*zip(string.ascii_uppercase, string.ascii_lowercase))
    )

The counts = Counter(s) line does essentially this:

counts = collections.defaultdict(int)

for char in s:
    counts[char] += 1

where the defaultdict (a handy class) is a dict that auto-initializes values based on the constructor you pass in, instead of throwing an exception for missing keys.

The chain(*zip(...)) is zipping together the uppercase and lowercase alphabets, then flattening them via chain() into a single list, ['A', 'a', 'B', ...].

  Should this be a class?

Nope. This makes sense as a function in Python since it has no external state.

  As somebody that is more comfortable in Java, things that aren't in classes make me irrationally uneasy.

Java ties files to classes, but each Python file is already a module, which is a good level of encapsulation. As a very rough rule, avoid classes in Python except when you want to hold shared state, in which case class away. Or, at least, don't reach first for classes.


Tag badges per user SEDE query I wanted to see where I lined up with other users on tag badges (I wanted to count just bronze but figured I would start with all of them to start out with).

Here is the query that I ended up with:

SELECT
    Users.Id as [User Link]
    , Users.DisplayName
    , COUNT (Badges.Id) AS Number_of_Tag_Badges
FROM
    Badges
    INNER JOIN Tags ON Tags.TagName = Badges.Name
    INNER JOIN Users ON Users.Id = Badges.UserId
GROUP BY Users.DisplayName, Users.Id
ORDER BY Number_of_Tag_Badges DESC

What can be done to make this a better query?

Implementation

The query is quite well written for what it does.  I just have a few minor nitpicks about its implementation.

The FROM, GROUP BY, and ORDER BY clauses are all subsidiary to the SELECT clause.  Therefore, I would indent them by one level.  (Indenting your INNER JOIN clauses so that they are part of the FROM clause was good.)

You're getting the disadvantages of the comma-first convention without reaping the benefits.  The advantage of putting commas first is that it makes it foolproof to add or remove columns in the SELECT: you should be able to delete an entire line of text without having to worry about fixing commas on neighbouring lines.  However, to take advantage of that property, you should put the first column on the same line as the SELECT keyword:

SELECT Users.Id as [User Link]
     , Users.DisplayName
     , COUNT (Badges.Id) AS Number_of_Tag_Badges
    FROM …

Remove the space before the parenthesis in the COUNT (…) call.

The joins would be better if the tables were listed linearly:

$$ \fbox{Users} \overset{\texttt{UserId}}{\longleftrightarrow}
   \fbox{Badges} \overset{\texttt{Name}}{\longleftrightarrow} \fbox{Tags}$$

Since the displayed results are user-centric, I would suggest listing the tables as Users, Badges, Tags rather than any other order.

Concept

It would be handy if you added a rank column.

The query doesn't distinguish between gold, silver, and bronze badges.  You should be able to report the breakdown.  The convention used by the International Olympic Committee is to sort by the gold medal count first, rather than by the total.  Perhaps you should do the same.

WITH EarnedTagBadges AS (
    SELECT Users.DisplayName
         , Badges.UserId
         , Badges.Name
         , RANK() OVER (PARTITION BY Users.Id, Badges.Name ORDER BY Date) AS Level
        FROM Users
            INNER JOIN Badges ON Users.Id = Badges.UserId
            INNER JOIN Tags ON Badges.Name = Tags.TagName
), UserTagBadges AS (
    SELECT UserId
         , DisplayName
         , COUNT(CASE WHEN Level = 3 THEN 1 END) AS Gold
         , COUNT(CASE WHEN Level = 2 THEN 1 END) AS Silver
         , COUNT(CASE WHEN Level = 1 THEN 1 END) AS Bronze
         , COUNT(Level) AS Total
        FROM EarnedTagBadges
    GROUP BY UserId, DisplayName
)
SELECT RANK() OVER (ORDER BY Gold DESC, Silver DESC, Bronze DESC) AS Rank
     , UserId AS [User Link]
     , DisplayName
     , Gold
     , Silver
     , Bronze
     , Total
    FROM UserTagBadges
    ORDER BY Gold DESC, Silver DESC, Bronze DESC;


Dynamic “filtering” list using jquery I'm building a list of filters for a website user to filter on, such as a product category page. I'm giving the user the option to filter on brandname, model name, or gender.

To avoid serverside code I'm trying to build it clientside. So, I'm looking on the different data-attr and building an array of filtering values of what's actually available to filter on.

I have made it work, but I'm not sure it's the most efficient way to do it.

HTML:

JS:

// Loop through all div's with .mix class

var Genders = [];
var Brands =  [];
var Models = [];
$( ".mix" ).each(function() {
   // build arrary with Gender

   if ($(this).attr('data-Gender')) {
           genderFilter = $(this).attr('data-Gender');
            var found = jQuery.inArray(genderFilter, Genders);
       if (found >= 0) { } else {
                // Element was not found, add it.
                Genders.push(genderFilter);
            }
   }
   // build arrary with Models
    if ($(this).attr('data-Brand')) {
           brandFilter = $(this).attr('data-Brand');
            var found = jQuery.inArray(brandFilter, Brands);
       if (found >= 0) { } else {
                // Element was not found, add it.
                Brands.push(brandFilter);
            }
   }
   // build arrary with Brands
    if ($(this).attr('data-Model')) {
           modelFilter = $(this).attr('data-Model');
            var found = jQuery.inArray(modelFilter, Models);
       if (found >= 0) { } else {
                // Element was not found, add it.
                Models.push(modelFilter);
            }
   }
});

console.log( Models.length );
console.log ( Models);
console.log( Brands.length );
console.log ( Brands);
console.log( Genders.length );
console.log ( Genders);

JSFiddle

It is customary to use lowercase names for variables and Capitalized names for classes, so I would rename Genders -> genders, and likewise the Models and Brands arrays too.

The if blocks are a bit tediously written. They would be better this way:

var genderFilter = $(this).attr('data-Gender');
if (genderFilter) {
    if (jQuery.inArray(genderFilter, genders) == -1) {
         // Element was not found, add it.
         genders.push(genderFilter);
    }
}

Btw, note that when you retrieve data-Gender="0" using .attr('data-Gender'), it's treated as the string "0", and in if ("0") { ... } it evaluates to true, so the genders array will have the values 0, 2, 1. Perhaps you might want to use .data('genders') instead, in which case the genders array will have the values 2, 1.

For models and brands, using .data('model') instead of .attr('data-Model') will give the same result, so I suggest using the simpler.

For genders, models, brands, you do essentially the same thing.
This calls for a helper function:

function addToArrayIfNew(arr, item) {
    if (item && jQuery.inArray(item, arr) == -1) {
        arr.push(item);
    }
}

With this, you could simplify the entire code like this:

$( ".mix" ).each(function() {
    addToArrayIfNew(genders, $(this).attr('data-Gender'));
    addToArrayIfNew(models, $(this).data('model'));
    addToArrayIfNew(brands, $(this).data('brand'));
});


Round a number and replace trailing zeros by spaces Goal

From a number x, I would like a string of the rounded value at n decimals and replace each trailing zeros by a space.

Examples

Let n = 4

f(0.1, n=4)
[1] "0.1   " # 3 whitespace
f(0.1111999, n=4)
[1] "0.1112" # 0 whitespace
f(0.12, n=4)
[1] "0.12  " # 2 whitespace
f(0.1234, n=4)
[1] "0.1234" # 0 whitespace

Current solution

f <- function(x,n)
{
    s = sprintf(paste0("%.",n,"f"), x)
    for (i in 1:n)
    {
        s = gsub(
            paste0("0", paste0(rep("\\s",i-1),collapse=""),"$"),
            paste0(rep(" ",i), collapse=""),
            s
        )
    }
    return(s)
}

It works fine but it is a little cumbersome. I suspect a better regex solution.

Apparently, printf already has a feature for padding data to a specific length, see for example https://stackoverflow.com/q/34346389/1201032. So you can do:

f <- function(x, n) {
  rounded_x <- as.character(round(x, n))
  num_lead_chars <- nchar(sub("[.].*", ".", rounded_x))
  sprintf("%-*s", n + num_lead_chars, rounded_x)
}

The function is vectorized for both inputs:

f(c(0.1, 0.1111999, 0.12, 0.1234), n = 4)
# [1] "0.1   " "0.1112" "0.12  " "0.1234"
f(0.1, n = 1:4)
# [1] "0.1"    "0.1 "   "0.1  "  "0.1   "


Merging Overlapping Intervals A while back I was asked the following question in a phone interview, and to be honest it stumped me. After many long nights of rolling the problem around in my head I think I came up with a decent solution.

The Question:

  Given a list of intervals like:

  [(5, 7), (11, 116), (3, 6), (10, 12), (6, 12)]

  Write a function that will merge overlapping intervals.

My solution:

def merge_intervals(intervals):
    """
    A simple algorithm can be used:
    1. Sort the intervals in increasing order
    2. Push the first interval on the stack
    3. Iterate through intervals and for each one compare current interval
       with the top of the stack and:
       A. If current interval does not overlap, push on to stack
       B. If current interval does overlap, merge both intervals in to one
          and push on to stack
    4. At the end return stack
    """
    si = sorted(intervals, key=lambda tup: tup[0])
    merged = []

    for tup in si:
        if not merged:
            merged.append(tup)
        else:
            b = merged.pop()
            if b[1] >= tup[0]:
                new_tup = tuple([b[0], tup[1]])
                merged.append(new_tup)
            else:
                merged.append(b)
                merged.append(tup)
    return merged

if __name__ == '__main__':

    l = [(5, 7), (11, 116), (3, 4), (10, 12), (6, 12)]
    print("Original list of ranges: {}".format(l))
    merged_list = merge_intervals(l)
    print("List of ranges after merge_ranges: {}".format(merged_list))

My questions are:

Run time: Without counting sorting I believe this runs in \$O(n)\$. With counting sorting that would go up to \$O(n*\log(n))\$. Is this correct?
Stylistically does anything need to be improved?
Is there a more efficient way of solving this problem?

This code has a bug. Consider merge_intervals([(0, 3), (1, 2)]). This returns [(0, 2)] although it should be [(0, 3)]. This can be solved through

new_tup = (b[0], max(b[1], tup[1]))

Your code is nice, and implements the simplest thing that works. However, you might want to work on improving your variable names. Neither l, b, or si are very descriptive, and tup and new_tup unnecessarily refer to their type name rather than their meaning. In contrast, merged is a very clear name. A rewrite of the function body might be:

sorted_by_lower_bound = sorted(intervals, key=lambda tup: tup[0])
merged = []

for higher in sorted_by_lower_bound:
    if not merged:
        merged.append(higher)
    else:
        lower = merged[-1]
        # test for intersection between lower and higher:
        # we know via sorting that lower[0] <= higher[0]
        if higher[0] <= lower[1]:
            upper_bound = max(lower[1], higher[1])
            merged[-1] = (lower[0], upper_bound)  # replace by merged interval
        else:
            merged.append(higher)
return merged

Notice that I decided not to use an explicit tuple(…) constructor – that's mostly useful for converting to tuples from iterables. For tuple literals, you can use the (…, …) syntax.

I also put the comments inside the code, rather than into the docstring. Docstrings are good, but they are intended to explain how to use the function (e.g. what the expected type of parameters is, what the function returns, …). To document implementation details, use normal comments.

You have correctly identified the (average and worst-case) algorithmic complexity as \$O(n \log n)\$. You must consider the sorting. However, best-case complexity is \$O(n)\$, as the Tim Sort used by Python detects already-sorted input.

While your code provides a simple and robust solution, it would be certainly possible to reduce average algorithmic complexity. I expect a kind of self-merging interval tree to have average complexity closer to \$O(n \log m)\$ where \$m\$ is the number of intervals after merging.


Font and color checker chrome extension in JavaScript I have written this code for a color and font checker on a webpage.

The code is current and not so good. I would really like if I can get comments, reviews or any better approach for my PoC.

PoC: I want to highlight all the colors or fonts which should not be used on the webpage (the domain is defined by me as of now). I am traversing the DOM and checking the color and font styles and then highlight them if there are values out of my domain.

The current approach is very naive and not optimal because I am traversing and storing element styles, which is bad for duplicated DOM elements.

Any comments are appreciated, please let me know if I should add any more details.

inject.js

var brandColor = [
  "rgb(255, 255, 255)",
  "rgb(0, 0, 0)",
  "rgb(0, 163, 224)",
  "rgb(0, 118, 168)",
  "rgb(1, 33, 105)"
];

var brandFont = ["Open Sans", "Verdana"];
var fontNotMatch;

// generic walkDOM function - iterate DOM
function walkDom(start_element) {
  var arr = []; // we can gather elements here
  var loop = function(element) {
    do {
      // we can do something with element
      if (element.nodeType == 1) {
        // do not include text nodes
        arr.push(element);
      }
      if (element.hasChildNodes()) loop(element.firstChild);
    } while ((element = element.nextSibling));
  };
  loop(start_element);
  //loop(start_elem.firstChild); // do not include siblings of start element
  return arr;
}

var arr = walkDom(document.body);

var stylesContainer = {};
var fontChecker = {};
// iterate through DOM array
for (elem in arr) {
  // get all colors - [need better approach for this as well]
  stylesContainer[arr[elem].tagName] = getComputedStyle(
    arr[elem]
  ).getPropertyValue("color");

  // get all fonts
  fontChecker[arr[elem].tagName] = getComputedStyle(arr[elem]).getPropertyValue(
    "font-family"
  );
}

//console.log(stylesContainer);

// iterate styles
Object.keys(stylesContainer).forEach(element => {
  if (brandColor.indexOf(stylesContainer[element]) > -1) {
    //pass
  } else if (document.querySelector(element).childNodes.length == 1) {
    document.getElementsByTagName(element)[0].style.border = "2px solid red";
    var path =
      "https://example.com/icons/favicon.ico";
    var img = document.createElement("img");
    img.setAttribute("src", path);
    img.setAttribute("width", "20");
    document.querySelector(element).appendChild(img);
  }
  // console.log(stylesContainer[element]);
});

// iterate font family
Object.keys(fontChecker).forEach(element => {
  // Loop through each element and check the font family
  // console.log(fontChecker[element]);
  if (fontChecker[element].indexOf("Open Sans") != 1) {
    fontNotMatch = true;
  }
});

if (fontNotMatch == true) {
  // alert("Incorrect font");

  var f = document.createElement("h3");
  f.classList.add("error");
  f.innerHTML = "hey bhansa";
  document.querySelector("BODY").appendChild(f);

  var pathCSS = chrome.runtime.getURL("demo.css");
  var head = document.getElementsByTagName("head")[0];
  var link = document.createElement("link");
  link.rel = "stylesheet";
  link.type = "text/css";
  link.href = pathCSS;
  head.appendChild(link);
}

Just some random comments from a quick read through:

1) Does this work if someone defines their colors using hex or name style (#fff, #ffffff, white, rgba(255,255,255,1)?

2) Walking the DOM and creating a huge array is probably not a good idea for anything but a small web page. After that you have another 3 separate loops. I would suggest that you create a function that walks the dom and calls a function for each node (function walkDom(start_element, callback) { .... Then you only need to store nodes that fail the test. Also combine ll those loops into one test.

3) Rather than comparing the nodetype with 1 I would use if (element.nodeType === Node.ELEMENT_NODE) ...

4) Rather than a do...while loop and nextSibling it is probably simpler just to get the childNodes and loop through them.

5) Or even better look into the TreeWalker api https://developer.mozilla.org/en-US/docs/Web/API/TreeWalker

6) This loop doesn't make sense:

for (elem in arr) {
  stylesContainer[arr[elem].tagName] = ...;
}

If you have two <div>'s in your tree the second one will over-write the first one.

7) A few things here:

if (brandColor.indexOf(stylesContainer[element]) > -1) {
  //pass
} else if (document.querySelector(element).childNodes.length == 1) {
  document.getElementsByTagName(element)[0].style.border = "2px solid red";
  ...

}

Firstly don't use an if with an empty block, use a negated if :

if (brandColor.indexOf(stylesContainer[element]) < 0 &&    document.querySelector(element).childNodes.length == 1) {

Also why only highlight elements with a single child and not those with two children or no children? Also consider using includes instead of indexOf And again this:

document.getElementsByTagName(element)

will return the first tag of that type in the document. It might not be the one with the issue.

8) Don't mix styles. You use for ... in in some places and forEach in others. If you're using ES6 use let and const instead of var.

9) It is unnecessary to compare to true. if (fontNotMatch == true) { can be written as just if (fontNotMatch) {

10) If you check color you might want to check background-color and the various border-color's too.


OO design of Reverse Polish Notation Calculator - follow-up This is a revised version of my previous code.

This application will take input string like "3 2 + 1 -" and output 4 because it is the reverse Polish notation for (3+2)-1 = 4. This solution focuses on the design of classes.The current code has 2 operators (plus and minus) in default.  There are 2 constructors. 1 will create the default calculator. The other can take an additional HashMap that will map a string to an Operator.

The code works. Any further recommendations are much appreciated! Questions I have:

Do I need to write getters for fields that I didn't use, such as public String getInput().
I didn't write any setters for the non-static variables. Do I need them?

 import java.util.*;
 public class RPNCalculator {

    public Stack<Integer> stack;
    private String input;
    public Map<String, Operator> map;
    private String operators="";

    public RPNCalculator(String userInput){
        input = userInput;
        stack = new Stack<Integer>();
        // default hashmap initialization
        map = new HashMap<String, Operator>();
        map.put("+", new Plus());
        map.put("-", new Minus());
        // this string is constructed for later use in processInput()
        for(String key: map.keySet()){
            operators+= key;
        }
    }
    public RPNCalculator(String userInput, HashMap<String, Operator> mapInput){
        input = userInput;
        stack = new Stack<Integer>();
        this.map = mapInput;
        for(String key: map.keySet()){
            operators+= key;
        }
    }

    public Stack<Integer> getStack(){
        return this.stack;
    }
    public String getInput(){
        return this.input;
    }
    public void processInput(){
        StringTokenizer st = new StringTokenizer(input, " ");
        while (st.hasMoreTokens()){
            String str = st.nextToken();
            if(!operators.contains(str)){               //test whether the token is an operator
                stack.push(Integer.parseInt(str));
            }
            else{
                map.get(str).calc(this);
            }
        }
        if(stack.size()!=1){
            System.out.println("The input expression is not the correct format");
        }else{
            System.out.println(stack.pop());
        }
    }
}

Other supporting classes and driver (contains main):

public abstract class Operator {
    abstract void calc(RPNCalculator rpn);
}
public class Minus extends Operator {
    @Override
    void calc(RPNCalculator rpn) {
        int a = rpn.getStack().pop();
        int b = rpn.getStack().pop();
        rpn.getStack().push(b-a);

    }
}
public class Plus extends Operator {
    @Override
    void calc(RPNCalculator rpn) {
        int a = rpn.getStack().pop();
        int b = rpn.getStack().pop();
        rpn.getStack().push(a+b);

    }
}
public class RPNDriver {
       public static void main(String[] args) {
           System.out.println("starting calculator...");
           RPNCalculator rpn = new RPNCalculator("1 21 + 2 -");
           rpn.processInput();
       }
}

Do I need to write getters for fields that I didn't use? such as
  public String getInput(). I didn't write any setters for the
  non-static variables. do I need them?

It depends. If you want to expose the field to the classes's clients, then you need a getter. For instance, it makes sense to write a getter for the stack in the calculator so that operators can use it (sure, you could have design it differently and pass a stack to an operator directly). It's really about the design of your class. There's no definitive answer. I don't think that you need a getter for the input here.

The operators String is redundant. You can check if a string is in the map using map's containsKey method.

I also think that the input should be passed as an argument to the processInput method, not to the constructor. I just makes more sense to me to build one calculator for a specific sets of operators and then run it on as many different inputs as you need. I don't think that the input is the essential part of the calculator entity. It's more like something the calculator can processes, not something it consists of.

I'd also recommend to decouple the computations from the output. Each method should do one focused thing. The processInput should do exactly this: process the input and return the result (or throw an exception). Printing it is a different concern. It also makes your code more reusable: if you just return the value, you can still use the class if just need to evaluate the expression without printing it or if your need to display it differently.

The comments should not repeat the code so something like is // default hashmap initialization is even worse than no comments as it clutters the code. It just creates more noise. It's clear that a new HashMap<>(); creates a new empty map. They should rather explain why specific decisions were made. It's also a good practice to write doc comments for your classes and methods to specify it's behavior (including what kind of exceptions it throws) so that one doesn't need to read the code of the method to figure out what it does and how it (and shouldn't) be used.

I'd also suggest to create a copy of the mapInput in this public RPNCalculator(String userInput, HashMap<String, Operator> mapInput) constructor (so that the map used by the calculator doesn't change even if the mapInput is later changed by the client). Either way, you need to document this kind of decisions so that the users of your class know if it's safe to change the map passed to the constructor later in their code.


Optimize MySQL double select inside for-loop I want to get the number if items with state 4 and 1 from my database for each day between a certain date. Is there a smarter and more performative way than this one?

I am aware that I should use MySQLi and that MySQL is deprecated.

Code explanation:

the for loop is to go through everyday between 2 dates
$sql_condition is in case the query has a specific item, otherwise empty variable

My code:

for( $thisDay = $start; $thisDay <= $end; $thisDay = $thisDay + 86400){

    $formatedDate = date('Y-m-d', $thisDay);
    // booked houses
    $sql="SELECT id FROM ".T_BOOKINGS." WHERE id_state=1 ".$sql_condition." AND the_date='".$formatedDate."'";
    $res=mysql_query($sql) or die("Error getting states
".mysql_Error());

    //reserved houses
    $sql2="SELECT id FROM ".T_BOOKINGS." WHERE id_state=4 ".$sql_condition." AND the_date='".$formatedDate."'";
    $res2=mysql_query($sql2) or die("Error getting states
".mysql_Error());

    $bookings['booked'][] = mysql_num_rows($res);
    $bookings['reserved'][] = mysql_num_rows($res2);
    $dates[] = $formatedDate;

}

Three major points:

Executing SQL queries in a loop will nearly always cause a performance problem.  You want to formulate a query that gives you all the data you want.
mysql_query() and similar functions are deprecated; use mysqli or PDO instead.
Composing your query by concatenation and interpolation, without escaping, could easily lead to an SQL injection vulnerability.  Better yet, use a database interface that supports placeholders for parameters so that you don't have to worry about escaping.

A better solution would go something like this:

function bookings_between($booking_state, $start, $end) {
    $formattedStart = date('Y-m-d', $start);
    $formattedEnd   = date('Y-m-d', $end);

    $query = mysql_query("
        SELECT the_date, COUNT(id)
            FROM ".T_BOOKINGS."
            WHERE id_state=$booking_state
                $sql_condition AND
                the_date BETWEEN '$formattedStart' AND '$formattedEnd'
            GROUP BY the_date;")
        or die ("Error getting states<br>".mysql_error());

    $results = array();
    while ($row = mysql_fetch_array($query, MYSQL_NUM)) {
        $results[$row[0]] = $row[1];
    }
    return $results;
}

$booked = bookings_between(1, $start, $end);
$reserved = bookings_between(4, $start, $end);

The results are not in the same format as your original.  This returns the bookings in associative arrays, keyed by the date (as formatted by MySQL).  Days that have no bookings will not have an entry.  If you need to, you can post-process $booked and $reserved back into a data structure compatible with the original code.  The big win, though, is that you execute just two queries instead of two queries per day of the period in question.


Calculation of RGB values given min and max values I made a start at translating the accepted answer's code here into C#. Any suggestions on the correctness of the translation and the correctness of the original code would be very much appreciated.

public class RgbValues
{
    public int Red { get; set; }
    public int Green { get; set; }
    public int Blue { get; set; }
}

public static RgbValues GetRgbValues(float minimumValue, float maximumValue, float value)
{
    var rgbValues = new RgbValues();
    var halfmax = (minimumValue + maximumValue) / 2.0;
    rgbValues.Blue = (int) Math.Max(0.0, 255.0 * (1.0 - value/halfmax));
    rgbValues.Red = (int)Math.Max(0.0, 255.0 * (value / halfmax - 1.0));
    rgbValues.Green = 255 - rgbValues.Blue - rgbValues.Red;

    return rgbValues;
}

What is a bit worrying is that:

GetRgbValues(10, 10113, 10113)

should really caclulate:

red = 255, green = 0, blue = 0

rather than:

red = 254, green = 1, blue = 0

I guess there is some rounding issue.

Any ideas?

Calculations like these can be hard to understand, so I would try to strive for something that is clearly correct, not just correct.

What I would do:

normalize the value from \$[min, max]\$ to \$[0, 2]\$
realize that the "strength" of a color is \$1 - |value - color|\$ (where \$color\$ is \$0\$ for blue, \$1\$ for green and \$2\$ for red), so compute that
clip the computer strength to remove negative numbers
finally multiply it by \$255\$ and convert to int (while also rounding the value, to avoid bias towards smaller numbers)

In code:

public static RgbValues GetRgbValues(float minimum, float maximum, float value)
{
    var normalizedValue = Normalize(minimum, maximum, value);

    return new RgbValues
    {
        Blue = Distance(normalizedValue, 0),
        Green = Distance(normalizedValue, 1),
        Red = Distance(normalizedValue, 2)
    };
}

private static float Normalize(float minimum, float maximum, float value)
{
    return (value - minimum) / (maximum - minimum) * 2;
}

private static int Distance(float value, float color)
{
    var distance = Math.Abs(value - color);

    var colorStrength = 1 - distance;

    if (colorStrength < 0)
        colorStrength = 0;

    return (int)Math.Round(colorStrength * 255);
}

This code is longer than the original, but I think it's also clearer about what it does. I didn't figure out what your code did until I read the SO question, I think it's much more likely I would have succeeded with this code.


Convert Persian and Arabic digits to English I use the following utility method to convert Persian and Arabic digits to English using regex:

convertNumbers2English: function (string) {
    return string.replace(/[٠١٢٣٤٥٦٧٨٩]/g, function (c) {
        return c.charCodeAt(0) - 1632;
    }).replace(/[۰۱۲۳۴۵۶۷۸۹]/g, function (c) {
       return c.charCodeAt(0) - 1776;
   });
}

Be nice to the maintenance programmer, even (especially?) if you expect it to be you. If you're mixing characters which are visually indistinguishable but don't need to be literal self-representations, you can use Unicode escapes and hexadecimal offsets as so:

convertNumbers2English: function (string) {
    return string.replace(/[\u0660-\u0669]/g, function (c) {
        return c.charCodeAt(0) - 0x0660;
    }).replace(/[\u06f0-\u06f9]/g, function (c) {
       return c.charCodeAt(0) - 0x06f0;
   });
}

Just that small change accomplishes the following:

I can easily see that I haven't missed any digits without having to count;
I can easily see that I haven't accidentally mixed digits from the two styles;
I can easily see that the offset subtracted is correct in each case;
I can easily see that the values returned by the anonymous functions are integers from 0 to 9 and not strings or codepoints corresponding to '0' to '9', which is useful if I'm not primarily a JS developer;
If I care about squeezing every last byte out of my JS, I can see a way to combine the two into one:

convertNumbers2English: function (string) {
    return string.replace(/[\u0660-\u0669\u06f0-\u06f9]/g, function (c) {
        return c.charCodeAt(0) & 0xf;
    });
}

The minimiser should take care of unescaping the Unicode escapes.
It might be slightly easier for me to find which characters they are, because I can look up the hex values in a Unicode character table.


Fetching translated strings, keeping in the philosophy of Zend framework I have been wondering this for a while. Take this example:

<?= Zend_Registry::get('translate')->_('translate me!');

I have my views cluttured with such code. My coworkers also complain often that its a lot to type juste to get translation and since it is repeated all over the place it gets tedious.

Some of them would love some global function that wraps everything in a short name like:

function t($text){
    return Zend_Registry::get('translate')->_($text);
}

But to me this is not good design and kinda defeats the idea of putting my translation object in the registry.

So I was wondering what others do to avoid having to write all this unnecessary code.

One solution would be to do in my controller:

$this->view->t = Zend_Registry::get('translate);

and then in my view just:

<?= $this->t->_('translate me!'); ?>

Another would be to create a view helper that does the job:

<?= this->translate('translate me!');?>

But it is more work and again adds a layer of logic on top of the already pretty robust and straigthforward Zend_Registry+ZendTranslate.

The two real questions are:

What are the advantages of having this in Zend_Registry?
What would you loose when using a helper function?

I believe the answers to these questions lead to this: use the helper function. This will:

save you a lot of typing,
highlight more importants parts of the code,
only add a tiny new layer of abstraction which is trivial to understand.

"Good design" is not about factories, registries, or whatever. It's about code that is easy to maintain and improve. The function is not going to make this any harder. If there's a translation error, the fix will stay the same: was the key correct? Is the stored translation correct? Still easy.


Implementing Functor Instance for `ITree` Looking at this Typeclassopedia exercise, I typed out foldTree on the following type:

data ITree a = Leaf (Int -> a) | Node [ITree a]

And my implementation of Functor:

instance Functor (ITree) where
    fmap = iTreeMap

iTreeMap :: (a -> b) -> ITree a -> ITree b
iTreeMap f (Leaf x)  = Leaf $ fmap f x
iTreeMap f (Node xs) = Node $ map (iTreeMap f) xs

Please critique its signature, correctness and style.

This looks mostly fine to me. If you wrote this code in a real codebase, I would not have any major qualms with it. Here are some nitpicks.

The strangest thing to me was just the way you defined a separate function, iTreeMap, then used that as the definition of fmap. I would just define fmap directly within the body of the instance definition—no need to give it a separate name.
The parentheses around ITree in the instance head are redundant. You could just write Functor ITree instead.
Given that the value inside of a Leaf is a function, the use of the function instance of fmap within the definition of iTreeMap is a bit of genericism that I think is unnecessary. I would probably just use (.) and make the composition explicit, but that’s really personal preference.

With those above changes in place, the instance would look like this:

data ITree a = Leaf (Int -> a) | Node [ITree a]

instance Functor ITree where
  fmap f (Leaf x) = Leaf $ f . x
  fmap f (Node xs) = Node $ map (fmap f) xs

However, in real code, I wouldn’t actually do that at all. With the DeriveFunctor language extension, you could just ask GHC to write the Functor instance for you. Therefore, in real Haskell code, I would probably just write this:

{-# LANGUAGE DeriveFunctor #-}

data ITree a = Leaf (Int -> a) | Node [ITree a]
  deriving (Functor)

But that’s probably against the spirit of the exercise. :)


Stopwatch dependency for unit-testing My AsyncDetector is internally using a Stopwatch to calculate time intervals. Because of this hardcoded dependency I am not able to write good unit-tests for it. So I must be able to use my own timestamps that I can use for assertions.

To do this I defined the IStopwatch interface that is a simplified version of the Stopwatch. Some of the properties I never use and my inteface does not provide them.

public interface IStopwatch
{
    bool IsRunning { get; }
    TimeSpan Elapsed { get; }
    IStopwatch Start();
    IStopwatch Stop();
    IStopwatch Restart();
    IStopwatch Reset();
}

Its default implementation is using of course the original Stopwatch so I provide it just for reference:

public class SystemStopwatch : IStopwatch
{
  private readonly Stopwatch _stopwatch;

  public SystemStopwatch()
  {
      _stopwatch = new Stopwatch();
  }

  public bool IsRunning => _stopwatch.IsRunning;

  public TimeSpan Elapsed => _stopwatch.Elapsed;

  public static IStopwatch StartNew()
  {
      return new SystemStopwatch().Start();
  }

  public IStopwatch Start()
  {
      _stopwatch.Start();
      return this;
  }

  public IStopwatch Stop()
  {
      _stopwatch.Stop();
      return this;
  }

  public IStopwatch Restart()
  {
      _stopwatch.Restart();
      return this;
  }

  public IStopwatch Reset()
  {
      _stopwatch.Restart();
      return this;
  }

  public override string ToString()
  {
      return _stopwatch.Elapsed.ToString();
  }
}

More interesing is the DebugStopwatch that will enumerate my timestamps on each access to the Elapsed property or it'll throw if there are not enough of them:

public class DebugStopwatch : IStopwatch
{
    private readonly IEnumerable<TimeSpan> _timestamps;
    private TimeSpan? _lastElapsed;
    private IEnumerator<TimeSpan> _enumerator;

    public DebugStopwatch([NotNull] IEnumerable<TimeSpan> elapses)
    {
        _timestamps = elapses ?? throw new ArgumentNullException(nameof(elapses));
    }

    public bool IsRunning { get; private set; }

    public TimeSpan Elapsed
    {
        get
        {
            if (IsRunning)
            {
                if (_enumerator.MoveNext())
                {
                    return (_lastElapsed = _enumerator.Current).Value;
                }

                throw new InvalidOperationException("You did not define enough timestamps.");
            }

            return _enumerator?.Current ?? _lastElapsed ?? TimeSpan.Zero;
        }
    }

    public static IStopwatch StartNew(IEnumerable<TimeSpan> elapses)
    {
        return new DebugStopwatch(elapses).Start();
    }

    public IStopwatch Start()
    {
        if (IsRunning)
        {
            return this;
        }
        _enumerator = _timestamps.GetEnumerator();
        IsRunning = true;
        return this;
    }

    public IStopwatch Stop()
    {
        IsRunning = false;
        return this;
    }

    public IStopwatch Restart()
    {
        Stop();
        Reset();
        Start();
        return this;
    }

    public IStopwatch Reset()
    {
        _enumerator = _timestamps.GetEnumerator();
        return this;
    }

    public override string ToString()
    {
        return (_lastElapsed ?? TimeSpan.Zero).ToString();
    }
}

Example Using it is very easy. I just need to provide a collection or enumeration with timestamps:

void Main()
{

    var stopwatch = DebugStopwatch.StartNew(Enumerable.Range(0, 10).Select(i => TimeSpan.FromSeconds(i)));

    stopwatch.Dump();
    stopwatch.Dump();
    stopwatch.Dump();

    stopwatch.Stop().Dump(nameof(IStopwatch.Stop));
    stopwatch.Dump();
    stopwatch.Dump();

    stopwatch.Reset().Dump(nameof(IStopwatch.Reset));
    stopwatch.Dump();
    stopwatch.Dump();
}

What do you think of the DebugStopwatch? Would you change anything about it? If so, how would you improve it?

I would not return IStopwatch from Start/Stop/etc. This IStopwatch is not an immutable Value Object, like String for example: it would be easier to set expectations by having just this:

public interface IStopwatch
{
    bool IsRunning { get; }
    TimeSpan Elapsed { get; }
    void Start();
    void Stop();
    void Restart();
    void Reset();
}

SystemStopwatch would be a way shorter:

class SystemStopwatch : IStopwatch
{
    Stopwatch Stopwatch { get; } = new Stopwatch();
    public bool IsRunning => Stopwatch.IsRunning;
    public TimeSpan Elapsed => Stopwatch.Elapsed;
    public void Start() => Stopwatch.Start();
    public void Stop() => Stopwatch.Stop();
    public void Reset() => Stopwatch.Reset();
    public void Restart() => Stopwatch.Restart();
}

As for the MockStopwatch (sounds better than Debug one for me) – it could be a little bit shorter:

class MockStopwatch : IStopwatch
{
    public MockStopwatch(params TimeSpan[] intervals)
        : this(intervals.AsEnumerable())
    {
    }

    public MockStopwatch(IEnumerable<TimeSpan> intervals)
    {
        Interval = intervals
            .Prepend(TimeSpan.Zero)
            .ToList()
            .GetEnumerator();

        Reset();
    }

    IEnumerator<TimeSpan> Interval { get; }
    public bool IsRunning { get; private set; }
    public TimeSpan Elapsed =>
        !IsRunning
        ? Interval.Current
        : Interval.MoveNext()
            ? Interval.Current
            : throw new InvalidOperationException("You did not define enough timestamps.");

    public void Start() => IsRunning = true;
    public void Stop() => IsRunning = false;

    public void Restart()
    {
        Stop();
        Reset();
        Start();
    }

    public void Reset()
    {
        Interval.Reset();
        Interval.MoveNext();
    }
}

Where you might need to define Prepend (.net core LINQ has one already):

static class PrependAppend
{
    public static IEnumerable<T> Prepend<T>(this IEnumerable<T> source, T item) =>
        Enumerable.Concat(new[] { item }, source);

    public static IEnumerable<T> Append<T>(this IEnumerable<T> source, T item) =>
        Enumerable.Concat(source, new[] { item });
}

Updated Elapsed

What do you say about this one? Looks cleaner for me.

    public TimeSpan Elapsed => IsRunning ? NextElapsed : SameElapsed;
    TimeSpan SameElapsed => Interval.Current;
    TimeSpan NextElapsed => Interval.MoveNext()
        ? Interval.Current
        : throw new InvalidOperationException("You did not define enough timestamps.");


Is there an easier way to use Rx's GroupBy operator? I'm just playing with the concept of GroupBy inside Rx. So, I wondered how hard it would be to write a console application that continuously reads lines, groups them by similar words and just prints out the word among the current count of how often the word was written before. It really was a breeze to do that but I wonder if my attempt could be rewritten in a more elegant way. Especially if I can get rid of the nested Subscribes.

Here is what I have:

static void Main(string[] args)
{
    var subject = new Subject<string>();

    var my = subject.GroupBy(x => x);

    my.Subscribe(x => x.Scan(new { Chars = string.Empty, Count = 0},
                                 (a, chars) => new { Chars = chars, Count = a.Count + 1})
      .Subscribe(result => Console.WriteLine("You typed {0} {1} times", result.Chars,
                 result.Count)));

    while (true)
    {
        subject.OnNext(Console.ReadLine());
    }
}

Result

test
you typed test 1 times
test
you typed test 2 times
hallo
you typed test 1 times
test
you typed test 3 times
...

You could use also use a counter provider per grouping observable, in the form of zipping a large stream of integers, like so:

static void Main(string[] args)
{
    var input = GetConsoleLines().ToObservable().TakeWhile(line => !string.IsNullOrEmpty(line));
    input.GroupBy(word => word)
         .SelectMany(grouping => grouping.Zip(Observable.Range(1, int.MaxValue), (s, i) => new Tuple<string, int>(s, i)))
         .Subscribe(r => Console.WriteLine($"you typed {r.Item1} {r.Item2} times"));
}

public static IEnumerable<string> GetConsoleLines()
{
    while(true)
        yield return Console.ReadLine();
}


Selection Sort Java -Arraylist I have implemented selection sort in java using arraylist. This selection sort is only for integers . Please have a look and give feedback. can we improve it ?

package selectionSort;

import java.util.ArrayList;
import java.util.Scanner;

public class SelectionSort {
private ArrayList<Integer> num_sort=new ArrayList<>();

public SelectionSort(ArrayList<Integer> userlist) {
    this.num_sort=userlist;
    sort_select();

}

public void sort_select() {
    //outer for loop to pick one element at a time
    //e.g if list is 20,12,3,4,5,6,98----this loop will first pick 20
    for(int i=0;i<this.num_sort.size();i++) {
        //assign that element as minimum
        //in our e.g 20 will be assigned min in first iteration
        int min=this.num_sort.get(i);
        int min_index=i;
        //go over the rest of the list and compare minimum by rest of list. if number smaller than min is found, then it is assigned as new min
        //so go over list starting from 12 and comparing 20 with each of them and finding the new min, in this case it will be  3
        for(int j=i+1;j<this.num_sort.size();j++) {
            if(this.num_sort.get(j)<min) {
                min=this.num_sort.get(j);
                min_index=j;

            }
        }
        if(i!=min_index) {
           exchange(i,min_index);
        }
    }
    System.out.println("Sorted entered are : ");
    for(int x:this.num_sort) {
        System.out.print(x+" ");
    }
}

// exchange the element at ith position with min
public void exchange(int current_elem,int new_min) {
    int temp=this.num_sort.get(current_elem);
    this.num_sort.set(current_elem, this.num_sort.get(new_min));
    this.num_sort.set(new_min, temp);

}

public static void main(String[] args) {
    // TODO Auto-generated method stub
    System.out.println("Enter how many numbers you want to sort");

    Scanner in=new Scanner(System.in);
    int num_count=in.nextInt();
    System.out.println("Enter the numbers you want to sort");
    ArrayList<Integer> userlist=new ArrayList<>();

    for(int i=0;i<num_count;i++) {
        userlist.add(in.nextInt());
    }

    SelectionSort s=new SelectionSort(userlist);

}

}

Style

Use proper styling. You should use more whitespaces, this will make your code more readable. Instead of num_sort=new use num_sort = new, insead of i!=min_index use i != min_index, etc
Follow the Java naming conventions: variable and function names should use camelCase, not snake_case.
You should include documentation that explains the user how the class is used. For example, without looking at the code I would not expect that creating a new instance of the class automatically sorts the list, so it is something you must make clear in the documentation.

Comments

Commenting the code is good, but too many comments can make a simple function look complicated. The general rule is that code tells you how, comments tell you why.

For example, I think int min = this.num_sort.get(i); does not need to be commented; it's pretty clear that you are getting the i-th item of the list.

Also, leave a whitespace between // and the text, it's more readable.

Code structure

It does not make sense to have this in a class; new SelectionSort(userlist) is not the way someone would expect to sort a list. I am going to make some recommendations that for the class design, but for the rest of the review I will restructurate the code so that it is more conventional.

As a user I expect select_sort to sort the list and that's all; I decide whether I want to print the list or not (what if I want to print it differently to you?). So you should move the printing code to the main function.

Class design

If you were to continue with the current class design, there must be some changes:

Do not sort the list in the construction. It is not the expected behaviour. Let the user call sortSelect(). Actually, I think selectionSort() would be a better name.
Is exchange a method that is meant to be used by the user? I don't think so, so make it private instead of public so only the class code can use it.
num_sort does not seem like an intuitive name; I had to look at the code to know what it is. Just calling it list would be better.
You don't care how the list is internally implemented, you only care that it is a list. So use the more generic List interface instead of ArrayList.
You are assigning your list twice: on num_sort=new ArrayList<>() and on this.num_sort=userlist;. The first one is not necessary, because it will always be replaced in the constructor. Furthermore, since you never reassign the list again, you should declare it final.

private final List<Integer> list;

public SelectionSort(List<Integer> userList) {
    this.list = userList;
}

Alternative design

In my opinion, your selection sort algorithm should just be one static method that takes the list as input. That would make it similar to the Collections.sort() method that already exists in Java.
Scanner is a resource that must be closed. You can make Java close it automatically by using a try with resources.

try (Scanner in = new Scanner(System.in)) {
    // your code
}

You can still keep the convenience method exchange (as static and taking the list as parameter), but since it is quite short and you only call it in one place I think you could just write the code directly. If you decide to keep the function, I would change the parameter names to just i and j, and the method name to swap (it's more common). Since it's the same doing exchange(current_elem, new_min) than exchange(new_min, current_elem) those parameter names do not make much sense. BUT you don't even need to implement that method, you can just use Collections.swap()

Final code

/**
 * Sorts the given list using a selection sort algorithm.
 * @param list The list to be sorted.
 */
public static void selectionSort(final List<Integer> list) {
    // outer for loop to pick one element at a time
    // e.g if list is 20,12,3,4,5,6,98----this loop will first pick 20
    for (int i = 0; i < list.size(); i++) {
        int min = list.get(i);
        int minIndex = i;
        // Go over the rest of the list and compare minimum by rest of list. If number smaller than min is found, then it is assigned as new min
        // So go over list starting from 12 and comparing 20 with each of them and finding the new min, in this case it will be  3
        for (int j = i + 1; j < list.size(); j++) {
            if (list.get(j) < min) {
                min = list.get(j);
                minIndex = j;
            }
        }
        if (i != minIndex) {
           Collections.swap(list, i, minIndex);
        }
    }
}

public static void main(String[] args) {
    try (Scanner in = new Scanner(System.in)) {
        System.out.println("Enter how many numbers you want to sort");
        int count = in.nextInt();

        System.out.println("Enter the numbers you want to sort");
        List<Integer> list = new ArrayList<>();
        for(int i = 0; i < count; i++) {
            list.add(in.nextInt());
        }

        selectionSort(list);

        System.out.println("Sorted entered are: ");
        for (int x : list) {
            System.out.print(x + " ");
        }
    }
}