Distinct sums of integers I need to get the distinct sums of naturals of a natural

What I came up with is:

type Sum = Stream[Int] //should maintain the invariant that
                       //* all Ints are positive
                       //* is non-strictly decreasing
                       //* is non-empty

def makesums(i: Int): Stream[Sum] = {

  /* Schmear will try to "schmear" a sum by decreasing the first number by one,
  and adding one again in the first position that won't violate the above invariants.
  This is possible when the stream is not all 1's, and the above invariants are met for
  the argument.

  returns an Option[Sum], which is Some(schmeared) if the above is possible,
  and None otherwise.
  */

  def schmear(sum: Sum): Option[Sum] = sum match {
    //if we can decrease the head and increase the next element while
    //staying ordered, do that
    case head #:: s #:: tail if (head - 1 >= s + 1) =>
      Some((head - 1) #:: (s + 1) #:: tail)

    //otherwise, if the head is only one larger than the second element, do the same,
    //but smear the tail, restoring the invariant
    case head #:: s #:: tail if head > s =>
      schmear((s + 1) #:: tail).map(nt => (head - 1) #:: nt)

    //otherwise, if there are at least two elements, just schmear the tail,
    //and keep the orignal head
    case head #:: s #:: tail =>
      schmear(s #:: tail).map(nt => head #:: nt)

    //otherwise, if the head is larger than 1, decrease by 1, and put a 1 at the end
    case head #:: tail if (head > 1) =>
      Some((head - 1) #:: tail  #::: Stream(1))

    //otherwise, it's not possible.
    case _ => None
  }

  def rec(sum: Sum): Stream[Sum] = {
    schmear(sum) match {
      case Some(schmeared) => sum #:: rec(schmeared)
      case None            => Stream(sum)
    }
  }

  //initiate the recursive algorithm with the sum of the identity
  rec(Stream(i))
}

Using this:

  println(makesums(5).map(_.toList).toList)

  List(List(5), List(4, 1), List(3, 2), List(2, 2, 1), List(2, 1, 1, 1), List(1, 1, 1, 1, 1))

Going through the algorithm:

Stream(5) takes case 4, yielding Stream(4, 1)
Stream(4, 1) takes case 1, yielding Stream(3, 2)
Stream(3, 2) takes case 2, starting with (3 - 1) = 2, and recurses with Stream(2 + 1) for the tail

Stream(3) takes case 4, yielding Stream(2, 1)

yielding Stream(2, 2, 1)
Stream(2, 2, 1) takes case 3, starting with 2, and recurses with Stream(2, 1)

Stream(2, 1) takes case 2, starting with (2 - 1) = 1, and recurses with Stream(2) for the tail
Stream(2) takes case 4, yielding Stream(1, 1)
yielding Stream(1, 1, 1)

yielding Stream(2, 1, 1, 1)
Stream(2, 1, 1, 1) takes case 2, taking 1 for the head, and recursing with Stream(2, 1, 1) for the tail

keep taking case 2 until you heave Stream(2)
Stream(2) takes case 4, yielding Stream(1, 1)

yielding Stream(1, 1, 1, 1, 1)

but if feels really complicated. In particular, having 5 different cases for the schmearing, which seems way more complicated than describing what you do.

What can I do to simplify this?

Apart from the five cases you have to distinguish, there is a more
severe problem with the code as it is: It misses some sums. In your
example of sums adding up to 5 it is the sum 3+1+1 that is missed. The
higher the number, the more sums will be missed.

The reason is that your algorithm greedily "schmears" down one from
the first number whenever possible. However, this should only happen
if the rest of the sum can not be schmeared anymore. So in your
example you have 3+2 and you try to reduce the 3 instead of splitting
up the 2 first.

If you fix that, an important consequence is that it is not sufficient
to modify the sum by schmearing alone, but you have to "reset" parts
of it it occasionally. If you go from 3+2 to 3+1+1, you cannot reach
2+2+1 anymore by schmearing.

A better strategy is trying to schmear the tail first and only if this
is not possible anymore, reduce the first number and reset the tail to
the most compact form not violating your invariants. This is what
uniformSum does in the following listing. Lets say your total is 10
and you reduce the first number to 3, then it sets the sum to 3+3+3+1.

type Sum = List[Int]

def sums(n: Int): Stream[Sum] = schmearStream(List(n))

def schmearStream(sum: Sum): Stream[Sum] =
  sum #:: (schmear(sum) map (schmearStream(_)) getOrElse Empty)

def schmear(nums: Sum): Option[Sum] =
  if (nums.isEmpty || nums.head == 1) None
  else schmear(nums.tail) match {
    case Some(schmearedTail) => Some(nums.head :: schmearedTail)
    case None => Some(uniformSum(nums.sum, nums.head - 1))
  }

def uniformSum(sum: Int, num: Int): Sum = {
  val rest = sum % num
  List.fill(sum / num)(num) ::: (if (rest == 0) Nil else List(rest))
}

You also see that it is sufficient to distinguish fewer cases because
you don't need a lookahead of 2. As long we don't have an
unschmearable sum (empty or starts with 1), we only care if we can
schmear the tail or not.

I tried to write it in a very compact form. If you think a function
should be more verbose for the sake of better readability, please let
me know.


Implement Factory pattern with multiple parameters and each parameters are interface I am a little bit confused on Factory Method with multiple parameters in which all parameters can change from GUI by user as seen below picture.

For each combobox item I have an interface and concrete implementations.
I have a SignalProcessor class which gets parameters as this 3 interfaces as below:
public interface ISignalProcessor
{
    double[] Process(double[] data);
}

public class SignalProcessor : ISignalProcessor
{
    private IFft _fft;

    private IWindowing _windowing;

    private IInverseSpectrum _inverseSpectrum;

    private IDecimation _decimation;

    public SignalProcessor(IWindowing windowing, IFft fft,  IInverseSpectrum inverseSpectrum, IDecimation decimation)
    {
        _windowing = windowing;
        _fft = fft;
        _inverseSpectrum = inverseSpectrum;
        _decimation = decimation;
    }

    public double[] Process(double[] data)
    {
        var windowingResult = _windowing.Calculate(data);
        var fftResult = _fft.Calculate(windowingResult);
        var inverseSpectrumResult = _inverseSpectrum.Calculate(fftResult);
        return _decimation.Calculate(inverseSpectrumResult);
    }
}

I decided to produce and use concrete classes according to the selected combobox values so the following factory class created.
  public static class FactorySP
{
    public static ISignalProcessor Create(string windowingType, int fftSize, bool isInverse, string decimationType)
    {
        return new SignalProcessor(CreateWindowing(windowingType), CreateFft(fftSize), CreateInverseSpectrum(isInverse), CreateDecimation(decimationType));
    }

    private static IWindowing CreateWindowing(string windowingType)
    {
        switch (windowingType)
        {
            case "Triangular":
                return new Triangular();
            case "Rectangular":
                return new Rectangular();
            case "Hanning":
                return new Hanning();
        }
    }

    private static IFft CreateFft(int fftSize)
    {
        switch (fftSize)
        {
            case 128:
                return new Fft128();
            case 256:
                return new Fft256();
            case 512:
                return new Fft512();
            default:
                return new FftNull();
        }
    }
    private static IInverseSpectrum CreateInverseSpectrum(bool isInverse)
    {
        if (isInverse)
            return new InverseSpectrumTrue();

        return new InverseSpectrumFalse();
    }

    private static IDecimation CreateDecimation(string decimationType)
    {
        if (decimationType == "RealTimeDecimation")
            return new RealTimeDecimation();

        return new SweepDecimation();
    }
}

Then used as follows:
_signalProcessor = FactorySP.Create(WindowingType, FftSize, InverseSpectrum, DecimationType);
result = _signalProcessor.Process(Enumerable.Range(0, 100).Select(a => (double)a).ToArray());

Is there a better way to get what I want than that? I feel there is something missing in the method I use :) I know Factory method is not like that but otherwise I have to create all combinations and permutations of overload of factory classes. Should I use the builder pattern to create the SignalProcessor object?

If I understand your intent and code properly then you rather have an abstract factory implementation than a factory method pattern implementation.

The Abstract Factory pattern, a class delegates the responsibility of object instantiation to another object via composition.

The Factory Method pattern uses inheritance and relies on a subclass to handle the desired object instantiation.

Reference 24th slide | Detailed discussion about the differences
Your FactoryFP exposes several methods to create multiple different objects (so called object family). Whereas a Factory Method's scope is a single object. And because of this an Abstract Factory can rely on multiple Factory Methods.

"Is there a better way to get what I want than that?"
As always it depends what do you want.

Do you want to hide direct object creation possibility? (Factory method refactoring)
Do you want to ease complex object creation? (Builder design pattern)
Do you want to have an easy to read complex object creation interface? (Fluent interface pattern)
etc.


Serialization/Deserialization with Generics in Java I've Implemented a Serialization Utility which Serializes/DeSerializes a class, along with writing JUnit Test Cases for the same.

Please Review the code and Suggest me how to improve it. Particularly in generics as I've not written much code with Generics in java.

SerializableEmployee.java - Class to be Serialized

public class SerializableEmployee implements Serializable{

    /**
     * This Serial version UID will change once any new version of class has been created
     */
    private static final long serialVersionUID = 1L;

    private String name;

    public SerializableEmployee(String name) {
        this.name = name;
    }

    public String getName(){
        return name;
    }

    @Override
    public String toString() {
        return "SerializableEmployee{" +
                "name='" + name + '\'' +
                '}';
    }
}

SerializationUtil.java - Util for Serializing and Deserializing

/**
 * Created by shashi on 21/12/15.
 *
 * @param <T> Type of class to Serialize and Deserialize from
 */
public class SerializationUtil<T> {

    /**
     * Logger for the class
     */
    public Logger LOG = LoggerFactory.getLogger("WHAT to Write here instead of T.class");

    /**
     * Serializes the given {@link T} object and save it into a file
     * @param type {@link T} object to be Serialized
     * @param fileName File in which {@link T} object is to be saved
     *
     * @return boolean specifying if {@link T} object has been serialized
     */
    public boolean serialize(T type, String fileName) {

        try(FileOutputStream fileStream = new FileOutputStream(fileName);
                ObjectOutputStream objectStream = new ObjectOutputStream(fileStream)) {
            objectStream.writeObject(type);
        }catch(IOException inputOutputException){
            LOG.error("Exception Occurred while Serializing {}. Message is ", "WHAT to Write here instead of T.class", inputOutputException.getMessage());

            return false;
        }

        return true;
    }

    /**
     * De-Serializes the given {@link T} object from the given file
     * @param fileName File from which {@link T} object has to be retrieved
     *
     * @return deserialized {@link T} object from the file
     */
    public T deSerialize(String fileName) {

        T employee = null;
        try(FileInputStream fileStream = new FileInputStream(fileName);
            ObjectInputStream objectStream = new ObjectInputStream(fileStream)) {
            employee = (T)objectStream.readObject();
        }catch(IOException | ClassNotFoundException inputOutputException){
            LOG.error("Exception Occurred while Serializing {}. Message is ", "WHAT to Write here instead of T.class", inputOutputException.getMessage());
        }

        return employee;
    }
}

SerializationUtilTest.java - jUnit Test cases for SerializationUtil class

/**
 * Created by shashi on 21/12/15.
 */
public class SerializationUtilTest {

    // Employee to Deserialize
    private static SerializableEmployee employee;
    // De-Serialized Employee
    private static SerializableEmployee deSerializedEmployee;

    // Utility class for Serialization
    private static SerializationUtil<SerializableEmployee> serializationUtil;

    // Provide Abstraction for Constants used
    interface Constants {
        String EMP_NAME = "Shashi";
        String FILE_NAME = "Emp-File";
    }

    @Before
    public void setUp(){
        employee = new SerializableEmployee(Constants.EMP_NAME);

        serializationUtil = new SerializationUtil<SerializableEmployee>();

        serializationUtil.serialize(employee, Constants.FILE_NAME);
        deSerializedEmployee = serializationUtil.deSerialize(Constants.FILE_NAME);
    }

    @Test
    public void employeeNotNullTest(){
        assertTrue(deSerializedEmployee != null);
    }

    @Test
    public void employeeNameEqualTest(){
        assertTrue(Constants.EMP_NAME.equals(deSerializedEmployee.getName()));
    }
}

SerializationUtil should work on T extends Serializable instead of T. This makes misuse harder.
Prefixing serializable to a data-holder is unnecessary for almost all intents and purposes.
You may be interested in operating on Path instead of String when Serializing and deSerializing
Your Util does not provide a way to serialize multiple instances of the same class :/


Determining whether or not a number is prime I wrote this code in Java without using any methods, just by using simple for loop and if statements.

When we input a number, it checks whether it's a prime or not. If it's a prime, then it prints "It's a prime". And if it's not a prime number, it says "It's not a prime" and prints the first number which divides it.

For example, if we input 1457, it will output "1457 is not a prime 1457 Divide by 31".

I want to know whether or not I can make this coding shorter.

import java.util.*;
public class PrimeNum{
public static void main(String args[]){
       Scanner x=new Scanner(System.in);
       System.out.println("Enter the number :  ");
       long y=x.nextLong();
       long i;
       for( i=2;i<y;i++){
       long z=y%i;
           if(z==0){
           System.out.println(y+" is not a prime");
           System.out.println(y+" Divide by "+i);
           i=y;
                         }

           }if(i==y) System.out.println("Number is prime");
            if(y==1) System.out.println("Number 1 is not a prime");
     }
}

Since this has been migrated to CodeReview, it makes sense to inspect it from a review perspective.

Others have correctly pointed out that the limit of your iteration is the root of the the number. That will impact the performance.... but what about your actual question: can the code be shorter (rather than faster)?

First, some comments....

you really should not use System.exit(...). A simple return would work better in this situation
You are not closing the Scanner when you are done with it. I know that in this case, working on System.in you don't think it's necessary, but, you should get in the habit of doing it. I have seen too many occasions where unclosed-handles create problems.
the variable names are horrible .... x, y and i? (Well, i is OK....).
in the current version of the code, you are still doing i++ and not i+=2. This is because you are starting at 2. If you start at 3 you can do a clean +=2.
Math.sqrt(...) returns a double. Doing a comparison against double for each loop is something the JIT compiler may be able to optimize, but I would err on the side of caution, and manually cast it outside the loop.

So, putting it together, I would suggest something like:

public static void main(String args[]){
    System.out.println("Enter the number:");
    try (Scanner scanner=new Scanner(System.in)) {
        final long target = scanner.nextLong();
        final long limit = (long)Math.sqrt(target);
        for(long factor = 2; factor <= limit; factor += factor == 2 ? 1 : 2){
            if(target % factor == 0) {
                System.out.printf("%d is not a prime\n%d divides by %d", target, target, factor);
                return;
            }

        }
        System.out.println(target + " is a prime number.");
    }
}

The above code is reasonably well structured, etc.

If I was aiming for raw performance though, and I threw out some of the validation rules, and allowed myself to hack it a bit, I would consider:

private static final long factor(final long target) {
    if (target <= 2) {
        return 1; // 1 and 2 are 'prime' external call will have to special-case 1 and negative numbers..
    }
    if ((target & 0x001) == 0) {
        return 2; // it's even.
    }
    final long limit = (long)Math.sqrt(target);
    for(long factor = 3; factor <= limit; factor += 2){
        if(target % factor == 0) {
            return factor;
        }
    }
    return 1;
}

public static void main(String args[]){
    System.out.println("Enter the number:");
    try (Scanner scanner=new Scanner(System.in)) {
        final long target = scanner.nextLong();
        final long fac = factor(target);
        if(fac > 1) {
            System.out.printf("%d is not a prime\n%d divides by %d", target, target, fac);
            return;
        }
        System.out.println(target + " is a prime number.");
    }
}

The reason for this is:

measuring performance with a single call is never going to do anything in Java - you need to call the code enough times to allow the JIT compiler to compile it.
It is unlikely that the JIT compiler will ever compile the main method
So I extract the 'hard' logic in to a seperate method that the JIT system can compile and isolate.
I handle the special cases seperately....
put the user-dialog outside the calculation....


Using includes() vs. hash function to check if an unordered_set is a subset of another unordered_set I did two methods to determine if an unordered_set is a subset of another unordered_set, using hashing, and the built-in includes().

I want to see if using a hash function will improve the run time, but I've noticed that there is no really big different in their time, so I start wondering, if what I did is the right idea of hashing!

Could you please look at my code to see if I did the hashing correctly?

#include <iostream>
#include <unordered_set>
#include <unordered_map>
#include <iomanip>
#include <algorithm>
#include <functional>

struct Sstruct {
    int Iv;
    float Fv1;
    float Fv2;
};

bool operator==(Sstruct a, Sstruct b) { return a.Iv == b.Iv; }

struct MyHash {
    size_t operator()(const Sstruct& x) const { return std::hash<int>()(x.Iv); }
};

bool IsIn(const std::unordered_set<int>& S1, const std::unordered_map <int, std::unordered_set<int>>::const_iterator& iter)
{
    for (std::unordered_set<int>::const_iterator iter2 = iter->second.begin(); iter2 != iter->second.end(); ++iter2)

        if (S1.find(*iter2) == S1.end())
        {
            return false;
        }

    return true;

}

int main()
{

    std::unordered_set<Sstruct, MyHash> S1{ { 1, 0.9, 0.1 }, { 2, 0.8, 0.2 }, { 3, 0.9, 0.01 }, { 4, 0.7, 0.5 }, { 7, 0.7, 0.2 }, { 8, 0.1, 0.5 } };

    std::unordered_map <int, std::unordered_set<int>> S2;

    S2[0].insert({ { 1 }, { 2 }, { 3} }); //  S2 is a subset of S1
    S2[1].insert({ { 3}, { 4 }, { 5} }); // S2 is a subset of S1
    S2[3].insert({ { 2 }, { 4 } }); // S2 is  a subset of S1
    S2[4].insert({ { 3 }, { 4 }}); // S2 is  a subset of S1
    S2[5].insert({ { 3 },  { 5 } }); // S2 is a subset of S1
    S2[6].insert({ { 1 }, { 2 }, { 8 } }); //  S2 is a subset of S1
    S2[7].insert({ { 3 }, { 4 }, { 6 } }); // S2 is not a subset of S1
    S2[8].insert({ { 2 }, {7 } }); // S2 is  a subset of S1
    S2[9].insert({ { 7 }, { 8 } }); // S2 is  a subset of S1
    S2[10].insert({ { 5 }, { 6 } }); // S2 is not a subset of S1

    std::unordered_set<int > SetOne;

    for (std::unordered_set<Sstruct, MyHash> ::iterator iter = S1.begin(); iter != S1.end(); ++iter)
        SetOne.insert(iter->Iv);

    float time1, time2;

    time1 = (float)clock() / CLOCKS_PER_SEC;

    // method 1: using hashing
    /*for (std::unordered_map <int, std::unordered_set<int>>::const_iterator SetTwo = S2.begin(); SetTwo != S2.end(); ++SetTwo)
        {
        if ((IsIn(SetOne, SetTwo)) == true)
            std::cout << "S2 is a subset of S1";

        else
            std::cout << "S2 is not a subset of S1";

        std::cout << "\n";
    }*/

    // method 2 using STL includes()
    std::unordered_map <int, std::unordered_set<int>>::const_iterator SetTwo = S2.begin();
    while (SetTwo != S2.end())
    {
        if (std::includes(SetOne.begin(), SetOne.end(), SetTwo->second.begin(), SetTwo->second.end()))

            std::cout << "S2 is a subset of S1";

        else
            std::cout << "S2 is not a subset of S1";
        ++SetTwo;
        std::cout << "\n";
    }

    time2 = (float)clock() / CLOCKS_PER_SEC;

    std::cout << "\n  Finishing Time " << time2 - time1 << " secs";
    std::cout << "\n\n";

    std::cin.get();
}

There are several things that are problematic:

Broken code

The version using std::includes is actually broken. When you read up on std::includes you will find that it requires the ranges it is operating on to be ordered by some comparison function (defaults to operator<).

Now compare this with the source of the iterators which is a template call unordered_set.

You should not use std::includes on unordered_set because the element sequence of the latter does not satisfy the preconditions of the former, thus resulting in an invalid algorithm.

Meaningless benchmark

There are several problems with your benchmarking code (some of which have already been addressed):

executed only once: to reduce the impact of noise in the measurements the benchmark is usually done several times and then the average is calculated
too short measurement period: This is somewhat connected the previous one. If the runtime of an algorithm is very short (close to the time measurement granularity limit) there will be big steps for very little change so one would try to increase the runtime (again my doing multiple runs)
too little problem size: the effect of hashing is the advantage of \$O(1)\$ element access compared to \$O(log n)\$ (for trees) or even \$O(n)\$ for linear structures. However, these are only asymptotic complexities which become meaningful as n grows towards infinity. For the little problem sizes you are presenting here they hardly matter and are dominated by surrounding (constant complexity) code
you print results during measuring which will most likely account for most of the time you are measuring because printing is very slow.

C++ 11

If you've got C++11 then why not use the whole package?

Use range-based for to clean up messy iterator loops:

for (std::unordered_map <int, std::unordered_set<int>>::const_iterator SetTwo = S2.begin(); SetTwo != S2.end(); ++SetTwo)

can become

for (auto const &element: S2)

However notice that element is already the element pointed to by the dereferenced iterator.

Function Interface

Now that we got away from the iterator we should clean up the interface of IsIn. This function is far too specialized by taking an iterator. Instead take the type you want directly:

bool IsIn(const std::unordered_set<int>& haystack, std::unordered_set<int>& needles) {
    for (auto const& needle: needles)
        if(haystack.find(needle) == haystack.end())
            return false;
    return true;
}

I renamed the variables to make their intention more clearly (though they are not fitting for the current task). The function should probably be renamed too.

Unused Variable

What is the intention of variable S1? You initialize it and then just copy some of its values into SetOne. You could have just initialized SetOne and be done.

Wrong container type

Using an unordered_map for S2 is totally overkill. You have a continuous range of indices starting at 0 and it seems like you want to iterate this in exactly this order. You can use a vector for this and initialize it with the desired values:

std::vector<std::unordered_set<int>> S2{
    { { 1 }, { 2 }, { 3} }, //  S2 is a subset of S1
    { { 3}, { 4 }, { 5} }, // S2 is a subset of S1
    { { 2 }, { 4 } }, // S2 is  a subset of S1
    { { 3 }, { 4 }}, // S2 is  a subset of S1
    { { 3 },  { 5 } }, // S2 is a subset of S1
    { { 1 }, { 2 }, { 8 } }, //  S2 is a subset of S1
    { { 3 }, { 4 }, { 6 } }, // S2 is not a subset of S1
    { 2 }, {7 } }, // S2 is  a subset of S1
    { 7 }, { 8 } }, // S2 is  a subset of S1
    { 5 }, { 6 } }, // S2 is not a subset of S1
};

