Data structure and movement for tilt maze (part 2) This is a design data structure and movement for a tilt maze. For example, this one.

My major idea is learned from abrarisme's smart idea of using two boolean matrix to represent wall. Please refer to this link for abrarisme's smart idea (Data structure and movement for tilt maze).

I need to (1) design the data structure to represent maze and (2) also implement movement function for 4 directions.

Since it is new code and I create this new post. Appreciate for code review advice on point (1) and point (2). Thanks!

An example of right matrix and related maze,

  __ __ __ __
 |__   |__   |           [[true,  false, true,  false]
 |  |  |     |            [false, false, true,  false],
 |  |   __|  |      =>    [false, true,  false, false],
 |     |   __|            [true,  false, true,  false],
 |__|__|__ __|            [false, false, true,  false]]

right = [[True, False, True, False],
         [False, False, True, False],
         [False, True, False, False],
         [True, False, True, False],
         [False, False, True, False]]
top = [[False, False, False, False],
       [False, True, False, True],
       [True, True, True, True],
       [True, True, False, True],
        [True, True, True, False]]

def move_right (start_x, start_y):
    while start_y < len(right)-1 and right[start_x][start_y] == True:
        start_y+=1
    return (start_x, start_y)

def move_left(start_x, start_y):
    while start_y >= 1 and right[start_x][start_y-1] == True:
        start_y -= 1
    return (start_x, start_y)

def move_top(start_x, start_y):
    while start_x > 0 and top[start_x][start_y] == True:
        start_x-=1
    return (start_x, start_y)
def move_down(start_x, start_y):
    while start_x < len(top) - 1 and top[start_x+1][start_y] == True:
        start_x+=1
    return (start_x, start_y)

if __name__ == "__main__":
    (x,y) = move_right(0,0)
    print(x,y) # output, (0, 1)
    (x,y) = move_down(x,y)
    print (x,y) # output, (4, 1)
    (x, y) = move_left(x, y)
    print (x,y) # output, (4, 1)
    (x, y) = move_top(x, y)
    print (x,y) # output, (0, 1)

I've a couple of problems with your code.

Creating both a right and top list splits up the data.
Instead you can merge flags into ints to reduce the amount of variables.

The way this can work is if we can 'move up' from that position we add 1.
If we can 'move right' we add 2.
This means if we can't move up or right, we will input 0.
Or if we can do both we'll input 3.

You can then expand on this to add 'move down' and 'move left'.
Where you'd add 4 if it's 'move down', and 8 if it's 'move left'.
This is as we should be able to move up, down, left and right from a single square.
Which would have the value \$1 + 2 + 4 + 8 = 15\$. Or if we couldn't 'move right' we'd have 13.
Your code is WET. As you write pretty much the same thing four times.
Instead I'd use a builder function to remove this duplicate logic.
This is as you can set the special changes in the builder function,
and mutate the data in the returned function.

Take:

def _move(band, x_inc, y_inc):
    def inner(x, y):
        maze = self.maze
        while maze[y][x] & band:
            x += x_inc
            y += y_inc
        return x, y
    return inner

move_right = _move(2, 1, 0)

I'd also like to point out that your variables are wrong.
Your x is actually the index on the y-axis.
This is as your board is in a y-major layout.
But you should fix this as it's outright confusing.
You're relying on a global variable.
This is bad. What if I make a global variable that overwrites yours?
Or if I want to have two boards in memory at the same time?

Instead you should create a class.
Nothing fancy, just an __init__ with top and right, or with my changes maze.
And your four functions.
You don't adhere to PEP8.
Sure, some people use a different style guide, but your code is not consistent.
So you should follow PEP8, like a hobgoblin, to build consistency.
This is as you:

Have both spaces and no spaces around your -=.
Have both a space and no space between your function name an it's parentheses.
Don't have consistent tabbing in your list top.

Sure it's three places of inconsistency, but your code is WET.
And definitely shouldn't have these inconsistencies if you copy and pasted the WET parts.
I'd like to also point out that your variable names start_x and start_y should instead be x and y.
As you're changing them, and so by the end of the function, they are no longer the starting x or y.

Additionally, to simplify the creation of the maze, so you only need to set the flags for if you can move up or right.
You can make a small private helper function.
This just adds if you can move down or left from the cell, without having to check the surroundings.
Just as I said in (1) above.

And so you can end with something like:

class Maze:
    def __init__(self, maze, position=(0, 0)):
        self.maze = self._normalize_maze(maze)
        self.position = position

    @staticmethod
    def _normalize_maze(maze):
        maze = maze[:]
        height = len(maze)
        width = len(maze[0])
        for y in range(height):
            for x in range(width):
                if not (0 <= maze[y][x] <= 3):
                    raise ValueError('Cells in array must be [0,3].')
                if y > 0:
                    maze[y-1][x] |= (maze[y][x] & 1) << 2
                if x > 0:
                    maze[y][x] |= (maze[y][x-1] & 2) << 2
        return maze

    def _move(band, x_inc, y_inc):
        def inner(self):
            maze = self.maze
            x, y = self.position
            while maze[y][x] & band:
                x += x_inc
                y += y_inc
            self.position = x, y
        return inner

    move_right = _move(2, 1, 0)
    move_left  = _move(8, -1, 0)
    move_up    = _move(1, 0, -1)
    move_down  = _move(4, 0, 1)

if __name__ == "__main__":
    maze = Maze([
        [2, 0, 2, 0],
        [0, 1, 2, 1],
        [1, 3, 1, 1],
        [3, 1, 2, 1],
        [1, 1, 3, 0],
    ])
    print(maze.position) # output, (0, 0)
    maze.move_right()
    print(maze.position) # output, (1, 0)
    maze.move_down()
    print(maze.position) # output, (1, 4)
    maze.move_left()
    print(maze.position) # output, (1, 4)
    maze.move_up()
    print(maze.position) # output, (1, 0)


Validating region/state/province codes for different countries I have a large table in which I store region/state/province codes (two letters) from different countries. I use these  region codes further downstream for multiple process. One of the steps I do is a cleanup of regions to ensure it is a valid region/state/province code. I have a lookup table consisting of a country vs region code to validate each column.

6 columns are validated separately. Is there a way to do this better?

UPDATE  table_region
SET     a_region = NULL
WHERE   a_region IS NOT NULL
        AND country IS NOT NULL
        AND dbo.IsValidRegion(country,a_region) = 0;

UPDATE  table_region
SET     b_region = NULL
WHERE   b_region IS NOT NULL
        AND country IS NOT NULL
        AND dbo.IsValidRegion(country,b_region) = 0;

UPDATE  table_region
SET     c_region = NULL
WHERE   c_region IS NOT NULL
        AND country IS NOT NULL
        AND dbo.IsValidRegion(country, c_region) = 0;

UPDATE  table_region
SET     d_region = NULL
WHERE   d_region IS NOT NULL
        AND country IS NOT NULL
        AND dbo.IsValidRegion(country,d_region) = 0;

UPDATE  table_region
SET     e_region = NULL
WHERE   e_region IS NOT NULL
        AND country IS NOT NULL
        AND dbo.IsValidRegion(country, e_region) = 0;

UPDATE  table_region
SET     f_region = NULL
WHERE   f_region IS NOT NULL
        AND country IS NOT NULL
        AND dbo.IsValidRegion(country, f_region) = 0;

The function is like this:

ALTER Function [dbo].[IsValidRegion](@country VARCHAR(20), @value

VARCHAR(20))
Returns INT
AS
BEGIN
    DECLARE @res INT
    BEGIN
        IF EXISTS (SELECT 1 FROM mapping.region WHERE country = @country AND region_code = @value)
            SELECT @res = 1
        ELSE
            SELECT @res = 0
    END
    RETURN @res
END

There's an intrinsic problem in using a scalar UDF to validate your country and region. Your scalar function essentially answers the "is it valid?" question for just a single pair of values - that might be fine in an "as-the-insert-happens" sense of a live system that only occasionally has a need for validation of a single row, but SQLServer design principles have a particular emphasis on thinking in terms of sets of data, rather than thinking of rows of data in a line-by-line fashion, requiring individual attention.

If you're performing this on a large table/lot of rows (let's say 100,000) then you could conceive that SQLServer will run your select query 600,000 times. It's going to be considerably slower to run more than half a million queries that pick out one item of data at a time, than it is going to be to run a query that joins together 100,000 rows (SQLServer is good at joining data efficiently) and then loops over it, checking some conditions and making changes.

There's a process you can follow that will allow SQLServer to more effectively pick apart your function and incorporate/integrate it with the main query more effectively, particularly in terms of processing the query in parallel - You can read more about it in blogs and stackexchange answers discussing swapping scalar UDFs for inline TVFs. Some relatively minor performance improvements can be had by compiling the function. There is also work afoot to improve SQLServer's ability to process scalar UDFs inline with the rest of the query, but at the moment it's potentially an absolute showstopper for the performance of your query

You also have the option of doing away with the function (or not using  it in this context) and doing the cleanup all in one go (and you could encapsulate this logic in a stored procedure if you wanted) :

    UPDATE t
    SET
       a_region = ra.region_code,
       b_region = rb.region_code,
       c_region = rc.region_code,
       d_region = rd.region_code,
       e_region = re.region_code,
       f_region = rf.region_code
    FROM
       table_region t
       LEFT OUTER JOIN mapping.region ra WHERE t.country = ra.country AND t.a_region = ra.region_code
       LEFT OUTER JOIN mapping.region rb WHERE t.country = rb.country AND t.b_region = rb.region_code
       LEFT OUTER JOIN mapping.region rc WHERE t.country = rc.country AND t.c_region = rc.region_code
       LEFT OUTER JOIN mapping.region rd WHERE t.country = rd.country AND t.d_region = rd.region_code
       LEFT OUTER JOIN mapping.region re WHERE t.country = re.country AND t.e_region = re.region_code
       LEFT OUTER JOIN mapping.region rf WHERE t.country = rf.country AND t.f_region = rf.region_code

It basically works by left joining the region table 6 times, once for each of the *_region columns.

If the relation works out, then the r*.region_code will be populated with a value (which means the *_region column is set to the same value it currently is, i.e. a non-op).
If it doesn't work out, then the join fails, null is present in r*.region_code

You could run this regularly as a periodic fix. You could also turn this into a SELECT query and run it, to identify the ones that are failed. If you were then to move those out (to another table) so your table only contains valid related records, you could then consider making table_region(country,*_region) have multiple foreign keys to mapping.region(country,region_code) to ensure that records cannot be inserted into table_region that don't have a valid country/region mapping. This devolves responsibility to maintaining a valid country/region pairing to the constraints mechanism of the database and it will become impossible to insert data that has an invalid country/region pairing


