texts:
I'm new to JS and jQuery. I wrote this function which just does what I want, but it seems very unreadable, and because of my experience, I don't know a better way to handle it.

Could you please give advise me how to refactor it?

function new_section(id, name, order) {

    return $('
')
        .attr('id', 'section_' + id)
        .attr('data-id', id)
        .attr('data-order', order)
        .append($('
')
            .addClass('head-row')
            .attr('id', 'section_' + id + '_head_row')
            .append($('')
                .attr('id', 'section_' + id + '_name_cell')
                .attr('colspan', window.row_length)
                .text(name)
                .addClass('bg-info')

                .append($('').addClass('edit-section').attr('href', '#')
                    .append($('').addClass('fa fa-pencil text-muted')))

                .append($('').addClass('pipe-edit-section text-muted').text('|'))

                .append($('').addClass('section-up').attr('href', '#')
                    .append($('').addClass('fa fa-chevron-up text-muted')))

                .append($('').addClass('section-down').attr('href', '#')
                    .append($('').addClass('fa fa-chevron-down text-muted')))

                .append($('').addClass('pipe-edit-section text-muted').text('|'))

                 .append($('').addClass('delete-section').attr('href', '#')
                    .append($('').addClass('fa fa-times-circle text-muted')))

        )
    );
}

UPD:

Found underscore templates. What do you think about this approach:

section = _.template([
            '<tbody id="section_<%= id %>" data-id="<%= id %>" data-order="<%= order %>">',
                '<tr id="section_<%= id %>_head_row" class="head-row">',
                    '<td id="section_<%= id %>_name_cell" class="bg-info" colspan="<%= row_length %>">',
                        '<%= name %>',
                        '',
                            '',
                        '',
                        '|',
                        '',
                            '',
                        '',
                        '',
                            '',
                        '',
                        '|',
                        '',
                            '',
                        '',
                    '	',
            '
'].join('\n'));


texts:
This has been tested and compiled under Visual Studio 2010. Are there any serious problems with this implementation?

PS. This implementation is fully lambda expression based. If I can make fixpoint::fix a real member function it will be simpler than this.

//As decltype(variable)::member_name is invalid currently,
//the following template is a workaround.
//Usage: t2t<decltype(variable)>::t::member_name
template<typename T>
struct t2t
{
    typedef T t;
};

template<typename R, typename V>
struct fixpoint
{
    typedef std::function<R (V)> func_t;
    typedef std::function<func_t (func_t)> tfunc_t;
    typedef std::function<func_t (tfunc_t)> yfunc_t;

    class loopfunc_t {
    public:
        func_t operator()(loopfunc_t v)const {
            return func(v);
        }
        template<typename L>
        loopfunc_t(const L &l):func(l){}
        typedef V Parameter_t;
    private:
        std::function<func_t (loopfunc_t)> func;
    };
    static yfunc_t fix;
};
template<typename R, typename V>
typename fixpoint<R, V>::yfunc_t fixpoint<R, V>::fix =
[](fixpoint<R, V>::tfunc_t f) -> fixpoint<R, V>::func_t {
    fixpoint<R, V>::loopfunc_t l = [f](fixpoint<R, V>::loopfunc_t x) ->
        fixpoint<R, V>::func_t{
            //f cannot be captured since it is not a local variable
            //of this scope. We need a new reference to it.
            auto &ff = f;
            //We need struct t2t because template parameter
            //V is not accessable in this level.
            return [ff, x](t2t<decltype(x)>::t::Parameter_t v){
                return ff(x(x))(v);
            };
        };
        return l(l);
    };

int _tmain(int argc, _TCHAR* argv[])
{
    int v = 0;
    std::function<int (int)> fac =
    fixpoint<int, int>::fix([](std::function<int (int)> f)
        -> std::function<int (int)>{
        return [f](int i) -> int{
            if(i==0) return 1;
            else return i * f(i-1);
        };
    });

    int i = fac(10);
    std::cout << i; //3628800
    return 0;
}


texts: A simple program that animates the Y position of multiple elements based on the window scroll position

texts:
The following code animates an item's Y position based on how much of its parent is currently visible. This is the first time I ever animated something on JavaScript based on the window scroll position and the current performance is extremely bad. I am looking for ways to get this running as fast as possible for a smooth animation.

The code I use to get a percentage between 0 and 100 based on how much an element is currently visible is the following:

    const calcVisibilityForElem = (elem) => {
      const windowHeight = window.innerHeight;
      const docScroll = window.pageYOffset || document.documentElement.scrollTop;
      const divPosition = elem.offsetTop;
      const divHeight = elem.offsetHeight;
      const hiddenBefore = docScroll - divPosition;
      const hiddenAfter = divPosition + divHeight - (docScroll + windowHeight);

      if (
        docScroll > divPosition + divHeight ||
        divPosition > docScroll + windowHeight
      ) {
        return 0;
      } else {
        let result = 100;

        if (hiddenBefore > 0) {
          result -= hiddenBefore * 100 / divHeight;
        }

        if (hiddenAfter > 0) {
          result -= hiddenAfter * 100 / divHeight;
        }

        return result;
      }
    };

The code I use to animate:

const calcVisibilityForAllArticles = () => {
  document.querySelectorAll('article').forEach((item) => {
    const top = calcVisibilityForElem(item);
    if (top !== 0) {
      item.querySelector('span').style.transform = `translateY(${Math.floor(
        top * 1.5
      )}px)`;
    }
    if (top >= 80) {
      const navItem = document.querySelector(`[href="#${item.id}"]`);
      document.querySelectorAll('nav a').forEach((navItem) => {
        navItem.classList.remove('highlight');
      });
      navItem.classList.add('highlight');
      navItem.focus();
    }
  });
};

In my process trying to boost its performance I made 2 changes, first of all, I animate using translate in the place of the top position, from what I understand changing any value other than transform causes a window repaint. The other change I made is to only animate elements that are inside my viewport. (top !== 0) === Only animate elements that are at least 1% inside the viewport.

I don't think that the code itself is very slow, however, the calcVisibilityForAllArticles function is run by:

document.onscroll = () => {
  calcVisibilityForAllArticles();
};

With means that the function is run back to back extremely fast. (With is needed for a smooth animation.)

Any help is more than welcome.


texts:
I've taken a crack at implementing Simple Diff in Rebol (versions 2 and 3). Simple Diff works by finding the longest common sequence in two series, then recursively applies itself either side of this sequence until there is nothing further in common. It returns a block containing additions (+), omissions (-) and matches (=). Example:

>> diff "The kuick brown fix." "The quick brown fox."
== [= "The " - "k" + "q" = "uick brown f" - "i" + "o" = "x."]

Originally this function was designed to work only on blocks, but since comparisons are done using the series API, I've permitted the use of strings and it seems to work.

I'm looking for feedback on:

The algorithm: is there a more efficient way to build the index (although the index is only as large as the number of unique components of the series), and to perform the comparisons?
The result: is the result block in a useful form?
Any bugs?

Note: the use of FUNC (not FUNCTION) is deliberate in development. This function is currently designed for use in both Rebol 2 and Rebol 3.

Simple Diff in Rebol

Rebol [
    Title: "SimpleDiff"
    Date: 22-May-2014
    Author: "Christopher Ross-Gill"
    Type: 'module
    Name: 'simplediff
    Exports: [diff]
    Comment: {
        Based on Simple Diff for Python, CoffeeScript v0.1
        (C) Paul Butler 2008 <http://www.paulbutler.org/>
        https://github.com/paulgb/simplediff
    }
]

diff: func [
    {
        Find the differences between two blocks. Returns a block of pairs, where the first value
        is in [+ - =] and represents an insertion, deletion, or no change for that list.
        The second value of the pair is the element.
    }
    before [block! string!] after [block! string!]
    /local items-before starts-before starts-after run this-run tests limit
][
    assert [equal? type? before type? after]

    ; Build a block with elements from 'before as keys, and
    ; each position starting with each element as values.
    items-before: make block! 100 ; arbitrary block memory allocation
    forall before [
        append/only any [
            select/case items-before first before
            last repend items-before [first before make block! 100]
        ] before
    ]

    ; Find the largest substring common to before and after
    forall after [
        if tests: select/case items-before first after [
            limit: length? after
            run: any [run 0]

            foreach before tests [
                repeat offset min limit length? before [
                    this-run: :offset
                    unless before/:offset == after/:offset [
                        this-run: offset - 1
                        break
                    ]
                ]

                if this-run > run [
                    run: :this-run
                    starts-before: :before
                    starts-after: :after
                ]
            ]
        ]
    ]

    collect [
        either run [
            ; The common substring is considered to have no change, and we recurse
            ; on the text before and after the substring

            keep diff copy/part before starts-before copy/part after starts-after
            keep reduce ['= copy/part starts-after run]
            keep diff copy skip starts-before run copy skip starts-after run
        ][
            ; Otherwise if no common substring is found, assume that an
            ; insert and delete has taken place

            unless tail? before [keep reduce ['- before]]
            unless tail? after [keep reduce ['+ after]]
        ]
    ]
]


texts: What is the common API endpoint architecture using DTO?

texts:
Hey I always used to create some pretty messy endpoints and I decided that it's about time to start writing cleaner code, I'll provide an example of how would I design an endpoint and I'll be  thankful for any insights why is it good or bad practice to do it like this also I'd be more than happy if you provide your own tweaks with explanation why would you do it like that.
Scenario: user post endpoint
Pathname: /api/user
Method: POST
Controller:
class UserPostEndpoint extends AbstractController
{
    private UserPostHandlerInterface $handler;
    private SerializerInterface $serializer;

    function __construct(UserPostHandlerInterface $handler, SerializerInterface $serializer)
    {
        $this->handler = $handler;
        $this->serializer = $serializer;
    }

    public function handleRequest(Request $request): Response
    {
        try {
            $userPostRequestDTO = $this->serializer->unserialize($request->getContent(), UserPostRequestDTO::class);
            $response = $this->handler->handle($userPostRequestDTO); // <- ApiSuccessResponse(statusCode = 201)
        } catch(SerializationException $e) {
            $response = new ApiErrorResponse('Invalid request content provided', 400);
        } catch(ApiRequestContentValidationException $e) {
            $response = new ApiErrorReponse($e->getPlainMessage(), 400);
        } catch(\Exception $e) {
            $response = new ApiErrorReponse('Internal server error', 500);
        } finally {
            return $response;
        }
    }
}

Handler would contain some basic things like: invoke createUser in UserFactory, persist the entity with repository.
ApiErrorReponse: message, statusCode
ApiSuccessReponse: UserPostResponseDTO, statusCode(201)
Would you add / change / remove something from the given example to make it more "correct"? Thanks for the insights
EDIT
After a few comments from @slepic I refactored the code into this
class UserPostEndpoint extends AbstractController
{
    private UserPostHandlerInterface $handler;
    private DataTransformerInterface $dataTransformer;

    function __construct(UserPostHandlerInterface $handler, DataTransformerInterface $dataTransformer)
    {
        $this->handler = $handler;
        $this->dataTransformer = $dataTransformer;
    }

    public function handleRequest(Request $request): Response
    {
        try {
            $userPostRequestDTO = $this->dataTransformer->toRequestDto($request->getContent(), $request->headers->get('Content-Type', 'application/json'));
            $userPostResponseDTO = $this->handler->handle($userPostRequestDTO);
            $response = new ApiSuccessResponse($userPostResponseDTO, Response::HTTP_CREATED);
        } catch(SerializationException $e) {
            $response = new ApiErrorResponse('Invalid request content provided', Response::HTTP_BAD_REQUEST);
        } catch(ApiRequestContentValidationException $e) {
            $response = new ApiErrorReponse($e->getPlainMessage(), Response::HTTP_BAD_REQUEST);
        } catch(\Exception $e) {
            $response = new ApiErrorReponse('Internal server error', Response::HTTP_INTERNAL_SERVER_ERROR);
        } finally {
            return $response;
        }
    }
}

I hope this is more appropriate


texts: Assign values to a matrix based on the location of non-zero elements in another matrix

texts:
I have a matrix, A containing ones and zeros. I want to create a new matrix B where the non-zero elements are in the same position as those in A, but where the values are given by the location of the first non-zero element in that row.

A few examples to show what I mean:

1  1  0  0   ->  1  1  0  0   (the first non-zero element is in column 1)
0  1  0  1   ->  0  2  0  2   (the first non-zero element is in column 2)
0  0  1  0   ->  0  0  3  0   (the first non-zero element is in column 3)
0  0  0  1   ->  0  0  0  4   (the first non-zero element is in column 4)

The code I have now is:

for i = 1:size(A,1)
for j = 1:size(A,2)
if A(i,j) == 1
B(i,:) = A(i,:) * find(A(i,:) == 1,1);
end
end
end

This gives the following results for a given A:

A
A =
     0     0     1     0
     0     1     1     1
     0     0     0     1
     1     1     1     1
     1     1     0     1
     0     1     1     1
     1     1     1     1
     1     1     1     1
     0     0     1     1
     0     0     1     1
B
B =
     0     0     3     0
     0     2     2     2
     0     0     0     4
     1     1     1     1
     1     1     0     1
     0     2     2     2
     1     1     1     1
     1     1     1     1
     0     0     3     3
     0     0     3     3

This code is slow if A is big. Is there a way to improve this code? I'm looking for improvements both on performance, and on the coding style / best practices etc.


texts:
I have a file containing lines having this structure :

var marker25 = createMarker(point, '

Katz\'s Deli
205 E. Houston Street, Manhattan, New York City,
New York, USA

');
var marker26 = createMarker(point, '

Rockerfeller Roof Gardens
5th Avenue between 49th &amp; 50th Streets, Manhattan, New York City,
New York, USA

');

I want to quickly be able to have as a result line of this type:

Katz\'s Deli 205 E. Houston Street, Manhattan, New York City,New York, USA,When_Harry_Met_Sally

Rockerfeller Roof Gardens,5th Avenue between 49th &amp; 50th Streets,,New York, USA, Spider-man

To reiterate, I want to remove all HTML/JS strings to keep only addresses, country and so on.

What I did so far is :

grep 'createMarker' New_York_Filming_Locations.php
cut -d'<' -f1,2,3,4,5,6,7,8
sed 's/
/,/g;s/
/,/g;s/<\/h3>/,/g'
cut -d',' -f3,4,5,7,8,9,11,12
sed 's///g'
cut -d',' -f1,2,4,5,6,7

It is done in a pipe, but for the clarity of the questions, I put each command on a separate line.

Is this the best way to do it? It is a small file, so I do not care about performance.

The sed syntax can be hard to understand. Do you guys know another way to do it using bash?


texts: Create a WordPress site data with Nginx app data automatically

texts:
The following script is aimed for Ubuntu >=16.04 LEMP environments with PHP-FPM >=7.0, MySQL, WP-CLI, Certbot, and WordPress apps.

The script get's one domain as an argument and creates the following aspects based on that argument (drt=document-root):

WP_app directory in drt.
WP_installation in drt/domain.
WP_conf in drt/domain.
NX_app conf in /etc/nginx/sites-available/
NX_symlink in /etc/nginx/sites-enabled/
NX_certbot configuration.

${drt} = document root.

One could then add a database stack via MySQL, accordingly (and also edit the website files, accordingly).

#!/bin/bash
domain="$1" && test -z ${domain} && return
read -sp "DB user password:" dbuserp

wp core download --path=${drt}/${domain}/ --allow-root # REDUNDANTS MKDIR
wp config create --path=${drt}/${domain}/ --dbname=${domain} --dbuser=${domain} --dbpass=${dbuserp} --dbhost="localhost" --allow-root

cat ~/myAddons/nginx_app > ${sava}/${domain}.conf
sed -i "s/\${domain}/${1}/g" /${sava}/${domain}.conf

ln -sf ${sava}/${domain}.conf ${sena}
certbot --nginx -d ${domain} -d www.${domain}

chown -R www-data:www-data ${drt}/
chmod -R a-x,a=rX,u+w ${drt}/
/etc/init.d/php*-fpm restart && systemctl restart nginx.service

echo "Please configure DBstack in phpmyadmin."
echo "Please change permissions as you prefer and restart the Nginx server."

Clarification

The conf template I redirect from ~/nginx_app, for the Nginx app conf, is this one:

server {
    root ${drt}/${domain}/;
    server_name ${domain} www.${domain};
    location ~* \.(jpg|jpeg|png|gif|ico|css|js|ttf|woff|pdf)$ { expires 365d; }
}

Please share your opinion on the above script and adjacent conf file.


texts: Extracting an adjaceny matrix containing haversine distance from points on map

texts:
I am extracting 10 lat/long points from Google Maps and placing these into a text file. The program should be able to read in the text file, calculate the haversine distance between each point, and store in an adjacency matrix. The adjacency matrix will eventually be fed to a 2-opt algorithm, which is outside the scope of the code I am about to present.

The following code is functional, but extremely inefficient. If I had 1000 points instead of 10, the adjacency matrix would need 1000 x 1000 iterations to be filled. Can this be optimized?

import csv
from haversine import haversine
import matplotlib.pyplot as plt
import numpy as np

def read_two_column_file(file_name):
    with open(file_name, 'r') as f_input:
        csv_input = csv.reader(f_input, delimiter=' ', skipinitialspace=True, )
        long = []
        lat = []
        for col in csv_input:
            x = float(col[0])  # converting to float
            y = float(col[1])
            long.append(x)
            lat.append(y)

    return long, lat

def display_points(long, lat):
    plt.figure()
    plt.ylabel('longitude')
    plt.xlabel('latitude')
    plt.title('longitude vs latitude')
    plt.scatter(long, lat)
    plt.show()

def main():
    long, lat = read_two_column_file('latlong.txt')

    points = []
    for i in range(len(lat)):
            coords = tuple([lat[i], long[i]])  # converting to tuple to be able to perform haverine calc.
            points.append(coords)

    hav = []
    for i in range(len(lat)):
        for j in range(len(long)):
            hav.append(haversine(points[i], points[j]))

    np.asarray(hav)
    adj_matrix = np.reshape(hav, (10, 10))  # reshaping to 10 x 10 matrix
    print(adj_matrix)

    display_points(long, lat)

main()

Sample Input:

35.905333, 14.471970
35.896389, 14.477780
35.901281, 14.518173
35.860491, 14.572245
35.807607, 14.535320
35.832267, 14.455894
35.882414, 14.373217
35.983794, 14.336096
35.974463, 14.351006
35.930951, 14.401137

Sample Output:

[[ 0.          1.15959635  5.15603243 12.15003864 12.66090817  8.06760374
  11.25481465 17.31108648 15.37358741  8.34541481]
 [ 1.15959635  0.          4.52227294 11.19223786 11.50131214  7.32033758
  11.72388583 18.35259685 16.41378987  9.29953014]
 [ 5.15603243  4.52227294  0.          7.44480948 10.26177912 10.15688933
  16.24592213 22.1101544  20.18967731 13.40020548]
 [12.15003864 11.19223786  7.44480948  0.          7.01813758 13.28961044
  22.25645098 29.42422794 27.49154954 20.48281039]
 [12.66090817 11.50131214 10.26177912  7.01813758  0.          9.22215871
  19.74293886 29.16680205 27.25540014 19.97465594]
 [ 8.06760374  7.32033758 10.15688933 13.28961044  9.22215871  0.
  10.66219491 21.06632671 19.24994647 12.24773666]
 [11.25481465 11.72388583 16.24592213 22.25645098 19.74293886 10.66219491
   0.         11.67502344 10.21846781  6.08016463]
 [17.31108648 18.35259685 22.1101544  29.42422794 29.16680205 21.06632671
  11.67502344  0.          1.93885474  9.20353461]
 [15.37358741 16.41378987 20.18967731 27.49154954 27.25540014 19.24994647
  10.21846781  1.93885474  0.          7.28280909]
 [ 8.34541481  9.29953014 13.40020548 20.48281039 19.97465594 12.24773666
   6.08016463  9.20353461  7.28280909  0.        ]]

Plot:


texts: Is there a better way to do get/set periodically in tornado?

texts:
I use a global variable to fit my need:

scores = {}

def update():
    global scores
    # fetch data from database
    scores = xxx

class MyRequestHandler(tornado.web.RequestHandler):
    @tornado.web.asynchronous
    def get(self):
        def choice_with_score(items):
            # return a key related to scores
            return key

        def get_key():
            global scores
            return choice_with_score(scores)

        self.write('%s' % get_key())
        self.finish()

if __name__ == '__main__':
    # initially update
    update()

    app = tornado.web.Application([
        (r'.*', MyRequestHandler),
    ])

    http_server = tornado.httpserver.HTTPServer(app)
    http_server.listen(port)
    ioloop = tornado.ioloop.IOLoop.instance()

    # background update every x seconds
    task = tornado.ioloop.PeriodicCallback(
            update,
            15 * 1000)
    task.start()

    ioloop.start()

Here, the function update() gets new data instead of updating in every incoming request, which is why I use a global variable.

Are there other ways to do the same work?


texts: Bidirectional numeric (floating point) sequence iterator

texts:
I wanted a neat iterator that will always give me neat sequence of step spaced numbers. This is what I came up with, but I am a bit skeptical that I covered all cases.

/**
 * Creates numeric range iterator. The iterator will iterate between start and end.
 * Start may be larger than end. The output will contain both start and end, but no value
 * will appear twice.
 * @param {number} start
 * @param {number} end
 * @param {number} step
 * @yields {number}
 * @returns {IterableIterator<number>}
 */
function* numrange(start = 0, end = 100, step = 1) {
    if (start > end) {
        step = -1 * step;
    }

    let i = start;
    for (; shouldLoop(i); i += step) {
        yield i;
        if (i!=end && !shouldLoop(i + step)) {
            yield end;
        }
    }

    function shouldLoop(ival) {
        return start > end ? ival >= end : ival <= end;
    }
}

Can this be improved?


texts: Is my C style good? 100 line timer program

texts:
This code works exactly as the prompt and the code predict.
Is my style good, my implementations, or what should I change, or what? I'm trying to improve my code, and writing more of it helps... Any and all relevant feedback is good.

#include <stdio.h>
#include <time.h>
#include <math.h>

#define SECONDS_PER_MINUTE 60
#define MINUTES_PER_HOUR 60
#define HOURS_PER_DAY 24
#define PROMPT_STRING "Type any key to show time, q to show time then quit: "

#define TIME_TYPE unsigned long

char getChar() ;
void updateTimes() ;
void initTimes() ;
void printPrompt() ;
void printTime (TIME_TYPE timeInit) ;

TIME_TYPE start, end;

int main (const char argc, char* argv[]) {
        char command = 0;
        initTimes();
        while (command != 'q') {
                printPrompt();
                command = getChar();
                updateTimes();
                printTime(end-start);
        }
        return 0;
}

char getChar() {
        char retVal = -1;
        char trashVal = -1;
        retVal = getc(stdin);
        while ( trashVal != '\n' && retVal != '\n') {
                trashVal = getc(stdin);
        }
        return retVal;
}

void updateTimes() {
        end = time(0);
}

void initTimes() {
        start = time(0);
        end = start;
}

void printPrompt() {
        printf(PROMPT_STRING);
}

void printTime (TIME_TYPE timeInit) {
        /* Basic declarations */
        TIME_TYPE time = timeInit;
        int days, hours, minutes, seconds;
        int timeDifferential = 0;
        /* Assigning crap, reassigning remaining seconds to 'time' */
        /* Days */
        timeDifferential = (SECONDS_PER_MINUTE *
                                MINUTES_PER_HOUR *
                                HOURS_PER_DAY);
        days = (time/timeDifferential);
        time -= timeDifferential*days;
        /* Hours */
        timeDifferential = (SECONDS_PER_MINUTE *
                                MINUTES_PER_HOUR);
        hours = (time/timeDifferential);
        time -= timeDifferential*hours;
        /* Minutes */
        timeDifferential = (SECONDS_PER_MINUTE);
        minutes = (time/timeDifferential);
        time -= timeDifferential*minutes;
        /* Seconds */
        seconds = time;
        /* Check for validity of times, then print.
         * Also print error if need be.*/
        if (!(seconds < 60 && seconds >= 0 &&
                        minutes < 60 && minutes >= 0 &&
                        hours < 24 && hours >= 0 )) {
                printf ("ERROR! TIME FORMAT SCREWY!\n");
        }
        printf ("Total time (s): %u\n %2dd %2dh %2dm %2ds\n", timeInit,
                        days, hours, minutes, seconds);
}


texts:
I want to parse some reports from multiple devices, reports looks like this:

VR            Destination      Mac                Age  Static  VLAN          VID   Port
VR-Default    192.168.11.13    90:e2:ba:3c:95:c0    2      NO  intra1        350   49
VR-Default    192.168.1.1      00:0e:a6:f7:b6:b5    0      NO  main          602   1
VR-Default    192.168.1.2      00:0d:88:63:bf:d1    3      NO  main          602   1
VR-Default    192.168.1.14     00:1c:f0:c7:d2:52    4      NO  main          602   1
etc...
Dynamic Entries  :          19             Static Entries            :          0
Pending Entries  :           1
In Request       :     3888802             In Response               :       4531
and some more data...
Rx Error         :           0             Dup IP Addr               :         0.0.0.0
and some more...

I need only vr, destination, mac, age, static, vlan, vid and port fields.
I can parse it using split function and regexes, but split fails if one field (e.g. Age) is empty.
perldoc says I can use unpack:

my $template = 'A13xA16xA18xA4xA7xA13xA5xA*';
for my $line ( split /\n/, $data ) {
   chomp $line;
   my ($vr, $destination, $mac, $age, $static, $vlan, $vid, $port) = unpack $template, $line;
...
}

But it dies on lines with length < 84. And I got to check string length every time (Or maybe using eval on unpack? Is it better?). And again I got to use regexes or index to find the end of main table and skip headers.
The code will looks like:

#!/usr/bin/perl
use strict;
use warnings;
my $arp = <<'ARP';
VR            Destination      Mac                Age  Static  VLAN          VID   Port
VR-Default    192.168.11.13    90:e2:ba:3c:95:c0    2      NO  intra1        350   49
VR-Default    192.168.1.1      00:0e:a6:f7:b6:b5    0      NO  main          602   1
VR-Default    192.168.1.2      00:0d:88:63:bf:d1    3      NO  main          602   1
VR-Default    192.168.1.14     00:1c:f0:c7:d2:52    4      NO  main          602   1

Dynamic Entries  :          19             Static Entries            :          0
Pending Entries  :           1
In Request       :     3888802             In Response               :       4531
Rx Error         :           0             Dup IP Addr               :         0.0.0.0
ARP
my $template = 'A13xA16xA18xA4xA7xA13xA5xA*';
for my $line ( split /\n/, $arp ) {
   last if index( $line, 'Dynamic E' ) == 0;
   next if length $line < 84;
   chomp $line;
   my ($vr, $destination, $mac, $age, $static, $vlan, $vid, $port) = unpack $template, $line;
   next if $mac eq 'Mac';
   print "$mac - $destination\n";
}

My question is: how would you parse this data? split, regexes, unpack, substr or something else?


texts:
Most properties have simple requirements so it should be possible to register their Dependency Property fields declaratively.

I made a small experiment and it seems to work just fine. The first attempt supports DefaultValue and Validation attributes.

It looks a little bit like JavaScript ;-)

The new DependencyPropertyBuilder loops over fields of type DependencyProperty. For each field it gets the necessary data with reflection from the property and its attributes.

class DependencyPropertyBuilder
{
    public static void RegisterFor<T>() where T : DependencyObject
    {
        var fields = typeof(T).GetFields().Where(x => x.FieldType == typeof(DependencyProperty));
        foreach (var field in fields)
        {
            var property = typeof(T).GetProperty(Regex.Replace(field.Name, "Property$", string.Empty));
            field.SetValue(
                null,
                DependencyProperty.Register(
                    property.Name,
                    property.PropertyType,
                    typeof(T),
                    new PropertyMetadata()
                    {
                        DefaultValue = new Func<object>(() =>
                        {
                            var defaultValue = property.GetCustomAttribute(typeof(DefaultValueAttribute)) as DefaultValueAttribute;
                            if (defaultValue != null)
                            {
                                return defaultValue.Value;
                            }

                            // Return the default value for the type.
                            if (property.PropertyType.IsValueType)
                            {
                                return Activator.CreateInstance(property.PropertyType);
                            }
                            return null;
                        })(),
                    },
                    new ValidateValueCallback(v => new Func<bool>(() =>
                    {
                        var validations = property.GetCustomAttributes(
                            typeof(ValidationAttribute))?.Cast<ValidationAttribute>()
                            ?? Enumerable.Empty<ValidationAttribute>();
                        // Evaluate all validators.
                        return validations.All(x => x.IsValid(v));
                    })())
                )
            );
        }
    }
}

The new test object is now really short:

class TestObject : DependencyObject
{
    public static readonly DependencyProperty CountProperty;

    static TestObject()
    {
        DependencyPropertyBuilder.RegisterFor<TestObject>();
    }

    [DefaultValue(5)]
    [Range(0, 15)]
    public int Count
    {
        get { return CountProperty.GetValue<int>(this); }
        set { CountProperty.SetValue(this, value); }
    }
}

The usage is the same:

var testObject = new TestObject();
testObject.Count.Dump("Default");

testObject.Count = 8;
testObject.Count.Dump("Changed");

testObject.Count = 22; // bam! out-of-range


texts:
I have written a simple pool allocator for C++ and I'm looking for ways to improve it, in speed, usability or safety. For example, I don't know how to allocate a buffer larger than the pool size.

#pragma once

#include <limits>
#include <vector>

template<class T, size_t poolObjectCount = 100>
class PoolAllocator
{
public:
    template<class U>
    struct rebind
    {
        typedef PoolAllocator<U> other;
    };
private:
    const size_t m_poolSize = poolObjectCount * sizeof(T);
    std::vector<T*> m_pools;
    size_t m_nextObject = 0;

public:
    PoolAllocator()
    {
    allocateNewPool();
    }

    PoolAllocator(const PoolAllocator& other) = delete; // Copy is deleted

    PoolAllocator(PoolAllocator& other) = delete; // Copy is deleted

    PoolAllocator(PoolAllocator<T, poolObjectCount>&& other) noexcept
        :m_poolSize(std::move(other.m_poolSize)),
    m_pools(std::move(other.m_pools)), m_nextObject(other.m_nextObject)
        {}

    PoolAllocator(const PoolAllocator<T, poolObjectCount>&& other) noexcept
        :m_poolSize(std::move(other.m_poolSize)),
    m_pools(std::move(other.m_pools)), m_nextObject(other.m_nextObject)
    {}

    ~PoolAllocator()
    {
        while (!m_pools.empty())
        {
            T* backPool = m_pools.back();
            for (T* i = backPool + poolObjectCount - 1; i > backPool; i--)
                i->~T();
            operator delete((void *)backPool);
            m_pools.pop_back();
        }
    }

    T* allocate(size_t objectCount)
    {
        if (objectCount >= poolObjectCount)
            throw "Cannot allocate array greater than pool size";
        if (m_nextObject + objectCount >= poolObjectCount)
            allocateNewPool();

        T* returnValue = m_pools.back() + m_nextObject;
        m_nextObject++;
        return returnValue;
    }

    template<class U = T>
    void construct(U * object)
    {
        new(object) U();
    }

    template<class U = T>
    void construct(U* object, const U& other)
    {
        new(object) U(other);
    }

    template<class U = T>
    void construct(U* object, U&& other)
    {
        new(object) U(other);
    }

    template<class U = T, class... ConstructorArguments>
    void construct(U* object, ConstructorArguments&& ...constructorArguments)
    {
        new(object) U(std::forward<ConstructorArguments>(constructorArguments)...);
    }

private:
    void allocateNewPool()
    {
    m_nextObject = 0;
    m_pools.emplace_back((T*)operator new(m_poolSize));
    }
};


texts: Ansible playbook to generate webserver folder structure with users and projects

texts:
I try to generate with ansible a folder structure for a webserver with users and linked projects.

The playbook works. But with more users and projects it gets quite complex to handle.
How can I simplify my code or vars sections?

I read a hint about using blocks so that all tasks inside it could use the same loop.
Is that the way to go?

The docs on blocks don't have a lot of examples. Any hint or link to examples is most appreciated.
Of course if you have any other pointers, please let me know.

---
- hosts: localhost
  become: yes
  become_method: sudo

#  check_mode: yes
  vars:
    project_base_path: /usr/src/project
    www_base_path: "/var/www/{{ansible_hostname}}"

    projects:
      mars: "{{ project_base_path }}/mars"
      venusnew: "{{ project_base_path }}/venus/new"
      venusold: "{{ project_base_path }}/venus/old"

    users:
      goku:
        present: true
        pw: #vault
      luffy:
        present: true
        pw: #vault

    user_projects:
      - uname: goku
        uproject:
          - lname: mars
            spath: "{{ projects.mars }}"
      - uname: luffy
        uproject:
          - lname: venusnew
            spath: "{{ projects.venusnew }}"
          - lname: project
            spath: "{{ projects.venusold }}"
  tasks:
    - name: check www path | Check if the path is available or create it
      file:
        path: "{{ www_base_path }}"
        owner: www-data
        group: www-data
        state: directory

    - name: check user www directory | Check if the directory of the user is available or create it
      file:
        owner: www-data
        group: www-data
        state: directory
        path: "{{ www_base_path }}/{{ item.key}}"
      with_dict: "{{ users }}"

    - name: check projects in usr src | Check if the directory of the user is available or create it
      file:
        owner: www-data
        group: www-data
        state: directory
        path: "{{ item.value}}"
      with_dict: "{{ projects }}"

    - name: link projects to users | Create links for the users
      file:
        state: link
#        force: yes
        owner: www-data
        group: www-data
        src:  "{{ item.1.spath }}"
        dest: "{{ www_base_path }}/{{ item.0.uname }}/{{ item.1.lname }}"
      with_subelements:
        - "{{ user_projects }}"
        - uproject


texts:
These extensions create an IObservable<T> that creates a long running task that can be cancelled. It runs the Func<T> after each interval of time and passes the result to OnNext() until the task is ended by the CancellationToken. The important thing here is that only one task is created with one loop. I'd prefer to use Observable.Create reactive extension, but I cannot find the equivalent.
What are the issues with this implementation?
using System;
using System.Collections.Generic;
using System.Reactive.Disposables;
using System.Threading;
using System.Threading.Tasks;

namespace Observables
{
    internal class BasicObservable<T> : IObservable<T>
    {
        readonly List<IObserver<T>> _observers = new List<IObserver<T>>();

        public BasicObservable(
            Func<T> getData,
            TimeSpan? interval = null,
            CancellationToken cancellationToken = default
            ) =>

            Task.Run(async () =>
            {
                while (!cancellationToken.IsCancellationRequested)
                {
                    try
                    {
                        await Task.Delay(interval ?? new TimeSpan(0, 0, 1));
                        _observers.ForEach(o => o.OnNext(getData()));
                    }
                    catch (Exception ex)
                    {
                        _observers.ForEach(o => o.OnError(ex));
                    }
                }

                _observers.ForEach(o => o.OnCompleted());

            }, cancellationToken);

        public IDisposable Subscribe(IObserver<T> observer)
        {
            _observers.Add(observer);
            return Disposable.Create(observer, (o) => _observers.Remove(o));
        }
    }
    public static class ObservableExtensions
    {
        public static IObservable<T> CreateObservable<T>(
            this Func<T> getData,
            CancellationToken cancellationToken = default)
        => new BasicObservable<T>(getData, default, cancellationToken);

        public static IObservable<T> CreateObservable<T>(
            this Func<T> getData,
            TimeSpan? interval = null,
            CancellationToken cancellationToken = default)
        => new BasicObservable<T>(getData, interval, cancellationToken);
    }
}

Usage
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Diagnostics;
using System.Reactive.Linq;
using System.Threading;
using System.Threading.Tasks;

namespace Observables
{
    class Subscriber
    {
        public string Name;

        //Listen for OnNext and write to the debug window when it happens
        public Subscriber(IObservable<string> observable, string name)
        {
            Name = name;
            var disposable = observable.Subscribe((s) => Debug.WriteLine($"Name: {Name} Message: {s}"));
        }
    }

    [TestClass]
    public class UnitTest1
    {
        string GetData() => "Hi";

        [TestMethod]
        public async Task Messaging()
        {
            var cancellationSource = new CancellationTokenSource();
            var cancellationToken = cancellationSource.Token;

            Func<string> getData = GetData;

            var publisher = getData.CreateObservable(cancellationToken);

            new Subscriber(publisher, "One");
            new Subscriber(publisher, "Two");

            for (var i = 0; true; i++)
            {
                if (i >= 5)
                {
                    cancellationSource.Cancel();
                }

                await Task.Delay(1000);
            }
        }
    }

}


texts: Make each element equal to its neighbouring element which is maximum in a matrix

texts:
I have a matrix and I want to make each of its element equal to the maximum of its neighbouring element and each time I increase number of counts till all the elements in the matrix becomes equal to the maximum element of the initial matrix. Note that this increase in element will happen simultaneously for each element.

For example:

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

1st time:

2 2 2 2
2 3 4 4
2 3 4 4

2nd time:

3 4 4 4
3 4 4 4
3 4 4 4

3rd time:

4 4 4 4
4 4 4 4
4 4 4 4

So, answer would be 3.

What I've tried:

#include<bits/stdc++.h>

using namespace std;
int main()
{
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);
    int t,i,j,k,n,m;
    cin>>t;
    while(t--)
    {
        cin>>n>>m;
        long int a[n+2][m+2],maxi[n][m],ma=0,counti=0;
        int flag[n][m];
        for(i=0;i<n+2;i++)
        {
            for(j=0;j<m+2;j++)
            {
                if(i==0 || j==0 || i==n+1 || j==m+1)
                {
                    a[i][j]=0;
                    continue;
                }
                cin>>a[i][j];
                flag[i][j]=0;
                if(a[i][j]>ma)
                    ma=a[i][j];
            }
        }
        for(i=1;i<n+1;i++)
        {
            for(j=1;j<m+1;j++)
            {
                int myints[] = {a[i][j+1],a[i][j-1],a[i-1][j],a[i+1][j],a[i+1][j+1],a[i+1][j-1],a[i-1][j+1],a[i-1][j-1]};
                maxi[i-1][j-1]= *max_element(myints,myints+8);
                if(maxi[i-1][j-1]<a[i][j])
                    maxi[i-1][j-1]=a[i][j];
                if(a[i][j]==ma)
                    counti++;
            }
        }
        if(counti==m*n)
        {
            cout<<"0"<<endl;
            continue;
        }
        int time=0;
        while(counti!=m*n)
        {
            counti=0;
            for(i=1;i<n+1;i++)
            {
                for(j=1;j<m+1;j++)
                {
                    a[i][j]=maxi[i-1][j-1];
                    if(a[i][j]==ma)
                    {
                        counti++;
                    }
                }
            }
            for(i=1;i<n+1;i++)
            {
                for(j=1;j<m+1;j++)
                {
                    int myints[] = {a[i][j+1],a[i][j-1],a[i-1][j],a[i+1][j],a[i+1][j+1],a[i+1][j-1],a[i-1][j+1],a[i-1][j-1]};
                    maxi[i][j]= *max_element(myints,myints+8);
                }
            }
            time++;
        }
        cout<<time<<endl;
    }
}

The variables I have used are badly used and make you uneasy to read the code but I used them for my comfort so please don't point out minor mistakes.

Also, I know that using namespace std and including bits/stdc++.h are also bad practices, so please avoid them and focus on the problem here.

The problem is my time complexity to traverse is going too high. So, I want the answer with least time complexity as possible. Any pseudocode or logic explanation with reduced complexity would be sufficient.


texts:
There are a lot similar questions out there. However, I wanted to get comments on my code. My implementation (as I believe) is simpler than the other complex ones as mine is \$O(n^2)\$.

My approach is simple:

Start with the biggest size of string
Check that string if its palindrome
Reduce the string size by 1 and check each string of that size in the given string if its palindrome

I am not doing any null/size checks since I just wanted to see if my code works.

I used test data:

HYTBCABADEFGHABCDEDCBAGHTFYW12345678987654321ZWETYGDE

and it gives the correct output of:

12345678987654321

Please let me know if you have any suggestions or comments.

public static String findLargestPalindrome(String str) {
    for (int palindromeSize = str.length(); palindromeSize > 0; palindromeSize--) {
        for (int i = 0; i + palindromeSize <= str.length(); i++) {
            int substr = i + palindromeSize;
            String test;
            if (substr > str.length()) {
                test = str.substring(i);
            } else {
                test = str.substring(i, substr);
            }
            if (isPalindrome(test)) {
                return test;
            }

        }
    }
    return null;
}

public static boolean isPalindrome(String str) {
    if (str == null || str.trim().equals("")) {
        return false;
    } else if (str.length() == 1) {
        return true;
    }

    for (int i = 0, j = str.length() - 1; i <= j; i++, j--) {
        if (str.charAt(i) != str.charAt(j)) {
            return false;
        }
    }
    return true;
}

I thought about this approach by myself without looking at any of existing solutions. I haven't even read any solution except for Manacher which solves this problem in \$O(n)\$.


texts: Python Inheritance and Class (Hackerank problem)

texts:
I just deep dived to Python and I came with this Hackerrank problem:

Create two class, Person with firstName, lastName, idNumber as its attributes with method printPerson() simply print last name and first name and id, and the derived class Student.

The Student class has additional attributes, its score and an array with two value, and I need to calculate the average of all scores in this array. Then finally I will decide which letter I should assign to this average score and print it.

Sample Input:

Heraldo Memelli 8135627
2
100 80

Sample Output:

Name: Memelli, Heraldo
ID: 8135627
Grade: O

My code in Python 3:

class Person:
    def __init__(self, firstName, lastName, idNumber):
        self.firstName = firstName
        self.lastName = lastName
        self.idNumber = idNumber
    def printPerson(self):
        print("Name:", self.lastName + ",", self.firstName)
        print("ID:", self.idNumber)

def avg(a):
    return sum(a)/len(a)

def m(a):
    return [int(r) for r in list(a.values())[0].split('-')]

class Student(Person):
    def __init__(self, f, l, i, s):
        Person.__init__(self, f, l, i)
        self.s = s
    def calculate(self):
        avgScore = avg(self.s)
        scoreList = [
          {'O': '90-100'},
          {'E': '80-89'},
          {'A': '70-79'},
          {'P': '55-69'},
          {'D': '40-54'},
          {'T': '0-39'},
        ]
        scoreLetter = list([x for x in scoreList if m(x)[0] <= avgScore == avgScore <=m(x)[1]][0].keys())[0]
        return '{}'.format(scoreLetter)

line = input().split()
firstName = line[0]
lastName = line[1]
idNum = line[2]
numScores = int(input()) # not needed for Python
scores = list( map(int, input().split()) )
s = Student(firstName, lastName, idNum, scores)
s.printPerson()
print("Grade:", s.calculate())

It passes all test cases. Could you please help me to review it and give me some advice?


texts:
Here is my Timer class code, and the context it is being used in. How accurate is the timer for measure elapsed time?

public class P3 {

    public static void main(String[] args) {
        Timer timer = new Timer();
        timer.startStop();
        System.out.println(PrimeNumber.getLargestPrimeFactor(600851475143L));
        timer.startStop().printTime().reset();
        Timer timerTwo = new Timer();
        timerTwo.startStop();
        for(int i = 0; i < 100; i++) {
            timer.startStop();
            PrimeNumber.getLargestPrimeFactor(6008514751435143L);
            timer.reset();
        }
        timerTwo.startStop().printTime().reset();
        timer.printAverageTime();
    }

    public class Timer {

    private static int timers;
    private static int id;
    private long startTime;
    private long time;
    private long totalTime;
    private int numberOfResets;
    private boolean running;
    private TimeUnit unit;

    public Timer() {
        timers++;
        id = timers;
        this.unit = TimeUnit.MILLISECONDS;
    }

    public Timer(TimeUnit unit) {
        timers++;
        id = timers;
        this.unit = unit;
    }

    public static enum TimeUnit {
        NANOSECONDS(1.0), MILLISECONDS(1000000.0), SECONDS(1000000000), MINUTES(60000000000.0);
        private final double conversion;

        private TimeUnit(double conversion) {
            this.conversion = conversion;
        }

        public double convert(double time) {
            return time / this.conversion;
        }
    }

    public Timer startStop() {
        if (running) { // Stopping
            stop();
        } else { // Starting
            start();
        }
        return this;
    }

    private void start() {
        startTime = System.nanoTime();
        running = true;
    }

    private void stop() {
        time += System.nanoTime() - startTime;
        running = false;
    }

    public Timer reset() {
        if(running)stop();
        totalTime += time;
        numberOfResets++;
        time = 0;
        return this;
    }

    private long getTimePrivate() {
        if (running)
            return time + (int) (System.nanoTime() - startTime);
        else
            return time;
    }

    public double getTime() {
        return getTime(unit);
    }

    public double getTime(TimeUnit unit) {
        return unit.convert(getTimePrivate());
    }

    private double getAverageTimePrivate() {
        return ((double) totalTime) / numberOfResets;
    }

    public double getAverageTime() {
        return getAverageTime(unit);
    }

    public double getAverageTime(TimeUnit unit) {
        return unit.convert(getAverageTimePrivate());
    }

    public String toString() {
        return toString(unit);
    }

    public String toString(TimeUnit unit) {
        return Double.toString(unit.convert(time));
    }

    public Timer printTime() {
        printTime(unit);
        return this;
    }

    public Timer printTime(TimeUnit unit) {
        System.out.printf("Timer %d: %.3f %s%n", id, getTime(unit), unit.toString().toLowerCase());
        return this;
    }

    public Timer printAverageTime() {
        printAverageTime(unit);
        return this;
    }

    public Timer printAverageTime(TimeUnit unit) {
        System.out.printf("Timer %d average: %.3f %s%n", id, getAverageTime(unit), unit.toString().toLowerCase());
        return this;
    }
}


texts:
I have a table with courses. The user that is currently logged in can mark these courses as attended and unattended. There can be multiple rows selected.

  The logic for this row selecting looks like this:

  It's not possible to select courses which you have attended when there are unattended courses selected. This works vica versa.
  When a unattended course is selected, a button for attending this course will be enabled.
  When a attended course is selected, a button for unattending this course will be enabled.
  For every row, the checkbox which is inside the table will be checked.

What I currently ended up with is this:

/**
 * The form for handling requests
 *
 * @type {jQuery|HTMLElement}
 */
const form = $('#attendCourseForm');

/**
 * The buttons for attending a course
 *
 * @type {jQuery|HTMLElement}
 */
const courseFollowButton   = $('#courseFollowButton'),
      courseUnFollowButton = $('#courseUnfollowButton');

/**
 * Selecting rows
 */
form.on('click', 'tbody tr', select);

/**
 * Select the course rows
 */
function select() {
    const $this    = $(this),
          attended = $this.hasClass('attendedCourse'),
          siblings = $this.siblings();

    let toggle = 'table-active',
        button = courseFollowButton;

    // Prevent selecting more types
    if (attended) {
        if (siblings.hasClass('table-active')) {
            return;
        }
        toggle = 'table-secondary';
        button = courseUnFollowButton;
    } else if (!attended && siblings.hasClass('table-secondary')) {
        return;
    }

    $this.toggleClass(toggle);

    // Toggle the checkbox
    let checkbox = $this.children().last().find('input[type=checkbox]');
    checkbox.prop('checked', $this.hasClass(toggle));

    // Turn buttons on and off
    let hasToggleClass = $this.hasClass(toggle) || siblings.hasClass(toggle);
    button.prop('disabled', !hasToggleClass);
}

This looks like a mess to me. Can this be done any better?


texts:
This  is my first attempt at solving Fizzbuzz. I've always been pretty weak at algorithms, so I'm trying to improve. Specific feedback on performance would be appreciated.

def fizzBuzz(fizzNumber, buzzNumber):
  i = 0
  for i in range(1, 101):
      fizzBuzzValues = [i%fizzNumber, i%buzzNumber, i%(fizzNumber * buzzNumber)]
      if(0 in fizzBuzzValues):
          if(fizzBuzzValues[2] == 0):
              print("Fizzbuzz")
          elif(fizzBuzzValues[0] == 0):
              print("Fizz")
          elif(fizzBuzzValues[1] == 0):
              print("Buzz")
          else:
              break
      else:
          print(i)

fizzBuzz(3, 5)


texts:
I have implemented an upgrades system in my Unity3d game, and I am pretty sure that I am not doing things in an optimal way. Any advice regarding best practices would be much appreciated.

The idea is that when the player collects a powerup, their run speed and jump speed increases.  Collect enough powerups, and you can jump around the level like the incredible hulk.

Play the game here: Super Voxel

The powerup is a basic Sphere object with its Sphere Collider Is Trigger checkbox activated.  It has this script attached:

SphereTriggerScript.cs

public class SphereTriggerScript : MonoBehaviour {

    public GameObject sphereObject;

    private GameObject playerObject;

    void Start() {
        playerObject = GameObject.Find("Player1");
    }

    void OnTriggerEnter (Collider other) {

        Destroy(sphereObject);

        PlayerScript script = playerObject.GetComponent<PlayerScript>();
        script.jumpForce += 1;
        script.runSpeed += 1;
    }
}

In the scene I have a basic Player1 prefab with this script attached:

PlayerScript.cs

public class PlayerScript : MonoBehaviour {

    public int runSpeed;
    public int jumpForce;

    void Start () {
        runSpeed = 20;
        jumpForce = 10;
    }
}

The powerup references this script with GameObject.Find. I do understand that this is suboptimal, however the powerups are created programmatically at run time, so it is not possible to simply drag and drop the Player1 game object onto the powerup prefab.

I have modified the default FPSController prefab (specifically the FirstPersonController script) to add a public GameObject field that I populate with the Player1 prefab.  Then when I need to get the jump or run speed, I access that script like so:

PlayerScript script = playerObject.GetComponent<PlayerScript>();
m_MoveDir.y = script.jumpForce;

Finally, I am doing something a bit funny to position the powerup orbs properly.  When creating them, I use a RayCast to position them at the "top" of the building:

int randomNumber = random.Next(0, 100);
if (randomNumber > 80) {

    int maxPossibleHeight = 250;
    RaycastHit hit;
    Ray ray = new Ray(new Vector3(x * tileSize, maxPossibleHeight, y * tileSize), Vector3.down);

    if (tileObject.GetComponentInChildren<MeshCollider>().Raycast(ray, out hit, 2.0f * maxPossibleHeight)) {

        int randomHeightOffset = random.Next(2, 12);

        float height = hit.point.y;
        GameObject powerup = (GameObject)GameObject.Instantiate (Resources.Load (powerupPrefabName));
        powerup.transform.position = new Vector3(x * tileSize, height + randomHeightOffset, y * tileSize);
    }
}


texts:
Okay, first things first:
Yes, I am aware of the logrotate tool, which would usually be used for something like this.
However, since the logfile i want to rotate already contains a timestamp in the filename, logrotate will never delete old logs.
This script is supposed to:

tell the application to create a new logfile (via SIGHUP)
find all existing, unprocessed logfiles of the application
compress all logfiles except the one currently in use by the application
keep the most recent 7 logs and delete the rest.

From what I can tell, everything seems to work just fine, but I'm curious if anything could be improved.
#!/usr/bin/bash

procname="foo"
srcpath="/var/log"
srcname="*${procname}.log"  # example: 2021-02-05_1200_foo.log
count=7

echo "rotate $procname logs: ${srcpath}/${srcname} ($count rotations)"

pid="$(pidof $procname)"
if [[ ! $? == 0 ]]
then
    # don't rotate anything if the application is not running
    echo "$procname process not running"
    exit 1
fi

# ask the application to create a new logfile
kill -HUP "$pid"

sleep 1 #probably not necessary?

# get array of all logfiles (should be exactly 2 in most cases)
mapfile -t list <  <(find "$srcpath" -maxdepth 1 -name "$srcname" | sort)
size=${#list[@]}

# don't do anything unless there are at least 2 files
if [[ $size -lt 2 ]]
then
    echo "nothing to do"
    exit 0
fi

# find the active logfile (should be the last one) and delete it from the array
for ((i=size-1; i>=0; i--));
do
    if [[ $(find -L /proc/"$pid"/fd -inum "$(stat -c '%i' "${list[i]}")") ]]
    then
        unset "list[i]"
        break
    fi
done

# compress all remaining files (usually just one)
gzip "${list[@]}"

unset list
unset size

# get array of all compressed logfiles
mapfile -t list <  <(find "$srcpath" -maxdepth 1 -name "$srcname.gz" | sort)
size=${#list[@]}

if [[ $size -gt $count ]]
then
    idx=("${!list[@]}")
    # remove $count most recent files from $list
    for i in "${idx[@]: -$count:$count}"
    do
        unset "list[$i]"
    done

    # delete the remaining old files
    rm -f "${list[@]}"
fi

exit 0


texts:
I'm new to JavaScript, and I made a Discord bot using discord.js that serves food and drinks and replies without the need of a prefix. My issue is that I want to try cleaning up the code and get rid of all the if-statements, but I don't know how to do so.
bot.on("message", message => {
  const reply = [
    "Here's your order!",
    "Enjoy!",
    "Here you go!",
    "Let me know if you need anything else!",
    "You've been served.",
    "That'll be $3.50.",
    "That'll be $5.50",
  ];
  const response = reply[Math.floor(Math.random() * reply.length)];

  if (message.content.toLowerCase().includes("order coffee")) {
    message.channel.send("Coming right up!").then(msg => {
    msg.delete({ timeout: 5000 })
  })
  .catch(console.error);
    setTimeout(function(){
      message.reply(response);
      message.channel.send("https://cdn.glitch.com/1f3ad41e-6c0c-4160-902b-a50330e419bd%2FCoffee%20cropped.gif?v=1613444146008");
    }, 5000);
  }

  if (message.content.toLowerCase().includes("order latte")) {
    message.channel.send("Coming right up!").then(msg => {
    msg.delete({ timeout: 5000 })
  })
  .catch(console.error);
    setTimeout(function(){
      message.reply(response);
      message.channel.send("https://cdn.glitch.com/1f3ad41e-6c0c-4160-902b-a50330e419bd%2FLatte.gif?v=1613444145762");
    }, 5000);
  }

  if (message.content.toLowerCase().includes("order muffin")) {
    message.channel.send("Coming right up!").then(msg => {
    msg.delete({ timeout: 5000 })
  })
  .catch(console.error);
    setTimeout(function(){
      message.reply(response);
      message.channel.send("https://cdn.glitch.com/1f3ad41e-6c0c-4160-902b-a50330e419bd%2FMuffin.gif?v=1613444146225");
    }, 5000);
  }

  if (message.content.toLowerCase().includes("order strawberry cake roll")) {
    message.channel.send("Coming right up!").then(msg => {
    msg.delete({ timeout: 5000 })
  })
  .catch(console.error);
    setTimeout(function(){
      message.reply(response);
      message.channel.send("https://cdn.glitch.com/1f3ad41e-6c0c-4160-902b-a50330e419bd%2FStrawberry%20cake%20roll.gif?v=1613444145762");
    }, 5000);
  }
});


texts: Creating a class object just based on the class type

texts:
I am trying to use a map as a way to implement an object factory. In Python it is possible to store a class type in a map, and use it later to create objects from that type:

class Foo:
    # ...

class Bar:
    # ...

factory_map = { 'foo' : Foo, 'bar' : Bar }
foo_object = factory_map['foo']()

I am not aware of a similar feature (i.e., storing a type in a map) in C++, so I came up with a solution based on lambda functions where the map stores functions responsible to create the objects:

class Base {
public:
    typedef std::unique_ptr<Base> Pointer;
    virtual void hi() = 0;
};

class Foo : public Base {
public:
    void hi() { std::cout << "Hi, it's foo\n"; }
};

class Bar : public Base {
public:
    void hi() { std::cout << "Hi, it's bar\n"; }
};

int main() {
    std::map<
        std::string,
        std::function<Base::Pointer()>> factory_map = {
            { "foo", []() { return Base::Pointer(new Foo()); } },
            { "bar", []() { return Base::Pointer(new Bar()); } },
        };

    Base::Pointer b1 = factory_map["foo"]();
    b1->hi();

    Base::Pointer b2 = factory_map["bar"]();
    b2->hi();
}

This might be the most straightforward solution to obtain Python's simplicity. I am wondering, however, if the usage of lambdas is the best way to create the factory. Specifically, I would like to know what are the pros/cons of this approach compared to a more "traditional" factory design (i.e., one using if/else conditionals to decide the type of the object to create).


texts:
I just started learning python yesterday, I have prior experience of C++. So I think I am able to get most of it pretty fast. I wrote a duplicate file finder for testing and practicing.

Can you guys look on this and give me some opinion if I am doing this right?

import argparse
import os
import fnmatch
import hashlib

class MyFile:
    partHashSize = 0
    def __init__(self, name):
        self.name = name
        self.size = os.path.getsize(self.name)
        self._processed = False
        self._partHash = None
        self._fullHash = None

    def __str__(self):
        return '{} is {}'.format(self.name, self.size)
    def __repr__(self):
        return '<MyFile {}:{}>'.format(self.name, self.size)

    def _getPartHash(self):
        if self._partHash is None:
            h = hashlib.sha1()
            with open(self.name, 'rb') as f:
                h.update(f.read(MyFile.partHashSize))
            self._partHash = h.hexdigest()
        return self._partHash
    partHash = property(_getPartHash)

    def _getFullHash(self):
        if self._fullHash is None:
            h = hashlib.sha256()
            with open(self.name, 'rb') as f:
                while True:
                    buf = f.read(MyFile.partHashSize)
                    if not buf:
                        break
                    h.update(buf)
                self._fullHash = h.hexdigest()
        return self._fullHash
    fullHash = property(_getFullHash)

    def findDuplicates(self, files):
        if self._processed:
            return list()
        dup = list()
        for f in files:
            if f.size == self.size and not os.path.samefile(f.name, self.name):
                if f.partHash == self.partHash and f.fullHash == self.fullHash:
                    f._processed = True
                    dup.append(f)
        if len(dup) > 0:
            dup.append(self)
        return dup

def sizeParse(szstr):
    suffix = ['GB', 'MB', 'KB', 'B']
    for i, s in enumerate(suffix):
        if szstr.endswith(s):
            return int(szstr[0: len(szstr) - len(s)]) * (1024 ** (len(suffix) - i - 1))
    return int(szstr)

def recursiveDir(dir, pattern, filter):
    l = list()
    for root, dirs, files in os.walk(dir):
        for file in files:
            if fnmatch.fnmatch(file, pattern):
                f = MyFile(os.path.join(root, file))
                if filter(f):
                    l.append(f)
    return l

def getFiles(arg, filter):
    if os.path.isfile(arg):
        return [MyFile(arg)]
    if os.path.isdir(arg):
        return recursiveDir(arg, '*', filter)
    [path, file] = os.path.split(arg)
    if len(path) == 0:
        path = '.'
    return recursiveDir(path, file, filter)

def main():
    parser = argparse.ArgumentParser(description='Duplicate File Finder')
    parser.add_argument('--min-size', dest= 'minsize', default='1KB', help='minimum file size, supports suffixes GB, MB, KB, B')
    parser.add_argument('--max-size', dest= 'maxsize', default='1024GB', help='maximum file size, supports suffixes GB, MB, KB, B')
    parser.add_argument('--hash-size', dest= 'hashsize', default='64KB', help='file hash size used for preliminary checking')
    parser.add_argument('dirs', metavar='dirs', type=str,
                        nargs='*', help='dirs or globs or files, supports glob patterns')
    args = parser.parse_args()
    MyFile.partHashSize = sizeParse(args.hashsize)
    MinimumSize = sizeParse(args.minsize)
    MaximumSize = sizeParse(args.maxsize)

    Files = list()
    [Files.extend(getFiles(x, lambda x: x.size > MinimumSize and x.size < MaximumSize)) for x in args.dirs]

    p = False

    for f in Files:
        dup = f.findDuplicates(Files)
        if len(dup) > 0:
            if not p:
                print("Following are the duplicates:")
                p = True
            print([x.name for x in dup])

if __name__ == '__main__':
    main()


texts: Create database connection and run the insert, delete, update queries class-Update

texts:
Based on the feedback I have got from the guys reviewing the code as posted in my previous question.

Create database connection and run the insert, delete, update queries class

I have used interfaces and wrote the following code

/* */

namespace SampleInterfaceT1
{
public interface IDbConSetup
{
    DbConnection OpenConnection(string connectionString);

    void CloseConnection();
}

public interface ISqlDataProvider : IDbConSetup
{
    int ExecuteCmd(string dbCmd, SqlParameter param);
}

public class SqlClient : ISqlDataProvider
{
    private SqlConnection _dbconnect;

    private string _conString;

    public DbConnection OpenConnection(string connectionString)
    {
        if (String.IsNullOrWhiteSpace(connectionString))
        {
            throw new ArgumentException("Invalid Connection String");
        }
        _conString = connectionString;

        Console.WriteLine("Sql Connection Opened.");

        _dbconnect = new SqlConnection(_conString);

        _dbconnect.Open();

        return _dbconnect;
    }

     public int ExecuteCmd(string dbCmd, SqlParameter param)
    {
        int _rc;

        if (String.IsNullOrWhiteSpace(dbCmd))
        {
            throw new ArgumentException("Invalid Connection String");
        }
        using (SqlCommand _sqlCmd = new SqlCommand(dbCmd, _dbconnect))
        {
            _sqlCmd.CommandType = CommandType.Text;

            _sqlCmd.Parameters.Add(param);

            _rc = _sqlCmd.ExecuteNonQuery();
        }

        Console.WriteLine("Command executed");

        return _rc;
    }

    public void CloseConnection()
    {
        _dbconnect.Close();
        Console.WriteLine("Sql Connection Closed.");
        _dbconnect.Dispose();
    }

   }
}

/*  Main Program execution */

namespace SampleInterfaceT1
{
 public class Program
 {
    private static void Main(string[] args)
    {
        string conString = @""; /* Connection String*/

        string dbCommand = @"INSERT INTO [dbo].[TestTable]([Name]) VALUES (@Name)";

        ISqlDataProvider SqlDataProviderObject = new SqlClient();

        SqlDataProviderObject.OpenConnection(conString);

        SqlDataProviderObject.ExecuteCmd(dbCommand, new SqlParameter("Name", "HellofromnewDictionary"));

        SqlDataProviderObject.CloseConnection();

        Console.ReadLine();
    }
}
}

I'm a newbie to the concept of interfaces. I'm I on the right path or did I got it completely wrong?


texts:
Considering the lack of general purpose library to manipulate trees (not to mention zipper ones), I may end up packaging this piece of code, so I would like it to be reviewed first.

Any comment is welcome, notably on the following points:

the use of Map within the Tree data type (e.g. versus HashMap or bare lists)
the semantic of the Foldable instance of ZTree
the implementation of the Comonad instance of ZTree
types/functions naming
opportunities of optimization/generalization/code reuse

EDIT: re-using Cofree to define Tree.

{-# LANGUAGE DeriveFunctor      #-}
{-# LANGUAGE StandaloneDeriving #-}
import           Control.Comonad -- from comonad
import           Control.Comonad.Cofree -- from free

import           Data.Containers -- from mono-traversable
import           Data.Map               (Map) -- from containers
import           Data.Maybe

import           Lens.Micro -- from microlens

import           Prelude                hiding (lookup)

-- * Generic tree

type Tree e = Cofree (Map e)

rootEdges :: (Ord e) => Tree e a -> [e]
rootEdges (_ :< c) = keys c

removeEdge :: (Ord e) => e -> Tree e a -> Tree e a
removeEdge e (a :< c) = a :< deleteMap e c

attach :: (Ord e) => e -> Tree e a -> Tree e a -> Tree e a
attach e t (a :< c) = a :< insertMap e t c

prune :: (Ord e) => Int -> Tree e a -> Tree e a
prune 0 (a :< _) = a :< mempty
prune n (a :< c) = a :< fmap (prune (n-1)) c

-- * Zipper tree

-- | A zipper tree is a 'Tree' with a cursor
data ZTree e a = ZRoot (Tree e a)
               | ZNode (Tree e a) e (ZTree e a)
deriving instance Functor (ZTree e)

-- | Only fold the 'descendants' of the currently focused node
instance Foldable (ZTree e) where
  foldMap f ztree = foldMap f $ ztree ^. underlyingTree

instance Traversable (ZTree e) where
  traverse f (ZRoot tree) = ZRoot <$> traverse f tree
  traverse f (ZNode tree e parent) = ZNode <$> traverse f tree <*> pure e <*> traverse f parent

instance (Ord e) => Comonad (ZTree e) where
  extract ztree = extract $ ztree ^. underlyingTree
  duplicate w@(ZRoot _) = ZRoot $ duplicate' w
  duplicate w@(ZNode _ e parent) = ZNode (duplicate' w) e (duplicate parent)

duplicate' :: (Ord e) => ZTree e a -> Tree e (ZTree e a)
duplicate' w = w :< mapFromList (map (\e -> (e, duplicate' $ forward e w)) $ nextEdges w)

instance (Eq a, Ord e) => Eq (ZTree e a) where
  a == b = extract a == extract b

instance (Ord a, Ord e) => Ord (ZTree e a) where
  compare a b = extract a `compare` extract b

-- | ZTree constructor
zTree :: Tree e a -> ZTree e a
zTree = ZRoot

underlyingTree :: Lens' (ZTree e a) (Tree e a)
underlyingTree f (ZRoot tree) = ZRoot <$> f tree
underlyingTree f (ZNode tree e parent) = (\tree' -> ZNode tree' e parent) <$> f tree

nextEdges :: (Ord e) => ZTree e a -> [e]
nextEdges = rootEdges . (^. underlyingTree)

removeEdgeZ :: (Ord e) => e -> ZTree e a -> ZTree e a
removeEdgeZ e = over underlyingTree (removeEdge e)

attachZ :: (Ord e) => e -> Tree e a -> ZTree e a -> ZTree e a
attachZ e t = over underlyingTree $ attach e t

pruneZ :: (Ord e) => Int -> ZTree e a -> ZTree e a
pruneZ n = over underlyingTree $ prune n

forwardMay :: (Ord e) => e -> ZTree e a -> Maybe (ZTree e a)
forwardMay e w = do
  child <- lookup e children
  return $ ZNode child e $ removeEdgeZ e w
  where _ :< children = w ^. underlyingTree

forward :: (Ord e) => e -> ZTree e a -> ZTree e a
forward e ztree = fromMaybe ztree $ forwardMay e ztree

backwardMay :: (Ord e) => ZTree e a -> Maybe (ZTree e a)
backwardMay (ZRoot _) = Nothing
backwardMay (ZNode tree e parent) = Just $ attachZ e tree parent

backward :: (Ord e) => ZTree e a -> ZTree e a
backward ztree = fromMaybe ztree $ backwardMay ztree


texts: F# functions implementing polynomial arithmetic

texts:
I have a couple of functions for doing basic arithmetic on polynomials.

let rec mulC x ys =
match (x,ys) with
| (_,[])                    -> []
| (x,y::ys) when x > 0    -> x * y::mulC x ys

let rec addE xs ys =
match (xs, ys) with
| ([],[])                   -> []
| ([], y::ys)            -> y::ys
| (x::xs,[])             -> x::xs
| (x::xs, y::ys)      -> (x + y) :: addE xs ys

let mulX xs =
match xs with
| []                    -> []
| xs                    -> 0::xs

let rec mul qs = function
| []                    -> []
| x::tail               -> addE (mulC x qs)
                                (mulX(mul qs tail))


texts: Count power of big numbers and then apply modulo on this numbers

texts:
I have this example code in which I have very big numbers as you see. The problem is that when I use this algorithm for some small numbers, it works well, but when I use it for big numbers like in this example, this algorithm is so slow.

Can you tell me why this algorithm is so slow for that big numbers? How can I make it faster?

n = 11698030645065745910098695770921
e = 9569991810443215702618212520777
d = 7874909554574080825236064017913
m = 104228568138
m = int(m)
e = int(e)
n = int(n)
def preparation(m, n):
    block_lenght= len(str(n)) - 1
    m = [str(m)[i:i+block_lenght] for i in range(0, len(str(m)), block_lenght)]
    return m

def encrypt(m, n, e):
    m = preparation(m, n)

    power = [int(i) ** e for i in m]

    modulo = [i%n for i in power]

    total_sum = sum(modulo)

    return total_sum

m = encrypt(m, n, e)
print("m = ", m)


texts: Avoiding Duplicated Code Fragments Graphene in FastAPI

texts:
How can I avoid repeating code fragments between the mutations and types with graphene in a FastAPI app? I really want to avoid repeating any codes for obvious reasons.
graphql\mutations.py
import graphene

from models.customers import CustomerLogin,  CustomerLogin_PydanticIn
from graphql.types import CustomerLoginType

class CreateUserMutation(graphene.Mutation):
    class Arguments:
        id = graphene.Int()
        shard_id = graphene.Decimal()
        seq_num = graphene.Decimal()
        event_timedate = graphene.DateTime()
        user_id = graphene.UUID()
        device_token = graphene.UUID()
        user_ip = graphene.String()
        user_agent = graphene.String()
        client_id = graphene.String()
        process = graphene.String()
        auth_result = graphene.String()
        auth_fail_cause = graphene.String()
        plain_email = graphene.String()

    user = graphene.Field(CustomerLoginType)

    @staticmethod
    async def mutate(parent, info, user: CustomerLogin_PydanticIn):
        user = await CustomerLogin.create(**user.dict())
        return CreateUserMutation(user=user)

graphql\types.py
import graphene

# Fields should coincide with model.CustomerLogin
class CustomerLoginType(graphene.ObjectType):
    id = graphene.Int()
    shard_id = graphene.Decimal()
    seq_num = graphene.Decimal()
    event_timedate = graphene.DateTime()
    user_id = graphene.UUID()
    device_token = graphene.UUID()
    user_ip = graphene.String()
    user_agent = graphene.String()
    client_id = graphene.String()
    process = graphene.String()
    auth_result = graphene.String()
    auth_fail_cause = graphene.String()
    plain_email = graphene.String()

graphql\queries.py
import graphene

from models.customers import CustomerLogin
from graphql.types import CustomerLoginType

class Query(graphene.ObjectType):

    all_customer_logins = graphene.List(CustomerLoginType)
    single_customer_login = graphene.Field(CustomerLoginType, id=graphene.Int())

    @staticmethod
    async def resolve_all_customer_logins(parent, info):
        users = await CustomerLogin.all()
        return users

    @staticmethod
    async def resolve_single_customer_login(parent, info, id):
        user = await CustomerLogin.get(id=id)
        return user

Then the ORM model using TortoiseORM
models\customers.py
from tortoise import fields
from tortoise.contrib.pydantic import pydantic_model_creator
from tortoise.models import Model

from models.events import ShardID, SequenceNum

class CustomerLogin(Model):
    shard_id: fields.ForeignKeyNullableRelation[ShardID] = \
        fields.ForeignKeyField(model_name='models.ShardID',
                               related_name='customerlogin_shardid',
                               to_field='shard_id',
                               on_delete=fields.RESTRICT,
                               null=True)
    seq_num: fields.ForeignKeyNullableRelation[SequenceNum] = \
        fields.ForeignKeyField(model_name='models.SequenceNum',
                               related_name='customerlogin_seqnum',
                               to_field='seq_num',
                               on_delete=fields.RESTRICT,
                               null=True)
    event_timedate = fields.DatetimeField(null=True)
    user_id = fields.UUIDField(null=True)
    device_token = fields.UUIDField(null=True)
    user_ip = fields.CharField(256, null=True)
    user_agent = fields.CharField(1024, null=True)
    client_id = fields.CharField(256, null=True)
    process = fields.CharField(256, null=True)
    auth_result = fields.CharField(256, null=True)
    auth_fail_cause = fields.CharField(256, null=True)
    plain_email = fields.CharField(256, null=True)

CustomerLogin_Pydantic = pydantic_model_creator(CustomerLogin, name='CustomerLogin')
CustomerLogin_PydanticIn = pydantic_model_creator(CustomerLogin, name='CustomerLoginIn', exclude_readonly=True)


texts: Print out symmetric matrix from compactly stored array

texts:
I have an array of the form (3x3 case as an example)
$$A = [a_{11}, a_{12}, a_{22}, a_{13}, a_{23}, a_{33}] $$
corresponding to the symmetric matrix
$$\begin{pmatrix} a_{11} & a_{12} & a_{13}\\ a_{12} & a_{22} & a_{23} \\ a_{13} & a_{23} & a_{33} \end{pmatrix}$$
I want to print out this very matrix (in general of size NxN) given the array A (in general of length N*(N+1)/2) in a nice way.
My approach was
void print__symm_matrix_packed(double* arr, int N){

  int idx2 = 0;

  for(int i=0; i<N; i++){
    printf("(");

    int idx1 = i;

    for(int j=0; j<N; j++){
      if(j < i){
        printf("%f ", arr[idx2 + j]);
      } else {
        printf("%f ", arr[idx1]);
      }
      idx1 += j+1;
    }
    idx2 += i+1;
    printf(")\n");
  }
}

Is there room for some elegant improvement?


texts:
Here is an implementation of Knapsack in Rust. How could it be improved?
Some things I have already spotted:

What would be the best way to extract result? Is using an option preferred unwrapping the last element of vector? I also want to show last value of vector regardless of its contents, so would unwrapping be preferable?

How to save casting all the time for array indices, vector definitions?

use std::cmp;

fn solve_knapsack_dynamically(
    weights: &Vec<i64>,
    profits: &Vec<i64>,
    knap_sack_max_weight: i64,
) -> Option<i64> {
    let mut prev_row = vec![0; knap_sack_max_weight as usize];
    let mut curr_row = vec![0; knap_sack_max_weight as usize];

    for i in 1..weights.len() {
        for j in 0..knap_sack_max_weight {
            if weights[i as usize] > j {
                curr_row[j as usize] = prev_row[j as usize];
            } else {
                curr_row[j as usize] = cmp::max(
                    prev_row[j as usize],
                    prev_row[(j - weights[i as usize]) as usize] + profits[i as usize],
                );
            }
        }

        prev_row = curr_row.to_vec();
    }

    curr_row.last().cloned()
}

fn main() {
    let weights = vec![10, 50, 20, 100];
    let profits = vec![56, 23, 11, 4];
    let knap_sack_max_weight = 120;

    let result = solve_knapsack_dynamically(&weights, &profits, knap_sack_max_weight);

    match result {
        Some(x) => println!("Result: {}", x),
        None => println!("Failed"),
    }
}


texts:
I'm new in python and I'm wondering if there any issue I should worry about in the following code?

from base64 import b64encode

class Base64Encoder:

    @classmethod
    def encode_basic(cls, usr, pwd):
       token = cls.base64_encode(f"{usr}:{pwd}")
       return f'Basic {token}'

   @classmethod
   def encode_bearer(cls, token):
       return f'Bearer {token}'

   @staticmethod
   def base64_encode(token):
       return b64encode(token.encode('ascii')).decode('ascii')


texts:
I'm new to programming, but want to build up a good habit of code review so that I can develop best practice. It's been couple of weeks I'm coding in C and my knowledge, so far, is data types, conditions, arrays, loop and, very minimal, pointers.

I'm creating multiple search and sorting algorithms - not only to understand them better, but also solidifying my understanding of concepts.

#include <stdio.h>
#include <cs50.h>

void swap(int *x, int *);
int midval(int x, int y);

int main(void)
{
    // taking count for characters
    printf("How many characters are you entering? ");
    int count = get_int();

    // creating the array
    int array[count];

    // taking string as an input and converting them to integers
    for (int i=0; i<count; i++)
    {
        printf("Please enter the character number %i: ", (i+1));
        array[i] = atoi(get_string());
    }

    //sorting - bubble sort
    int j=count-1;
    do
    {
        for(int i=0; i<j; i++)
        {
            if (array[i] > array[i+1])
            {
                swap(&array[i], &array[i+1]);
            }
        }
        j--;
    }
    while (j!=0);

    //binary search
    printf("Please enter the character you want to search: ");
    int search = atoi(get_string());
    int i=0;

    do
    {
        if (search == array[midval(i, count-1)])
        {
            printf("The character exists in the list.\n");
            return 0;
        }
        else if (search > array[midval(i, count-1)])
        {
            i = midval(i, count-1) + 1;
        }
        else if (search < array[midval(i,count-1)])
        {
            count = midval(i, count-1);
        }
    }
    while (count != i);

    printf("The character does not exist in the list.\n");

}

void swap(int *x, int *y)
{
    int temp[1];
    temp[0] = *x;
    *x = *y;
    *y = temp[0];
}

int midval(int x, int y)
{
    int z = (x+y)/2;
    return z;
}


texts: Get bibtex entries from metadata of PDF files

texts:
When I have to write a report or an article, I usually have my bibliography as PDFs in a specific folder, so I wrote this script to automate the generation of bibtex entries.

It works so far, but I'd like to have suggestions about what I could improve

#!/usr/bin/env bash

FOLDER=$1
BIBTEX_FILE=$2

cd $FOLDER
for f in *; do
    echo "Examining $f"
    TITLE=`pdfinfo $f | grep Title | cut -c17-`

    echo "Title found in PDF metadata is : $TITLE"

    case "$TITLE" in
        doi*)
            echo "This is a DOI, nice!"
            DOI=`echo $TITLE | cut -c5-`;;
        *)
            case "$TITLE" in
                "untitled")
                    echo "Let's see what we can find in the text"
                    DOI=`pdftotext $f /tmp/pdf | cat /tmp/pdf | grep -i 'doi\|Digital Object Identifier' | awk 'NF>1{print $NF}'`;;
                *)
                    echo "Let's find a DOI from this title"
                    TITLE=`echo $TITLE | sed 's/ /%20/g'`
                    URL="http://api.crossref.org/works?query=$TITLE&rows=1"
                    DOI=`curl -s $URL | jq '.message.items[].DOI' | sed 's/"//g'`;;
            esac
    esac

    echo "The DOI is $DOI"
    echo "----------------------------------"
    URL="http://api.crossref.org/works/$DOI/transform/application/x-bibtex"
    curl -s $URL >> $BIBTEX_FILE
    echo >> $BIBTEX_FILE
    echo >> $BIBTEX_FILE
done


texts: intersection observer multiple animation

texts:
I want to achieve different animation for many elements on scroll, so instead of using window.scroll i'm using intersection observer api, but i want to know if my approach is effective and won't cause performance drop, basically what i did is make a single function to hold the entire animation of the website and check if the target has specific class then do something like so :

const one = document.querySelector('.one')
const two = document.querySelector('.two')
const three = document.querySelector('.three')

function animation (entires) {
    entires.forEach(entry => {
        if(entry.isIntersecting) {
            if(entry.target.classList.contains('text')) {
               entry.target.style.transform = 'translateY(0)'
            }
            if(entry.target.classList.contains('one')) {
               entry.target.style.transform = 'translateX(100px)'
            }
            if(entry.target.classList.contains('two')) {
               entry.target.style.transform = 'translateY(0)'
            }
            if(entry.target.classList.contains('three')) {
               entry.target.style.transform = 'skew(10deg)'
            }
        }
    })
}
const observer = new IntersectionObserver(animation)

i'm not experienced enough but i feel like it's spaghetti code and not efficient and how can i observe multiple elements ? do i have to repeat observer.observe for each element i want to observe ?


texts: Displaying separated multi-line text fields

texts:
The following code grabs the HTML-encoded, multi-line content of a text field. It then splits the content on line breaks, and finally displays it with commas as separators.

I would like to have this code reviewed to see if there is a simpler way to grab the string, split and display it.

Note - I hated the idea of writing 2 collection iterations, but I found if a user in the CMS entered one line of real data, and then a couple of empty line breaks, it would throw the array length off and display a comma on a single item e.g. output should look like this :

Correct: Allowed Uses: example 1 | Allowed Uses: example 1, example 2
Incorrect: Allowed Uses: example 1, | Allowed Uses: example 1, example 2,

  var retailBreaks = umbraco.library.ReplaceLineBreaks(Model.landAllowedUses);
  string[] retailBreaksSplit = retailBreaks.Split(new string[] { "
" }, StringSplitOptions.RemoveEmptyEntries);
  int breaksLength = 0;
  List<String> repeatableProperty = new List<String>();
  foreach (string s in retailBreaksSplit)
  {
    if (!string.IsNullOrWhiteSpace(s))
       {
         repeatableProperty.Add(s);
       }
  }
 breaksLength = repeatableProperty.Count();

    Allowed Uses:

    @foreach (string s in repeatableProperty)
    {
     @s.Trim()@((breaksLength > 1 && repeatableProperty.Last<string>() != s) ? ", " : string.Empty)
    }


texts: An example of transferring the C ++ class hierarchy to Golang. Is it done correctly?

texts:
I am trying to transfer my c ++ experience to the Go area. I'm new to Go, so not sure if the implementation is correct. In any case, it looks very ugly compared to C ++ code. Is there a nicer solution? Both solutions are executable in playground and give same result.
c++ playground: https://code.sololearn.com/c67xbW2AEWW2/#cpp
#include <iostream>
using namespace std;

// Abstract class
class AbstractGenerator
{
public:
    AbstractGenerator() {}
    std::string generate(std::string some_internal_data)
    {
        _some_internal_data = some_internal_data;
        return step1() + step2();
    }

protected:
    // some shared fuctions
    std::string generationHelper1(std::string s) { return s + _some_internal_data + "123"; }
    std::string generationHelper2(std::string s) { return s + _some_internal_data + "456"; }
    // abstract fucntions
    virtual std::string step1() = 0;
    virtual std::string step2() = 0;

private:
    std::string _some_internal_data;
};
// Implementation
class MyGenerator : public AbstractGenerator
{
public:
    MyGenerator() {}

protected:
    std::string step1() override { return generationHelper1("my step1") + generationHelper2("my step1"); }
    std::string step2() override { return "my step2"; }
};

int main() {
    MyGenerator my_gen;
    AbstractGenerator* abstract_gen = &my_gen;
    cout << abstract_gen->generate("data");
    return 0;
}

Go playground: https://play.golang.org/p/e3iXfYar4YJ
package main

import "fmt"

// some shared fuctions - interface
type ImplementationHelper interface {
    generationHelper1(s string) string
    generationHelper2(s string) string
}

// abstract fucntions - interface
type Implementation interface {
    step1() string
    step2() string
}

// Public main interface
type Generator interface {
    Generate(s string) string
}

type AbstractGenerator struct {
    someInternalData string
    implementation   Implementation
}

func NewAbstractGenerator(i Implementation) *AbstractGenerator {
    g := new(AbstractGenerator)
    g.implementation = i
    return g
}
func (g *AbstractGenerator) Generate(s string) string {
    g.someInternalData = s
    return g.implementation.step1() + g.implementation.step2()
}
func (g *AbstractGenerator) generationHelper1(s string) string { return s + g.someInternalData + "123" }
func (g *AbstractGenerator) generationHelper2(s string) string { return s + g.someInternalData + "456" }

// Implementation of AbstractGenerator
type MyGenerator struct {
    basic *AbstractGenerator
}

// MyGenerator constructor
func NewMyGenerator() *MyGenerator {
    myGen := new(MyGenerator)
    myGen.basic = NewAbstractGenerator(myGen)
    return myGen
}

// Interface Generator
func (i *MyGenerator) Generate(s string) string {
    return i.basic.Generate(s)
}

// Interface Implementation
func (i *MyGenerator) step1() string {
    return i.basic.generationHelper1("my step1") + i.basic.generationHelper2("my step1")
}
func (i *MyGenerator) step2() string {
    return "my step2"
}

func main() {
    myGen := NewMyGenerator()

    var abstractGen Generator
    abstractGen = myGen

    fmt.Println(abstractGen.Generate("data"))
}


texts:
Is there a better way to write this?

$query = $db->getConnection()->prepare("INSERT INTO `users` (first_name, last_name, email, username, password, unique_id, date_joined) VALUES(:fname, :lname, :email, :username, :pass, :uniqueid, :date_joined)");
$query->bindParam(':fname', $first_name, PDO::PARAM_STR);
$query->bindParam(':lname', $last_name, PDO::PARAM_STR);
$query->bindParam(':email', $email, PDO::PARAM_STR);
$query->bindParam(':username', $username, PDO::PARAM_STR);
$query->bindParam(':pass', $passHash, PDO::PARAM_STR);
$query->bindParam(':uniqueid', $emailHash, PDO::PARAM_STR);
$query->bindParam(':date_joined', $date, PDO::PARAM_STR);
$query->execute();


texts: One reader / one writer no-memory-allocation lock-free ring-buffer

texts:
I have two threads - one thread queues items another thread dequeues. dequeue is fast enough and so we can assume that queue is never contains more than 65536 items.

C++ doesn't contain "ring-buffer."  Boost has one, but it doesn't allow "reuse" of elements. So I wrote my own ring-buffer, which I think is very fast and requires no memory allocation.  The code below has not been tested but it should show the general idea.

Do you find my code fine? Can you suggest how I can improve it or if there's something I can use instead of it?
    #include
    #include
    #include

#include <chrono>
#include <thread>

template<class T> class ArrayPool
{
public:
    ArrayPool() {
    };

    ~ArrayPool(void) {
    };

    // reader thread
    bool IsEmpty() {
        return curReadNum == curWriteNum;
    }

    // reader thread
    T* TryGet()
    {
        if (curReadNum == curWriteNum)
        {
            return NULL;
        }
        T* result = &storage[curReadNum & MASK];
        ++curReadNum;
        return result;
    }

    // writer thread
    T* Obtain() {
        return &storage[curWriteNum & MASK];
    }

    // writer thread
    void Commit()
    {
                    // Ensure storage is written before mask is incremented ?
                    // insert memory barrier ?
        ++curWriteNum;
        if (curWriteNum - curReadNum > length)
        {
            std::cout <<
                "ArrayPool curWriteNum - curReadNum > length! " <<
                curWriteNum << " - " << curReadNum << " > " << length << std::endl;
        }
    }

    // writer thread
    void ObtainAndCommit(T* val) {
        memcpy(&storage[curWriteNum & MASK], val, sizeof(T));
        // copy constructor will likely be slower cause every field is copied
        // storage[curWriteNum & MASK] = *val;
        Commit();
    }

private:
    static const uint32_t length = 65536;
    static const uint32_t MASK = length - 1;
    T storage[length];

    // curWriteNum must be volatile because access from both
    // reader and writer threads
    // curReadNum don't need to be volatile because accessed
    // only from one (reader) thread
    volatile uint32_t curWriteNum;
    uint32_t curReadNum;
};

struct myStruct {
    int value;
};

ArrayPool<myStruct> pool;

void ReadThread() {
    myStruct* entry;
    while(true) {
        while ((entry = pool.TryGet()) != NULL) {
            std::cout << entry->value << std::endl;
        }
    }
}

void WriteThread(int id) {
    std::chrono::milliseconds dura(1000 * id);
    std::this_thread::sleep_for(dura);

    myStruct* storage = pool.Obtain();
    storage->value = id;
    pool.Commit();
    std::cout << "Commited value! " << id << std::endl;
}

int main( void )
{
    boost::thread readThread = boost::thread(&ReadThread);
    boost::thread writeThread;
    for (int i = 0; i < 100; i++) {
        writeThread = boost::thread(&WriteThread, i);
    }
    writeThread.join();
    return 0;
}


texts: Given hexadecimal rgb color, find the closest predefined color

texts:
The following is a function that accepts a hex value (with or without a #, 3 or 6 character) and returns another hex value that is "closest" to it from a set of static hex values defined within the function. It involves a conversion to RGB.

How do I make this function more "elegant"? This is more of a question in general JS syntax and style, but I figured this was a good general example to present. I'd imagine I need to include some kind of nested functions, anonymous functions or closures that handle each part of the algorithm.

Here's the code, taking colors from Google's logo, for instance:

function nearestHex(hex) {

  var hexToRgb = function(hex) {
    var shortRegEx = /^#?([a-f\d])([a-f\d])([a-f\d])$/i;
    hex = hex.replace(shortRegEx, function(full, r, g, b) {
      return [r, r, g, g, b, b].join();
    });
    var longRegEx = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})?/i;
    var rgbArray  = longRegEx.exec(hex);
    var rgbObj = rgbArray ? {
      r: parseInt(rgbArray[1], 16),
      g: parseInt(rgbArray[2], 16),
      b: parseInt(rgbArray[3], 16)
    } : null;
    return rgbObj;
  }();

  var closestHexFromRgb = function(rgbObj) {
    if (!rgbObj) {
      throw new Error("The hex you provided is not formatted correctly. Please try in a format such as '#FFF' or '#DDFFDD'.");
    };

    var staticColors = [
      { color: 'red',    hex: '#EA4235', rgb: { r: 234, g: 66,  b: 53  } },
      { color: 'green',  hex: '#34A853', rgb: { r: 512  g: 168, b: 83  } },
      { color: 'blue',   hex: '#4285F4', rgb: { r: 66,  g: 133, b: 244 } },
      { color: 'yellow', hex: '#FBBC05', rgb: { r: 251, g: 188, b: 5   } }
    ];
    var minDistance = Number.MAX_SAFE_INTEGER;
    var nearestHex = null;

    for (var i=0; i<staticColors.length; i++) {
      var currentColor = staticColors[i];
      var distance = Math.sqrt(
        Math.pow((rgbObj.r - currentColor.rgb.r), 2) +
        Math.pow((rgbObj.g - currentColor.rgb.g), 2) +
        Math.pow((rgbObj.b - currentColor.rgb.b), 2)
      );
      if (distance < minDistance) {
        minDistance = distance;
        nearestHex = currentColor.hex;
      }
    };
    return nearestHex;
  }();

  closestHexFromRgb(hexToRgb(hex));

};


texts:
1
    /  \
   2    3
 /  \     \
4    5     8
          /  \
         6    7

  Width of a tree is maximum of widths of all levels.

  For the above tree:

  width of level 1 is 1
  width of level 2 is 2
  width of level 3 is 3
  width of level 4 is 2

  So the maximum width of the tree is 3.

This code is attributed to GeeksForGeeks. I'm looking for code-review, best practices and optimizations. I'm verifying space complexity to be \$O(n)\$.

public class MaxWidthOfTree<T> {

    private TreeNode<T> root;

    public MaxWidthOfTree(List<T> items) {
        create(items);
    };

    private void create(List<T> items) {
        if (items.isEmpty())  {
            throw new NullPointerException("The input array is not empty.");
        }

        root = new TreeNode<>(items.get(0));

        final Queue<TreeNode<T>> queue = new LinkedList<TreeNode<T>>();
        queue.add(root);

        final int half = items.size() / 2;

        for (int i = 0; i < half; i++) {
            if (items.get(i) != null) {
                final TreeNode<T> current = queue.poll();
                final int left = 2 * i + 1;
                final int right = 2 * i + 2;

                if (items.get(left) != null) {
                    current.left = new TreeNode<>(items.get(left));
                    queue.add(current.left);
                }
                if (right < items.size() && items.get(right) != null) {
                    current.right = new TreeNode<>(items.get(right));
                    queue.add(current.right);
                }
            }
        }
    }

    private static class TreeNode<T> {
        private TreeNode<T> left;
        private T item;
        private TreeNode<T> right;

        TreeNode(T item) {
            this.item = item;
        }
    }

    public int getMaxWidth() {
        if (root == null) {
            throw new IllegalArgumentException("The root is empty");
        }

        int h = getHeight(root);
        int[] arr = new int[h + 1]; // NOTE: h + 1

        computeWidth(root, arr, 0);

        return maxElementOfArray (arr);
    }

    private int maxElementOfArray(int[] arr) {
        int max = Integer.MIN_VALUE;
        for (int i = 0; i < arr.length; i++) {
            if (arr[i] > max) {
                max = arr[i];
            }
        }
        return max;
    }

    private void computeWidth(TreeNode<T> node, int[] arr, int level) {
        if (node == null) return;
        arr[level]++;  // NOTE: you can place this as preorder, inorder or postorder, does not matter.
        computeWidth(node.left, arr, level + 1);
        computeWidth(node.right, arr, level + 1);
    }

    public int getHeight(TreeNode<T> node) {
        if (node == null) return -1;
        return Math.max(getHeight(node.left), getHeight(node.right)) + 1;
    }
}

public class MaxWidthOfTreeTest {

    @Test
    public void testLevel3() {
        MaxWidthOfTree<Integer> mwot1 = new MaxWidthOfTree<>(Arrays.asList(1, 2, 3, 4, 5, null, 7, null, null, null, null, null, null, 14, 15));
        assertEquals(3, mwot1.getMaxWidth());
    }

    @Test
    public void testTestLevel4() {
        MaxWidthOfTree<Integer> mwot2 = new MaxWidthOfTree<>(Arrays.asList(1, 2, 3, 4, 5, null, 7, null, null, 14, 15, null, null, 16, 17));
        assertEquals(4, mwot2.getMaxWidth());
    }
}