I would propose renaming S2 to testSets or some other name that indicates that there are multiple sets that should be tested. It may even be advisable to create two vectors, one with subsets and one that has no subsets.

Inadequate loop

In your second method you are using a while loop instead of a for loop. Benchmarkwise this might skew your results because you don't want to measure differences in the loops, so you should be using the same code there.

The for loop is clearly the better alternative here because you intend to loop over the whole container anyways.


React Redux mutating implementation I am making a Trello clone just for personal project and I wonder if my implementation on mutating the state is good.

My state is basically shaped like this:

boards: [
    {
        id: Number,
        title: String,
        tasks: Array,
        columns: Array,
        columnOrder: Array
    }
]

I want to mutate the state to add the new task to the tasks array given that the payload of the reducer has boardId, columnId, task.

My current implementation of adding a new object to an array:

switch (action.type) {
    case ADD_TASK: {
      console.log(state)
      let newBoard = state.boards.find(
        board => board.id === action.payload.boardId
      )

      let column = newBoard.columns.find(
        column => column.id === action.payload.columnId
      )
      column.tasks = [...column.tasks, action.payload.task]

      newBoard.columns = [...newBoard.columns, column]

      const addToBoard = state.boards.map(board => {
        if (board.id === action.payload.boardId) {
          board = newBoard
        }
        return board
      })

      const newState = {
        boards: addToBoard
      }
      console.log(newState)
      return newState
     //code omitted
 }

Is there a better way to mutate the state rather than my current implementation?

Mutation is generally discouraged in Redux (and React in general) because it breaks tooling/libraries that expect x === y to mean that x and y are the same throughout time.

If you use the React.useEffect or React.useMemo or React.useCallback dependency arguments, or React.memo, you'll run into problems if you mutate objects that you're passing.

We can clean up your code to avoid this mutation in several passes. First, we'll just remove the logs since they don't affect behavior (and they expose certain implementation details we'll want to change):

switch (action.type) {
  case ADD_TASK: {

    let newBoard = state.boards.find(
      board => board.id === action.payload.boardId
    )

    let column = newBoard.columns.find(
      column => column.id === action.payload.columnId
    )
    column.tasks = [...column.tasks, action.payload.task]

    newBoard.columns = [...newBoard.columns, column]

    const addToBoard = state.boards.map(board => {
      if (board.id === action.payload.boardId) {
        board = newBoard
      }
      return board
    })

    const newState = {
      boards: addToBoard
    }
    return newState
  }
  //code omitted
}

Next, let's inline some of these variables. newState and addToBoard are each only used once:

switch (action.type) {
  case ADD_TASK: {

    let newBoard = state.boards.find(
      board => board.id === action.payload.boardId
    )

    let column = newBoard.columns.find(
      column => column.id === action.payload.columnId
    )
    column.tasks = [...column.tasks, action.payload.task]

    newBoard.columns = [...newBoard.columns, column]

    return {
      boards: state.boards.map(board => {
        if (board.id === action.payload.boardId) {
          board = newBoard
        }
        return board
      })
    }
  }
  //code omitted
}

Next, consider this arrow function:

      board => {
        if (board.id === action.payload.boardId) {
          board = newBoard
        }
        return board
      }

You've made your control-flow more complicated by reassigning the parameter, when an early return would do just fine:

      board => {
        if (board.id === action.payload.boardId) {
          return newBoard
        }
        return board
      }

Also, we only actually need newBoard inside this function (it's never used more than once), so we can move it to where it's needed:

switch (action.type) {
  case ADD_TASK: {
    return {
      boards: state.boards.map(board => {
        if (board.id === action.payload.boardId) {
          let newBoard = state.boards.find(
            _board => _board.id === action.payload.boardId
          )

          let column = newBoard.columns.find(
            column => column.id === action.payload.columnId
          )
          column.tasks = [...column.tasks, action.payload.task]

          newBoard.columns = [...newBoard.columns, column]
          return newBoard
        }
        return board
      })
    }
  }
  //code omitted
}

Now we begin to see some redundancy! For example, newBoard is being initialized to "the board with id equal to action.payload.boardId, but we already have a name for it: that's just board! So we can actually get rid of the name newBoard entirely:

switch (action.type) {
  case ADD_TASK: {
    return {
      boards: state.boards.map(board => {
        if (board.id === action.payload.boardId) {
          let column = board.columns.find(
            column => column.id === action.payload.columnId
          )
          column.tasks = [...column.tasks, action.payload.task]

          board.columns = [...board.columns, column]
          return board
        }
        return board
      })
    }
  }
  //code omitted
}

But now we need to deal with the unnecessary mutations. We don't want to modify board (or any of its fields, like columns). Instead, we want to return a copy with changes.

We can do this in parts. For example, instead of

          board.columns = [...board.columns, column]
          return board

we can instead say

          return { ...board, columns: [...board.columns, column] }

which copies board and then replaces the columns field with the new given value.

We now have

          let column = board.columns.find(
            column => column.id === action.payload.columnId
          )
          column.tasks = [...column.tasks, action.payload.task]
          return { ...board, columns: [...board.columns, column] }

and similarly, we can change the last two lines to obtain the non-modifying equivalent:

          let column = board.columns.find(
            column => column.id === action.payload.columnId
          )
          return {
            ...board,
            columns: [
              ...board.columns, { ...column, tasks: [...column.tasks, action.payload.task] }
            ]
          }

However, at this point, it seems likely that you have a bug here. This change duplicates the entire column, in addition to adding the single task to it! It seems that you instead wanted to just add a task to the one column with matching ID, which we can do instead:

switch (action.type) {
  case ADD_TASK: {
    return {
      boards: state.boards.map(board => {
        if (board.id === action.payload.boardId) {
          return {
            ...board,
            columns: board.columns.map(column => {
              if (column.id === action.payload.columnId) {
                return { ...column, tasks: [...column.tasks, action.payload.task] };
              }
              return column;
            })
          }
        }
        return board
      })
    }
  }
  //code omitted
}

This gives us a fully cleaned-up and immutable version of your code. Of course, you might rightfully observe that this is more-heavily nested than your original, which is a common result of switching to non-mutating state. You can use some existing ones or build your own.

For example, in this case, you're frequently using the following pattern:

find a matching object in an array
return the array with all other objects unchanged, and apply a transformation to the one that matches

This is easy to write as a helper function. Here mapIf is used to select the right board and then the right column:

function mapIf(array, condition, transform) {
  return array.map(item => condition(item) ? transform(item) : item);
}

switch (action.type) {
  case ADD_TASK: {
    return {
      boards: mapIf(state.boards, board => board.id === action.payload.boardId, board => ({
        ...board,
        columns: mapIf(board.columns, column => column.columnId === action.payload.columnId, column =>
          ({ ...column, tasks: [...column.tasks, action.payload.task] })
        ),
      })),
    }
  }
  //code omitted
}

Even this is still a bit long, so you can write more helpers, like a hasId higher-order function:

function hasId(id) {
    return item => item.id === id
}

hasId returns a function that checks whether its argument has the original id. So we can instead write:

function mapIf(array, condition, transform) {
  return array.map(item => condition(item) ? transform(item) : item);
}

function hasId(id) {
  return item => item.id === id
}

switch (action.type) {
  case ADD_TASK: {
    return {
      boards: mapIf(state.boards, hasId(action.payload.boardId), board => ({
        ...board,
        columns: mapIf(board.columns, hasId(action.payload.columnId), column =>
          ({ ...column, tasks: [...column.tasks, action.payload.task] })
        ),
      })),
    }
  }
  //code omitted
}

Lastly, you frequently only want to touch one (or a couple) fields in an object. Here's one helper you can write to clean up access to the tasks and columns fields:

function onField(field, func) {
  return item => ({ ...item, [field]: func(item[field]) })
}

this helper allows you to write (for example) onField("x", val => val + 1) to get a function that increases the .x field of its argument by 1, leaving all the others alone. You can use it like so:

function onField(field, func) {
  return item => ({ ...item, [field]: func(item[field]) })
}

function mapIf(array, condition, transform) {
  return array.map(item => condition(item) ? transform(item) : item);
}

function hasId(id) {
  return item => item.id === id
}

switch (action.type) {
  case ADD_TASK: {
    return {
      boards: mapIf(
        state.boards,
        hasId(action.payload.boardId),
        onField('columns', columns => mapIf(
          columns,
          hasId(action.payload.columnId),
          onField('tasks', tasks => [...column.tasks, action.payload.task]),
        )),
      ),
    }
  }
  //code omitted
}

This change suggests a new way to write mapIf, so that it works better with onField, by making it return a transforming function instead of directly taking the array as an argument:

function onField(field, func) {
  return item => ({ ...item, [field]: func(item[field]) })
}

function mapperIf(condition, transform) {
  return array => array.map(item => condition(item) ? transform(item) : item);
}

function hasId(id) {
  return item => item.id === id
}

switch (action.type) {
  case ADD_TASK: {
    return onField(
      'boards',
      mapperIf(
        hasId(action.payload.boardId),
        onField(
          'columns',
          mapperIf(
            hasId(action.payload.columnId),
            onField('tasks', tasks => [...column.tasks, action.payload.task]),
          )
        ),
      ),
    )(state);
  }
  //code omitted
}

The main downside to this approach is that there's lots of nesting that can make it hard to understand what's going on. So if we make one more transformation, and write a chain helper, we can get the (in my opinion, rather beautiful):

function onField(field) {
  return func => item => ({ ...item, [field]: func(item[field]) })
}

function mapperIf(condition) {
  return transform => array => array.map(item => condition(item) ? transform(item) : item);
}

function hasId(id) {
  return item => item.id === id
}

function apply(transform) {
  return func => item => transform(func(item));
}

function chain(func, ...funcs) {
  if (func === undefined && funcs.length === 0) {
    return item => item;
  }
  return func(chain(...funcs));
}

switch (action.type) {
  case ADD_TASK: {
    return chain(
      onField("boards"),
      mapperIf(hasId(action.payload.boardId)),
      onField("columns"),
      mapperIf(hasId(action.payload.columnId)),
      onField("tasks"),
      apply(tasks => [...tasks, action.payload.task]),
    )(state)
  }
  //code omitted
}
```


Cutting stock recursion This problem is identical to the one here:

  Suppose that you have been assigned the job of buying the plumbing
  pipes for a construction project. Your foreman gives you a list of the
  varying lengths of pipe needed, but the distributor sells stock pipe
  only in one fixed size. You can, however, cut each stock pipe in any
  way needed. Your job is to figure out the minimum number of  stock
  pipes required to satisfy the list of requests, thereby saving money
  and minimizing  waste.

  Your job is to write a recursive function

int cutStock(Vector<int> & requests, int stockLength);

  that takes two arguments—a vector of the lengths needed and the length
  of stock pipe  that the distributor sells—and returns the minimum
  number of stock pipes needed to  service all requests in the vector.
  For example, if the vector contains [ 4, 3, 4, 1, 7, 8 ]  and the
  stock pipe length is 10, you can purchase three stock pipes and divide
  them as  follows:

  Pipe 1: 4, 4, 1

  Pipe 2: 3, 7

  Pipe 3: 8

  Doing so leaves you with two small remnants left over. There are other
  possible  arrangements that also fit into three stock pipes, but it
  cannot be done with fewer.

/*
 * File: StockCutting.cpp
 * ----------------------
 * Name: abdulrhman eaita
 * This code minimize the needed stock for a diffrent length requests
 *
 */

#include <iostream>
#include "console.h"
#include "vector.h"
#include "simpio.h"
using namespace std;

/* Function prototypes */

int cutStock(Vector<int> & requests, int stockLength);
void bibesCutter(Vector<int> & requests, int stockLength, int &rest, int &bibes);
/* Main program */

int main() {
   Vector<int> requests;
   while (true) {
       while (true) {
           int x = getInteger("enter your requests, 0 to end: ");
           if(x == 0) break;
           requests.add(x);
       }
       int stoclLen = getInteger("Stock length?: ");
       cout << "Minimum number of stock pipes: " << cutStock(requests, stoclLen) << endl;
       requests.clear();
   }
   return 0;
}

/*
 * Function: cutStock
 * Usage: int units = cutStock(requests, stockLength);
 * ---------------------------------------------------
 * wrapper function for bibesCutter();
 */

int cutStock(Vector<int> & requests, int stockLength) {
    int bibes = 0;
    int rest = 0;
    bibesCutter(requests,stockLength, rest, bibes);
    return bibes;
}
/*
 * Function: bibesCutter
 * USage: bibesCutter(requests, stocklen, rest, bibes);
 * ----------------------------------------------------
 * Computes the minimum number of stock pipes required to satisfy
 * the vector of requests of individual pieces.
 */
void bibesCutter(Vector<int> & requests, int stockLength, int & rest, int & bibes){
    if (requests.size() == 1) {
        if (requests[0] > rest) {
            bibes++;

            //creating new rest as it's new stock and substracting the request after adding new bibe
            rest = stockLength - requests[0];

            return;
        }else{
            // substracting the request from current rest only.
            rest -= requests[0];
            return;
        }
    }else{
        Vector<int> tmp ;
        int toCheck = 0;
        // checking if there's a smaller value to remove first
        for (int i = 0; i < requests.size(); ++i) {
            if (requests[i] < rest) {
                toCheck = i;
            }
        }
        // removing first item by default, if there's no smaller cut.
        tmp += requests[toCheck];
        requests.remove(toCheck);
        bibesCutter(tmp, stockLength, rest, bibes);
        bibesCutter(requests, stockLength, rest, bibes);
        return;
    }
}

void function

The bibesCutter itself doesn't care how many bibes have been claimed already. It only calculates how many are needed for the remaining requests. Therefore I'd recommend to change its signature to

int bibesCutter(Vector<int> & requests, int stockLength, int & rest)

Recursion

The first recursive call to bibesCutter always falls into a base case (tmp has exactly 1 element). I suppose it is much cleaner to deal with it inline. At least you'd spare creating and destroying a vector.

Once this is done' you'd notice that a code becomes tail recursive, so the recursion could be eliminated at all.
Correctness

It would be nice to prove that the algorithm yields the optimal solution. The request to fulfill with the remaining piece of pipe (toCheck) is selected pretty much at random. That, along with the above observation on recursion elimination, is a red flag.
Misc

tmp and toCheck are not best identifiers.

stoclLen is a very funny typo.


Produce an array of strings from a single string I have a function that reads a string like this

(AnimalCount+HumanCount)

and the result of this function is an array of strings

[ "(" , "AnimalCount" , "+" , "HumanCount" , ")" ]

Now, I have done 2 functions in order to do this:

The first one to check if a given char is "special" from the input string

function Validate(Character: Char): Boolean;
begin
  Validate:= Character in [',' , '+' , '-' , '*' , '/' , '(' , ')' , '^' ,
                         '[' , ']' , '%' , '&' , '=' , '<' , '>' , ' ' ,
                         '.' , ';' , ':'];
end;

The second one to separate the strings from the input:

function GetToken(Chain:String):ArrayofString;
Var NTokens,i,j:Integer;
begin
  NTokens:=0;
  SetLength(Result,0);
  For i := 1 to Length(Chain) do
    if Validate(Chain[i]) then
      begin
        Inc(NTokens);
        setlength(Result,NTokens+1);
        Result[NTokens]:=Chain[i];
        Inc(NTokens);
      end
    else
      begin
        If Length(Result)<NTokens+1 then
          begin
            setlength(Result,NTokens+1);
            Result[NTokens]:='';
          end;
        Result[NTokens]:=Result[NTokens]+Chain[i];
      end;
end;

Additionally, I had to put this after type to make it work this way:

Arrayofstring = array of String;

This functions are working, but I wonder if there is any way to improve it even further.  I am new to Delphi, so any help would be appreciated.

Validate is a misleading name for what the function does. It does not validate anything - rather it checks if the given character is one of a special set. So it should be named IsSpecial or IsTokenDelimiter.
Growing an array one entry at a time is quite a bit of overhead. There are some ways of mitigating this.
Consider creating a local variable like currentCharacter in which Chain[i] - this would make it a little bit easier to read.


Advent of Code: "Not Quite Lisp" I have solved this simple challenge on Advent of Code:

  Santa is trying to deliver presents in a large apartment building, but
  he can't find the right floor - the directions he got are a little
  confusing. He starts on the ground floor (floor 0) and then follows
  the instructions one character at a time.

  An opening parenthesis, (, means he should go up one floor, and a
  closing parenthesis, ), means he should go down one floor.

  The apartment building is very tall, and the basement is very deep; he
  will never find the top or bottom floors.

This is my first time trying out Lisp (and functional programming at all) and would like to see if there is anything that I could do better, or more "functionally".

I wrote the function in a manner to be quite generic, i.e., it can take any input string, and any two characters. It returns a list containing the amount of up and down characters along with the difference between the two (which is the answer to the challenge). Demo on Coding Ground

(defun count-up-down-characters-with-difference (input-string up-char down-char)
    "Given a string of any length, iterate each character of the string looking for up- and down-characters
        provided by the caller, and return the number of each, as well as the difference between them."
    (setf count-up 0)
    (setf count-down 0)
    (loop for c across input-string do
        (if (char-equal c up-char)
            (incf count-up))
        (if (char-equal c down-char)
            (decf count-down)))
    (list count-up count-down (+ count-up count-down)))

Example generic usage:

(setf night-before-xmas "'Twas the night before Christmas, when all through the house, Not a creature was stirring, not even a mouse; The stockings were hung by the chimney with care, In hopes that St. Nicholas soon would be there;")
(time (print (count-up-down-characters-with-difference night-before-xmas #\e #\a)))
;; prints:
;(21 -10 11)
;Real time: 5.97E-4 sec.
;Run time: 5.7E-4 sec.
;Space: 1400 Bytes

The IDE you linked uses CLISP, which is a bit lenient; when I evaluate
that definition, I immediately get two warnings from SBCL:

; in: DEFUN COUNT-UP-DOWN-CHARACTERS-WITH-DIFFERENCE
;     (SETF COUNT-DOWN 0)
; ==>
;   (SETQ COUNT-DOWN 0)
;
; caught WARNING:
;   undefined variable: COUNT-DOWN

;     (SETF COUNT-UP 0)
; ==>
;   (SETQ COUNT-UP 0)
;
; caught WARNING:
;   undefined variable: COUNT-UP
;
; compilation unit finished
;   Undefined variables:
;     COUNT-DOWN COUNT-UP
;   caught 2 WARNING conditions

That is because count-up and count-down weren't defined anywhere.
It's implementation-defined what happens in this case.

So firstly let's define them with defvar:

(defvar *count-up*)
(defvar *count-down*)
...
(defvar +night-before-xmas+ "...")
...

(Constants usually have + as markers, globals *.  Indentation is
usually a bit different as well, I'm only going to show the
Emacs-formatted code without more explanation though.)

Then again, if you want a functional solution, don't use setf (that
is, assignment) or globals at all.  Instead (and in general) prefer
let.

A few other things to make it more idiomatic (for some value of
idiomatic) are the use of the most strict equality operator possible,
which here would be eql (since you check for exact equality between
characters), and not using if if there's only one case, instead when
or unless would be preferable.

(defun count-up-down-characters-with-difference (input-string up-char down-char)
  "..."
  (let ((count-up 0)
        (count-down 0))
    (loop
      for c across input-string
      do (when (eql c up-char)
           (incf count-up))
         (when (eql c down-char)
           (decf count-down)))
    (list count-up count-down (+ count-up count-down))))

loop also has more grammar to compress it more, but I think this is
fine for now.  Also consider using count instead of a manual loop, i.e.:

(defun count-up-down-characters-with-difference (input-string up-char down-char)
  "..."
  (let ((count-up (count up-char input-string))
        (count-down (- (count down-char input-string))))
    (list count-up count-down (+ count-up count-down))))

Or also (count up-char input-string :test #'char-equal) (see COUNT).


Registration and login Right now I'm creating a community. You can register and create your own profile and post on a forum etc. I'm just doing this for fun and learning. I'm not planning on becoming a professional programmer this is just a hobby of mine.

Anyway, I want do it right though. Please review my script and tell me if it seems OK and safe. And please if you have a suggestion or anything go ahead.

This is the login (I use sessions):

// Trim values sent from form
$username = trim($_POST['username']);
$password = trim($_POST['password']);

// Get user info and their rights matching login attempt
$stmt = $db->prepare("SELECT id, username, g_can_delete_users, g_can_edit_post, g_can_handle_reports FROM users LEFT JOIN groups ON groups.g_id = users.group_id WHERE users.username = ? AND SHA1(CONCAT(users.salt, ?)) = users.password");
$stmt->execute(array($username, $password));
$row = $stmt->fetch();

// Did we find a match?
if ($row) {
    $_SESSION['user'] = $row;
    header("Location: index.php");
    exit;
} else {
header("Location: index.php");
exit;
}

And the registration part:

// Example of a generated salt: &O93Wrl`x#iY

$username = trim($_POST['username']);
$email = strtolower(trim($_POST['email']));
    $password1 = trim($_POST['password1']);
    $password2 = trim($_POST['password2']);

    // Validate the username
    if (strlen($username) < 4)
        $errors[] = "Username must be at least 4 characters.";
    // ... and the password
    else if (strlen($password1) < 4)
        $errors[] = "Password too short";
    else if ($password1 != $password2)
        $errors[] = "Passwords do not match";
    else

$stmt = $db->prepare("INSERT INTO users (username, password, email, salt, registered, registration_ip) VALUES (:username, :password, :email, :salt, :registered, :registration_ip)");
        $stmt->execute(array(':username'=>$username, ':password'=>sha1($salt.$password1), ':email'=>$email, ':salt'=>$gen_salt, ':registered'=>time(), ':registration_ip'=>$_SERVER['REMOTE_ADDR']));

A few things to add to Michael Zedeler's review:

Your formatting is a little odd. Pick an indenting scheme and stick with it. (This seems to be part of a bigger script though, so maybe it's just copy/paste gone wrong?)

Don't assume array indexes exist (read the first section of this).

You assume username's are available?

By the HTTP standard, Location headers must have a full URL.

I would pull the hashed password into PHP land and do the comparison there. This has multiple advantages:

1) You can know whether the error is because the user doesn't exist or because the password is wrong
2) The MySQL query log is guaranteed to not contain the password in plain text

Your last if clause is a perfect example of why you should always use braces with if/else. It comes down to a stylistic choice whether or not to actually always use them, but in this situation, your code is wrong without them on the last clause:

    else
        $stmt = $db->prepare("INSERT INTO users (username, password, email, salt, registered, registration_ip) VALUES (:username, :password, :email, :salt, :registered, :registration_ip)");
        $stmt->execute(array(':username'=>$username, ':password'=>sha1($salt.$password1), ':email'=>$email, ':salt'=>$gen_salt, ':registered'=>time(), ':registration_ip'=>$_SERVER['REMOTE_ADDR']));

Is the same thing as:

    else {
        $stmt = $db->prepare("INSERT INTO users (username, password, email, salt, registered, registration_ip) VALUES (:username, :password, :email, :salt, :registered, :registration_ip)");
    }
    $stmt->execute(array(':username'=>$username, ':password'=>sha1($salt.$password1), ':email'=>$email, ':salt'=>$gen_salt, ':registered'=>time(), ':registration_ip'=>$_SERVER['REMOTE_ADDR']));

This means if that if any of the other branches are followed, you'll get an invalid object fatal error since you'll be trying to call execute on null.

What is the data type of registered? I'm a little concerned that it might be an int. It should be either a timestamp or a datetime (likely a timestamp in this situation).

While you've made good steps using sha1 and a salt, you might should consider using a better scheme for hashing. There's a lot of good information here.

I'd use a different flow to handle the errors. In particular, there's no reason that a username error and a password error can't happen at the same time:

$errors = array();

if (strlen($username) < 4) {
    $errors[] = "Username must be at least 4 characters.";
}

if (strlen($password1) < 4) {
    $errors[] = "Password too short";
} else if ($password1 != $password2) {
    $errors[] = "Passwords do not match";
}

if (!$errors) {
    //Create the user
}

You should declare $errors ahead of appending to it. $errors[] will create the variable fine without complaining, but it's much easier to read code if you know where all of the variables come into play. And, from a technical perspective, reading a non-existent $errors will complain (and error reporting should be cranked all the way up! especially in development).

I don't like the g_ prefix for the groups table. What happens when you run out of letters? What happens if you have another g table? It seems odd. I would just name the columns naturally, and then when you join on it, alias the columns when necessary.

(I agree with Michael though: your authentication and access code should be separate. Authenticate first and then worry about permissions.)

I don't know how I feel about triming a password. That could be confusing for someone who legitimately wants a space on the end of a password (and I'm a huge fan of not restricting what characters are allowed in passwords). Then again, it's a rather questionable choice to end a password with white space anyway.

I like to always use named parameters in prepared statements. It's easier to read, and it can save you from a "Wtf?" later if you rearrange or add clauses.

I don't see a session_start() anywhere? But I guess this is just a snippet of a bigger script?


An algorithm to calculate the check digit for 18-digit SSCC GS1 codes I'm calculating the GS1 SSCC codes that are 18-digit barcodes. The 18th digit is a check digit which is used to validate the rest of that code and check that it is correct. the check digit is a number between 0-9 and is calculated using a specific algorithm on the preceding 17 digits which are the input for this code. You can find more information on: http://www.morovia.com/kb/Serial-Shipping-Container-Code-SSCC18-10601.html

static int getCheckDigit(string SSCC)
{
    int[] SSCCArray = SSCC.ToCharArray().Select(c => (int)char.GetNumericValue(c)).ToArray();

    int position = 0;
    int oddPisitonsSUM = 0;
    int evenPositionsSUM = 0;
    int oddSumMultiply3;
    int totalSUM;
    int mod10Remainder;
    int CheckDigit;

    foreach (int i in SSCCArray)
    {
        position += 1;

        if (position % 2 == 0)
        {
            evenPositionsSUM += i;
        }
        else
        {
            oddPisitonsSUM += i;
        }
    }
    oddSumMultiply3 = oddPisitonsSUM * 3;
    totalSUM = oddSumMultiply3 + evenPositionsSUM;
    mod10Remainder = totalSUM % 10;

    if (mod10Remainder == 0)
    {
        return mod10Remainder;
    }
    else
    {
        CheckDigit = (10 - mod10Remainder);
        return CheckDigit;
    }
}

There is no doubt a more elegant solution to this, but this is my first crack at it.
All constructive criticisms are welcome.

First, you iterate through the input string twice: the first time when converting string to int[] SSCCArray and the second time when iterating through array.

Next, you don't need to know the position itself in the array (or string), you just need to know if the position is odd or even. This can be reached via bool variable.

Next, what is the input string has some invalid chars? It makes sense to handle this case.

My proposal:

private static int getCheckDigit(string sscc)
{
    int oddPisitonsSum = 0;
    int evenPositionsSum = 0;

    bool evenPosition = false;

    foreach (char c in sscc)
    {
        int i = (int)char.GetNumericValue(c);
        if (i < 0)
        {
            // Invalid char detected
            continue; // or throw an exception
        }

        if (evenPosition)
        {
            evenPositionsSum += i;
        }
        else
        {
            oddPisitonsSum += i;
        }
        evenPosition = !evenPosition; // Toggle the flag
    }
    int totalSum = oddPisitonsSum * 3 + evenPositionsSum;
    int mod10Remainder = totalSum % 10;

    return mod10Remainder == 0 ? mod10Remainder : 10 - mod10Remainder;
}


Finding the shortest path (between source and destination) with the least number of edges I wrote a program which finds the shortest path between a source and a destination in a graph, so that the path will be to one with th least number of edges. In order to write it, I used Dijkstra's algorithm with several modifications.

Is there any way to improve or modify my code?

#include<stdio.h>
#include<string.h>
#define INFINITY 9999
#define n 5
#define s 0
#define d 4

void Dijkstra(int Graph[n][n], int _n,int _s, int _d);

int main()
{
    int Graph[n][n]={{0,6,5,1,INFINITY},{6,0,3,INFINITY,INFINITY},{5,3,0,2,5},{1,INFINITY,2,0,6},{INFINITY,INFINITY,5,6,0}};

    Dijkstra(Graph,n,s,d);
    getchar();
    return 0;

}

void Dijkstra(int Graph[n][n], int _n,int _s, int _d)
{

    int distance[n],pred[n] ,visited[n],edge[n]={0},count,mindistance,nextnode=_s,i,j;

    //pred[] stores the predecessor of each node
    //count gives the number of nodes seen so far
    //edge[] stores the number of edged of every vertex's shortest path
      from the source

    //initialize pred[],distance[] and visited[]
    for(i=0;i<n;i++)
    {
        distance[i]=Graph[_s][i];
        pred[i]=_s;
        visited[i]=0;
        if(distance[i]>0 && distance[i]<INFINITY)
            edge[i]++;        //the neighbours of the source
    }

    distance[_s]=0;
    visited[_s]=1;
    count=1;

    while(count<n-1 && nextnode!=_d )
    {
        mindistance=INFINITY;

        //nextnode gives the node at minimum distance
        for(i=0;i<n;i++)
            if(distance[i]<mindistance && !visited[i])
            {
                mindistance=distance[i];
                nextnode=i;

            }

            //check if a better path exists through nextnode
            visited[nextnode]=1;

            if (nextnode!=_d)
            for(i=0;i<n;i++)
                if(!visited[i])
                {
                    if(mindistance+Graph[nextnode][i]<distance[i] )
                    {
                        distance[i]=mindistance+Graph[nextnode][i];

                        pred[i]=nextnode;
                        edge[i]=edge[nextnode]+1;

                    }

                    if(mindistance+Graph[nextnode][i]==distance[i] )
                    {
                        if(edge[i] >= edge[nextnode]+1)

                        {pred[i]=nextnode;

                        edge[i]=edge[nextnode]+1;
                        }
                    }
                }

                count++;
    }

    //print the path

    i=nextnode;

printf("\n%d",_d);

j=_d;
do
{
  j=pred[j];
  printf("<-%d",j);
} while(j!=_s);

}

Naming
#define n 5
#define s 0
#define d 4

We normally use ALL_CAPS for preprocessor macros, to warn readers.
void Dijkstra(int Graph[n][n], int _n,int _s, int _d);

I'd prefer lower case for the function name and arguments (PascalCase is conventionally used for typedefs).  The identifiers beginning with underscore are risky, because they are reserved for use by your compiler and standard library; also they don't tell us anything about their meaning.  n seems to be the number of nodes; are s and d the start and target?
Separate the work from the I/O
At the moment, the Dijkstra() function both finds a route and prints it.  Well-structured code separates these two activities, so you can do other things with the route.  You'll need to define a suitable data structure to return for the route - you can start by filling in an array (remember to check bounds); perhaps move to a linked list or an allocated array.
Flexibility
At some stage, you'll want to move to supporting graphs of arbitrary size.  For that, you're going to need to change n from constant to variable, and allocate and free storage for the distances.  That will be worthy of its own review when you reach that stage.


Inserting OAuth data into a database I am totally new to PHP. I just wrote a PHP script for google oauth to pull the data and insert into my database. I don't know if my code is vulnerable to SQL injection. Should I have used prepared statements and should I rewrite the code?

index.php

 <?php ini_set('display_errors', 1);
    error_reporting(E_ALL ^ E_NOTICE); ?>

    <?php

    include_once("config.php");
    include_once("includes/functions.php");

    //print_r($_GET);die;

    if(isset($_REQUEST['code'])){
      $gClient->authenticate();
      $_SESSION['token'] = $gClient->getAccessToken();
      header('Location: ' . filter_var($redirect_url, FILTER_SANITIZE_URL));
    }

    if (isset($_SESSION['token'])) {
      $gClient->setAccessToken($_SESSION['token']);
    }

    if ($gClient->getAccessToken()) {
      $userProfile = $google_oauthV2->userinfo->get();
      //DB Insert
      //$gUser->setApprovalPrompt ("auto");

      $gUser = new Users();
      // As of PHP 5.3.0

      $gUser->checkUser('google',$userProfile['id'],$userProfile['given_name'],$userProfile['family_name'],$userProfile['email'],$userProfile['gender'],$userProfile['locale'],$userProfile['link'],$userProfile['picture'],$username);
      $_SESSION['google_data'] = $userProfile; // Storing Google User Data in Session
      header("location: feed.php");

      $_SESSION['token'] = $gClient->getAccessToken();
    } else {
      $authUrl = $gClient->createAuthUrl();
    }

      $email  = $_SESSION['google_data']['email'];
      $user = strstr($email, '@', true);
      $username = $user;
?>

functions.php

 <?php ini_set('display_errors', 1);
error_reporting(E_ALL ^ E_NOTICE); ?>

<?php
 session_start();
class Users {
    public $tableName = 'users';

 function __construct(){
        //database configuration
        $dbServer = 'localhost'; //Define database server host
        $dbUsername = 'root'; //Define database username
        $dbPassword = ''; //Define database password
        $dbName = 'livelor'; //Define database name

        //connect databse
        $con = mysqli_connect($dbServer,$dbUsername,$dbPassword,$dbName);
        if(mysqli_connect_errno()){
            die("Failed to connect with MySQL: ".mysqli_connect_error());
        }else{
            $this->connect = $con;
        }
    }

    function checkUser($oauth_provider,$oauth_uid,$fname,$lname,$email,$gender,$locale,$link,$picture,$username){
        $prevQuery = mysqli_query($this->connect,"SELECT * FROM $this->tableName WHERE oauth_provider = '".$oauth_provider."' AND oauth_uid = '".$oauth_uid."'") or die(mysqli_error($this->connect));
        if(mysqli_num_rows($prevQuery) > 0){
            $update = mysqli_query($this->connect,"UPDATE $this->tableName SET oauth_provider = '".$oauth_provider."', oauth_uid = '".$oauth_uid."' ,fname = '".$fname."', lname = '".$lname."', email = '".$email."', gender = '".$gender."', locale = '".$locale."', picture = '".$picture."', gpluslink = '".$link."', modified = '".date("Y-m-d H:i:s")."' WHERE oauth_provider = '".$oauth_provider."' AND oauth_uid = '".$oauth_uid."'") or die(mysqli_error($this->connect));
        }else{
            $insert = mysqli_query($this->connect,"INSERT INTO $this->tableName SET oauth_provider = '".$oauth_provider."', oauth_uid = '".$oauth_uid."', fname = '".$fname."', lname = '".$lname."', email = '".$email."', gender = '".$gender."', locale = '".$locale."', picture = '".$picture."', gpluslink = '".$link."', created = '".date("Y-m-d H:i:s")."', modified = '".date("Y-m-d H:i:s")."' ,  username='".$username."' ") or die(mysqli_error($this->connect));
        }

        $query = mysqli_query($this->connect,"SELECT * FROM $this->tableName WHERE oauth_provider = '".$oauth_provider."' AND oauth_uid = '".$oauth_uid."'") or die(mysqli_error($this->connect));
        $result = mysqli_fetch_array($query);
        return $result;

    }
}

I don't know that my code is vulnerable to SQL injection.

Yes, it is.

You should never put any variables directly into SQL statements. Even if you think that the variables may possibly be safe, it's just really bad practice, and you will mess it up sooner or later. In your case, an attacker could use the profile fields, which would very likely lead to SQL injection (this depends a bit on the input filter for the profile fields, but I would be surprised if it caught all injections, and you should definitely not rely on it).

  Should I have to use prepared statements and rewrite the code.

Yes. Prepared statements are the only reliable way to prevent SQL injection, and you should never write any SQL statements without prepared statements. It is bad style and very insecure.

Misc

You really don't want to display errors in production.
You have too much vertical whitespace.
Some may disagree, but 2 spaces for indentation makes code harder to read. If you need this because your code is too nested, remove some levels of nesting instead of removing indentation.
functions.php is quite a generic name. It also doesn't fit it's content at all. As it contains a class, it should have the same name as the class (possibly with .class added).
You should create your database connection only once, and then pass it to the functions needing it, instead of creating a new connection for each object needing it.
don't shorten variable names, just write them out.
don't die in functions, it makes it hard for the calling code to handle.


Finding acronyms with >=1 letters at the start of each consecutive word Problem
I'm seeking a clean and efficient way to determine whether one string is an initialism/acronym of another.
Example: IBM => International Business Machines
However, a key condition for my use case is that an initialism might be constructed using more than one letter from each consecutive word.
Example: ANEXAIST = An Example Is This
Working solution
My solution works, though only returns a single answer (even when multiple might exist - this is fine for my use case). I wonder if there's a cleaner and more efficient implementation?
s1 = 'anexithi'
s2 = 'an example is this'

def recursive_split(s1, s2, mapping=[]):
    for s1_sub in [s1[:i] for i in range(4)]:
        if s1_sub!='' and s1_sub == s2[:len(s1_sub)]:
            mapping_ = mapping + [(s1_sub, s2.split()[0])]
            if s1_sub == s1:
                return mapping_
            rec = recursive_split(s1[len(s1_sub):], ' '.join(s2.split()[1:]), mapping_)
            if rec is not None:
                return rec

recursive_split(s1, s2)

Output
[('an', 'an'), ('ex', 'example'), ('i', 'is'), ('thi', 'this')]

Correctness

Your code allows partial acronyms which doesn't seem right. "I'm seeking a clean and efficient way to determine whether one string is an initialism/acronym of another."
recursive_split('aei', 'an example is this')
# [('a', 'an'), ('e', 'example'), ('i', 'is')]

Performance 1

A list comprehension being fed into a for loop is not idiomatic. It would be better if you move the expression into the for's expression.
for i in range(4):
    s1_sub = s1[:i]

It should be clear if len(s1_sub) != i then s1_sub == s2[:len(s1_sub)] is going to call the body multiple times with the same values. To address this wastage we can bound the for loop.
for i in range(min(4, 1 + len(s2))):

Rather than s1_sub!='' we can start the range at 1.
for i in range(1, min(4, 1 + len(s2))):

If len(s1) < len(s2) then we are wasting iterations of the for loop when we could just adjust the range.
for i in range(1, min(4, 1 + len(s1), 1 + len(s2))):

If s1[:i] != s2[:i] then i+1 will always be false too. You should instead break if this is ever false.
for i in range(1, min(4, 1 + len(s1), 1 + len(s2))):
    s1_sub = s1[:i]
    if s1_sub != s2[:i]:
        break
    # do stuff

We don't need to slice s1 and s2 to compare the values. We can just index. This makes the range a little simpler.
for i in range(min(3, len(s1), len(s2))):
    if s1[i] != s2[i]:
        break
    s1_sub = s1[:1 + i]

def recursive_split(s1, s2, mapping=[]):
    for i in range(min(3, len(s1), len(s2))):
        if s1[i] != s2[i]:
            break
        s1_sub = s1[:1 + i]
        mapping_ = mapping + [(s1_sub, s2.split()[0])]
        if s1_sub == s1:
            return mapping_
        rec = inner(s1[len(s1_sub):], ' '.join(s2.split()[1:]), mapping_)
        if rec is not None:
            return rec

Clean code
Many of the changes above have increased the readability of your code.

The names s1 and s2 aren't very descriptive.

Performance 2
These are some more advanced performance changes. Depending on the person the decreased readability may not outweigh the performance gains.

Rather than using mapping=[] you can use a closure and pass a fresh mapping.
def recursive_split(s1, s2):
    def inner(s1, s2, mapping):
        for i in range(min(3, len(s1), len(s2))):
            if s1[i] != s2[i]:
                break
            s1_sub = s1[:1 + i]
            mapping_ = mapping + [(s1_sub, s2.split()[0])]
            if s1_sub == s1:
                return mapping_
            rec = inner(s1[len(s1_sub):], ' '.join(s2.split()[1:]), mapping_)
            if rec is not None:
                return rec
    return inner(s1, s2, [])

Constantly calling s2.split() and ' '.join(s2.split()[1:]) are very wasteful. Instead you could call str.split once and just work with the split list.
def recursive_split(s1, s2):
    def inner(s1, s2_index, mapping):
        try:
            s2 = s2s[s2_index]
        except IndexError:
            return None
        for i in range(1, min(4, 1 + len(s1), 1 + len(s2))):
            s1_sub = s1[:i]
            if s1_sub != s2[:i]:
                break
            mapping_ = mapping + [(s1_sub, s2s[s2_index])]
            if s1_sub == s1:
                return mapping_
            rec = inner(s1[len(s1_sub):], s2_index + 1, mapping_)
            if rec is not None:
                return rec
    s2s = s2.split()
    return inner(s1, 0, [])

We don't need to add s2s[s2_index] to mapping_ because s2_index only ever increases by 1 each time so we can do that outside of inner.
mapping_ = mapping + [s1_sub]

ret = inner(s1, 0, [])
if ret is None:
    return None
return list(zip(ret, s2s))

With mapping + [s1_sub] will make near duplicate copy each time you recurse. We can improve the performance by mutating the mapping.
To do this we just append to the stack where you did mapping + [s1_sub] and then pop after any recursion.
def recursive_split(s1, s2):
    def inner(s1, s2_index, mapping):
        try:
            s2 = s2s[s2_index]
        except IndexError:
            return None
        for i in range(min(3, len(s1), len(s2))):
            if s1[i] != s2[i]:
                break
            s1_sub = s1[:1 + i]
            mapping.append(s1_sub)
            if s1_sub == s1:
                return mapping
            else:
                rec = inner(s1[1 + i:], s2_index + 1, mapping)
                if rec is not None:
                    return rec
            mapping.pop()
    s2s = s2.split()
    ret = inner(s1, 0, [])
    if ret is None:
        return None
    return list(zip(ret, s2s))

We can do something similar to s1. However instead of appending and popping we can pop in the for loop and then extend after the for loop. As such we just need to reverse s1.
def recursive_split(s1, s2):
    def inner(s1, s2_index, mapping):
        try:
            s2 = s2s[s2_index]
        except IndexError:
            return None
        s1_sub = []
        for i in range(min(3, len(s1), len(s2))):
            s1_sub.append(s1.pop())
            if s1_sub[-1] != s2[i]:
                break
            mapping.append(s1_sub)
            if not s1:
                return mapping
            else:
                rec = inner(s1, s2_index + 1, mapping)
                if rec is not None:
                    return rec
            mapping.pop()
        s1.extend(s1_sub[::-1])
    s2s = s2.split()
    ret = inner(list(reversed(s1)), 0, [])
    if ret is None:
        return None
    return [
        (''.join(s1_sub), s2)
        for s1_sub, s2 in zip(ret, s2s)
    ]

We can use generators and a couple of tricks to reduce the line count.
def recursive_split(s1, s2):
    def inner(s1, s2_index, mapping):
        s2 = s2s[s2_index]
        s1_sub = []
        for i in range(min(3, len(s1), len(s2))):
            s1_sub.append(s1.pop())
            if s1_sub[-1] != s2[i]:
                break
            mapping.append(s1_sub)
            if not s1:
                yield mapping
            elif s2_index + 1 < len(s2s):
                yield from inner(s1, s2_index + 1, mapping)
            mapping.pop()
        s1.extend(s1_sub[::-1])
    s2s = s2.split() or ['']
    rets = (
        [(''.join(s1_sub), s2) for s1_sub, s2 in zip(ret, s2s)]
        for ret in inner(list(reversed(s1)), 0, [])
    )
    return next(rets, None)

Given your examples it would be better to use a greedy search. For each letter you recurse straight away however if you went from the point we break in the for loop then inner would never return None on your example data.
def recursive_split(s1, s2):
    def inner(s1, s2_index, mapping):
        s2 = s2s[s2_index]
        s1_sub = []
        for i in range(min(3, len(s1), len(s2))):
            s1_sub.append(s1.pop())
            if s1_sub[-1] != s2[i]:
                break
        while s1_sub:
            mapping.append(s1_sub)
            if not s1:
                yield mapping
            elif s2_index + 1 < len(s2s):
                yield from inner(s1, s2_index + 1, mapping)
            mapping.pop()
            s1.append(s1_sub.pop())
        # nonlocal counter
        # counter += 1
    # counter = 0
    s2s = s2.split() or ['']
    rets = (
        [(''.join(s1_sub), s2) for s1_sub, s2 in zip(ret, s2s)]
        for ret in inner(list(reversed(s1)), 0, [])
    )
    ret = next(rets, None)
    # print(counter)
    return ret

This prints 0, if you uncomment the code, where as the previous code printed 2 because it recursed on a from an and e from ex.

We can remove the recursion and so we can remove the stack frames.
In the previous example it should be clear that mapping is acting like a stack and we can actually get s2_index from it.
Additionally we can see that the code is quite reliant now on the fact that we're mutating s1.
So we can think of the code another way.

Build the rest of the stack based on the state of s1.

At first this is just the same as the for i in range(...) loop.
If there are no matches, s1_sub is empty, then we have to start the popping process.
Otherwise we add the value to the stack.
Then if the length of the stack is the same as s2s then we have a value to return.

Pop from the stack.

If we make a value in the stack empty, then we need to pop again from the stack, otherwise we'll have an infinite loop. As the builder will just build the exact same way.
If we pop from the entire stack, we're done.

def recursive_split(s1, s2):
    s1_ = list(reversed(s1))
    s2s = s2.split()
    stack = []
    while True:
        while len(stack) < len(s2s):
            s1_sub = []
            for value in s2s[len(stack)]:
                if not s1_ or value != s1_[-1]:
                    break
                s1_sub.append(s1_.pop())
            if not s1_sub:
                break
            else:
                stack.append(s1_sub)
                if len(stack) == len(s2s):
                    return [(''.join(values), s2) for values, s2 in zip(stack, s2s)]
        for _ in range(len(stack)):
            s1_.append(stack[-1].pop())
            if stack[-1]:
                break
            stack.pop()
        else:
            return


Generating random N-dimensional arrays For this code challenge, I want to create a performant function that creates a rectangular N-dimensional array. (min_dim_size, max_dim_size) is the span size of every dimension. So rectangular_properties is a list with sizes of every dimension of the matrix. The matrix contains random integer values. Also I want the matrix to be immutable on every dimension.

Now I have this code:

def random_hyperrectangular_matrix(dimensions, min_dim_size, max_dim_size):
    rectangular_properties = [randint(min_dim_size, max_dim_size) for _ in range(dimensions)]
    def recc2(dim):
        if dim == 0:
            return randint(0, 100)
        return tuple([recc2(dim - 1) for _ in range(rectangular_properties[dim - 1])])
    random_n_dimensional_matrix = recc2(dimensions)
    return random_n_dimensional_matrix

When I run my code it seems that the generation of this matrix takes a huge amount of time. Is there a lack of performance in it?
Does the generation of tuple([...]) out of a list takes much time?

For something like this, numpy is probably unbeatable in terms of performance, since its underlying functions are implemented in C.

In your case the implementation would be rather easy:

import numpy as np

def random_hyperrectangular_matrix(dimensions, min_dim_size, max_dim_size):
    shape = np.random.randint(min_dim_size, max_dim_size + 1, dimensions)
    return np.random.randint(0, 101, shape)

Note the +1 on the upper limits, since np.random.randint excludes the upper bound, whereas random.randint includes it.

Note also that dimensions is in this case limited to be less than or equal to 32 (because of limits in the internal implementation). Your algorithm will only fail once the recursion depth reaches the limit (1000 by default). But if you need more than 32 dimensions, you are probably doing something wrong, anyways...

This might also make the rest of your program (which you don't show) easier, because operations can act on each element of the array, or only certain dimensions.

With min_dim_size, max_dim_size = 2, 2 (the lowest practical numbers, and the same to eliminate one source of randomness in the timings) this consistently improves the timing (note the logarithmic scale on the y-axis):

Especially noteworthy is that at low dimensions, the numpy approach is basically constant in time. For higher dimensions it scales the same as your approach, but consistently lower.


Javascript Object of Arrays manipulation I am writing a function to decode data from a run length encoded format like:

{
  dataGroup: {
    count: [4, 4, 2, 1],
      dataOne: [1, 3, 2, 1],
      dataTwo: [7, -1, 9, 0],
      dataThree: [3, 8, 1, 2]
  }
}

to

{
  groupName: {
    dataOne:   [1, 1, 1, 1, 3, 3, 3, 3, 2, 2, 1],
    dataTwo:   [7, 7, 7, 7,-1,-1,-1,-1, 9, 9, 0],
    dataThree: [3, 3, 3, 3, 8, 8, 8, 8, 1, 1, 2]
  }
}

I have written two solutions to date but feel like there may yet be a better way.

function decode(obj) {

    const arrayLengthN = (N, data=null) => [...Array(N)].map(_ => data);

    const [ group ] = Object.keys(obj);
    const { count, ...data } = obj[group];
    const dataKeys = Object.keys(data);

    // method one

    // output object to be written upon iteration over count and data
    const output = {};

    // populate output with empty arrays to push to
    dataKeys.map(key => output[key] = []);

    // do the decoding
    count
        .map((n, i) => {
            dataKeys
                .map(key => {
                    output[key].push(...arrayLengthN(n, data[key][i]));
                });
        });

    // method two

    const otherMethod = {
        [group]: Object.assign(
            {},
            ...dataKeys.map((key) => {
                return {
                    [key] : count
                        .map((n, i) => dataKeys
                            .map(key => arrayLengthN(n, data[key][i]))
                        )
                        .flat(2)
                };
            })
        )};

    return {[group]: output}
    // or return otherMethod
}

Is there anything wrong with the first method? It feels clunky to create an object, add empty arrays to it, and then mutate that object from within a .map call. That being said, to me it seems far more readable.

Any help or comments much appreciated.

Cheers,

P

May i suggest a shorter code?

var data = {
  dataGroup: {
    count: [4, 4, 2, 1],
      dataOne: [1, 3, 2, 1],
      dataTwo: [7, -1, 9, 0],
      dataThree: [3, 8, 1, 2]
  }
}

var processedData = Object.keys(data.dataGroup).filter(key => key != 'count').reduce((acc, key) => {
  acc.groupName[key] = [];
  data.dataGroup.count.forEach((amount, index) => {
    for (let i = 0; i < amount; i++) {
      acc.groupName[key].push(data.dataGroup[key][index]);
    }
  });
  return acc;
}, { groupName: {}});
console.log(processedData);


Limiting the amount of Calls to a Server I have a server side operation which takes a percentage value from 0 - 100. The user controls this percentage using a SeekBar on the android client.

Time-wise the operation is expensive, so I don't want to send commands faster than the server can update. To limit the amount of actions sent, I have limited the client it to 10 calls per second by doing the following:

public class ControlPanel extends Activity {
    private SeekBar seekbar;

    private Thread updateServerThread;
    private final Runnable updateServerRunnable = new Runnable() {
        @Override
        public void run() {
            try {
                updateServer(seekbar.getProgress());
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    };

    @Override
    protected void onCreate(final Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.control_panel);

        seekbar = (SeekBar) findViewById(R.id.my_seekbar);

        seekbar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekbar, int progress, boolean fromUser) {
                if (updateServerThread == null || !updateServerThread.isAlive()) {
                    updateServerThread = new Thread(updateServerRunnable);
                    updateServerThread.start();
                }
            }
            @Override public void onStartTrackingTouch(SeekBar seekbar) { }
            @Override public void onStopTrackingTouch(SeekBar seekbar) { }
        });
    }
    ...

I see several problems with your code:

You're mixing server code with UI
You're leaking activity reference in the Runnable
Your call takes longer time than 100ms
With code inside of you runnable you will miss changes to values that happened after the thread started (if it's not finished yet)

It is quite extensive to solve the first point. But all other points are quite easy to do:

Make inner class static and use a static variable to be delivered to server. This is not a nice solution, since everything should be stateless but at least you will fix the memory leak. If you make a presenter or uploader class that I would always notify it about UI updates and this new class will be resposnsible about removing back pressure from network uploading
I don't know if it is problem or not but I will do it a bit differently. I would create a Handler and submit Runnable to upload with delay 1 second (or your preferrable delay). And if there are changes are happening I would just reschedule the submission with same delay to later. So it will guarantee that you submit only "final" values in the delay context
Will be solved by #3


2 methods to parse the same pattern of line in a file I use 2 methods in order to parse those 2 lines:

flux=rp_evtmedprev_out
partitions=a054010a,a054020a,a054030a,a034040a,a054050a,a054060a,a054070a,a054080a,a054090a

This is the call:

BufferedReader reader = new BufferedReader(new InputStreamReader(
        httpConn.getInputStream()));
StringBuilder buf = new StringBuilder();
String line = null;

String flux = reader.readLine();
String partitionsString = reader.readLine();
insertToplogieNatures(flux, topologie);
insertToplogiePartitions(partitionsString, topologie);

Is there a way to merge those 2 methods:

public void insertToplogiePartitions(String line, Topologie topologie) {
    String[] splitLigneDeuxiemePartie = line.split("=");
    splitLigneDeuxiemePartie = splitLigneDeuxiemePartie[1].split(",");
    Partition partTemp;
    List<Partition> partitionsBuild = new ArrayList<Partition>();

    for (String partStringTemp : splitLigneDeuxiemePartie) {
        partTemp = new Partition();
        partTemp.setHostname(partStringTemp);
        partitionsBuild.add(partTemp);
    }
    topologie.setPartitions(partitionsBuild);
}

public void insertToplogieNatures(String line, Topologie topologie) {
    String[] splitLigneDeuxiemePartie = line.split("=");
    splitLigneDeuxiemePartie = splitLigneDeuxiemePartie[1].split(",");

    List<String> naturesBuild = new ArrayList<String>();

    for (String natureTemp : splitLigneDeuxiemePartie) {
        naturesBuild.add(natureTemp);
    }
    topologie.setNatures(naturesBuild);
}

If it's possible, I'm not even sure that it would be a good idea due to readability.

The first part could be merged, for sure.

public void insertToplogiePartitions(String line, Topologie topologie) {
    String[] splitLigneDeuxiemePartie = line.split("=");
    splitLigneDeuxiemePartie = splitLigneDeuxiemePartie[1].split(",");

Wrap it in a method

public String[] extractSplitLigneDeuxiemePartieFromLine(String line){
    String[] splitLigneDeuxiemePartie = line.split("=");
    return splitLigneDeuxiemePartie[1].split(",");
}

and use it like so:

public void insertToplogiePartitions(String line, Topologie topologie) {
    String[] splitLigneDeuxiemePartie = extractSplitLigneDeuxiemePartieFromLine(line);
    Partition partTemp;
    List<Partition> partitionsBuild = new ArrayList<Partition>();

    for (String partStringTemp : splitLigneDeuxiemePartie) {
        partTemp = new Partition();
        partTemp.setHostname(partStringTemp);
        partitionsBuild.add(partTemp);
    }
    topologie.setPartitions(partitionsBuild);
}

public void insertToplogieNatures(String line, Topologie topologie) {
    String[] splitLigneDeuxiemePartie = extractSplitLigneDeuxiemePartieFromLine(line);
    List<String> naturesBuild = new ArrayList<String>();

    for (String natureTemp : splitLigneDeuxiemePartie) {
        naturesBuild.add(natureTemp);
    }
    topologie.setNatures(naturesBuild);
}

For the rest, it's better to take a separate approach because these functions do different things.

Try Arrays.asList for the natures.

public void insertToplogieNatures(String line, Topologie topologie) {
    topologie.setNatures(
        Arrays.asList(extractSplitLigneDeuxiemePartieFromLine(line))
    );
}

For the partitions, you could perhaps simplify by making a new constructor for Partition that takes hostName as parameter:

public void insertToplogiePartitions(String line, Topologie topologie) {
    String[] splitLigneDeuxiemePartie = extractSplitLigneDeuxiemePartieFromLine(line);
    Partition partTemp;
    List<Partition> partitionsBuild = new ArrayList<Partition>();

    for (String partStringTemp : splitLigneDeuxiemePartie) {
        partTemp = new Partition(partStringTemp);
        partitionsBuild.add(partTemp);
    }
    topologie.setPartitions(partitionsBuild);
}

Allowing you to remove storing to temporary local variable:

public void insertToplogiePartitions(String line, Topologie topologie) {
    String[] splitLigneDeuxiemePartie = extractSplitLigneDeuxiemePartieFromLine(line);

    List<Partition> partitionsBuild = new ArrayList<Partition>();
    for (String partStringTemp : splitLigneDeuxiemePartie) {
        partitionsBuild.add(new Partition(partStringTemp));
    }
    topologie.setPartitions(partitionsBuild);
}

But now that you have only a single use of splitLigneDeuxiemePartie, you don't need to store that in a local variable either:

public void insertToplogiePartitions(String line, Topologie topologie) {
    List<Partition> partitionsBuild = new ArrayList<Partition>();
    for (String partStringTemp : extractSplitLigneDeuxiemePartieFromLine(line)) {
        partitionsBuild.add(new Partition(partStringTemp));
    }
    topologie.setPartitions(partitionsBuild);
}

Sometimes local stores help with clarification, and sometimes they don't. In this case, you have french variable names which I don't understand, and the local variable names don't help me understand your code, so I prefer the shortened form.

...

Although, if we're going to use a constructor which takes a hostName, you might as well label your temporary variable as such.

public void insertToplogiePartitions(String line, Topologie topologie) {
    List<Partition> partitionsBuild = new ArrayList<Partition>();
    for (String hostName : extractSplitLigneDeuxiemePartieFromLine(line)) {
        partitionsBuild.add(new Partition(hostName));
    }
    topologie.setPartitions(partitionsBuild);
}


Calculator Program improvements I'm pretty new to programming and made a few programs so far. I recently made a Calculator program and I hope you guys could tell me what I could do to improve.
int firstNumber;
string sign;
int secondNumber;
int answer;

Console.WriteLine("Input Number:");
firstNumber = Convert.ToInt32(Console.ReadLine());
Console.Clear();

Console.WriteLine("Input Sign:");
sign = Console.ReadLine();
Console.Clear();

Console.WriteLine("Input Second Number:");
secondNumber = Convert.ToInt32(Console.ReadLine());
Console.Clear();

switch (sign)
{
    case "+":
        answer = firstNumber + secondNumber;
        Console.WriteLine(answer);
        Console.ReadKey();
    break;
    case "-":
        answer = firstNumber - secondNumber;
        Console.WriteLine(answer);
        Console.ReadKey();
    break;
    case "*":
        answer = firstNumber * secondNumber;
        Console.WriteLine(answer);
        Console.ReadKey();
    break;
    case "/":
        answer = firstNumber / secondNumber;
        Console.WriteLine(answer);
        Console.ReadKey();
    break;
    default:
        Console.WriteLine("Invalid Input");
    break;
}

In general
Whenever you try to implement an application try to use sentences to describe the desired behavior. After that ask yourself: "Can it be further refined?" If so, then write new sentences to detail your plan in a more fine-grained level.
Let me show you what I mean:
The view from 10 000 feet

The application can perform basic operations between two operands.

What can be further refined?

What does it mean basic operation?
What did we mean by two operands?

High-level view

The application can perform basic operations between two operands.

It allows addition, subtraction, multiplication and division.

User can provide two numbers and the desired operation.
The application will perform it on the user's behalf.

What can be further refined?

How can an user provide numbers?

Fine-grained problem decomposition

The application can perform basic operations between two operands.

It allows addition, subtraction, multiplication and division.

User can provide two numbers and the desired operation.

The application receives an input from the user then it perform a preliminary check.

If it is valid then it goes to the next statement.
If it is invalid then it ask the user again to provide a valid input.

The application will perform it on the user's behalf.

Let's put together the skeleton
Now, we can translate each sentence into instructions.
This problem decomposition also helps us to well-organize our code:
///
/// The application can perform basic operations between two operands.
///
public static void Main()
{

}

///
/// User can provide two numbers and the desired operation.
///
private static void AskForInputs()
{

}

///
/// The application receives an input from the user then it perform a preliminary check.
/// <list type="bullet">
/// <item>
/// <description>If it is valid then it goes to the next statement.</description>
/// </item>
/// <item>
/// <description>If it is invalid then it ask the user again to provide a valid input.</description>
/// </item>
/// </list>
///
///
private static int AskForNumber()
{

}

///
/// The application receives an input from the user then it perform a preliminary check. <para />
/// It allows addition, subtraction, multiplication and division.
///
private static char AskForOperation()
{

}

///
/// The application will perform it on the users behalf.
///
private static void PerformRequestedOperation()
{

}

Observations about your implementation
The implementation is bit naive, because:

It does not handle those cases when the user provides malformed input

For example: instead of 3 (s)he provides three

It does not handle under- or overflow cases

For example: int.MaxValue + 100

It does not handle zero division case

For example: 100 / 0

It does not handle properly a division where the result is a floating number

For example: 10 / 3

etc.

In your switch statement you repeat the following two statement in each case:
Console.WriteLine(answer);
Console.ReadKey();

An alternative implementation could be:
switch (operation)
{
    case "+":
        answer = firstNumber + secondNumber;
    break;
    case "-":
        answer = firstNumber - secondNumber;
    break;
    case "*":
        answer = firstNumber * secondNumber;
    break;
    case "/":
        answer = firstNumber / secondNumber;
    break;
}

Console.WriteLine(answer);
Console.ReadKey();

This can be easily enhanced to include all the above validations as well:
switch (operation)
{
    case "+":
        answer = PerformAddition(lhs, rhs);
    break;
    case "-":
        answer = PerformSubtraction(lhs, rhs);
    break;
    case "*":
        answer = PerformMultiplication(lhs, rhs);
    break;
    case "/":
        answer = PerformDivision(lhs, rhs);
    break;
}

Console.WriteLine(answer);
Console.ReadKey();

Now as you can see we have introduced 4 new functions to abstract away the complexity to deal with different edge cases and the main flow remained easy to follow.


Cleaning HTMLs to extract text I have written the following routine to clean an html raw code and extract the text.

It works, but the code is not very well written. Any ideas how to solve this faster and with fewer lines of code?

Thanks a lot for your help!

import re
def cleanhtml(raw_html):
    cleanr = re.compile('<.*?>')
    cleantext1 = re.sub(cleanr, ' ', raw_html)
    cleanr = re.compile('&amp;')
    cleantext2 = re.sub(cleanr, '&', cleantext1 )
    cleanr = re.compile('\n')
    cleantext3 = re.sub(cleanr, ' ', cleantext2)
    cleanr = re.compile('&nbsp;')
    cleantext4 = re.sub(cleanr, ' ', cleantext3)
    cleanr = re.compile('&#8217;')
    cleantext5 = re.sub(cleanr, '\'', cleantext4)
    cleanr = re.compile('&#8230;')
    cleantext6 = re.sub(cleanr, '...', cleantext5)
    cleanr = re.compile('&#8216;')
    cleantext7 = re.sub(cleanr, '\'', cleantext6)
    cleanr = re.compile('&#8221;')
    cleantext8 = re.sub(cleanr, '\'', cleantext7)
    cleanr = re.compile('&#8220;')
    cleantext9 = re.sub(cleanr, '\'', cleantext8)
    cleanr = re.compile('&#8211;')
    cleantext10 = re.sub(cleanr, '\'', cleantext9)
    cleanr = re.compile('&#8212;')
    cleantext11 = re.sub(cleanr, '\'', cleantext10)
    cleanr = re.compile('&#38;')
    cleantext12 = re.sub(cleanr, '&', cleantext11)
    cleanr = re.compile('&#2026;')
    cleantext13 = re.sub(cleanr, '...', cleantext12)
    cleanr = re.compile('&#160;')
    cleantext14 = re.sub(cleanr, ' ', cleantext13)
    cleanr = re.compile('&#038;')
    cleantext15 = re.sub(cleanr, '&', cleantext14)
    return cleantext15.strip()

Since you have basically the same statements over and over with different parameters, this can be turned into a loop. You can pair the pattern and the string you want to use to replace in a dict. This makes it clear what is paired with what. Take a look:

import re

def strip_html(raw_html: str) -> str:
    pairs = {
        '<.*?>': ' ',
        '&amp;': '&',
        '\n': ' ',
        '&nbsp;': ' ',
        '&#8217;': '\'',
        '&#8230;': '...',
        '&#8216;': '\'',
        '&#8221;': '\'',
        '&#8220;': '\'',
        '&#8211;': '\'',
        '&#8212;': '\'',
        '&#38;': '&',
        '&#2026;': '...',
        '&#160;': ' ',
        '&#038;': '&'
    }
    previous = raw_html
    for pattern in pairs:
        clean_text = re.sub(re.compile(pattern), pairs[pattern], previous)
        previous = clean_text
    return clean_text.strip()