Simple AJAX view loading approach I'm writing my own MVC framework for learning purposes. Usually in my projects I like to use AJAX to send requests and retrive data. Now my doubt is if this can be a best approach to make a one page dashboard.

I've created an .htaccess who will display only folders that have an index file inside, the dashboard will be loaded only after user login, the login form is on the index file who is inside a folder named user. On the root of the project there is another index file who will be publicy available.

Assuming I've this code in the user dashboard file:

HTML

settings

show database entry

new insert

What is the best approach to load the requested view for the user selected action?
I want to avoid duplication of the jquery code who now is something like this

$('#open-settings').on('click',function(e){
    e.preventDefault();
    preloader.modal('show');
      $.ajax({
        type: 'GET',
        url: 'view/settings.php',
        cache: false,
        beforeSend: function(){
          preloader.modal('show');
      },
      success: function(response){
         $('#display-view').html(response)
      }
  });

Without really knowing a great deal about how your code is structured and basing it purely on your ajax function you could so somethhing like this;

function loadView(url, beforeSend, callback) {
    $.ajax({
        type: 'GET',
        url: url,
        cache: false,
        beforeSend: function(){
            beforeSend();
        },
        success: function(response){
            callback(response);
        }
    });
}

You could then use it like this

var showPreLoaderModal = function() {
    preloader.modal('show');
}

loadView("view/settings.php", showPreLoaderModal, function(response){
    $('#display-view').html(response)
});

But this is dirty the modern approach would involve promises!


Java TreeMap.floorKey() equivalent for std::map I wanted something equivalent to this Java program:

TreeMap<Integer,Integer> map = new TreeMap<Integer,Integer>();
    map.put(10, 100);
    map.put(20, 200);
    map.put(30, 300);
    map.put(40, 400);
    map.put(50, 500);
    map.put(60, 600);
    map.put(70, 700);
    map.put(80, 800);

    System.out.println(map.floorKey(5));
    System.out.println(map.floorKey(9));
    System.out.println(map.floorKey(10));
    System.out.println(map.floorKey(11));
    System.out.println(map.floorKey(90));

output:

null null 10 10 80

As there is no direct API to achieve the same in C++, I wrote the following code to implement a similar floorKey() function:

template <typename key,typename value>
int floorKey(map<key, value> input, int key)
{
    auto begin = input.begin();
    if (begin->first > key)//if key is less than the first key. It must retrun -1;
        return -1;

    auto end = input.end();
    end--;
    if (end->first < key)//if key is greater than last key, it must return last key
        return end->first;

    //if key is equal to any existing key, it should return the key
    auto find = input.find(key);

    if (find != input.end())
        return key;

    //Return the floor key for the given key
    auto lower = input.lower_bound(key);

    lower--;
    return lower->first;
}

Here's the test program:

int main()
{
    map<int, int> map;
    map.insert({ 10, 100 });
    map.insert({ 20, 200 });
    map.insert({ 30, 300 });
    map.insert({ 40, 400 });
    map.insert({ 50, 500 });
    map.insert({ 60, 600 });
    map.insert({ 70, 700 });
    map.insert({ 80, 800 });

    cout << floorKey(map, 5) << endl;
    cout << floorKey(map, 9) << endl;
    cout << floorKey(map, 10) << endl;
    cout << floorKey(map, 11) << endl;
    cout << floorKey(map, 90) << endl;
    return 0;
}

output:

-1 -1 10 10 80

Is there any better way to get the same?  Anything else I can improve?

Headers and namespaces
The function is missing a definition of map.  This is probably what you want:
#include <map>

using std::map;

Similarly, the main() needs:
#include <iostream>
using std::cout;
using std::endl;

That said, there's no good reason for std::endl in this code: an ordinary newline is sufficient, and we don't need the extra flushing behaviour of std::endl.
Naming
It's an error to use the typename key as the name of a parameter here:

template <typename key,typename value>
int floorKey(map<key, value> input, int key)

It's pretty idiomatic to use PascalCase for template arguments, to distinguish them from function parameters:
template<typename Key, typename Value>
int floorKey(std::map<Key, Value> input, Key key)

(I've also corrected the function to accept the correct type for the key argument).
There's a similar problem in main(), where we have a conflict between the type map and our identifier map.  This is one of the reasons I'd argue against bringing the type name into the global namespace.
Don't pass containers by value
We have a potentially large map, which we don't need to modify.  That suggests that it's better passed as a reference to a const object.  As we don't know the type of the key, we should probably assume that it's also better passed by reference (it could plausibly be a std::string, for example).  That gives us:
template<typename Key, typename Value>
int floorKey(const std::map<Key, Value>& input, const Key& key)

It's good that we used auto for the iterators begin and end, as it means that we don't need to change the body of the function to deal with them both now being const iterators.
Think about edge cases
What happens in this code when the input argument is an empty map?  We dereference input.first() without checking whether it's equal to input.end(), giving Undefined Behaviour at that point.
Algorithm
There's really no need to search for an exactly matching key if we then go on to call lower_bound() - we could just call upper_bound() instead, which will find the first key that's strictly greater than key, then decrement (if doing so is valid) to get the result:
auto it = input.upper_bound(key);

return it == input.begin()
    ? -1
    : (--it)->first;

Note that we have a problem here: if Key isn't a signed numeric type, then we can't return -1.  We really need a type-dependent value for this.  Better still, return a std::optional, so a defaulted value can be clearly distinguished from an actual result.

Modified code
#include <map>
#include <optional>

template<typename Key, typename Value>
std::optional<Key> floorKey(const std::map<Key,Value>& input,
                            const Key& key)
{
    if (auto it = input.upper_bound(key);  it != input.begin()) {
        return (--it)->first;
    } else {
        return std::nullopt;
    }
}

#include <iostream>

int main()
{
    std::map<int, int> map =
        {
         { 10, 100 },
         { 20, 200 },
         { 30, 300 },
         { 40, 400 },
         { 50, 500 },
         { 60, 600 },
         { 70, 700 },
         { 80, 800 },
        };

    std::cout << floorKey(map, 5).value_or(-1) << '\n'
              << floorKey(map, 9).value_or(-1) << '\n'
              << floorKey(map, 10).value_or(-1) << '\n'
              << floorKey(map, 11).value_or(-1) << '\n'
              << floorKey(map, 90).value_or(-1) << '\n';
}


Simple template engine in PHP I tried writing my very first template engine today. I designed it to just replace variables in templates, and keep it basic for now. Can anyone give me some constructive criticism?

I'm getting ready to write my own mini framework, and want to improve as much as I can. I just need to know if this is the default way (logic) to write one, or is there a better way?

<?php

class Template {

    public $variables = [];

    public function assign($key, $value) {
        $this->variables[$key] = $value;
    }

    public function render($template, $variables = []) {
        if (empty($variables)) {
            $variables = $this->variables;
        }

        $code = file_get_contents($template);

        foreach ($this->variables as $key => $variable) {
            $code = str_replace('%' . $key . '%', $this->variables[$key], $code);
        }

        return $code;
    }
}

This template is either unusable or would make you write HTML in the business logic part  spoiling the whole idea.

A template engine is a more complex application than people often think. There is always a presentation logic that could be quite complex. Which means a template must support programming statements. At least loops and conditions. Without them, it will be almost unusable.

Imagine you need to list 10 posts an a blog. How it could be done in your template? Going to add all the HTML formatting to variables before assigning them? Really?

So, such a simple template could be made viable only by letting PHP to interpret the template. So it could be like

public function render($template, $variables = []) {
    array_merge($this->variables, $variables);
    extract($variables)
    ob_start();
    include $template;
    return ob_get_clean();
}

this way you will be able to use full featured templates that will contain all the logic needed for the presentation of your data.


Inserting an object pointer to a two-level map I'm working on requirement that involves creating a N x N table of blocks, with each block having a weight.

Consider the following classes

Block - The fundamental unit of the table, having a weight
RowBlock - A set of blocks that join together one row
BlockTable - A set of rows that join together to form the table

The program simulates inserting one block at a time to form the table altogether.

I know it is not a C++ thing to play around with pointers but rather use const references, but again this is part of a bigger problem that we are trying to solve.

This below code seems to work for now. But I'm a novice C++ programmer, want to know the potential pitfalls/vulnerabilities in the code

#include <iostream>
#include <utility>
#include <stdint.h>
#include <cstdlib>
#include <map>

class Block
{
    private:
        int m_value;
    public:
        Block(int value)
        {
            m_value = value;
        }
        void setvalue(int value);
        int getvalue();
};

class RowBlock
{
    private:
        std::map<int, Block*> m_rowBlock;

    public:
        RowBlock() = default;
        void insertBlock(Block* newBlock);
        const std::map<int, Block*> getList();
};

class BlockTable
{
    private:
        std::map<int, RowBlock*> m_BlockTable;
    public:
        BlockTable() = default;
        ~BlockTable();
        void insertBlockRow(Block* newBlock);
        const std::map<int, RowBlock*> getList();
};

int Block::getvalue(void)
{
    return(m_value);
}

void RowBlock::insertBlock(Block* newBlock)
{
    m_rowBlock.emplace(newBlock->getvalue(), newBlock);
}

void BlockTable::insertBlockRow(Block* newBlock)
{
    std::map <int, RowBlock*>::iterator iter;
    RowBlock *localRowBlock = NULL;
    iter = m_BlockTable.find( newBlock->getvalue() );

    if( iter == m_BlockTable.end() )
    {
        localRowBlock = new RowBlock;
        localRowBlock->insertBlock(newBlock);
        m_BlockTable.emplace(newBlock->getvalue(), localRowBlock);
    }
    else
    {

        localRowBlock = iter->second;
        localRowBlock->insertBlock(newBlock);
        m_BlockTable.emplace(newBlock->getvalue(), localRowBlock);
    }
}

const std::map<int, RowBlock*> BlockTable::getList()
{
    return m_BlockTable;
}

const std::map<int, Block*> RowBlock::getList()
{
    return m_rowBlock;
}

BlockTable::~BlockTable()
{
    std::map<int, Block*>::iterator iter_1;
    std::map<int, RowBlock*>::iterator iter_2;
    std::map <int, RowBlock*> tmpList_1 = getList();
    std::map <int, Block*> tmpList_2;

    for ( iter_2 = tmpList_1.begin(); iter_2 != tmpList_1.end(); iter_2++ )
    {
        tmpList_2 = iter_2->second->getList();
        for ( iter_1 = tmpList_2.begin(); iter_1 != tmpList_2.end(); iter_1++ )
            delete iter_1->second;
        delete iter_2->second;
    }
}

int main() {
    BlockTable newBlockTable;

    for (auto i=1; i<=5; i++)
    {
        Block *newBlock = new Block(i*10);
        newBlockTable.insertBlockRow( newBlock );
    }

    std::map<int, Block*>::iterator iter_1;
    std::map<int, RowBlock*>::iterator iter_2;
    std::map <int, RowBlock*> tmpList_1 = newBlockTable.getList();
    std::map <int, Block*> tmpList_2;

    for ( iter_2 = tmpList_1.begin(); iter_2 != tmpList_1.end(); iter_2++ )
    {
        tmpList_2 = iter_2->second->getList();
        for ( iter_1 = tmpList_2.begin(); iter_1 != tmpList_2.end(); iter_1++ )
            printf("%d\n", iter_1->second->getvalue());
    }

    return 0;
}

General improvements

Names

C++ member and variable declarations don't tell you the type of an object; they tell you what operations on it are legal.  Prefer Block *newBlock (object dereferenceable to value of type Block) to Block* newBlock; the latter will only confuse you.

Tradition is to use all lowercase and separate words with underscores, but your naming convention is fine too.

Do you really mean "table"?

Technically, what you've written here is not a table, but closer to a jagged array.  You have no compile-time constraints forcing the members of each row to be of the same length, so you could have a table looking like this:

This image was pulled off the internet; the naming convention doesn't quite match your code.

Do you mean that to be the case?

It's not just the varying row lengths that's strange.  Because each row is a map to the values of each block, the idea of each block having a fixed index is wrong.  In short, make sure your data structure matches your mental image of it.

Finally, if you do want each block to have a fixed index and you want a rectangular table, I wouldn't bother with an intermediate data type RowBlock.  Instead, I would just have BlockTable manage the row/column distinction directly.  This also allows you to flatten your table, if performance demands: instead of n different rows of length n, you have a single array of length n*n.  What consumers of your class call the (r,c)th element is then internally at index n*r+c.  This reduces memory fragmentation.  I'm not going to flatten your tables for you, but it is something to consider.

Memory management

  I know it is not a C++ thing to play around with pointers but rather use const references, but again this is part of a bigger problem that we are trying to solve.

No!  The important thing is to be aware of the lifetime of your memory and ensure that your code architecture manages it correctly.  If you need mutable references, or just to allow nullptr sentinels, then pointers are the way to go.

Better still are the stdlib's smart pointers; choose std::unique_ptr or std::shared_ptr as appropriate.

A usual way to handle this is to assume that the lifetime of each block and row should be the lifetime of the enclosing row and table, respectively.  If a consumer wants to preserve data beyond that time, they'll need to copy or swap it away.

For example, you have lines like this:

const std::map<int, Block*> getList();

Never return large objects (like std::map) by value, if you can avoid it.

const std::map<int, Block*> &getList() const;

is better (and const-correct).

RAII

It should be hard to create your objects without initializing them.  (Ideally, it should be impossible, but for some of your objects,  induces undue performance limitations, so you'll have to trust your coworkers.)  This means you should support brace-initializion and swapping objects, so you don't need to create them twice.  For example, BlockTable should have lines looking something like this:

public:
    BlockTable() = default;
    BlockTable(std::initializer_list<std::pair<int,RowBlock>> &&elems) :
        m_BlockTable(elems)
    {}
    template<typename T>
    BlockTable(T start, T end) :
        m_BlockTable(start, end)
    {}
    friend std::swap<BlockTable>(BlockTable &&left, BlockTable &&right);

If you manage memory properly, using smart pointers, etc., your destructors should be trivial.  The long and complex ones you've written are a code smell.

Const-correctness

Your classes offer almost no support for const-correctness.  Make sure to mark procedures that do not mutate as such!  A consumer of your class who cares about const-correctness will have fits if you don't.

ABI?

You may want variants of these classes for different sizes of integers, i.e. long long int, short int.  The easy way to do this uses templates, but then compile-time constraints can be hidden by typos, and you do not have a consistent binary layout across compilers.  I'm going to assume that you specialized to int on purpose; the templated version is not much more than a find-and-replace if done correctly.

Synchronization

C++ is no longer a single-threaded language, but most code is still written that way.  I assume you externally synchronize any accesses to BlockTable objects in multithreaded contexts, in which case there is no problem.

I/O

C-style I/O (i.e. printf) has been superseded by <iostream>.  Prefer that, but if you aren't taking user input or writing anything complicated out, it doesn't matter too much.

MWE

You forgot to define Block::setvalue.  Did you mean

void Block::setvalue(int value)
{
    m_value=value;
}

perchance?  This also shows that your test suite (which appears to be main) is woefully incomplete.  Make sure the data structure behaves sanely with regard to inserted, non-random values!

Other stylistic tips

auto is your friend.  Use it.

The range-based for is your friend too.  Use that.

If you have to manipulate iterators by hand, prefer ++iter.  iter++ requires the iterator to spend a lot of effort copying itself, only for the old version to get promptly thrown away.

Specific rewriting

I don't understand the exact purpose of your data structure; the maps don't seem to do what your documentation in the question describes.  So I can't tell you how to make main more informative.  But even without understanding the most important semantics of your code, I can tell you that, if you can add a few constructors and automatic memory management to your data structures so that the following mechanical rewriting of main is correct, your code will be better.

void main()
{
    BlockTable newBlockTable;
    for (auto const i : {1, 2, 3, 4, 5})
    {
        newBlockTable.insertBlockRow(Block(i * 10));
        //or better:
        //newBlockTable.insertBlockRow({i * 10});
        //or maybe even:
        //newBlockTable.insertBlockRow(i * 10);
    }
    //or best of all:
    //BlockTable const newBlockTable{10, 20, 30, 40, 50};

    //The names of your variables were too uninformative; I've changed them
    auto const &row_map{newBlockTable.getList()}; //No need for complicated iterator types!
    for (auto const &key_and_row : row_map)
    {
        auto const &block_map{key_and_row.second->getList()};
        for (auto const &key_and_block : block_map)
            printf("%d\n", key_and_block.second->getvalue());
    }
    //If you aren't going to return anything but success, don't bother returning a value.
}


Returning nested array with added key=>value This works, but do I have to make a new array, result, or is there a way to just insert the field I need into each $key of the received parameter $data?

Won't this way take up more memory needlessly?

function add_tax($data){
            $result = [];
            foreach($data as $product => $details) {
                $details['tax'] = 0;
                $result[$product] = $details;
                }
            return $result;
          }

You could try something along these lines:

function add_tax($data){
        foreach($data as $product => $details) {
            $data[$product]['tax'] = 0;
        }
        return $data;
}

EDIT 1:

After a bit more researching on foreach I have come up with the following alternative:

function add_tax(&$data) {
    foreach($data as &$details)
        $details['tax'] = 0;
}

In reference to Alex L: I apologize, the original answer was rushed. The first snippet was simply a way of answering the question, that yes, it is possible to iterate through $data without generating a new variable. Also, to MikeiLL, yes, that would be a waste of memory. This second snippet passes both variables by reference, which does not require any excess usage of memory. It is the most optimal format of this process.

NOTE: The unset in the function is not exactly necessary, but as your question referenced memory usage, unset breaks the reference and releases that memory.

EDIT 2:

Due to very strong backing in the comments, I've removed the call to unset (truth be told I'd never use it myself, but wanted to reference it's usage within the function)


Python function to implement an image-processing pipeline I have written the following function to process images. Now I am not sure if it's pythonic or considered as spaghetti code. I know being flat is better than nested, but I don't see a way around it.

I could easily apply list comprehensions if the "if" statements are only resolving true/false, but each step depends on the output of the previous steps, so I don't think I could use itertools.

def get_image(width, height, collection_sku, order_id, name, handle):
    """image processing pipeline"""

    # Check-1 image exception should be checked before proceeding further
    # covers both images in exception(currently bookshelves) list and also personal true doors
    #   1. bookshelves need to be cropped
    #   2. personal images needs to be added in the required size
    if helpers.image_exception(collection_sku):

        # Step-1 Find image folder
        directory_sizes = helpers.find_directory(width, height)

        if directory_sizes is not None:
            # Step-2 Find the image from the given folder.
            key = helpers.find_image(directory_sizes, collection_sku)

            if key is not None:

                requires_resize = helpers.should_resize(width, height)
                requires_flip = helpers.should_flip(handle) and not helpers.flip_exception(collection_sku)

                # Check-2 check whether image requires resizing or flipping
                if requires_resize or requires_flip:

                    # Step-3 Create local directory to store temporary images
                    location, is_created = helpers.local_directory(
                        order_id)

                    if is_created:
                        # Step-4 Download image
                        image = helpers.download_image(key, location, name)

                        if image is not None:
                            width_px = helpers.cm_to_pixel(width)
                            height_px = helpers.cm_to_pixel(height)
                            image_modified = False

                            # Step-5.1 Resize image
                            if requires_resize:
                                helpers.resize_image(image, width_px, height_px)
                                image_modified = True

                            # Step-5.2 Flip image
                            if requires_flip:
                                helpers.flip_image(image)
                                image_modified = True

                            # Step-6 Upload image
                            if image_modified:
                                helpers.upload_image(image, key)

                    # Step-3 No local dir created
                    # Step-4 Can't download image
                    # Step-5.1 Can't resize image
                    # Step-5.2 Can't flip image
                    # Step-6 Can't upload image
                    return None

                # Check-2 if no image processing required then copy image over
                helpers.copy_image(key, target=None) # TODO
                return True

    # raise exception in sub job
    #   Check-1 if image door image cannot be processed
    #   Step-1 if directory not available
    #   Step-2 if image not available

    return None

As Reinderien mentions, you can decrease some of the complexity of your code by inverting your if-statements. While I cannot test this because I do not have your whole code, here is how it could be done:

def get_image(width, height, collection_sku, order_id, name, handle):
    """image processing pipeline"""

    # Check-1 image exception should be checked before proceeding further
    # covers both images in exception(currently bookshelves) list and also personal true doors
    #   1. bookshelves need to be cropped
    #   2. personal TD images needs to be added in the required size when it's submitted by the user.
    if not helpers.image_exception(collection_sku):
        return None

    # Step-1 Find image folder
    directory_sizes = helpers.find_directory(width, height)

    if directory_sizes is None:
        return None

    # Step-2 Find the image from the given folder.
    key = helpers.find_image(directory_sizes, collection_sku)

    if key is None:
        return None

    requires_resize = helpers.should_resize(width, height)
    requires_flip = helpers.should_flip(handle) and not helpers.flip_exception(collection_sku)

    # Check-2 check whether image requires resizing or flipping
    if requires_resize or requires_flip:

        # Step-3 Create local directory to store temporary images
        location, is_created = helpers.local_directory(
            order_id)

        if not is_created:
            return None

        # Step-4 Download image
        image = helpers.download_image(key, location, name)

        if image is not None:
            width_px = helpers.cm_to_pixel(width)
            height_px = helpers.cm_to_pixel(height)
            image_modified = False

            # Step-5.1 Resize image
            if requires_resize:
                helpers.resize_image(image, width_px, height_px)
                image_modified = True

            # Step-5.2 Flip image
            if requires_flip:
                helpers.flip_image(image)
                image_modified = True

            # Step-6 Upload image
            if image_modified:
                helpers.upload_image(image, key)

        # Step-3 No local dir created
        # Step-4 Can't download image
        # Step-5.1 Can't resize image
        # Step-5.2 Can't flip image
        # Step-6 Can't upload image

    # Check-2 if no image processing required then copy image over
    helpers.copy_image(key, target = None) # TODO
    return True

    # raise exception in sub job
    #   Check-1 if image door image cannot be processed
    #   Step-1 if directory not available
    #   Step-2 if image not available

This, for me, vastly increases readability -- before, it was hard to figure out which if-statements do what (especially with fragments of code at the ends of them). However, your comments are useful in describing the process as it goes along.

I'm sure it could be flattened more, but this should demonstrate the idea of it. Hope this helps!


Transform snake_case to camelCase I want to convert db columns such as is_deleted or product_code which consist of xx_xx to java-style names: isDeleted or productCode. I wonder if there is a way to improve my following code, using regex or such things.

def getJavaName(column):
   words = column.split('_')
   first = words[0]
   return first + ''.join((w.capitalize() for w in words[1:]))

You should remove the many trailing spaces.

You can replace slicing with unpacking and the double-brackets can be removed:

def getJavaName(column):
   first, *rest = column.split('_')
   return first + ''.join(word.capitalize() for word in rest)

Python uses snake_case, even if your DB columns don't, so you should be calling this get_java_name - although personally it's still better named snake_to_camel_case and the column parameter should be renamed to, say, name.


Pretty-print Pascal's triangle def printTrg(rows):
    r1 = [1]
    r2 = [1, 1]
    trg = [r1, r2]
    r = []
    if rows == 1:
        r1[0] = str(r1[0])
        print(' '.join(r1))
    elif rows == 2:
        for o in trg:
            for a in range(len(o)):
                o[a] = str(o[a])
            print((' ')*(2-(a+1)), (' '.join(o)))
    else:
        for i in range(2, rows):
            trg.append([1]*i)
            for n in range(1, i):
                trg[i][n] = (trg[i-1][n-1]+trg[i-1][n])
            trg[i].append(1)
        for x in range(len(trg)):
            for y in trg[x]:
                s = str(y)
                r.append(s)
            print((' ')*(rows-(x+1)), (' ' .join(r)))
            r = []

I've been learning Python for a month, and developed this program that prints out the Pascal triangle with the number of rows you want.  It works fine with 5 rows.

For example, it prints:

     1
    1 1
   1 2 1
  1 3 3 1
 1 4 6 4 1

But with more rows, it begins to be a little unbalanced because you have more digits on each number.

For example, a 10 row triangle:`

          1
         1 1
        1 2 1
       1 3 3 1
      1 4 6 4 1
     1 5 10 10 5 1
    1 6 15 20 15 6 1
   1 7 21 35 35 21 7 1
  1 8 28 56 70 56 28 8 1
 1 9 36 84 126 126 84 36 9 1

If you could help me with the output, it would be great.

EDIT:

def generate_pascals_triangle(rows):
    """ Returns a list of rows of a Pascal's Triangle with how many rows you want """
    triangle = [[1], [1, 1]]
    if rows == 1:
        return triangle[0]
    else:
        for row_number in range(2, rows):
            triangle.append([1]*row_number)
            for number in range(1, row_number):
                triangle[row_number][number] = (triangle[row_number-1][number-1]+triangle[row_number-1][number])
            triangle[row_number].append(1)
        return triangle

def difference_between_rows(row, next_row):
    """ Returns the difference between two rows in the formatted way """
    row_len = 0
    next_row_len = 0
    for number in row:
        string_number = str(number)
        row_len += (len(string_number)+1)
    for number in next_row:
        string_number = str(number)
        next_row_len += (len(string_number)+1)
    return (next_row_len-1) - (row_len-1)

def print_pascals_triangle(triangle):
    """ Prints the Pascal's Triangle previously generated by generate_pascals_triangle in a formatted form """
    for row in triangle:
        difference = int((difference_between_rows(row, triangle[len(triangle)-1]))/2)
        for number in range(len(row)):
            row[number] = str(row[number])
        print ((' ')*(difference), ' '.join(row))

if __name__ == '__main__': #credit to @alexwlchan
    again = 'y'
    while again == 'y':
        rows = int(input('Enter the number of rows you want in your Pascal`s Triangle: '))
        print_pascals_triangle(generate_pascals_triangle(rows))
        again = input('Do it again ? <y/n> ')

Some brief comments:

Your variable names are quite short (often one letter), which makes the code harder to follow. Longer and more descriptive variable names would make it easier to read and debug (e.g., trg to triangle, r1 to row1).

The input to the function printTrg is rows, but we also have variables like r, r1 and r2 which look like rows. Perhaps this would be better named as row_count?

The main style guide for Python is PEP 8, which is very readable and friendly. It gives advice on how you choose variable names, functions, and so on. In particular, for function names, it says:

  Function names should be lowercase, with words separated by underscores as necessary to improve readability.

So you should rename the function printTrg to be print_trg, or even better print_triangle, to match the Python conventions.

There's also something called a docstring, which is used in Python functions to explain what the function is supposed to do.
This usually occurs in triple quotes, directly below the def line.
For example, you might write:

def printTrg(rows):
    """Prints Pascal's triangle up to the (rows)th row."""
    ...

There's a more detailed explanation of docstrings in PEP 257.
Right now the code which generates Pascal's triangle, and the code which prints it to the console, are tightly bound together.
You might be better off splitting the two into two functions:

generate_pascals_triangle(row_count), which would return the list of lists trg which your function already creates.
print_pascals_triangle(triangle), which could take the output from generate and print it to the console.

The elif rows == 2 block is redundant, as the else block does exactly the same thing. The range(2, rows) never executes if rows is 2.

While we're in the else block, I’m unclear why your range goes to rows in the first for loop, but to len(trg) in the second. Unless I've confused myself, these are always the same thing. And later in the same loop, you use rows to count the number of spaces you need.
The way you generate the next row of Pascal's triangle (insert a list of 1s, update the entries, then put an extra 1 on the end) could be simplified. Since you’re making a list for the entries in that row, you could use a list comprehension. (If you're not familiar with these, then there are lots of good explanations on Google.)

Here's a simple example of a function which takes the previous row of Pascal's triangle, works out which row you're in now (by looking at the length of the previous row), then generates the new row with a list comprehension:

def next_row(row):
    """Returns the next row of Pascal's triangle."""
    n = len(row)
    new_row = [row[0]] + [row[i] + row[i+1] for i in range(n - 1)] + [row[-1]]
    return new_row

We're still doing essentially the same thing, but this looks cleaner, and we've split up some more of the logic. This can make life easier when it comes to debugging.

This also works if we give it the first row [1], so we don't need to consider the cases rows == 1 and rows != 1 separately when we generate Pascal's triangle. Again, we're able to simplify some of the code.
As you’ve pointed out, things get out of line if you print a large number of rows, as two and three digit numbers come in to play. If you split this into two functions, then you can play around with the printing without affecting the arithmetic (which works perfectly).

So with all that in mind, here's how I might rewrite your code.
First I have the function which I mentioned above, which takes one row of Pascal's triangle and returns the next:

def next_row(row):
    """Returns the next row of Pascal's triangle."""
    n = len(row)
    new_row = [row[0]] + [row[i] + row[i+1] for i in range(n - 1)] + [row[-1]]
    return new_row

Next, we have a function which just generates the entries of Pascal's triangle. Since we're not printing anything (that will come later), and the arithmetic for generating new rows is in another function, this is much shorter than before:

def generate_pascals_triangle(row_count):
    """Returns the entries of Pascal's triangle."""
    row1 = [1]
    triangle = [row1]
    for i in range(1, row_count):
        triangle.append(next_row(triangle[-1]))
    return triangle

If we wanted, we could supply the first entry (or even a whole first row) as an argument. You could see what happens if you make 2 the top entry, or started several levels deep. This is left for you to play with. (You may find this explanation of optional and named arguments useful.)

Finally, we come to the printing problem. We can use the logic from your else block, almost unmodified (just with more descriptive variable names):

def print_pascals_triangle(triangle):
    """Prints the entries of Pascal's triangle."""
    for row_no in range(len(triangle)):
        row = triangle[row_no]
        printed_row = []
        for entry in row:
            printed_row.append(str(entry))
        print (' ' * (len(triangle) - (row_no + 1)), ' '.join(printed_row))

If you wanted, that could become a little shorter using list comprehensions (I leave that as an exercise).

Here's an idea for how you could solve the spacing issue: first, find the longest number in your triangle. (You don't need to examine every entry: which row will always contain the longest entry?) Then, add spaces to every number you print, so that they're always the same length.

For example, if the longest entry was 2704156 (which you get in a 25-triangle), you would transform

1 -> _ _ _ 1 _ _ _

15 -> _ _ 1 5 _ _ _

165 -> _ _ 1 6 5 _ _

and so on. I haven't tried that, so I don't know how good it looks, but it might be something for you to get you started.

ETA: One more comment, based on your updated code:

At the end of the script, you have a little “interactive” section, which gets the user to give you a row count, and then you print their Pascal’s triangle.

If you load this file with import pascal-triangle in a larger script, then you immediately get asked to start drawing Pascal triangles. This can be unhelpful (imagine if everything you imported did that!).

Instead, you can put this code inside a special if statement:

if __name__ == '__main__':
    again = 'y'
    while again == 'y':
        rows = int(input('Enter the number of rows you want in your Pascal`s Triangle: '))
        print_pascals_triangle(generate_pascals_triangle(rows))
        again = input('Do it again ? <y/n> ')

Any code within this if statement is only used if the script is run directly; that is, if somebody types

$ python pascal-triangle.py

at a command prompt. If it gets loaded as import pascal-triangle in another script, then any code inside this if statement won’t be run. This means that you can reuse these functions later without any hassle.

You can find out more in this Stack Overflow question: https://stackoverflow.com/questions/419163/what-does-if-name-main-do


How to use inversion of control within a strategy when using the strategy pattern I am creating a skeleton application to demonstrate use of the Strategy design pattern and inversion of control inside a Strategy.

The application is the backend of a simple board game, which also has the capability to save and load the board. Since we can have different types of data stores for saving, I have used an interface PersistenceStrategy and concrete implementations of it like the FilePersistenceStrategy.

I have listed the code below. However, I am stuck in one place. Inside the FilePersistenceStrategy class, the save() as well as load() methods need to communicate with a file. I do not want these methods to create a file handle (Reader/Writer) themselves, since this will be bad for testability.

I know there are several ways for these methods to get hold of FileReader and FileWriter objects - like getting them from a factory, or getting the FQN from a properties file and instantiating them using reflection.

The most common method of solving this problem - Dependency Injection, cannot be used here because the load() and save() methods come from an interface and we cannot add Strategy specific parameters to the interface.

How would you solve this problem, and what in your opinion are the pros and cons of different approaches ?

Code follows:

Board.java

package com.diycomputerscience.example.sanddi;

public class Board {

    private PersistenceStrategy persistenceStrategy;
    private BoardState state;

    public Board(PersistenceStrategy persistenceStrategy) {
        this.persistenceStrategy = persistenceStrategy;
    }

    //various methods of playing the board game

    public void load() throws PersistenceException {
        this.state = this.persistenceStrategy.load();
    }

    public void save() throws PersistenceException {
        this.persistenceStrategy.save(this.state);
    }
}

BoardState.java

package com.diycomputerscience.example.sanddi;

public class BoardState {

}

PersistenceStrategy

package com.diycomputerscience.example.sanddi;

public interface PersistenceStrategy {
    public void save(BoardState state) throws PersistenceException;
    public BoardState load()  throws PersistenceException;
}

FilePersistenceStrategy.java

package com.diycomputerscience.example.sanddi;

import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;

public class FilePersistenceStrategy implements PersistenceStrategy {

    @Override
    public void save(BoardState state) throws PersistenceException {
        FileWriter writer = getFileWriter();
        //logic to save the state
        if(writer != null) {
            try {
                writer.close();
            } catch(IOException ioe) {
                String msg = "Could not close FileWriter";
                throw new PersistenceException(msg, ioe);
            }
        }
    }

    @Override
    public BoardState load() throws PersistenceException {
        FileReader reader = getFileReader();
        BoardState state = parseFileForBoardState(reader);
        return state;
    }

    private BoardState parseFileForBoardState(FileReader reader) {
        // TODO Auto-generated method stub
        return null;
    }

    /**
     * HOW DO I USE INVERSION OF CONTROL HERE FOR BETTER TESTABILITY ?
     * @return
     */
    private FileReader getFileReader() {
        // Create a FileReader from a well known file name...
        // perhaps a hardcoded name or read name from a config file
        return null;
    }

    /**
     * HOW DO I USE INVERSION OF CONTROL HERE FOR BETTER TESTABILITY ?
     * @return
     */
    private FileWriter getFileWriter() {
        // Create a FileWriter from a well known file name...
        // perhaps a hardcoded name or read name from a config file
        return null;
    }
}

PersistenceException.java

package com.diycomputerscience.example.sanddi;

public class PersistenceException extends Exception {
    //Override all constructors from the superclass

    public PersistenceException(String msg, Throwable cause) {
        super(msg, cause);
    }
}

For me the question is how the strategy is created. Is it possible to inject the file name during construction of the strategy? That would be the way I would do it.

Else you can create callbacks that are created and injected. When you need the file call this callback and let this decide (eg asking the user).


Sending an SMS message using zenoss and python I have just finished a simple python script which uses this module to call Zenoss API for getting live events. What the script does:

connects to zenoss
reads a file which has one phone number on each line
sends a message to each number by POSTing some data(first of all it authenticates) to a specific URL with the following parameters: phonenr, smstxt, Submit

The script speaks for itself and it doesn't need comments. What I'm looking for is some logic in the script / cases that I didn't covered / coding standards that are wrong / design patterns and maybe some advices on how I can improve the code ( in a way that will make each number receive the message at the same time - maybe using multithreading will help )

The file that contains the phone numbers looks like this:

phone_no1
phone_no2
..
phone_non

The code is:

#!/usr/bin/env python
# -*- coding: UTF-8 -*-

import urllib2 as urllib
from urllib import urlencode
from os.path import join as joinPath
from traceback import print_tb
from os.path import isfile
from sys import exc_info

import myzenoss

zenoss = myzenoss.Zenoss('ip_of_zenoss', 'admin', 'pass')
hdrs = {'User-Agent': "Mozilla/5.0 (X11; U; Linux i686) Gecko/20071127 Firefox/2.0.0.11"}
gh_url = 'http://ip-for-post/txsms.cgi'  # basically this is an IP for a Mobilink which sends the SMS

APPLICATION_PATH = '/srv/sms_alert/'
ALERT_POINT_PATH = joinPath(APPLICATION_PATH, 'alert_contact')

try:
    isInProduction = False
    for evt in zenoss.get_events():
        if evt['prodState'] == 'Production':
            isInProduction = True

            if isInProduction and isfile(ALERT_POINT_PATH):
                alertContactContent = None
                with open(ALERT_POINT_PATH, 'r') as alertContactFile:
                    alertContactContent = alertContactFile.read()
                alertContactContent = alertContactContent.splitlines()

                if alertContactContent:
                    evt['summary'] = ':zenoss]\n\nError: {0}'.format(evt['summary'])
                    evt['device']['text'] = '{0}'.format(evt['device']['text'])

                    final_message = '{0}\nName: {1}\n\n'.format(evt['summary'], evt['device']['text'])

                    for alertContactContentLine in alertContactContent:
                        data = {'phonenr': alertContactContentLine, 'smstxt': str(final_message), 'Submit': 'SendSms'}
                        data = urlencode(data)

                        req = urllib.Request(gh_url, data, headers=hdrs)
                        password_manager = urllib.HTTPPasswordMgrWithDefaultRealm()
                        password_manager.add_password(None, gh_url, 'admin', 'password')

                        auth_manager = urllib.HTTPBasicAuthHandler(password_manager)
                        opener = urllib.build_opener(auth_manager)

                        urllib.install_opener(opener)
                        handler = urllib.urlopen(req)
                break  # used this to only get the last event
            else:
                evt['summary'] = '#[ERROR: SMS ALERT NO CONTACT]# {0}'.format(evt['summary'])

except Exception as e:
    ex_type, ex, tb = exc_info()
    print('\n #[ERROR]#  TRANSFORM: exception: {ex}\n'.format(ex=e))
    print('\n #[ERROR]#  TRANSFORM: exception traceback: {trace}\n'.format(trace=print_tb(tb)))

The one coding standard is
PEP8 and indeed it would
be good if at least names are in common Python spelling, not like
Java.  E.g. it should be join_path (if you really want to rename
it), not joinPath, etc.
The names vs. positional arguments for format are a bit
inconsistent; I'd say that unless you have a lot of arguments you can
usually get by with unnamed positional instead, i.e.
"{} {}".format(...).
I don't like the tendency for stripping out characters in names
unnecessarily:  hdrs and evt aren't exactly much saving compared
to headers and event.
The import for os.path is mentioned twice, that could also be just
one line instead.
'{0}'.format(...) should probably be str(...) if you need the
string conversion.

Now for the structure I see a couple of things.

The try/catch block looks like it's not very much improving on
what the Python interpreter would print by default.
"Declaring" the isInProduction variable is not needed and
considering it's set to True immediately it looks like it's not
needed at all.  Or the indentation is wrong, in which case it should
instead be immediately initialised like
is_in_production = event['prodState'] == 'Production'.
Actually, initialising variables this way like again with
alertContactContent is just not useful in Python.  I'd likely move
reading the file and splitting the content into a function and use
that instead (like
alert_contact_content = read_and_split(ALERT_POINT_PATH) or so).
Again, the body of the innermost for-loop looks like it should be a
function instead, like create_auth_manager() and should only be
created once - unless I'm missing something all of those
password_manager instances are the same, so it makes sense to reuse
them instead.
I don't understand the break.  Or the comment on it.  At all.

Basically reading all of this nested stuff would be much easier if it
was structured, e.g. using functions or so.


Refactor jquery (coffescript) code with checkboxes I have two different set of checkboxes. With the coffescript code below I set the maximum amount of checkable items at 3. I would like to refactor this code, to be cleaner and compact, but I can't get it.

$("div.feature_list :checkbox").click ->
  if $("div.feature_list :checked").length >= 3
    $("div.feature_list :checkbox:not(:checked)").attr "disabled", "disabled"
    $("div.feature_list :checkbox:not(:checked)").button disabled: true
  else
    $("div.feature_list :checkbox:not(:checked)").button disabled: false

$("div.style_list :checkbox").click ->
   if $("div.style_list :checked").length >= 3
     $("div.style_list :checkbox:not(:checked)").attr "disabled", "disabled"
     $("div.style_list :checkbox:not(:checked)").button disabled: true
   else
     $("div.style_list :checkbox:not(:checked)").button disabled: false

Step 1: DRY. Encapsulate the "limit checkboxes" behavior in a function

limitCheckboxesIn = (container, limit = 3) ->
  checkboxes = $(container).find ":checkbox"
  checkboxes.on "click", (event) ->
    checked   = checkboxes.filter ":checked"
    unchecked = checkboxes.not checked
    state     = disabled: checked.length >= limit
    unchecked.prop(state).button state

Step 2: ... well, that pretty much it. Call it like so:

$ ->
  limitCheckboxesIn "div.feature_list"
  limitCheckboxesIn "div.style_list"

Here's a demo

By the way, if you just want the most compact solution, you can skip some assignments:

limitCheckboxesIn = (container, limit = 3) ->
  checkboxes = $(container).find ":checkbox"
  checkboxes.on "click", (event) ->
    disabled = checkboxes.filter(":checked").length >= limit
    checkboxes.not(":checked").prop({disabled}).button {disabled}

Personally, I find this a little less readable, but it's a matter of taste; the code's functionally identical.


My implementation of the Union-Find data structure in MATLAB I was assigned the connected components labeling (CCL) algorithm and in order to implement the CCL algorithm I first had to implement the Union-Find algorithm.

This is my try at it, any review and tip would be greatly appreciated

classdef UnionFind < handle
   properties
       PARENT = containers.Map('KeyType', 'double', 'ValueType','any');
   end
   methods
       % Constructor Function
%        function obj = UnionFind(items)
%            for i = 1:5
%                obj.PARENT(items(i)) = items(i);
%            end
%        end
       % Add Item Function
       function addItem(obj, itemToAdd)
          obj.PARENT(itemToAdd) = itemToAdd;
       end
       % Find Function
       function root = Find(obj, itemToFind)
          while (obj.PARENT(itemToFind) ~= itemToFind)
             obj.PARENT(itemToFind) = obj.PARENT(obj.PARENT(itemToFind));
             itemToFind = obj.PARENT(itemToFind);
          end
          root = itemToFind;
       end
       % Union Function
       function Union(obj, setOne, setTwo)
          obj.PARENT(setOne) = setTwo;
       end
   end
end

I made a scrip that executes your data structure to test it. It doesn't verify correctness, it's just for timing purposes.

tic
uf = UnionFind;
uf.addItem(1);
for ii = 2:10000
    uf.addItem(ii);
    n = randi(4);
    if n == 4 % happens in 25% of cases
        uf.Union(ii, uf.Find(randi(ii-1)));
    end
    if n ~= 1 % happens in 75% of cases
        uf.Union(uf.Find(ii), uf.Find(randi(ii-1))); % ii is no longer necessarily the root
    end
end
toc

Basically, it adds 10,000 elements to the data structure, taking the union of the new element with a randomly selected prior element in 50% of the cases, and with two prior elements in an additional 25% of cases. This does not exactly match how the data structure will be used in a connected components labeling algorithm (Find would be called much more frequently), but it gets close.

This script takes about 1.7 s to run using MATLAB Online (R2019b). Making the simple change of replacing the containers.Map with a normal numeric array:

   properties
       %PARENT = containers.Map('KeyType', 'double', 'ValueType','any');
       PARENT = [];
   end

changes the execution time to 0.097 s. containers.Map is not a very efficient data structure (it's a custom class, much like any user can write, which is obviously going to be more expensive to access than a native type). Assuming that the elements are consecutive integers (as should be the case in the connected component labeling algorithm and any other image processing algorithm that uses Union-Find), there is no advantage whatsoever to using a map, a simple array can be indexed using the element's value.

A second improvement that can be made to the code is in usability: the Union operation should always be made on two roots. It is convenient to have the Union function find the roots of its two input arguments, and it prevents wrong use (taking the union with a non-root element would produce wrong results in any algorithm using this data structure):

       function Union(obj, setOne, setTwo)
          %obj.PARENT(setOne) = setTwo;
          obj.PARENT(obj.Find(setOne)) = obj.Find(setTwo);
       end

We can now simplify our test code to not call Find at all. An additional improvement is to return the new root. This is quite common as well, and will also improve our test code:

       function root = Union(obj, setOne, setTwo)
          root = obj.Find(setTwo);
          obj.PARENT(obj.Find(setOne)) = root;
       end

Typically the Union operation selects the smaller of the two trees to become the child of the other. It is however not directly clear if the additional storage space and logic required to maintain the tree sizes is worth it, one would have to implement this and compare to be sure. A simple alternative is to always make the root with the smaller index the parent of the other tree. This ensures that, more often than not, it is the larger tree that will be the parent. It could look like this:

       function root = Union(obj, setOne, setTwo)
          roots = sort([obj.Find(setOne), obj.Find(setTwo)]);
          obj.PARENT(roots(1)) = roots(2);
          root = roots(1);

This increases runtime by about 40%, so it's not a good change.

Our test code is now simplified to:

tic
uf = UnionFind;
uf.addItem(1);
for ii = 2:10000
    root = ii;
    uf.addItem(root);
    n = randi(4);
    if n == 4 % happens in 25% of cases
        root = uf.Union(root, randi(ii-1));
    end
    if n ~= 1 % happens in 75% of cases
        root = uf.Union(root, randi(ii-1));
    end
end
toc

Regarding the use of handle as a base class: this converts the class into a "handle class", objects of this type cannot be copied, all "copies" refer to the same underlying data. This leads at times to unexpected behavior in MATLAB, where typically b=a, b(1)=0 does not not change a. However I think in this case it is reasonable to use a handle class for this data structure, for the same reasons that MATLAB's containers.Map is a handle class.

Path compression. Union-Find data structures do not become truly efficient until one implements path compression. This means that trees remain totally flat, with all leaves pointing directly at the root. Find in this case is usually an O(1) operation, rather than O(log n), converting the CLL algorithm that uses this data structure from O(n log n) to something that is nearly O(n).

Path compression is typically implemented using recursion. Implementing it without recursion is quite awkward. But MATLAB's function calls are still quite expensive, so it is not directly clear that this would be an improvement. Again, one would need to implement it and compare to know for sure.

The code in the OP uses tree halving instead. This is a reasonable compromise because it can be implemented without recursion.

Path compression would look like this:

       function root = Find(obj, item)
          root = obj.PARENT(item);
          if root ~= item
              root = obj.Find(root);
              obj.PARENT(item) = root;
          end
       end

This increases the test code running time by about 15%, so it is not a good change.

Finally:

A variable name in all caps (PARENT) looks strange to me, using all lowercase letters would be more in line with customary MATLAB style.
The constructor is commented out. You don't need this constructor in most cases, you could either delete it altogether, or uncomment it. A block of commented out code can be confusing.
There is no help text. A comment block at the top of the file should explain the purpose of the class and how to use it. Typing help UnionFind in MATLAB will show this comment block. Likewise, each function should have some documentation as a comment block either just above or just below the function line.


Finding the nth ugly number I'm trying to optimize my solution to this LeetCode problem:

  Write a program to find the nth super ugly number.

  Super ugly numbers are positive numbers whose all prime factors are in
  the given prime list primes of size k.

My working, accepted solution:

import heapq
class Solution:
    def nthSuperUglyNumber(self, n: int, primes: List[int]) -> int:
        heap = [1]
        seen = set()
        while n>=0:
            num = heapq.heappop(heap)
            n -=1
            if n == 0:
                return num
            for p in primes:
                if num * p not in seen:
                    seen.add(num*p)
                    heapq.heappush(heap, num*p)

        return heapq.heappop(heap)

What are some ways to optimize it in terms of time and space complexity?

As already explained in this answer, there is no need to use a class with an instance method here. In addition, the convention for function names in Python is to use snake_case, not camelCase.

On the other hand, this template is given on the LeetCode submission template, so you are not free to change it.

What you can do is to make the required solution method a wrapper for a free function (which then is universally usable):

def nth_super_ugly_number(n: int, primes: List[int]) -> int:
    # ...

class Solution:
    def nthSuperUglyNumber(self, n: int, primes: List[int]) -> int:
        return nth_super_ugly_number(n, primes)

Generating the ugly numbers can be separated from counting them (until the nth ugly number is reached) if the former is done with a generator. The generator is now a reusable function as well, and you might want to add a docstring comment:

def super_ugly_numbers(primes: List[int]) -> int:
    """Generate super ugly numbers.

    Super ugly numbers are positive integers whose all prime factors are in
    the given prime list.
    """

    heap = [1]
    seen = set()
    while True:
        num = heapq.heappop(heap)
        yield num
        for p in primes:
            if num * p not in seen:
                seen.add(num * p)
                heapq.heappush(heap, num * p)

def nth_super_ugly_number(n: int, primes: List[int]) -> int:
    ugly_numbers = super_ugly_numbers(primes)
    for _ in range(n - 1):
        next(ugly_numbers)
    return next(ugly_numbers)

The last function can be simplified using itertools.islice:

import itertools

def nth_super_ugly_number(n: int, primes: List[int]) -> int:
    ugly_numbers = super_ugly_numbers(primes)
    return next(itertools.islice(ugly_numbers, n - 1, n))


Unity Static Singleton JSON Serialisation I have a static PlayerData singleton which stores all the data for the player (gold, upgrades, heroes etc) but JsonUtility cannot serialise static or private methods so I have implemented a singleton with an intermediate SaveFile struct which is used in the serialisation.
PlayerData will have more complex objects likes HeroCollection etc but for now, I simply have a gold stat.
I am looking for a potentially better alternative solution or simply how to improve this.
Thanks.
struct SaveFile
{
    public int Gold;
}

public class PlayerData
{
    static PlayerData Instance = null;

    // # - Private Attributes - #
    int _Gold;

    // ... Heroes
    // ... Upgrades
    // ... Etc
    // # - - - - - - - #

    // # - Public Static Attributes - #
    public static int Gold { get { return Instance._Gold; } set { Instance._Gold = value; } }
    // # - - - - - - - #

    public static void Create(string json)
    {
        if (Instance == null)
            Instance = FromJson(json);
    }

    public static string ToJson()
    {
        return JsonUtility.ToJson(

            new SaveFile()
            {
                Gold = Instance._Gold
            }

        );
    }

    static PlayerData FromJson(string json)
    {
        SaveFile save = JsonUtility.FromJson<SaveFile>(json);

        return new PlayerData()
        {
            _Gold = save.Gold
        };
    }
}

Here are my observations after a quick review:

First of all your class is not a thread-safe singleton.

Please read Jon Skeet's guidance how to implement is properly.

As I understand you would like to implement a Memento pattern in C#.

There are a couple of good samples how to implement it properly: 1, 2, 3
BTW you can also use the Solid nuget package as well

Sorry but your naming is terrible, please try to follow some guideline, like:

Name your functions / methods in a way that they start with a verb, for example: SaveState, RestoreState
Name Your classes/ structs in a way that they are nouns (w/o adjective), for example: PlayerState,PortablePlayerState


Get 3 counts from a table I am trying to show the following results to the user

  All:8000 enabled:8000 disabled:0

What can I do to improve this code?

$Val = explode(",", urldecode($_POST['Val']));
$table = mysqliChkData($Val[0]);

$addSQL = '';
if (!empty($Val[2])) {
  // parrent.guid
  $addSQL.= " and up_cls='".mysqliChkData($Val[2])."'";
}

$getSQL = "Select guid From `".$table."` Where 1=1".$addSQL." GROUP BY guid";
$listData = $sql->Select($getSQL);
$arr['allNum'] = $listData['num'];

$getSQL = "Select guid From `".$table."` Where `chk`='Y'".$addSQL." GROUP BY guid";
$listData = $sql->Select($getSQL);
$arr['openNum'] = $listData['num'];
$arr['closeNum'] = $arr['allNum'] - $arr['openNum'];

echo json_encode($arr);
exit;

Same records but different languages will have same guid.

Child tables have up_cls column.

Few tables don't have chk column because no need to disable.

CREATE TABLE tablee (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `lang` varchar(100) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
  `chk` varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
  `date` datetime DEFAULT NULL,
  `guid` varchar(64) COLLATE utf8mb4_unicode_ci NOT NULL,
  `modify_date` timestamp NOT NULL DEFAULT '1970-12-31 16:00:00' ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`,`guid`) USING BTREE
) ENGINE=InnoDB AUTO_INCREMENT=28 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci ROW_FORMAT=COMPACT;

method Select

function Select($sql) {
  global $mysqli;
  $reData = array();
  $reData['data'] = array();

  $rs = mysqli_query($mysqli, $sql);
  if ($rs) {
    $thisNum = $rs->num_rows;
  }
  else {
    $thisNum = 0;
  }
  $reData['num'] = $thisNum;
  if ($thisNum != 0) {
    while ($row = $rs->fetch_assoc()) {
      $reData['data'][] = $row;
    }

  }
  return $reData;
}

===============

  Why are you mentioning child tables in this question?

$addSQL.= " and up_cls='".mysqliChkData($Val[2])."'";

  Are you comfortable with scrapping your Select function ...because it is insecure.
  Why are you mixing procedural with object-oriented mysqli syntax?

It passed acunetix last year, I don't know it's insecure. Could you give me some advice about this.

  Is there a reason that you cannot query once, then use php to filter the result set based on chk?
  How about a conditional count within the SELECT clause?

It is because some tables don't have chk . If the query has chk it will broken.

You can select multiple counts from the table based on a condition using a CASE WHEN statement, and when writing SQL or something where formatting helps readability it's normally a good idea to use heredoc.

$getSQL = <<<SQL
SELECT
    COUNT(DISTINCT guid) AS allNum,
    COUNT(DISTINCT CASE WHEN chk='Y' THEN guid END) AS openNum
FROM `{$table}`
WHERE
    1=1
    {$addSQL}
SQL;

$listData = $sql->Select($getSQL);
$arr = $listData['data'][0];

$arr['closeNum'] = $arr['allNum'] - $arr['openNum'];

echo json_encode($arr);
exit;


Keep elements present an odd number of times in an unsorted vector From an unsorted vector of integers, I would like to keep only elements that are present an odd number of times and have them sorted. Below is an example of a working code.

#include<vector>
#include <iostream>

using namespace std;

int main()
{
        vector<int> input = { 11, 3, 7, 3, 9, 3, 8, 11, 9, 3, 2, 9 };

        // print  input
        cout << "Input:" << endl;
        for (int i = 0 ; i < input.size() ; i++)
        {
          cout << input[i] << " ";
        }
        cout << endl;

        // sort the input
        sort(input.begin(), input.end());

        // print sorted input
        cout << "Sorted Input:" << endl;
        for (int i = 0 ; i < input.size() ; i++)
        {
          cout << input[i] << " ";
        }
        cout << endl;

        // Keep only elements present an odd number of times
        vector<int> output;
        int nbRepeats = 1;
        for (int i = 1 ; i < input.size() ; i++)
        {
                if (input[i-1] == input[i])  // if the ith element is a repeat
                {
                        nbRepeats++;
                } else
                {
                        if (nbRepeats % 2)  // Given that we have a new element, we will add the previous element to 'output' if the number of repeats of this previous element was odd
                        {
                                output.push_back(input[i-1]);
                        }
                        nbRepeats = 1;      // set nbRepeats back to 1 for the next series of elements.
                }
        }
        if (nbRepeats % 2)  // This is for the last series of elements
        {
                output.push_back(input.back());
        }

        // print the output
        cout << "Output:" << endl;
        for (int i = 0 ; i < output.size() ; i++)
        {
          cout << output[i] << " ";
        }
        cout << endl;
}

it rightly outputs

Input:
11 3 7 3 9 3 8 11 9 3 2 9
Sorted Input:
2 3 3 3 3 7 8 9 9 9 11 11
Output:
2 7 8 9

Question

The process is being a bit too slow for my needs. Is there alternative faster solution?

Typical input

Please note that a typical input is only between 1 and 10 elements long but cases of repeats will be quite common.

Potential ways to improve the code

I don't need to use the input, so I would be happy to directly modify the input rather than having to allocate memory an output vector if you think that would be faster.

It might eventually be more strategic to first remove elements we don't want (and get something like {7 9 8 2}) and sort them afterward but I doubt we can do the first step in better than O(n^2)

Since you asked for performance relevant code review I will answer these questions first and than will make some comments on the coding style.

The comments allready mentioned Profiling, so I will start with your original code and run it with CodeXL. Afterwards I will modify the code based on the profiling and will comment on possible performance improvements.

Profiling the Program

Since CodeXL works with samples wich is a statistical method (see https://en.wikipedia.org/wiki/Profiling_(computer_programming) ). For compilation I used MSVC2013 with the "-O2" flag for code optimization. I run your code in 10^5 times in for-loop. The result was this:

The Column with % of deep samples is an indicator of how much time the program spends in a function and its child function. Thus the main function is typically on the top.
Interesting are the third and fourth row which show that the "<<" operator and "std::endl" does take around 48% of your program. Based on this I just deleted the code for output and rerun the program. With 10^5 repeats it finished in less than a second. It should be mentioned that that was a lot faster than just 50%. The reason for this can be better compiler-optimization possibilities due to the missing ouput, because the loop has not more sideeffects, but this is only a guess. Nevertheless I rerun the program with 10^6 repeats to gather good profiling Data.

The top three functions (ignoring main) were:

std::vector<...>::_Reallocate 58.13% of deep samples
std::vector<...>::_Insert 11.96% of deep samples
std::_Sort<...> 10.01% of deep samples

Based on this I will give some comments about how to speed up the Code.

General possibilities for performance improvements

As shown above the vector::_Reallocate does take a lot of time in the code. This might be cause by the line output.push_back(input[i-1]); in your code. It will reallocate if the allocated memory of the vector needs to increase to store all elements. It will then allocate new memory and copy all its elements. This can be avoided by calling output.reserve(x); aft the construction of output. This will preallocate the memory for x elements. Since you optimize for speed and not for memory input.size() would be a good guess for the "x", because than you can be sure that output will not reallocate within the loop.

For your question of using the input vector for output and directly operating on it: I would guess that such an approach would include a lot of "erase" calls wich will also lead to a lot of copying, thus I do not think it would be faster.
Since you mentioned that your input will only have around 10 elements, I would not take to much time considering O-Notations because they are mainly interesting for large amounts of elements. In small dimensons the so oft forgotten constant in front of an O(...) will matter.
On the original code: The use of std::endl may have a big performace impact since it does not only produce a newline but it also flushes the putput. The use of "\n" or '\n' might be better.
Some times the compiler flags may have a big impact on performance. I does not have the knowledge for a detailed review, but I know of many cases were people look for code improvements because the program is slow but they compiled their program with debug configuration, so I thought it shopuld be mentioned.

Some small comments on coding style

Avoid "using namespace std" it is considered bad practice because it can lead to suprising collisions and ambiguity.
Prefer the prefix "++" to the postfix "++" unless you really want to increase a value and get the original value returned.
Avoid the using of std::endl, for the reasons stated above.

I hope this give a good overview on how to improve code for performance.


Finding the maximum inclusive distance between two duplicate numbers in an array The prompt that made me put this function together was sourced from CodingBat.

I was curious about cleaner, more correct methods of doing putting this together such as finding a cleaner way to tell if there is or is not a duplicate in the array. I am also trying to be as efficient as possible. I believe this is an \$O(n^2)\$ function. Let me know what I should change.

The code works just fine. I just feel like there is quite a lot I can streamline and I would like to be pointed in the right direction.

 public int maxSpan(int[] nums) {
    int highestSpan = 0;
    int span;
    boolean duplicate = false;
    if (nums.length == 0)
        return highestSpan;
    for (int i = 0; i < nums.length; i++) {
        for (int j = 0; j < nums.length; j++){

            if ((nums[i] == nums[j])&& j != i){ //if duplicate
                duplicate = true;
                //get the absolute value of j - i
                span = j - i + 1; //Add 1 because it needs to count itself
                //if it is larger than the highestSpan then record it
                if (span > highestSpan)
                    highestSpan = span;
            }
        }
    }
    if (duplicate)
        return highestSpan;
    else
        return 1;
}

Avoid unnecessary flag variables

The variable duplicate is unnecessary, because you could drive the same meaning from highestSpan > 0. It's an extra hurdle to keep this flag, I suggest to drop it.

Improving the algorithm

I believe this can be solved in \$O(N)\$ time and space, by using a map to record the position of the first occurrences of numbers. If a number was seen already, check the distance and update the max distance if necessary. Otherwise record the current position.


If non-array property exists convert it to one and push new value Is there a simpler/shorter/better way to do this?

let obj={a:1,b:[1,2]}

function add(key,value){
  if(!obj[key].push){
    obj[key]=[obj[key]]
  }
  obj[key].push(value)
}

Basically after reading over the code, I interpret that the conditional (i.e. !obj[key].push) checks if the value at the given key is not an array. A more robust way to do that is to use (the negated value of) Array.isArray() instead. That may not be any shorter, but perhaps a better way to determine if the property at key is an array.

var obj={a:1,b:[1,2]}

function add(key,value){
  if(!Array.isArray(obj[key])){
    obj[key]=[obj[key]]
  }
  obj[key].push(value)
}
add('a',3);
console.log(obj);

It would be difficult to prevent the re-assignment of the property .push (see example below). .push could be assigned to something other than a function, like an integer, string or object, or a function that does something other than push the supplied argument on the array.

var obj={a:1,b:[1,2]}

function add(key,value){
  if(!obj[key].push){
    obj[key]=[obj[key]]
  }
  obj[key].push(value)
}
obj.b.push = undefined;
add('b',3);
console.log(obj);

Edit
insertusernamehere made a good point in a comment: Perhaps it would be wise to guard against the case where the obj[key] is undefined. The current code would add that to the array, which is likely not preferable.
There are multiple ways to achieve this, including calling obj.hasOwnProperty(), checking the array returned by Object.keys(obj) does include key, etc.

var obj={a:1,b:[1,2]}

function add(key,value){
  if (!Object.hasOwnProperty(key)) {
      obj[key]=[];
  }
  if(!Array.isArray(obj[key])){
    obj[key]=[obj[key]]
  }
  obj[key].push(value)
}
add('a',3);
add('c',4);
console.log(obj);


Getting multiple inputs from single EditText This is an Android app and there is a EditText box, and I need to accept multiple types of inputs one after another in order. This order is predefined. On USER_INP_NAME object newUser is created. After this multiple properties are set with this object. Finally on USER_INP_STATE the object is added to a list. This cycle repeats.

I am a "C" programmer, so this is coded in procedure-oriented manner. The switch case is looking ugly for now.  Is there a better solution to do this ?

userInputs.setOnKeyListener(new OnKeyListener() {

    @Override
    public boolean onKey(View v, int keyCode, KeyEvent event) {
        if (event.getAction() == KeyEvent.ACTION_DOWN) {
            switch (keyCode) {
            case KeyEvent.KEYCODE_ENTER:
                int val = (Integer) userInputs.getTag();
                switch (val) {
                case USER_INP_NAME:
                    newUser = new Users();
                    newUser.setUsersName(userInputs.getText()
                            .toString());
                    userInputs.setTag(USER_INP_NUMBER);
                    userInputs.setText("");
                    userInputs.setHint("User Name");
                    break;
                case USER_INP_NUMBER:
                    newUser.setUnitWeight(Integer
                            .parseInt(userInputs.getText().toString()));
                    userInputs.setTag(USER_INP_STATE);
                    userInputs.setText("");
                    userInputs.setHint("User Number");
                    break;
                case USER_INP_STATE:
                    newUser.setShelfLife(Integer
                            .parseInt(userInputs.getText().toString()));
                    userInputs.setTag(USER_INP_NAME);
                    userInputs.setText("");
                    userInputs.setHint("User State");
                    uList.add(newUser);
                    adapter.notifyDataSetChanged();
                    break;
                default:
                    break;
                }

            default:
                break;
            }
        }
        return false;
    }
});

I think I would consider using three controls to achieve this and resetting their visibility on submission.

Reusing whatever you have used to create the userInputs control, rename that to nameInput and create two others weightInput and shelfLifeInput. Importantly when creating the other two controls set their visibility.
In XML:

<TextView
            android:id="@+id/weightInput"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:text=""
            android:hint="@string/weightHint"
            android:visibility="gone" />

or programatically:

weightInput.setVisibility(View.GONE);

It is import to use View.GONE as opposed to View.HIDDEN as a HIDDEN control still takes up space in the page.

Each of your three inputs can have a handler similar to the one you have created above, but now each handler performs a slightly different function.
Name Input:

userInput.setOnKeyListener(new OnKeyListener() {

    @Override
    public boolean onKey(View v, int keyCode, KeyEvent event) {
        if (event.getAction() == KeyEvent.ACTION_DOWN) {
            switch (keyCode) {
            case KeyEvent.KEYCODE_ENTER:
                userInput.setVisibility(View.GONE);
                weightInput.setVisibility(View.VISIBLE);
                break;
            default:
                break;
            }
         }
         return false;
     }
 });

Weight Input:

weightInput.setOnKeyListener(new OnKeyListener() {

    @Override
    public boolean onKey(View v, int keyCode, KeyEvent event) {
        if (event.getAction() == KeyEvent.ACTION_DOWN) {
            switch (keyCode) {
            case KeyEvent.KEYCODE_ENTER:
                weightInput.setVisibility(View.GONE);
                shelfLifeInput.setVisibility(View.VISIBLE);
                break;
            default:
                break;
            }
         }
         return false;
     }
 });

Shelf Life Input:

shelfLifeInput.setOnKeyListener(new OnKeyListener() {

    @Override
    public boolean onKey(View v, int keyCode, KeyEvent event) {
        if (event.getAction() == KeyEvent.ACTION_DOWN) {
            switch (keyCode) {
            case KeyEvent.KEYCODE_ENTER:
                //this can probably be locally scoped now.
                //Users is an odd name for what this class appears to be.
                //assume validation will have been added.
                Users newUser = new Users();
                newUser.setUsersName(userInput.getText().toString());
                newUser.setUnitWeight(Integer.parseInt(weightInput.getText().toString()));
                newUser.setShelfLife(Integer.parseInt(shelfLifeInput.getText().toString()));
                uList.add(newUser);
                adapter.notifyDataSetChanged();
                shelfLifeInput.setVisibility(View.GONE);
                userInput.setVisibility(View.VISIBLE);

                break;
            default:
                break;
            }
         }
         return false;
     }
 });

You would probably want to break the user creation code out into a separate function so that it is not tightly bound with the view, but for brevity I have followed more closely to your original code.


Whitelist for textarea and save input to file I'm working with product codes, so a user can only scan these type of product codes into a textarea element.
I don't know if my code is written the best way possible, or has good performance.
I'm using a whitelist solution for preventing bad entries.
It saves into file all product codes after 3 seconds of last keyup.
Is it good to use javascript and jQuery mixed?
And is it the correct way to use a php query to fetch product code and product code ending?
Why is "use strict" mode useless in my code?
"use strict";
toFile.focus();

var timeoutId;
toFile.addEventListener("keyup", event => {
    clearTimeout(timeoutId);
    timeoutId = setTimeout(function() {
        const data = toFile.value.split("\n");
        const result = data.unique();
        info.textContent = result.length !== data.length ? "Duplicate removed" : "";
        toFile.value = result.join('\n');
    }, 100);

    timeoutId = setTimeout(function() {
        onInput(document.getElementById('toFile'));
    }, 3000);
});

if (!Array.prototype.unique) {
    Object.defineProperty(Array.prototype, "unique", {
        configurable: false,  // these 3 properties default to false so not needed
        enumerable: false,    // But have added them just to show their availability.
        writable: false,
        value: function() {
            const existing = {};
            return this.filter(a => existing[a] = !existing[a] ? true : false);
        }
    });
} else {
    throw new Error("Array.prototype.unique already defined.");
}

const regexNounFilters = [<?php
    $data = $pdo->query("SELECT PRODUCT_CODE AS code, ENDING AS ec FROM test")->fetchAll(PDO::FETCH_OBJ);

    foreach ($data as $key) {
        $separator = ($key != end($data)) ? ", " : '';
        $std = "/^(" . $key->code . ")([a-zA-Z0-9]{" . $key->ec . "})$/";
        echo $std.$separator;
    }
?>];

// example: const regexNounFilters = [/^(AAAB)([a-zA-Z0-9]{7})$/, /^(BBBBBC)([a-zA-Z0-9]{9})$/];

const extractNouns = string =>
  string
  .split('\n')
  .filter(line =>
    regexNounFilters.some(re =>
      line.trim().toUpperCase().match(re)
    )
);

function onInput(target) {
    target.value = extractNouns(target.value).join('\n');
}

function saveToFile() {
    console.log('Saving to the db');
    toFile = $('#toFile').val().replace(/\n\r?/g, '<br />');
    $.ajax({
        url: "test2.php",
        type: "POST",
        data: {toFile:toFile}, // serializes the form's elements.
        beforeSend: function(xhr) {
            // Let them know we are saving
            $('#status').html('Saving...');
        },
        success: function(toFile) {
            // You can get data returned from your ajax call here. ex. jqObj.find('.returned-data').html()
            // Now show them we saved and when we did
            var d = new Date();
            $('#status').html('Saved! Last: ' + d.toLocaleTimeString());
        },
    });
}

$('.form').submit(function(e) {
    saveToFile();
    e.preventDefault();
});

Responses to your questions

Is it good to use javascript and jQuery mix?

If you are going to include the jQuery library, you might as well use it whenever possible. That may mean converting expressions like
document.getElementById('toFile')

to
$('#toFile')

and
target.value = extractNouns(target.value).join('\n');

to
target.val(extractNouns(target.val()).join('\n');

However, there are some people who believe jQuery isn't as relevant in today's web. For more information, check out youmightnotneedjquery.com/, which offers alternatives to many of the utilities jQuery offers, like the Fetch API for AJAX requests.

And is it correct way use php query to fetch product code and product code ending?

It is difficult to tell what "correct way" means. Do you mean is it acceptable to use PHP to generate Javascript code inline? If so, there are many factors, like who would be reading your code (including your future self), etc. Refer to answers to Is it considered bad practice to have PHP in your JavaScript.
The product codes and endings timeoutId used to generate regexNounFilters could be output using implode() and the values stored in $std inside the foreach could be returned in a callback passed to array_map() -
So instead of:

foreach ($data as $key) {

    $separator = ($key != end($data)) ? ", " : '';
    $std = "/^(" . $key->code . ")([a-zA-Z0-9]{" . $key->ec . "})$/";
    echo $std.$separator;
}

Something like this could be used:
echo implode(", ", array_map(function($key) {
    return "/^(" . $key->code . ")([a-zA-Z0-9]{" . $key->ec . "})$/";
}, $data);

##Other review feedback
var keyword
Because EcmaScript-6 features like arrow functions are used, the ES-6 keywords for variable declarations - i.e. let and const can be used instead of var. Due to the peculiar implications of var (e.g. hoisting) some recommend avoiding the var keyword in modern JS.
Global variable reference
At the start of the JavaScript code I see this:

toFile.focus();

where is toFile defined? is it just utilizing that element using the id attribute? If so, this is basically a global variable reference, which can lead to trouble/confusion in the future as the code grows. Refer to answers to Do DOM tree elements with ids become global variables?. It would be wise to utilize document.getElementById('toFile'), as is done in the second callback in the keyup event handler.
Timer Assignment over-writing
In the keyup event listener on toFile, timeoutId is assigned to two separate timers,

timeoutId = setTimeout(function() {

    const data = toFile.value.split("\n");
    const result = data.unique();
    info.textContent = result.length !== data.length ? "Duplicate removed" : "";
    toFile.value = result.join('\n');
}, 100);

timeoutId = setTimeout(function() {

    onInput(document.getElementById('toFile'));
}, 3000);

Should the first assignment be preserved? Because the second one overwrites it, there is not any way the first can be cleared via clearTimeout(). If the first should be clearable, use a different name for those two timer ids.
DOM Queries
The DOM queries could be optimized by saving references in variables -
for example, $('#status') appears in the beforeSend and success handlers of the AJAX call.

beforeSend: function(xhr) {

    // Let them know we are saving
    $('#status').html('Saving...');
},

A reference could be stored to the DOM element before the call to $.ajax() - e.g.
const successContainer = $('#status')

Then the beforeSend callback could be simplified to a function partial:
beforeSend: successContainer.html.bind(successContainer, "Saving..."),

And the success callback can also utilize that variable:
success: function(toFile) {
    // You can get data returned from your ajax call here. ex. jqObj.find('.returned-data').html()
    // Now show them we saved and when we did
    var d = new Date();
    statusContainer.html('Saved! Last: ' + d.toLocaleTimeString());
},

A function partial could also be used to simplify the second timer:
timeoutId = setTimeout(onInput.bind(null, document.getElementById('toFile')), 3000);

Selector for <form> element
You didn't include the HTML so I am not sure which element(s) this targets:

$('.form').submit(function(e) {

But I would guess it is a <form> tag with attribute class="form". If that is the case, the class attribute isn't necessary, even for CSS. The form element(s) could be selected with the tag name:
$('form').submit(function(e) {