ESLint rule for Jasmine/Protractor In Protractor, Jasmine expectations are patched to resolve WebDriver
  promises implicitly.

  For instance, if you need to assert a count of certain elements, you
  can use count() method (which returns a promise) directly:

expect($$(".myclass").count()).toEqual(5);

  But, newcomers to Protractor can miss that and would do the same
  resolving promises explicitly which leads to a more complex code:

$$(".myclass").then(function (elements) {
    expect(elements.length).toEqual(5);
});

I've developed an ESLint rule to try to catch this kind of explicit "count" value check. The logic behind the rule is:

It first locates the .length "member expression"
Iterates over the ancestors and checks if inside expect
Iterates over the ancestors and checks if inside a "then" callback and there is at least one argument passed to the callback function
Determines if .then was called on an "element array finder"

'use strict'

/**
 * @fileoverview Recommend using `count()` instead of `then()` and `length`
 * @author Alexander Afanasyev
 */

var isElementArrayFinder = require('../is-element-array-finder')
var isThenCallBack = require('../is-then-callback')
var isExpect = require('../is-expect')

module.exports = {
  meta: {
    schema: []
  },

  create: function (context) {
    return {
      MemberExpression: function (node) {
        if (node.property && node.object && node.property.name === 'length') {
          // remember the variable name the ".length" was used on
          var variableName = node.object.name

          // find out if we are in an expect()
          var expectAncestor
          var thenAncestor
          var ancestors = context.getAncestors(node)

          for (var i = 0; i < ancestors.length; i++) {
            expectAncestor = ancestors[i]
            if (expectAncestor && expectAncestor.type === 'CallExpression' && isExpect(expectAncestor)) {
              // find out if we are inside a then callback
              ancestors = context.getAncestors(expectAncestor)
              for (var j = 0; j < ancestors.length; j++) {
                thenAncestor = ancestors[j]
                if (thenAncestor && thenAncestor.type === 'CallExpression') {
                  var thenCallback = isThenCallBack(thenAncestor)

                  // it has to have at least one argument
                  if (thenCallback && thenCallback.params && thenCallback.params.length > 0) {
                    var thenCallbackArgument = thenCallback.params[0]

                    // the same variable is a "then" callback function argument
                    if (thenCallbackArgument && thenCallbackArgument.name === variableName) {
                      // check that it was an ElementArrayFinder resolution
                      if (thenAncestor.callee && thenAncestor.callee.object) {
                        if (isElementArrayFinder(thenAncestor.callee.object)) {
                          context.report({
                            node: node,
                            message: 'Array.length inside promise resolution function detected. Use count() instead.'
                          })
                          return
                        }
                      }
                    }
                  }
                }
              }
            }
          }
        }
      }
    }
  }
}

Source code is also available on GitHub.

The rule is overly complicated, very deep and nested and not readable at all (cyclomatic code complexity is 10). What refactoring methods would you apply to improve on readability?

FYI, using standard style.

Your naming of variables is good, they're mostly descriptive and easy to follow.

You could use reverse conditional to reduce the cyclomatic code complexity, doing that your code would look something like:

module.exports = {
  meta: {
    schema: []
  },

  create(context) {
    return {
      MemberExpression(node) {
        if (!node.property || !node.property.object || node.property.name !== 'length') {
          return
        }

        const variableName = node.object.name

        const expectAncestors = context.getAncestors(node)
        for (const expectAncestor of expectAncestors) {
          if (!expectAncestor || expectAncestor.type !== 'CallExpression' || !isExpect(expectAncestor)) {
            continue
          }

          const thenAncestors = context.getAncestors(expectAncestor)
          for (const thenAncestor of thenAncestors) {
            if (!thenAncestor || thenAncestor.type !== 'CallExpression') {
              continue
            }

            const thenCallback = isThenCallBack(thenAncestor)
            const hasParams = thenCallback && thenCallback.params && thenCallback.params.length > 0

            if (!hasParams) {
              continue
            }

            const [thenCallbackParam] = thenCallback.params
            const paramIsDesiredVariable = thenCallbackParam && thenCallbackParam.name === variableName

            const isElementArrayFinderResolution = thenAncestor.callee && thenAncestor.calle.object && isElementArrayFinder(thenAncestor.callee.object)

            if (!paramIsDesiredVariable || !isElementArrayFinderResolution) {
              continue
            }

            context.report({
              node,
              message: 'Array.length inside promise resolution function detected. Use count() instead.'
            })

            return
          }
        }
      }
    }
  }
}

I've included some extra changes in the above code, such as using some ES6.

Property shorthand: { node: node } -> { node }
Method properties: create: function(context) { -> create(context) {
For-of: for (var i = 0; i < ancestors.length; i++) { expectAncestor = ancestors[i] -> for (const thenAncestor of thenAncestors), which is nice since the index was only used to access the ith element
Constants: Using const to denote variables that cannot be re-assigned
Using param instead of "argument" to be consistent with eslint api
Creating expectAncestors/thenAncestors instead of re-assigning ancestors

We could further refactor using extract method:

const getExpectAncestor = (context, node) =>
  context.getAncestors(node).find(expectAncestor => expectAncestor && expectAncestor.type === 'CallExpression' && isExpect(expectAncestor))

const getThenAncestor = (context, expectAncestor) =>
  context.getAncestors(expectAncestor).find(thenAncestor => thenAncestor && thenAncestor.type === 'CallExpression')

const getThenCallbackParam = thenAncestor => {
  const thenCallback = isThenCallback(thenAncestor)
  const hasParams = thenCallback && thenCallback.params && thenCallback.params.length > 0

  if (hasParams) {
    return thenCallback.params[0]
  }
}

// Ideally you'd rename this something even more descriptive
const isDesiredVariable = (thenCallbackParam, variableName) => {
  const paramIsDesiredVariable = thenCallbackParam && thenCallbackParam.name === variableName
  const isElementArrayFinderResolution = thenAncestor.callee && thenAncestor.calle.object && isElementArrayFinder(thenAncestor.callee.object)

  return paramIsDesiredVariable && isElementArrayFinder
}

module.exports = {
  meta: {
    schema: []
  },

  create(context) {
    return {
      MemberExpression(node) {
        // You could extract this into a `isLengthVariable` function
        if (!node.property || !node.property.object || node.property.name !== 'length') {
          return
        }

        const expectAncestor = getExpectAncestor(context, node)
        if (!expectAncestor) {
          return
        }

        const thenAncestor = getThenAncestor(context, expectAncestor)
        if (!thenAncestor) {
          return
        }

        const thenCallbackParam = getThenCallbackParam(thenAncestor)
        if (!thenCallbackParam) {
          return
        }

        const variableName = node.object.name

        if (isDesiredVariable(thenCallbackParam, variableName)) {
          context.report({
            node,
            message: 'Array.length inside promise resolution function detected. Use count() instead.'
          })
        }
      }
    }
  }
}

Here, we have extracted the main logic into seperate methods: getExpectAncestor, getThenAncestor, getThenCallbackParam

These methods are using Array.prototype.find() to find the first element that matches the predicate provided. If no such element is found, it returns undefined and we can exit MemberExpression

Further notes

You could use arrow functions shorthand since you are directly returning:

create = context => ({
  MemberExpression(node) {
    // ...
  }
}

You could declare MemberExpression outside of module.exports to further reduce the indentation level, though since the function relies on context you would need to pass context as an additional parameter. You could achieve this through a higher-order function:

const MemberExpression = context => node => {
  // ...
}

module.exports = {
  // ...

  create: context => ({
    MemberExpression: MemberExpression(context)
  }
}

You'd probably want to refactor this further since there are some especially long lines when checking conditionals, you can use a formatter such as prettier

Prettifying the solution with extracted methods gives the following:

const getExpectAncestor = (context, node) =>
  context
    .getAncestors(node)
    .find(
      expectAncestor =>
        expectAncestor &&
        expectAncestor.type === "CallExpression" &&
        isExpect(expectAncestor)
    );

const getThenAncestor = (context, expectAncestor) =>
  context
    .getAncestors(expectAncestor)
    .find(
      thenAncestor => thenAncestor && thenAncestor.type === "CallExpression"
    );

const getThenCallbackParam = thenAncestor => {
  const thenCallback = isThenCallback(thenAncestor);
  const hasParams =
    thenCallback && thenCallback.params && thenCallback.params.length > 0;

  if (hasParams) {
    return thenCallback.params[0];
  }
};

// Ideally you'd rename this something even more descriptive
const isDesiredVariable = (thenCallbackParam, variableName) => {
  const paramIsDesiredVariable =
    thenCallbackParam && thenCallbackParam.name === variableName;
  const isElementArrayFinderResolution =
    thenAncestor.callee &&
    thenAncestor.calle.object &&
    isElementArrayFinder(thenAncestor.callee.object);

  return paramIsDesiredVariable && isElementArrayFinder;
};

module.exports = {
  meta: {
    schema: []
  },

  create(context) {
    return {
      MemberExpression(node) {
        // You could extract this into a `isLengthVariable` function
        if (
          !node.property ||
          !node.property.object ||
          node.property.name !== "length"
        ) {
          return;
        }

        const expectAncestor = getExpectAncestor(context, node);
        if (!expectAncestor) {
          return;
        }

        const thenAncestor = getThenAncestor(context, expectAncestor);
        if (!thenAncestor) {
          return;
        }

        const thenCallbackParam = getThenCallbackParam(thenAncestor);
        if (!thenCallbackParam) {
          return;
        }

        const variableName = node.object.name;

        if (isDesiredVariable(thenCallbackParam, variableName)) {
          context.report({
            node,
            message: "Array.length inside promise resolution function detected. Use count() instead."
          });
        }
      }
    };
  }
};


Safely open a list of links in Firefox I receive a list of links via http and I want to open them all in a new Firefox (or default browser) window as tabs; that is my script must not touch existing windows.

This is the best solution I could come up with:

from subprocess import call

links = GetListViaHTTP()

if len(links) == 1:
    call(['firefox', '-new-window'] + links)
elif len(links) > 1:
    call(['firefox'] + links)
else:
    print('Nothing to do.')

This worked like a charm when I tested it, but putting something I received via http into subprocess.call does not look save to me at all. So the question is:

How can I improve this code to avoid being vulnerable to MITM attacks?

If the list was not tampered with by an attacker, all links it contains will point to Stack Overflow answers, so maybe somehow validating the links with urllib.parse is good enough?

Rather than implementing this yourself, Python by default has webbrowser. This allows you to open one link in a; new tab, or new window. And so, to open all links in the list with the default web-browser you can:

import webbrowser

for link in links:
    webbrowser.open_new_tab(link)

Since you say you don't trust the source of these urls, you can make sure they are actually URLs, and check there is no shell injection going on. This question says how you could do that.

And so I personally would use:

import webbrowser

import rfc3987

def open_links(links):
    links = (
        link
        for link in links
        if rfc3987.match(link, rule='IRI') is not None
    )
    # Get default webbrowser, change if you want to force a specific browser
    browser = webbrowser.get()
    try:
        browser.open_new(next(links))
    except StopIteration:
        pass
    else:
        for link in links:
            browser.open_new_tab(link)


Fast "index of minimum" for distances to points on single thread The problem in simple words: I have three arrays of double values (x-, y- and z-coordinates) and need to find the index of the point which has minimum distance to a reference points. I do not need the actual value of this distance. If the minimum distance is not unique, any index where its value occurs may be returned.

I will be using this function for determining the squared distance between points:

double distSqr(double xa, double ya, double za,
               double xb, double yb, double zb)
{
    double X = xa - xb;
    double Y = xa - xb;
    double Z = xa - xb;

    return X * X + Y * Y + Z * Z;
}

Taking the square root in the final step will not be necessary.

First of all, consider a "naive" implementation where you simply compare the "current" value to all other values, exchanging the "current" value if a smaller value is found:

// Take the three arrays of x-, y-, and z-coordinates filled with arbitrary values.
#define SIZE 20

double cx[SIZE];
double cy[SIZE];
double cz[SIZE];

int min_naive(double x, double y, double z)
{
    double minDist = distSqr(x, y, z, cx[0], cy[0], cz[0]);
    int minIndex = 0;

    for (int i = 1; i < SIZE; i++)
    {
        double d = distSqr(x, y, z, cx[i], cy[i], cz[i]);
        if (d < minDist)
        {
            minDist = d;
            minIndex = i;
        }
    }

    return minIndex;
}

// Finally, determin the index, e.g.
int minInd = min_naive(0, 0, 0);

This does not seem like an optimal solution to me, especially since it might not be fast enough if the loop has to run over all distances where only one comparison happens at each step. Obviously, sooner or later all distances have to be calculated.
Next, I came up with a better solution that first calculates all distances and then compares them in a loop in such a way, that each loop halves the number of possible distances left.
I hoped that the compiler might auto-vectorize this function, instead of using a simple loop over all points, but I have not checked that yet.

This is the code I came up with:

void cmpmv(int lower, int upper, int *inds, double *dists)
{
    double a = dists[lower];
    double b = dists[upper];

    if (a > b)
    {
        inds[lower] = inds[upper];
        dists[lower] = b;
    }
}

int min_better(double kax, double kay, double kaz)
{
    double dists[SIZE];
    int inds[SIZE];
    for (int i = 0; i < SIZE; i++)
    {
        dists[i] = distSqr(kax, kay, kaz, nncx[i], nncy[i], nncz[i]);
        inds[i] = i;
    }

    int div, mod;
    int s = SIZE;
    while (s > 1)
    {
        div = s / 2;
        mod = s % 2;

        for (int i = 0; i < div; i++)
            cmpmv(i, i + div, inds, dists);
        if (mod == 1)
            cmpmv(0, s - 1, inds, dists);

        s = div;
    }

    return inds[0];
}

(Note that this must differentiate the cases where SIZE and later s are not a multiple of 2.)

Are there maybe even better and especially faster ways to implement this?

There are two restrictions:

I only have one thread available.
I have to use arrays/pointers.

The major compilers did not really auto-vectorize this, but it can be done manually. For example with AVX, we could do something like (not tested)

int indexOfMin(double pt_x, double pt_y, double pt_z, int n)
{
    __m256d ptx = _mm256_set1_pd(pt_x);
    __m256d pty = _mm256_set1_pd(pt_y);
    __m256d ptz = _mm256_set1_pd(pt_z);
    __m256d xdif = _mm256_sub_pd(ptx, _mm256_loadu_pd(cx));
    __m256d ydif = _mm256_sub_pd(pty, _mm256_loadu_pd(cy));
    __m256d zdif = _mm256_sub_pd(ptz, _mm256_loadu_pd(cz));
    __m256d min_dist = _mm256_add_pd(_mm256_add_pd(_mm256_mul_pd(xdif, xdif),
                                                   _mm256_mul_pd(ydif, ydif)),
                                                   _mm256_mul_pd(zdif, zdif));
    __m128i min_index = _mm_set_epi32(3, 2, 1, 0);
    __m128i index = min_index;
    __m256d dist;
    for (int i = 4; i < n; i += 4) {
        xdif = _mm256_sub_pd(ptx, _mm256_load_pd(cx + i));
        ydif = _mm256_sub_pd(pty, _mm256_load_pd(cy + i));
        zdif = _mm256_sub_pd(ptz, _mm256_load_pd(cz + i));
        dist = _mm256_add_pd(_mm256_add_pd(_mm256_mul_pd(xdif, xdif),
                                           _mm256_mul_pd(ydif, ydif)),
                                           _mm256_mul_pd(zdif, zdif));
        index = _mm_add_epi32(index, _mm_set1_epi32(4));
        __m256 mask256 = _mm256_castpd_ps(_mm256_cmp_pd(dist, min_dist, _CMP_LT_OS));
        // mask256 has the masks as 4 x int64, but we need 4 x int32
        // there's no nice 'pack' to do it, but shufps can extract
        // the relevant floats, and then we can reinterpret as integers
        // mask256 = * D * C * B * A (* is an ignored float)
        __m128 maskL = _mm256_castps256_ps128(mask256);   // * B * A
        __m128 maskH = _mm256_extractf128_ps(mask256, 1); // * D * C
        __m128 maskps = _mm_shuffle_ps(maskL, maskH, _MM_SHUFFLE(2, 0, 2, 0)); // D C B A
        __m128i mask = _mm_castps_si128(maskps);
        min_dist = _mm256_min_pd(min_dist, dist);
        // if the mask is set (this distance is LT the old minimum) then take the current index
        // otherwise keep the old index
        min_index = _mm_blendv_epi8(min_index, index, mask);
    }

    double mdist[4];
    _mm256_storeu_pd(mdist, min_dist);
    uint32_t mindex[4];
    _mm_storeu_si128((__m128i*)mindex, min_index);
    double closest = mdist[0];
    int closest_i = mindex[0];
    for (int i = 1; i < 4; i++) {
        if (mdist[i] < closest) {
            closest = mdist[i];
            closest_i = mindex[i];
        }
    }
    return closest_i;
}

The relevant header to include is <immintrin.h> and to compile you would need to enable AVX with -mavx (GCC, Clang) or /arch:AVX (MSVC).

Most of the code is just subtracting the values from the given coordinate, squaring the difference, and summing the squares. That's not very interesting to discuss, though it plays a significant part in making the code fast. Finding the minimum is more interesting, and is what prevented auto-vectorization. The approach I used is comparing the distance (obviously that was going to be part of it) which results in a bit-mask that is all set where the comparison is true, and then I use that to blend between the "index of best-so-far" and the current index, to conditionally replace values without branching.

Because AVX was targeted instead of AVX2, the simpler approach of using an __m256i for the indexes could not be used. That would have removed the need to extract/shuffle the mask, as it would have already been the right size. With AVX2 there are no 256 bit wide integer operations (well, mostly) so it would not be possible to add 4 to the indexes. It would be possible to do a 256 bit blend by using a floating point type blend, then the blend mask is easy but it just pushes the problem to incrementing the indexes.

Finally at the end there is a small loop to select the best index among the 4 candidates.

The array size must be a multiple of 4, it would not be hard to remove that requirement. 32-byte alignment of the arrays is not required but would be better.

By the way this is related to an SSE2 version that I did a couple of years ago, which used single precision floats.


HackerRank challenge - index palindrome I have a solution but it fails the performance for two tests. How can I speed it up?

def palindrome?(str)
  str.reverse == str
end

def parse(str)
  return -1 if palindrome?(str)

  str.length.times do |i|
    before = str[0...i]
    after = str[i+1...str.length]
    return i if palindrome?(before + after)
  end
end

tests = gets.strip.to_i
tests.times do
  str = gets.strip
  puts parse(str)
end

I tried replacing my palindrome checker function but using benchmarking this seems to actually execute slower:

def palindrome?(str)
  (str.length/2).times do |i|
    return false if str[i] != str[-(i+1)]
  end
  true
end
enter code here

First of all, your palindrome function uses inefficient logic. Reversing a string takes N steps, where N is the length of the string. Comparing a string to its reverse takes some additional steps, though typically not that many for ordinary strings, near N / 2 steps for almost-palindromes, N steps for palindromes, but that's not a real concern.

The important thing is that you can check if a string is palindrome in N / 2 steps by comparing the ith character from start and end. The even more important thing is that you can use this logic to fond the index that breaks a palindrome, significantly speeding up your parse function.

As a final remark about good coding practices, your parse function does too many things, and it's also poorly named. It would be better to decompose this to multiple functions that each do one logical thing, and name them accordingly.


Maxwell's distribution using Box-Muller transform I am given the following problem to solve (This text is translated from Russian. So, there may be some translation issues):

  ... Another method to draw from the normal distribution is to draw two independent random numbers from the uniform distribution x1, x2 ∈ [0:0, 1:0). Then apply the following transformation:

  \$n_1 = \sqrt{-2\log{x_1}}\cos{2\pi x_2}\$

  \$n_2 = \sqrt{-2\log{x_1}}\sin{2\pi x_2}\$

  resulting in two randomly independent numbers n1, n2 from a normal distribution with zero expected value and unit variance.

  To change the distribution parameters to other parameters, e.g. the expected value for and the variance to, you should multiply the result of the draw by and add, i.e.

  \$N(\mu, \sigma) = \sigma N(0, 1) + \mu\$

  In the equation above, N(μ, σ) is a random variable with normal distribution with expected value μ and variance σ.

  According to the Maxwell distribution, each component (x, y or z) of the velocity vector v is a random variable from a normal distribution with zero expected value, and variance \$\sqrt{\dfrac{k_B T}{m}}\$
  where m is the mass of the molecule, T is the temperature in Kelvin, kB is Boltzmann constant.

  Your task: Draw 10,000 velocity vectors for the N2 nitrogen molecule at 300K. Calculate the average length of these vectors, and therefore the average value of the speed of the nitrogen molecule, using the formula:

  \$\bar{v} = \dfrac{1}{N}\sum_{i=1}^N\sqrt{v_{x_i}^2 + v_{y_i}^2 + v_{z_i}^2}\$

using System;

public class CommonDistributions
{
    public static int Uniform(Random random, int n)
    {
        return (int)(random.NextDouble() * n);
    }

    public static double Uniform(Random random, double lo, double hi)
    {
        return lo + random.NextDouble() * (hi - lo);
    }

    public static double Gaussian(Random random)
    {
        double r, x, y;
        do
        {
            x = Uniform(random, -1.0, 1.0);
            y = Uniform(random, -1.0, 1.0);
            r = x * x + y * y;
        }
        while (r >= 1 || r == 0);

        return x * Math.Sqrt(-2 * Math.Log(r) / r);
    }

    public static double Gaussian(Random random, double mu, double sigma)
    {
        return sigma * Gaussian(random) + mu;
    }
}

public class MaxwellBolzman
{
    static double KB = 1.38064852e-23;

    static double MaxwellVariance(double mass, double temperature)
    {
        return Math.Sqrt(KB * temperature / mass);
    }

    static double MaxwellComponent(Random random, double mass, double temperature)
    {
        double mu = 0.0;
        double sigma = MaxwellVariance(mass, temperature);

        return CommonDistributions.Gaussian(random, mu, sigma);
    }
    public static double Maxwell(Random random, double mass, double temperature)
    {
        double one = MaxwellComponent(random, mass, temperature);
        double two = MaxwellComponent(random, mass, temperature);
        double thr = MaxwellComponent(random, mass, temperature);

        return Math.Sqrt(one * one + two * two + thr * thr);
    }
}

public static class MainClass
{
    public static void Main(String[] args)
    {
        Random random = new Random();

        const int N = 10000;
        const int T = 300;//300K
        const double mass = 28.02;//28.02 g/mol

        double sum = 0.0;

        for (int i = 1; i < N; i++)
        {
            sum = sum + MaxwellBolzman.Maxwell(random, mass, T);
        }

        Console.WriteLine($"Maxwell-Boltzman Vector = {sum/N}");

        string str = string.Empty;
    }
}

Kindly, review the implementation.

I am not sure about the values of temperature and the mass of Nitrogen 2.

The implementation of Gaussian(Random random) does not match the description. You should add the comment about the polar form. I know the equivalence. Some reviewers may not.
Polar form comes with the price. The loop

    do
    {
        x = Uniform(random, -1.0, 1.0);
        y = Uniform(random, -1.0, 1.0);
        r = x * x + y * y;
    }
    while (r >= 1 || r == 0);

is potentially infinite. I'd be scared to see it in the production code.
The Wiki article warns against the price of the basic form coming from the computation of \$\sin\$ and \$\cos\$. I don't buy it. sincos is cheap. Thou shalt profile.
The condition r == 0 is pretty much guaranteed to fail, and I wouldn't trust the result of Math.Log(r) / r for really small r. Do not compare floating point values for equality. Chose an \$\epsilon\$, and compare for r < eps.
Maxwell calls MaxwellComponent three times, and each time MaxwellComponent computes the same MaxwellVariance. Seems excessive.


Refactor Jquery .text () function I'm really concerned about clean programming and nice readable code.

My goal is to change string (text), when user clicks on various products on the webpage. I noticed that my code is repeating and looks very simple (not professional). The most appropriate option would be to refactor my code and make it look better.

var text = $('.inner-container h1').text();
var changeString = $('.inner-container h1');

$('.ottogi').click(function() {
    if (text == 'Ottogi') {
        $(changeString).text('Ottogi');
    }
});
 $('.sajo').click(function() {
     if (text == 'Ottogi') {
        $(changeString).text('Sajo Hapyo');
    }
 });
  $('.natura').click(function(){
     if (text == 'Ottogi') {
        $(changeString).text('Natura Bogata');
    }
 });
$('.maloo').click(function(){
     if (text == 'Ottogi') {
        $(changeString).text('ТОО Малу');
    }
 });
$('.dongush').click(function(){
     if (text == 'Ottogi') {
        $(changeString).text('Dongsuh');
    }
 });
 $('.may').click(function(){
     if (text == 'Ottogi') {
        $(changeString).text('ООО Май');
    }
 });

You could reduce duplication by using an object mapping the selectors (class names in this case) to their responses

const selectorToResponse = {
  '.ottogi': 'Ottogi',
  '.sajo': 'Sajo Hapyo',
  '.natura': 'Natura Bogata',
  '.maloo': 'TOO Maлy',
  '.dongush': 'Dongsuh',
  '.may': 'OOO Maй'
}

Note, that for the first case (.ottogi) you are changing the text to Ottogi if it is Ottogi which has no change, so it can be removed.

const selectorToResponse = {
  '.sajo': 'Sajo Hapyo',
  '.natura': 'Natura Bogata',
  '.maloo': 'TOO Maлy',
  '.dongush': 'Dongsuh',
  '.may': 'OOO Maй'
}

From here you could loop over the object entries using a for...in loop and define the event handlers. This way you only have to add further entries to selectorToResponse instead of duplicating.

const selectorToReponse = {
  '.ottogi': 'Ottogi',
  '.sajo': 'Sajo Hapyo',
  '.natura': 'Natura Bogata',
  '.maloo': 'TOO Maлy',
  '.dongush': 'Dongsuh',
  '.may': 'OOO Maй'
}

// Prefixing with $ to denote that is an element, not text etc
const $header = $('.inner-container h1')

for (const selector in selectorToResponse) {
  $(selector).click = function () {
    // using $header.text() inside function so that is current header text
    // `text` never changed in your example
    if ($header.text() === 'Ottogi') { // using === instead of ==
      const response = selectorToResponse[selector]

      $header.text(response)
    }
  }
}

Notes

Above uses strict equality comparison (===) instead of abstract equality comparison (==). https://developer.mozilla.org/en/docs/Web/JavaScript/Equality_comparisons_and_sameness

Solution uses const, an ES6 feature. The benefits are that selectors scope is confined to the for loop and that the variable identifier cannot be reassigned.

Depending on your desired browser compatibility it may or may not be available.

As @IcePickle pointed out, using var in the for...in loop would mean that selector is always .may in the click handlers due to var having different socping rules. See Creating closures in loops - A common mistake for a detailed explanation.

Using var and another closure:

var selectorToReponse = {
  '.ottogi': 'Ottogi',
  '.sajo': 'Sajo Hapyo',
  '.natura': 'Natura Bogata',
  '.maloo': 'TOO Maлy',
  '.dongush': 'Dongsuh',
  '.may': 'OOO Maй'
}

var $header = $('.inner-container h1')

for (var selector in selectorToResponse) {
  $(selector).click = (function (selector) {
    return function () {
      if ($header.text() === 'Ottogi') {
        var response = selectorToResponse[selector]

        $header.text(response)
      }
    }
  })(selector)
}


String manipulation in Python I have this very ugly piece of code which runs ethtool and then parses the output (Lilex is just a static class encapsulating subprocess and is not relevant to the question. I'm looking for someone to suggestions to shorten the string manipulation.

        bash_command = "/sbin/ethtool -P " + identifier

        output = Lilex.execute_command(bash_command)

        mac_address = str(output)

        mac_address = mac_address.replace("Permanent address: ", "")
        mac_address = mac_address.replace("\\n", "")
        mac_address = mac_address.replace("'", "")
        mac_address = mac_address[1:].strip()

This is example output that is produced by ethtool -P:

Permanent address: 12:af:37:d0:a9:c8

I'm not sure why I'm replacing single quotes with nothing, but I'm sure I've seen the command output single quotes before, so that part needs to stay.

An alternative suggestion (which is actually not much different):

mac_address = mac_address \
                          .split(":")[1]\
                          .replace("\\n","") \
                          .replace("'","") \
                          .strip()

How about this?

mac_address = mac_address[19:].translate(str.maketrans("", "", "\n':")).strip()


Python snake game with pygame I am a new programmer and I sill don't know how to write a clean code.
please suggest me ways to improve my skill and how to write a proper code.

import pygame
import time
import random

pygame.init()

# defines the width and height of the display
display_width = 800
display_height = 600

white = (255, 255, 255)
d_white = (250, 250, 250)
black = (0, 0, 0)
teal = (0, 128, 128)
blue_black = (50, 50, 50)
game_display = pygame.display.set_mode((display_width, display_height))

factor = 10

food_x = random.randrange(5, display_width - 5)
food_y = random.randrange(5, display_height - 5)
print(food_x, food_y)
score = 60
clock = pygame.time.Clock()

class snake_body:
    x = 0
    y = 0

    def __init__(self, x_position, y_position):
        self.x = x_position
        self.y = y_position

snake = [snake_body(20, 20), snake_body(20, 30), snake_body(20, 40), snake_body(20, 50), snake_body(20, 60),
         snake_body(20, 70), snake_body(20, 80), snake_body(20, 90), snake_body(20, 100), snake_body(20, 110),
         snake_body(20, 120), snake_body(20, 130), snake_body(20, 140), snake_body(20, 150), snake_body(20, 160),
         snake_body(20, 170)]

# class food():
#     x=0
#     y=0
#
#     def __init__(self):

def update_snake(score):
    i = len(snake) - 1

    while i > 0:
        snake[i].x = snake[i - 1].x
        snake[i].y = snake[i - 1].y
        i -= 1

def check_death():
    if snake[0].x < 1 or snake[0].x > display_width or snake[0].y < 1 or snake[0].y > display_height:
        pygame.quit()
        quit()
    for i in range(1, len(snake)):
        if snake[0].x == snake[i].x and snake[0].y == snake[i].y:
            pygame.quit()
            quit()

def drawsnake(snake):
    for i in range(len(snake)):
        pygame.draw.rect(game_display, teal, (snake[i].x, snake[i].y, factor, factor))

x = 0
y = 0
x_change = 0
y_change = 0
first_time = True
eat = True
while True:

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            quit()
        if event.type == pygame.KEYDOWN:
            first_time = False
            if event.key == pygame.K_a:
                if x_change is not 10:
                    x_change = -10
                    y_change = 0
            elif event.key == pygame.K_d:
                if x_change != -10:
                    x_change = 10
                    y_change = 0
            elif event.key == pygame.K_w:
                if y_change is not 10:
                    x_change = 0
                    y_change = -10
            elif event.key == pygame.K_s:
                if y_change != -10:
                    x_change = 0
                    y_change = 10
            elif event.key == pygame.K_c:
                x_change = 0
                y_change = 0

    if not first_time:
        update_snake(score)
    if score % 10 == 0 and eat:
        snake.append(snake_body(snake[len(snake)-1].x, snake[len(snake)-1].y))
        print(len(snake))
        eat = False

    snake[0].x += x_change
    snake[0].y += y_change
    if snake[0].x < food_x+10 and snake[0].x > food_x-10 and snake[0].y < food_y+10 and snake[0].y >food_y-10:
        score = score + 10
        food_x = random.randrange(5, display_width - 5)
        food_y = random.randrange(5, display_height - 5)
        eat = True

    check_death()
    game_display.fill(white)

    pygame.draw.rect(game_display, black, (food_x, food_y, factor, factor))
    drawsnake(snake)

    pygame.display.update()
    time.sleep(0.035)
    clock.tick(60)

Here are some changes I would make:

Your snake_body class (which should be called SnakeBody, according to PEP8), does not need to initialize its attributes before the initialization, so you can just have:

class SnakeBody:

    def __init__(self, x, y):
        self.x, self.y = x, y

    def __repr__(self):
        return "SnakeBody({self.x}, {self.y})".format(self=self)

I also gave it a __repr__ method so it prints nicer.

Currently, your full snake is just a list of body parts. While this is nice, you also have a few functions that just operate on a snake, so it would be nice to add these two things together and make snake a class as well. I would do something like this, which inherits from list so the rest of your code stays basically unchanged, except that instead of draw_snake() you now have snake.draw(), etc:

class Snake(list):

    def __init__(self, start_x, start_y, n):
        list.__init__(self, [SnakeBody(start_x, start_y + i * factor)
                             for i in range(n)])

    def move_head(self, dx, dy):
        self[0].x += dx
        self[0].y += dy

    def update(self, score):
        for i in range(len(self) - 1, 0, -1):
            self[i].x = self[i - 1].x
            self[i].y = self[i - 1].y

    def check_death(self):
        if not (1 <= self[0].x <= display_width and 1 <= self[0].y <= display_height):
            return True
        return any(body_part.x == self[0].x and body_part.y == self[0].y for body_part in self[1:])

    def draw(self):
        for body_part in self:
            pygame.draw.rect(game_display, teal,
                             (body_part.x, body_part.y, factor, factor))

Note that I also simplified the check_death function. It now returns True if the snake needs to die. I used the fact that Python can do multiple comparisons, so a <= x <= b is legal in Python.

The actual game code I would put into a main function which you can call within a if __name__ == "__main__": guard to allow importing this from another script. With these changes, your code becomes:

Final code:

import pygame
import time
import random

pygame.init()

# defines the width and height of the display
display_width = 800
display_height = 600

white = (255, 255, 255)
d_white = (250, 250, 250)
black = (0, 0, 0)
teal = (0, 128, 128)
blue_black = (50, 50, 50)
game_display = pygame.display.set_mode((display_width, display_height))

factor = 10

clock = pygame.time.Clock()

class SnakeBody:

    def __init__(self, x, y):
        self.x, self.y = x, y

    def __repr__(self):
        return "SnakeBody({self.x}, {self.y})".format(self=self)

class Snake(list):

    def __init__(self, start_x, start_y, n):
        list.__init__(self, [SnakeBody(start_x, start_y + i * factor)
                             for i in range(n)])

    def move_head(self, dx, dy):
        self[0].x += dx
        self[0].y += dy

    def update(self, score):
        for i in range(len(self) - 1, 0, -1):
            self[i].x = self[i - 1].x
            self[i].y = self[i - 1].y

    def check_death(self):
        if not (1 <= self[0].x <= display_width and 1 <= self[0].y <= display_height):
            return True
        return any(body_part.x == self[0].x and body_part.y == self[0].y for body_part in self[1:])

    def draw(self):
        for body_part in self:
            pygame.draw.rect(game_display, teal,
                             (body_part.x, body_part.y, factor, factor))

def main():
    food_x = random.randrange(5, display_width - 5)
    food_y = random.randrange(5, display_height - 5)
    print(food_x, food_y)
    score = 60

    snake = Snake(20, 20, 16)

    x = 0
    y = 0
    x_change = 0
    y_change = 0
    first_time = True
    eat = True

    while True:

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                quit()
            if event.type == pygame.KEYDOWN:
                first_time = False
                if event.key == pygame.K_a:
                    if x_change != 10:
                        x_change = -10
                        y_change = 0
                elif event.key == pygame.K_d:
                    if x_change != -10:
                        x_change = 10
                        y_change = 0
                elif event.key == pygame.K_w:
                    if y_change != 10:
                        x_change = 0
                        y_change = -10
                elif event.key == pygame.K_s:
                    if y_change != -10:
                        x_change = 0
                        y_change = 10
                elif event.key == pygame.K_c:
                    x_change = 0
                    y_change = 0

        if not first_time:
            snake.update(score)
        if score % 10 == 0 and eat:
            snake.append(snake_body(
                snake[len(snake) - 1].x, snake[len(snake) - 1].y))
            print(len(snake))
            eat = False
        snake.move_head(x_change, y_change)

        if snake[0].x < food_x + 10 and snake[0].x > food_x - 10 and snake[0].y < food_y + 10 and snake[0].y > food_y - 10:
            score += 10
            food_x = random.randrange(5, display_width - 5)
            food_y = random.randrange(5, display_height - 5)
            eat = True

        if snake.check_death():
            pygame.quit()
            quit()

        # update game display
        game_display.fill(white)

        pygame.draw.rect(game_display, black, (food_x, food_y, factor, factor))
        snake.draw()

        pygame.display.flip()
        time.sleep(0.035)
        clock.tick(60)

if __name__ == "__main__":
    main()

                                        <br>


Find the max number in list after m operations between indices a and b Given the problem:

  You are provided a list of N elements all initialized to 0, and a list of M operations. Where each m in M consists of 3 elements a, b, and k. For each m in M add k to all indices in the range [a, b]. At the end of all M operations print out the max.

I have two implementations, one of which is faster because of constant time lookups, whereas the other can be more memory usage efficient. I am looking for a third implementation which might run faster than the previous two.

#include <cassert>
#include <climits>
#include <cstdlib>
#include <ctime>
#include <iostream>
#include <iterator>
#include <map>
#include <sstream>
#include <string>
#include <vector>

void run_tests1(int N, int M, const std::vector<std::vector<int> > &a_b_k)
{
    std::vector<int> LIST(N);
    int max = INT_MIN;

    for (int m = 0; m < M; ++m) {
        int a = a_b_k[m][0];
        int b = a_b_k[m][1];
        int k = a_b_k[m][2];

        clock_t now = clock();
        for (int i = a; i <= b; ++i) {
            LIST[i] += k;
            if (LIST[i] > max) {
                max = LIST[i];
            }
        }
        clock_t end = clock() - now;
        std::cout << "Took " << ((float)end / CLOCKS_PER_SEC) << " on "
          << __FUNCTION__ << " to insert " << (b - a + 1) << std::endl;
    }
}

void run_tests2(int /*N*/, int M, const std::vector<std::vector<int> > &a_b_k)
{
    std::map<int, int> LIST;
    int max = INT_MIN;

    for (int m = 0; m < M; ++m) {
        int a = a_b_k[m][0];
        int b = a_b_k[m][1];
        int k = a_b_k[m][2];

        clock_t now = clock();
        for (int i = a; i <= b; ++i) {
            std::pair<std::map<int, int>::iterator, bool> status =
              LIST.insert(std::make_pair(i, 0));

            status.first->second += k;
            if (status.first->second > max) {
                max = status.first->second;
            }
        }
        clock_t end = clock() - now;
        std::cout << "Took " << ((float)end / CLOCKS_PER_SEC) << " on "
          << __FUNCTION__ << " to insert " << (b - a + 1) << std::endl;
    }
}

void run_tests3(int N, int M, const std::vector<std::vector<int> > &a_b_k)
{
    // Choose Data Structure
    int max = INT_MIN;

    for (int m = 0; m < M; ++m) {
        int a = a_b_k[m][0];
        int b = a_b_k[m][1];
        int k = a_b_k[m][2];

        clock_t now = clock();
        // Run Algorithm
        clock_t end = clock() - now;
        std::cout << "Took " << ((float)end / CLOCKS_PER_SEC) << " on "
          << __FUNCTION__ << " to insert " << (b - a + 1) << std::endl;
    }
}

int main()
{
    const int K = 1000;
    const int N = 10000000;
    const int M = 10;
    std::vector<std::vector<int> > data(M);

    for (int m = 0; m < M; ++m) {
      data[m].resize(3);
      data[m][0] = rand() % N;
      data[m][1] = rand() % N;
      data[m][2] = rand() % K;

      if (data[m][0] > data[m][1]) {
          std::swap(data[m][0], data[m][1]);
      }
    }

    run_tests1(N, M, data);
    run_tests2(N, M, data);
    run_tests3(N, M, data);
}

For the record, don't ask us to write code for you. Writing the code is your responsibility; we will just critique it.

Why are you concerned about how long it takes to process each operation? The only thing that matters is the overall time and space requirement, and it's not a given that the best solution is going to operate by processing each operation in sequence. Thus, the timing does not belong in the loop. And I would even make the case that the timing does not belong in the run_testsn() functions. The timing belongs in your main function, which will call each of the run_testsn() in sequence. Each function should have one purpose only. It shouldn't be "Do this in this particular way and then time subunits of it.".
You've got a lot of unnecessary #includes. That just clutters up the code. Only use the ones you need.
Kudos to you for qualifying your C++ types with std::. But as @Morwenn said, don't forget to do it for functions from the C standard library too.
Is it necessary to take your input as a vector of vectors? It would make a lot more sense to build a struct with members int a; int b; int k; and then pass vectors of that around.
A map is pretty good for representing a sparse array; there are several other libraries out there that do better. See https://stackoverflow.com/questions/4306/what-is-the-best-way-to-create-a-sparse-array-in-c and https://stackoverflow.com/questions/21310680/sparse-array-in-c
You have two (soon-to-be three) functions that take the same parameter list and do the same thing. This looks like a job for an abstract base class (specifying the interface/params) and three subclasses of that class that each have implementations.
In run_tests2 you have

       std::pair<std::map<int, int>::iterator, bool> status =
         LIST.insert(std::make_pair(i, 0));

       status.first->second += k;

What's wrong with LIST[i] += k;? If the item doesn't exist yet, it will be auto-created with the default value (0). (And even if not, please declare it using auto status = as that type is just plain ugly and doesn't add anything. You're using C++11, take advantage of ways it can produce better code)


Get all the attributes of a DOM Node I needed this small function for one of my project.

Fetch Attributes

function fetchAttrs(node) {

  if (!node || !node.hasAttributes()) return {};
  var attrs = node.attributes;
  var res = {};
  var length = attrs.length;
  for (var i = 0; i < length; i++) {
    var attr = attrs[i];
    res[attr.name] = attr.value;
  }
  return res;
}

It's working fine as expected but I wanted to know if I am missing something from a performance point of view or good coding practices. Just need a second opinion :)

Update

How to handle exceptions, is it a good practice?

There's not much of a performance difference between the two (reduce is very slightly favoured in my own tests), but I prefer the more readable reduce function over the for loop. I believe it makes the code simpler, too. Also sort of a personal preference - why not use the full name? No real need in shortening it. :-)

var fetchAttributes = function(node) {
  return node && Array.prototype.reduce.call(node.attributes, function(list, attribute) {
    list[attribute.name] = attribute.value;
    return list;
  }, {}) || {};
};

http://jsperf.com/reduce-vs-for-fetch-attributes

Edit: In fact you can simplify this further, as you aren't transforming the attributes in any way.

var fetchAttributes = function(node) {
    return node && node.attributes || {};
};


Declaring a large number of 2D arrays to be used as 2D graphic sprites I'm creating a Space Invaders game, and graphics sprites in it are defined as 2D arrays of colors.

It seems like it's going to be cumbersome declaring these arrays the way I currently am:

//This creates an inverting red/blue cross animation
public Sprite myFirstAnimation()
{
    Sprite frame1 = new Sprite(new Color[,]
                    {{Color.Red, Color.Blue, Color.Red},
                        {Color.Blue, Color.Blue, Color.Blue},
                        {Color.Red, Color.Blue, Color.Red}});

    Sprite frame2 = new Sprite(new Color[,]
                    {{Color.Blue, Color.Red, Color.Blue},
                        {Color.Red, Color.Red, Color.Red},
                        {Color.Blue, Color.Red, Color.Blue}});

    AnimatedSprite myAnimatedSprite = new AnimatedSprite(new Sprite[] { frame1, frame2 });
    return myAnimatedSprite;
}

Can you point me the the direction for a nicer way of doing this, as to make it more maintainable and readable, and less arduous?

You're trying to store data in code. While that is not bad idea by itself, you shouldn't overuse it and I think that's what you're doing here.

If your data is bitmaps, store them in some bitmap format (BMP or maybe PNG) and then load them into your program from that. As an additional advantage, you will be able to edit your images using normal image editing software (like Paint), instead of having to edit your code.

If you want to keep having your bitmaps in code, you want to decrease the verbosity and you're willing to lose some type-safety, you could encode your bitmaps as strings and then transform them into 2D array using a helper function.

It could look something like:

Color[,] frame1 = FormatMatrix("010 111 010", Color.Red, Color.Blue);

Or even:

Color[,] frame1 = FormatMatrix(@"
010
111
010", Color.Red, Color.Blue);

The helper function would look something like this:

static T[,] FormatMatrix<T>(string format, params T[] values)
{
    var formatParts = format.Split(new char[0], StringSplitOptions.RemoveEmptyEntries);

    T[,] result = new T[formatParts.Length, formatParts[0].Length];

    for (int i = 0; i < formatParts.Length; i++)
    {
        var formatPart = formatParts[i];

        for (int j = 0; j < formatPart.Length; j++)
        {
            if (formatPart[j] >= '0' && formatPart[j] <= '9')
                result[i,j] = values[formatPart[j] - '0'];
            else
                throw new ArgumentException("format");
        }
    }

    return result;
}


Generic observer pattern implementation in C++ Implemented observers in C++11 in a generic and statically accessible way. Though an instance is created, it's used only for cleanup and lifetime management.

template<typename... Args>
class Observers
{
private:
    unordered_map<int, vector<function<void(Args...)>>> observers;
    static Observers<Args...> *instance;
public:
    Observers()
    {
        instance = this;
    }

    template<typename Observer>
    static void Register(int ev, Observer &&observer)
    {
        instance->observers[ev].push_back(forward<Observer>(observer));
    }

    static void Notify(int ev, Args... args)
    {
        try
        {
            auto &obs = instance->observers.at(ev);
            for (auto &o : obs)
                o(args...);
        }
        catch (...){}
    }
};

template<typename... Args>
Observers<Args...> *Observers<Args...>::instance;

usage:

using IntIntObservers = Observers < int, int > ;//optional type declaration

IntIntObservers o;//observer instance

IntIntObservers::Register(1, [=](int a, int b){whatever});

IntIntObservers::Notify(1, 4, 5);

An observer set can be accessed statically as long as the instance is alive. Multiple instances of the same type could be achieved by adding an id parameter to the template declaration, making it

template<int id, typename... Args>

Anything that I missed and could be improved?

Briefly, I find the following:

The current static behaviour is not intuitive (what does int ev really mean? why numbers and not names?), not efficient (why search in an unordered map rather that direct access?) and not thread-safe (instance is shared among all threads).
A list might be more appropriate to store observers of one event, enabling easier management like removing an observer.
Catching all exceptions in such a generic tool is a limitation. If needed, it could be at least parametrized.
Parameter pack Args... does not take into account return types.
Your Notify takes its arguments by value. Forwarding is not appropriate when calling multiple functions, but at least arguments should be passed by reference.

At a very basic level, I would prefer an object, called e.g. signal, templated on full function signature e.g. R(A...), with non-static members:

(private) observers: std::list or some associative container of std::function<R(A...)>
add()/remove() or connect()/disconnect() to manage the content of observers. remove() would need some form of identification of existing observers, hence the need for an associative container.
operator()(A&&... a) so that signal behaves like a function object. Arguments a... are passed without forwarding to underlying functions, so that they are copied if needed, and not invalidated between subsequent calls.
additional management like clear()/empty().

Your example usage would be rather like

signal<void(int, int)> s;
s.connect([=](int a, int b){whatever});
s(4, 5);

Isn't that better? Since everything is non-static, the user controls how many instances there are, and names them properly. In fact, a single object may have e.g. ten methods, each with its own observers. Each such method is then a signal and behaves like a function object.

Additionally

std::function expects the 1st argument of a call to be the object if bound on a member function. It would be much more convenient to have functionality such that the object is stored separately and the signal's signature matches exactly that of the member function. In many applications everything is about objects + member functions rather than free functions.
Though non-trivial, possibly provide a mechanism to collect return values of called (observer) functions plus policies to choose, compute and return a single return value from operator().

Have a look at boost::signals and boost::signals2 for more ideas.

I have implemented my own model in the past, using delegates instead of std::function. There is an amazing amount of additional work if such "signals" are to fully mimic functions or member functions, including:

default arguments (arbitrary values encoded into types in the signature itself)
overloading (with different signatures)
inheritance (overriding member functions in base/derived classes)
virtual functions
...

I have used it as a full C++-compliant replacement for Qt signals/slots and wrapped most of the Qt Gui module so that a project can be built without moc and without qmake. One day I will hopefully clean and rewrite in C++11.


Shell command to output all plugins that exist across multiple wordpress installations I'm working on a server and need a complete list of plugins that are installed for all wp installations. I only need to know whether a plugin exists or not, it doesn't matter where it exists.

For example, given:

/siteA/wp-content/plugins/someplugin
/siteA/wp-content/plugins/anotherplugin

/siteB/wp-content/plugins/someplugin

I need the following result:

someplugin
anotherplugin

Here is the working command:

for i in $(find . -type d -name 'plugins' | grep 'wp-content/plugins$'); do find ${i} -maxdepth 1 -type d -exec sh -c 'for f do basename -- "$f"; done' sh {} + ; done | sort -u

Can this command be shortened?

If plugins only contain directories, list every unique entry in plugins:

shopt -s globstar
\ls -- **/wp-content/plugins |sort -u

Otherwise, include the final targets in the glob, plus a trailing slash to limit globbing to directories.

That will yield paths relative to ., with trailing slash like siteA/wp-content/plugins/anotherplugin/.  We clean it up with basename (shorter, easier) or awk (faster if there are very many results EDIT: nope, awk is slower in spite of the algorithmic efficiency).

The backslash ignores aliases, just in case an aliased ls would mess up the output.

shopt -s globstar

# probably easier to remember
\ls -d -- **/wp-content/plugins/*/ |xargs -n1 basename -- |sort -u

# slower, fancier
\ls -d -- **/wp-content/plugins/*/ |awk -F/ '!u[$(NF-1)]++ { print $(NF-1) }'


Conditionally replacing an input field when submitting a form I just wrote this, and cleaned it up as much as I could. A couple things worry me:

I change the scope of $(this) twice (and apparently don't know how to use =>)
The big if if/else statement. Is there a better way to write that?

Also, it's an IIFE, and the big identing makes the )() at the end look out of place.

  emptyTagFieldsOnDeletion = (->
    $('form.simple_form').submit ->
      $form = $(this)
      $form.find('.fake-input').each ->
        $fakeInput = $(this)
        $ulId = $fakeInput.closest('ul').attr('id')
        if $fakeInput.children('li').length is 1
          $fakeInput.children().remove()
          if $ulId is 'primary_diagnosis_select'
            $fakeInput.append emptyListArrayHTML('primary_icd9_codes')
          else if $ulId is 'secondary_diagnosis_select'
            $fakeInput.append emptyListArrayHTML('secondary_icd9_codes')
          else
            $fakeInput.append emptyListArrayHTML('med_names')
  )()

For reference, the emptyListArrayHTML method looks like this:

emptyListArrayHTML = (list_type)->
  "<input type='text' name='#{nameWithListType(list_type)}' value=''>"

You mention the changes in scope as though they're a problem. But you actually want them here, since that's how jQuery operates, and using => would be counterproductive. Anyway here are some notes

CoffeeScript has a do keyword for IIFEs. So do -> ... is equivalent to (-> ...)() without the need for all those parentheses
It seems your IIFE isn't returning something you'll need later; it's just encapsulating some code. In that case, don't bother giving it a name. Just invoke it.
You don't need to cache $form - you only use it once
Don't call the UL id $ulId - that is, don't use a $ in the name. It's not a jQuery object, it's just a string
You can use a switch statement instead of the if... else, which helps a bit (but read on for a better solution)

Here's the code with these tweaks:

do ->
  $('form.simple_form').submit ->
    $(this).find('.fake-input').each ->   # don't bother caching $form
      $fakeInput = $ this
      return unless $fakeInput.children().length is 1 # return early instead of a big if-block

      $fakeInput.empty()

      switch $fakeInput.closest('ul').attr('id')
        when 'primary_diagnosis_select'
          $fakeInput.append emptyListArrayHTML('primary_icd9_codes')
        when 'secondary_diagnosis_select'
          $fakeInput.append emptyListArrayHTML('secondary_icd9_codes')
        else
          $fakeInput.append emptyListArrayHTML('med_names')

However, I'd make the relationships explicit in the markup. For instance, give the UL element a data-codes attribute or something:

...

...

Then you can shorten the code like so:

do ->
  $('form.simple_form').submit ->
    $(this).find('.fake-input').each ->
      $fakeInput = $ this
      return unless $fakeInput.children().length is 1
      $fakeInput.empty()
      codes = $fakeInput.closest('ul').data("codes") or "med_names"
      $fakeInput.append emptyListArrayHTML(codes)

Now the CoffeeScript handles only logic while the data and relationships are declared in the markup. You can add the single line from emptyListArrayHTML back into the function with complicating things too much, though.

p.s. CoffeeScript also has a triple-quote Python-like heredoc syntax, if you want to use double quotes in a string without escaping them. So your emptyListArrayHTML function could be written as

emptyListArrayHTML = (list_type) ->
  """<input type="text" name="#{nameWithListType list_type}" value="">"""

It looks a little strange at first (and the syntax highlighting is messed up here), but I like to use it, because I prefer to always use double quotes for HTML attributes (just personal preference).


Simple Android Flashlight app One of my first projects. I present to you - Android Flashlight app!

public class MainActivity extends AppCompatActivity {
    Camera cam = null;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    public void onBtn(View view) {
        if (checkCameraHardware(this)){
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
               if (checkSelfPermission(Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED){
                    ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA}, 1);
                    handleFlash();
               }else {
                   handleFlash();
                   System.out.println("Check : has permission");
               }
            }
        }
    }
    public void handleFlash() {
            if (cam == null){
                cam = getCameraInstance();
            }
            Camera.Parameters parameters = cam.getParameters();
            if (parameters.getFlashMode().equals(Camera.Parameters.FLASH_MODE_OFF)) {
                parameters.setFlashMode(Camera.Parameters.FLASH_MODE_TORCH);
                cam.setParameters(parameters);
                cam.startPreview();
            } else if (parameters.getFlashMode().equals(Camera.Parameters.FLASH_MODE_TORCH)) {
                parameters.setFlashMode(Camera.Parameters.FLASH_MODE_OFF);
                camEnd();
            }
    }

    public static Camera getCameraInstance(){
        Camera camera = null;
        try {
            camera = Camera.open(); // attempt to get a Camera instance
        }
        catch (Exception e){
            // Camera is not available (in use or does not exist)
            e.printStackTrace();
        }
        return camera; // returns null if camera is unavailable
    }
    private boolean checkCameraHardware(Context context) {
        if(context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA)) {
            return true;
        } else {
            return false;
        }
    }

    public void camEnd() {
        cam.release();
        cam = null;
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        camEnd();
    }
}

I have tested this on my Marshmallow device and it works as expected (but no on my lollipop device for some reason). Any suggestions would be great!

Your inner if-else is incorrect, and that's why it's not working under Marshmallow.

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
    if (checkSelfPermission(Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
        System.out.println("Check : has permission");
        ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA}, 1);
        handleFlash();
    }
} else {
    handleFlash();
}


Finding all neighbors of any given element in a matrix like structure This is the code I currently have to get all neighbors of any given element in a matrix like structure:

struct Coordinates: IEquatable<Coordinates>
{
    public int Row { get; }
    public int Column { get; }

    public Coordinates(int row, int column)
    {
        Row = row;
        Column = column;
    }

    public bool Equals(Coordinates other) => Column == other.Column && Row == other.Row;

    public override bool Equals(object obj)
    {
        if (obj is Coordinates)
        {
            return Equals((Coordinates)obj);
        }

        return false;
    }

    public override int GetHashCode() => unchecked(27947 ^ Row ^ Column);

    public IEnumerable<Coordinates> GetNeighbors(int numberOfRows, int numberOfColumns)
    {
        var increasedRow = Row + 1;
        var decreasedRow = Row - 1;
        var increasedColumn = Column + 1;
        var decreasedColumn = Column - 1;
        var canIncreaseRow = increasedRow < numberOfRows;
        var canIncreaseColumn = increasedColumn < numberOfColumns;
        var canDecreaseRow = decreasedRow > -1;
        var canDecreaseColumn = decreasedColumn > -1;

        if (canDecreaseRow)
        {
            if (canDecreaseColumn)
            {
                yield return new Coordinates(decreasedRow, decreasedColumn);
            }

            yield return new Coordinates(decreasedRow, Column);

            if (canIncreaseColumn)
            {
                yield return new Coordinates(decreasedRow, increasedColumn);
            }
        }

        if (canIncreaseRow)
        {
            if (canDecreaseColumn)
            {
                yield return new Coordinates(increasedRow, decreasedColumn);
            }

            yield return new Coordinates(increasedRow, Column);

            if (canIncreaseColumn)
            {
                yield return new Coordinates(increasedRow, increasedColumn);
            }
        }

        if (canDecreaseColumn)
        {
            yield return new Coordinates(Row, decreasedColumn);
        }

        if (canIncreaseColumn)
        {
            yield return new Coordinates(Row, increasedColumn);
        }
    }
}

This works but it seems kind of clunky and I can't help thinking there is a more elegant, concise and obvious way of doing this.

Considerations to take into account:

By elegant I mean more concise but readable and mantainable even if performance is slightly worse.
I don't want dependencies on System.Drawing.Point or similar because I don't want to use mutable structs and I don't like using types that conceptually represent unrelated things even though they happen to provide usable functionality to solve the problem at hand.
There is no bound checking in the arguments. This is simply because the code where I'm using this algorithm already ensures that the current coordinates instance is a valid location. As per comments, the current implementation will give erroneous results if you happen to enter matrix bounds that makes the current coordinates invalid. This is not an issue that concerns me.

You could use a 2-dimensional loop to iterate over neighbors as follows:

public IEnumerable<Coordinates> GetNeighbors(int numberOfRows, int numberOfColumns)
{
    var canIncreaseRow = Row < numberOfRows - 1;
    var canIncreaseColumn = Column < numberOfColumns - 1;
    var canDecreaseRow = Row > 0;
    var canDecreaseColumn = Column > 0;

    var maxRow = canIncreaseRow ? Row + 1 : Row;
    var minRow = canDecreaseRow ? Row - 1 : Row;
    var maxColumn = canIncreaseColumn ? Column + 1 : Column;
    var minColumn = canDecreaseColumn ? Column - 1 : Column;

    for (int row = minRow; row <= maxRow; row++)
    {
        for (int column = minColumn; column <= maxColumn; column++)
        {
            if (row != Row || column != Column)
            {
                yield return new Coordinates(row, column);
            }
        }
    }
}


Find common characters Given two strings, find the common characters.

Is there better implementation for this problem?

#include<iostream>
#include<string>
#include<algorithm>

std::string   find_intersection(std::string & first, std::string & second)
{
   std::sort(std::begin(first),std::end(first));
   std::sort(std::begin(second), std::end(second));
   int length = std::min(first.length(), second.length());
   std::string result(length,' ');
   std::set_intersection(std::begin(first),std::end(first),std::begin(second),std::end(second),std::begin(result));

   result.shrink_to_fit();
   return result;
}

int main()
{
   std::string first="GermanTown";
   std::string second="Georgia";
    std::cout<<find_intersection(first,second)<<"\n";
   return 0;
}

For the same reasons as @DJanssens, I would like to compliment you for a simple and clean algorithm making proper use of the standard library. That may seem basic, but there are too many people ignoring the standard <algorithm> in the world, so I'm glad that you decided to use it. I only want to add two more things:

First, I don't think that shrink_to_fit will do what you expect it to do. When you construct result, you allocate memory and fill it with spaces, so result's size probably grew to. shrink_to_fit will get rid of the allocated but unused memory, but it won't get rid of the extra spaces that you allocated at construction.
What you can do is default-construct your std::string and use an std::back_inserter to fill it the lazy way. The std::back_inserter will perform some magic so that the result's push_back method is called whenever an element has to be added:

std::string find_intersection(std::string & first, std::string & second)
{
    std::sort(std::begin(first),std::end(first));
    std::sort(std::begin(second), std::end(second));

    std::string result;

    std::set_intersection(
        std::begin(first), std::end(first),
        std::begin(second), std::end(second),
        std::back_inserter(result)
    );

    return result;
}


Make logparser faster I'm learning go. I wrote a simple logparser for SLF4J in Python some time ago and tried to port it to go as an exercise. The algorithm is identical, but the go-solution isn't quite as fast (the Python solution is about 1.5 times faster for large enough logfiles). Is there any way to get more speed out of it? It do not care, which one is the fastest, but I wanted to know if I could do better with go. Any inspiration is welcome.

A typical logline looks like

[INFO 05:00:07] CoolServiceImpl.executeReminderCC(601) | ==================Finish transaction with id  (REMINDER, 1394424006830)

Others include Stacktraces which span multiple lines.

My code:

package main

import (
    "bufio"
    "flag"
    "fmt"
    "io"
    "log"
    "os"
    "regexp"
    "strings"
)

func isStampRelevant(level, timestamp string) bool {
    return level == "ERROR" && timestamp > "10:00:00" && timestamp < "10:10:00"
}

func isMessageRelevant(lineBuffer string) bool {
    return strings.Contains(lineBuffer, "4020829010703")
}

func readFile(filename string) {
    lineStart := regexp.MustCompile("(TRACE|DEBUG|INFO|WARN|ERROR|FATAL).*?(\\d{2}:\\d{2}:\\d{2})")
    lineBuffer := ""
    fileHandle, err := os.Open(filename)
    if err != nil {
        log.Fatal(err)
    }

    buffer := bufio.NewReader(fileHandle)
    for {
        line, isPrefix, err := buffer.ReadLine()

        if err == io.EOF {
            break
        }
        if err != nil {
            log.Fatal(err)
        }
        if isPrefix {
            log.Fatal("Error: Unexpected long line reading", fileHandle.Name())
        }
        currentLine := string(line)

        matches := lineStart.FindStringSubmatch(currentLine)
        if len(matches) == 3 {
            level := matches[1]
            timestamp := matches[2]

            if len(lineBuffer) > 0 {
                if isMessageRelevant(lineBuffer) {
                    fmt.Println(lineBuffer)
                }
            }

            if isStampRelevant(level, timestamp) {
                lineBuffer = currentLine
            } else {
                lineBuffer = ""
            }
        } else if len(lineBuffer) > 0 {
            lineBuffer += currentLine + "\n"
        }
    }

    if len(lineBuffer) > 0 {
        if isMessageRelevant(lineBuffer) {
            fmt.Println(lineBuffer)
        }
    }
}

func printUsage() {
    fmt.Fprintf(os.Stderr, "usage: %s [inputfile]\n", os.Args[0])
    flag.PrintDefaults()
    os.Exit(2)
}

func main() {
    if len(os.Args) < 2 {
        printUsage()
    }
    filename := os.Args[1]
    readFile(filename)
}

You should use bufio.Scanner rather than a bufio.Reader. It won't make your code any faster, but it'll simplify things a bit.

One reason your code is slow is that you're converting every line from []byte to string. You can avoid this by using the raw bytes from scanner.Bytes() until you need to print the string. The regexp module provides functions for matching against []byte, so the translation is rather easy.

A secondary improvement would be to change your regexp to:

`^\[(TRACE|DEBUG|INFO|WARN|ERROR|FATAL) (\d{2}:\d{2}:\d{2})\]`

By anchoring your regexp and tightening the syntax it recognizes, you'll avoid scanning the entire log line when the regexp doesn't match. Use of raw strings (with backtick), means you don't have to escape the backslashes. This probably won't be a big speed improvement though, since most of your log lines should be single lines.

In terms of structuring the code, I'd probably separate out the part that parses the logs from the part that selects log entries and prints them out.

Perhaps something like this:

type LogReader struct {
    s bufio.Scanner
    ... some internal state
}

type LogEntry struct {
    level []byte
    timestamp []byte
    lines [][]byte
}

func (lr *logReader) Next() (LogEntry, error) {
    ... code here
}

func (lr *logReader) Done() bool {
    ... code here
}

This code should deal entirely in []byte and not string, for the reasons given before.

With this separation, the main code is much easier to read, and you have a nice LogReader abstraction that you can write unit tests for. Here's the main loop using a LogReader:

lr := NewLogReader(filename)
for !lr.Done() {
    e, err := lr.Next()
    if err != nil {
        ... handle errors
    }
    if isStampRelevant(e.level, e.timestamp) && isMessageRelevant(e.level, e.lines) {
        fmt.Println(string(bytes.Join(e.lines, []byte("\n")))
    }
 }


Superscript all numeric characters after ^ in an excel cell I have material property entries in a cell those look something like this:

cell.value="O2 Permeability [cm^3/m^2]"

The goal is to format the numeric value after each ^ to be superscripted and to remove all ^.

Here my code:

Public Function FormatSuperscript(cell As Range) As Boolean
Dim i As Integer
Dim value As String
Dim cnum As New Collection
Dim num As Integer
Dim clen As New Collection

value = cell.value

num = 0

' first count the amount of ^

num = InStr(num + 1, value, "^")
If num <> 0 Then
    cnum.Add num
    ' count the length of the numeric entry
    clen.Add SuperScriptLength(value, num)
End If

While num <> 0
    num = InStr(num + 1, value, "^")
    If num <> 0 Then
        cnum.Add num
        ' count the length of the numeric entry
        clen.Add SuperScriptLength(value, num)
    End If
Wend

' remove all ^
cell.value = Replace(value, "^", vbNullString)

' go through all ^ places and superscript the length of the numeric entry from there on
For i = 1 To cnum.count
    cell.Characters(Start:=cnum(i) - i + 1, Length:=clen(i)).Font.Superscript = True
Next i

FormatSuperscript = True

End Function
Private Function SuperScriptLength(value As String, StartCharacter As Integer) As Integer
Dim s As String
Dim c As Integer
Dim i As Integer

c = 0
s = Right(value, Len(value) - StartCharacter)
While StringPop(s) = "-" Or IsNumeric(StringPop(s))
    c = c + 1
    s = Right(s, Len(s) - 1)
Wend

SuperScriptLength = c
End Function

Private Function StringPop(ByRef s As String) As String
StringPop = Left(s, 1)
End Function

Any suggestions on how to improve the run time on it?

Formatting individual characters in a string is relatively slow.  My solution convert the exponents to superscript using Ascii and Unicode characters.  This allows me to work with the values in an array and then write it back over the original range.

Using characters code took 0.79 seconds to process 10,000 cells compared to 42.05 using formatting individual characters.  The file size increased by 14KB using the character codes and 50KB using character formatting.

Before                                                          After

Code to Convert Exponents to SuperScript Characters

Function convertExponentsToSuperScript(Text As String, Optional ExponentChar As String = "^") As String
    If InStr(Text, ExponentChar) = 0 Then
        convertExponentsToSuperScript = Text
        Exit Function
    End If
    Dim newText() As String
    ReDim newText(Len(Text) - UBound(Split(Text, ExponentChar)))

    Dim exponentChars() As Variant
    exponentChars = Array(ChrW(&H2070), Chr(185), Chr(178), Chr(179), _
                          ChrW(&H2074), ChrW(&H2075), ChrW(&H2076), ChrW(&H2077), _
                          ChrW(&H2078), ChrW(&H2079))

    Dim textIndex As Long, newTextIndex As Long
    Dim ch As String
    Dim flag As Boolean

    For textIndex = 1 To Len(Text)
        ch = Mid(Text, textIndex, 1)
        If ch = ExponentChar Then
            flag = True
        Else
            newTextIndex = newTextIndex + 1
            If flag Then
                If IsNumeric(ch) Then
                    ch = exponentChars(ch)
                Else
                    flag = False
                End If
            End If

            newText(newTextIndex) = ch
        End If
    Next

    convertExponentsToSuperScript = Join(newText, "")
End Function

Test Code

Sub TestConvertExponentsToSuperScript()
    Dim target As Range
    Dim results As Variant
    Set target = Selection ' getTestRange(10000)
    results = target.value

    Dim t As Double: t = Timer

    Dim r As Long
    For r = 1 To UBound(results)
        results(r, 1) = convertExponentsToSuperScript(CStr(results(r, 1)))
    Next

    target.value = results

    Debug.Print Round(Timer - t, 2)
End Sub

Function getTestRange(TestRows As Long) As Range
    Dim results() As String
    ReDim results(1 To TestRows, 1 To 1)
    Dim r As Long
    For r = 1 To UBound(results)
        results(r, 1) = "O2 Permeability [cm^" & WorksheetFunction.RandBetween(0, 1000) & "/m^" & WorksheetFunction.RandBetween(0, 1000) & "]"
    Next
    Application.ScreenUpdating = False

    With Worksheets.Add
        .Range("A1") = "Test Data"
        With .Range("A2").Resize(UBound(results))
            .value = results
            Set getTestRange = .Cells
        End With
    End With
End Function


Sieve of eratosthenes with std::vector How can I improve and optimise this code?

#include <iostream>
#include <vector>

std::vector<bool> sieve_of_eratosthenes(int n)
{
    std::vector<bool> primes(n+1, true);
    primes[0] = false;
    primes[1] = false;

    for (int i = 2; i <= n; i++)
    {
        if (primes[i] == true)
        {
            for (int j = i * 2; j <= n; j += i)
            {
                primes[j] = false;
            }
        }
    }
    return primes;
}

int main()
{
    int n;
    std::cout << "Enter number :\n";
    std::cin >> n;
    std::vector<bool> result = sieve_of_eratosthenes(n);
    std::cout << "Prime numbers upto " << n << " is :\n";
    for (int i = 0 ; i < result.size(); i++)
    {
        if (result[i] == true)
        {
            std::cout << i << " ";
        }
    }
    std::cout << '\n';
}

Aside from the other optimizations, if you are using the sieve to check for primality of a number, you can optimize further, every prime after 2 is odd, therefore any even number that isn't 2 is not prime. This can easily be checked without the sieve.  I would suggest that marking all the even numbers false is superfluous.  So mark 2 as true and start the outer loop at 3 and increment by 2. As was mentioned, the inner loop can start at i*i, and since this will be an odd number you only need to mark every other multiple, therefore you can increment by i*2.  Something like this:

std::vector<bool> sieve_of_eratosthenes(int n)
{
    std::vector<bool> primes(n+1, true);
    primes[0] = false;
    primes[1] = false;
    int limit = (int)sqrt(n) + 1;
    for (int i = 3; i < limit; i += 2)
    {
        if (primes[i])
        {
            int step = i * 2;
            for (int j = i * i; j <= n; j += step)
            {
                primes[j] = false;
            }
        }
    }
    return primes;
}


Simple image scraping I wrote this code over the last few days and I learned a lot, and it works as I expect. However I suspect it's woefully inefficient:

import requests, bs4, os

os.chdir('../../Desktop')
wallpaperFolder = os.makedirs('Wallpapers', exist_ok=True)

pageCount = 1
GalleryUrl = 'https://wall.alphacoders.com/search.php?search=Game+Of+Thrones&page=%s' % (pageCount)

linkList = []
while not GalleryUrl.endswith('page=3'):
    # Download the page
    GalleryUrl = 'https://wall.alphacoders.com/search.php?search=Game+Of+Thrones&page=%s' % (pageCount)
    print('Opening gallary... %s' % (GalleryUrl))
    res = requests.get(GalleryUrl)
    res.raise_for_status()
    soup = bs4.BeautifulSoup(res.text, 'html.parser')

    # find urls to image page
    section = soup.find_all('div', attrs={'class': 'boxgrid'})

    for images in section:
        imageLink = images.find_all('a')
        for a in imageLink:
            imageUrl = a.get('href')
            linkList.append(imageUrl)
            print('Image found at... ' + imageUrl)
    linkCount = 0
# Follow links and download images on page.
    while linkCount != len(linkList):
        print('Downloading image at... %s' % (str(linkList[linkCount])))
        imagePageUrl = ('https://wall.alphacoders.com/' + str(linkList[linkCount]))
        res = requests.get(imagePageUrl)

        wallpaperSoup = bs4.BeautifulSoup(res.text, 'html.parser')

        link = wallpaperSoup.find(id='main_wallpaper')
        imageSrc = link['src']

        # Save image to folder

        res = requests.get(imageSrc)
        imageFile = open(os.path.join(os.getcwd(), 'Wallpapers', os.path.basename(imageSrc)), 'wb')
        for chunk in res.iter_content(12000):
            imageFile.write(chunk)
        imageFile.close()
        linkCount += 1

    # Move to next page and empty link list
    pageCount += 1
    del linkList[:]

print('Done')

Aside from cutting the print statements and simply letting the program do its thing, how could I optimize this code to run more efficiently?

os.chdir('../../Desktop')

Halt. Stop right there. This assumes the script is located at some specific location. Desktop happens to be always in the same place, but this assumes the script to be in a place relative to Desktop. On what OS do you intent to run this? If it's Linux-only, you could replace it by:

os.chdir('~/Desktop')

Now it will work regardless of where the script is located. Of-course, you just made the problem worse for non-Linux systems.

Even better would be to ask where the user wants to drop his files, possibly by using arguments (take a look at argparse).

But why don't you simply drop it instead? A map named Wallpapers will simply be created in the current directory. This would be obvious and expected behaviour.

for images in section:
    imageLink = images.find_all('a')
    for a in imageLink:
        imageUrl = a.get('href')
        linkList.append(imageUrl)
        print('Image found at... ' + imageUrl)

This isn't your bottleneck (not by a long shot), but that second for reeks of bad time complexity for something simple as telling the user where the images are.

One of the major time-consumers appears to be the downloading itself.

I ran cProfile against your code to find the bottleneck(s):

python3 -m cProfile -s tottime CR_133564.py

This automatically sorts the output on the total time taken per function, highest first. Don't forget to import cProfile. Let's take a look at everything with a total time higher than 0.5 seconds:

         8989953 function calls (8984594 primitive calls) in 108.880 seconds

   Ordered by: internal time

   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
    20393   59.314    0.003   59.314    0.003 {method 'read' of '_ssl._SSLSocket' objects}
      183   28.853    0.158   28.853    0.158 {method 'do_handshake' of '_ssl._SSLSocket' objects}
      183    9.689    0.053    9.689    0.053 {method 'connect' of '_socket.socket' objects}
      183    1.547    0.008    1.548    0.008 {built-in method _socket.getaddrinfo}
      183    1.005    0.005    1.005    0.005 {method 'load_verify_locations' of '_ssl._SSLContext' objects}
    78129    0.621    0.000    3.383    0.000 parser.py:301(parse_starttag)
   585660    0.580    0.000    0.580    0.000 {method 'match' of '_sre.SRE_Pattern' objects}
       93    0.549    0.006    5.750    0.062 parser.py:134(goahead)

That's responsible for 102.2 seconds out of the 108.9 it takes. If you want to optimize, do it here. The rest is peanuts.

Do you notice anything? You're wasting half a minute on handshakes. That's almost 30 seconds you could be doing something useful instead. Unless you find a trick to carry all files over one handshake, there's not much you can do about it. It also takes almost 60 seconds simply to read (AKA: download) the data. That's only slightly more than I'd expect with my internet connection, so there's not much you can do about that either.


Fetching all the project's items for a specific project id In the following query, I am fetching all the projects items with specific project id. At the same time, I am using a join in Select to fetch the delivered quantity of items of this project only. The delivered quantity join feels very costly because if I have 7000 items, it will multiply the iterations. In there any better solution. It can be SQL related, backend programming or anything else.

SELECT
    msprojectitems.idJobItem,
    msprojectitems.project_id,
    msprojectitems.hashcode,
    msprojectitems.itemID,
    msprojectitems.itemName,
    msprojectitems.itemNum,
    msprojectitems.itemWeight AS totalWeight,
    msprojectitems.itemUnit,
    msprojectitems.deleted,
    msprojectitems.LastUpdated,
    msprojectitems.itemWeight_assigned AS assignedWeight,
    IFNULL(
        (
            SELECT
                Sum(
                    IFNULL(
                        msjobitems.itemWeight_loaded,
                        msjobitems.itemWeight
                    )
                ) AS quantity_delivered
            FROM
                msjobcustomer
            INNER JOIN msjobcusttoitems ON msjobcustomer.idJobCustomer = msjobcusttoitems.idJobCustomer
            INNER JOIN msjobitems ON msjobcusttoitems.idJobItem = msjobitems.idJobItem
            WHERE
                msjobcustomer.project_id = 10
            AND msjobitems.itemID = msprojectitems.itemID
            AND msjobcustomer.jobstatus = 1
            GROUP BY
                msjobitems.itemID
        ),
        0
    ) AS quantity_delivered
FROM
    msprojectitems
WHERE
    msprojectitems.project_id = 10
ORDER BY
    msprojectitems.itemID ASC

Result of Expanded Explain of this query:

It seems likely that the subquery in the SELECT is causing a row-by-row lookup.  Try moving into a LEFT JOIN to get the set-based performance we're looking for:

SELECT
    msprojectitems.idJobItem,
    msprojectitems.project_id,
    msprojectitems.hashcode,
    msprojectitems.itemID,
    msprojectitems.itemName,
    msprojectitems.itemNum,
    msprojectitems.itemWeight AS totalWeight,
    msprojectitems.itemUnit,
    msprojectitems.deleted,
    msprojectitems.LastUpdated,
    msprojectitems.itemWeight_assigned AS assignedWeight,
    IFNULL(cte_quantity_delivered.quantity_delivered,0) AS quantity_delivered
FROM
    msprojectitems
LEFT JOIN
    (
        SELECT
            msjobitems.itemID,
            Sum(
                IFNULL(
                    msjobitems.itemWeight_loaded,
                    msjobitems.itemWeight
                )
            ) AS quantity_delivered
        FROM
            msjobcustomer
        INNER JOIN msjobcusttoitems ON msjobcustomer.idJobCustomer = msjobcusttoitems.idJobCustomer
        INNER JOIN msjobitems ON msjobcusttoitems.idJobItem = msjobitems.idJobItem
        WHERE
            msjobcustomer.project_id = 10
        AND msjobcustomer.jobstatus = 1
        GROUP BY
            msjobitems.itemID
    ) cte_quantity_delivered ON cte_quantity_delivered.itemID = msprojectitems.itemID
WHERE
    msprojectitems.project_id = 10
ORDER BY
    msprojectitems.itemID ASC


Generate dyamic 'week of' date range I was in need of a method to dynamically generate a week range, so that the view reads something like "Week of May 16 - 22" and updates automatically. Here's the helper method I came up with, but I'm wondering if there's a more efficient way to have gone about this.

Dashboards Helper:

def week_range
  today = DateTime.now
  week_start = today.beginning_of_week(:monday).strftime("%B %d")
  week_end = today.end_of_week(:monday).strftime("%d")
  "#{week_start} - #{week_end}"
end

Dashboards View:

Week of <%= week_range %>

Output:

Week of May 16 - 22

Your code looks pretty good. Just a couple of details:

Instead of hardcoding DateTime.now within the method, add an optional argument. Easier to test and more versatile to use.
The month leap is not considered.

I'd write:

def week_range(date: DateTime.now, start_day: :monday)
  start_date = date.beginning_of_week(start_day)
  end_date = date.end_of_week(start_day)
  start_date_string = start_date.strftime("%B %d")
  week_end_string = (start_date.month == end_date.month) ?
    end_date.strftime("%d") : end_date.strftime("%B %d")
  "#{start_date_string} - #{week_end_string}"
end


Probabilistically pick a candidate I have a list of candidates which looks like this:

candidates = [
    {
        'name': 'John',
        'rank': 13
    },
    {
        'name': 'Joe',
        'rank': 8
    },
    {
        'name': 'Averell',
        'rank': 5
    },
    {
        'name': 'William',
        'rank': 2
    }
]

What I want to do is semi-randomly pick one of these candidates, based on its squared rank. So that a candidate A having a rank twice as big as B, will have 4 times more chances to be picked than B.

Here is a naive implementation of the idea I had to solve this problem:

def pick_candidate(candidates):
    # initiates a global probability space
    prob_space = []

    # bring the max rank to 20
    # to avoid useless CPU burning
    # while keeping a good granularity -
    # basically, just bring the top rank to 20
    # and the rest will be divided proportionally
    rate = candidates[0]['rank'] / 20

    # fills the probability space with the indexes
    # of 'candidates', so that prob_space looks like:
    # [0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1]
    # if candidates[0] has rank 3 and candidates[1] has rank 2
    for i, c in enumerate(candidates):
        rank = c['rank'] / rate
        for j in range(int(rank*rank)):
            prob_space.append(i)

    # picks a random index from the probability space
    picked_prob_space_index = random.randint(0, len(prob_space)-1)

    # retrieves the matching candidate
    picked_candidate_index = prob_space[picked_prob_space_index]

    return candidates[picked_candidate_index]

The questions I'm thinking of, concerning the above code, are:

Concept: Is the core principle of the algorithm (the idea of building prob_space, etc) overkill and solvable more easily in other ways or with builtins
Implementation: This core principle put aside, what do you think of the implementation? Would you think of a better, cleaner way to write it?

Concept

imho you don't need build prob_space or normalize by max rank == 20
you only need

John: 1 ... 13^2
Joe:  13^2+1 ... 13^2+8^2
Averell: 13^2+8^2+1 ... 13^2+8^2+5^2
William: 13^2+8^2+5^2 ... 13^2+8^2+5^2+2^2
and choice a man having ranint(1, 13^2+8^2+5^2+2^2)

transform list [13**2, 8**2, 5**2, ...] to [13**2, 13**2+8**2, 13**2+8**2+5**2, ...] we can by accumulate
searching in this sorted list [13**2, 13**2+8**2, 13**2+8**2+5**2, ...] we can by binary search algorithm implemented in bisect module
the algorithm:

from collections import namedtuple
from itertools import accumulate
from random import randint
from bisect import bisect_left

Candidate = namedtuple('Candidate', 'name rank')

def pick_random_candidate(candidates):
    assert (len(candidates) > 0) # note: probably we want return None with empty list?
    squared_ranks_accumulated = list(accumulate(c.rank ** 2 for c in candidates))
    random_pick = randint(1, squared_ranks_accumulated[-1])
    return candidates[bisect_left(squared_ranks_accumulated, random_pick)]

if __name__ == "__main__":
    candidates = [Candidate(*t) for t in [('John', 13), ('Joe', 8), ('Averell', 5), ('William', 2)]]
    random_candidate = pick_random_candidate(candidates)
    print(random_candidate)

Implementation

better use from random import randint instead of import random
if you have randint(0, x - 1) you can replace it by randrange(x)
constants like 20 should be defined as variable, e.g. top_rank = 20 or even def pick_candidate(candidates, top_rank=20). Reason: if someone change 20 to 21 in next three months there are high probability that don't change comment (so better when comment explains top_rank not 20)
you can often define structure Candidate as namedtuple (dict is better only sometimes if have some dynamic fields to store)
what's with the empty list of candidates (exception KeyError is expected or something else should be?)


C++ program to swap links of a Linked List In this code I tried to swap links in a linked list instead of swapping data.Please Review my code.

#include <iostream>

    template<class T>
    class LinkedList
    {
struct Node{
  T data;
  Node * next;
  Node(T val): data(val), next(nullptr){}
};

Node* head;

public:

  LinkedList() : head(nullptr) {}

  void insert(T val)
  {
    Node* node = new Node(val);
    Node* tmp  = head;

    if(tmp == nullptr)
    {
      head = node;
    }
    else
    {
      while(tmp->next != nullptr)
      {
        tmp = tmp->next;
      }
      tmp->next = node;
    }
  }

  void swapLinks(T val1, T val2)
  {
    Node* prevNode1 = nullptr;
    Node* prevNode2 = nullptr;
    Node* nextNode1 = nullptr;
    Node* nextNode2 = nullptr;
    Node* node      = head;
    Node* node1     = search(val1);
    Node* node2     = search(val2);

    while(node->next != node1)
    {
      node = node->next;
    }
    if(node->next == node1)
    {
      prevNode1 = node;
      nextNode1 = node1->next;
    }

    node = head;

    while(node-> next != node2)
    {
      node = node->next;
    }
    if(node->next == node2)
    {
      prevNode2 = node;
      nextNode2 = node2->next;
    }

    prevNode1->next = node2;
    Node* tmp       = node2->next;
    node2->next     = node1->next;
    prevNode2->next = node1;
    node1->next     = tmp;
  }

  friend std::ostream & operator <<(std::ostream & os, LinkedList<T>& ll)
  {
    ll.display(os);
    return os;
  }

private:

  struct Node *search(T val)
  {
    Node* node = head;
    while(node != nullptr)
    {
      if(node->data == val)
      {
        return node;
      }
      node = node->next;
    }
    std::cerr << "No such element in the List \n";
    return nullptr;
  }

  void display(std::ostream& out = std::cout) const
  {
    Node* node = head;
    while(node != nullptr)
    {
      out << node->data <<" ";
      node = node->next;
    }
  }
};

int main()
{
  LinkedList<int> ll1;
  ll1.insert(10);
  ll1.insert(15);
  ll1.insert(12);
  ll1.insert(13);
  ll1.insert(28);
  ll1.insert(14);
  ll1.insert(16);
  std::cout << "LinkedList1 : "<< ll1 <<"\n";
  ll1.swapLinks(12, 14);
  std::cout << ll1 <<"\n";

}

Is there any another solution or better solution? Please suggest.

This works as long as 2 conditions are met.

val1 and val2 are in the list.
Neither are in the head node.

Otherwise you access stuff via null pointers:

  void swapLinks(T val1, T val2)
  {
    Node* prevNode1 = nullptr;
    Node* prevNode2 = nullptr;
    Node* nextNode1 = nullptr;
    Node* nextNode2 = nullptr;
    Node* node      = head;
    Node* node1     = search(val1);
    Node* node2     = search(val2);

    // This will not find values in the "head node"
    // If the value is in head the you will not find a previous node.
    // You need to take into account this special case at the bottom.
    while(node->next != node1)
    {
      node = node->next;
    }
    if(node->next == node1)
    {
      prevNode1 = node;
      nextNode1 = node1->next;
    }

    node = head;

    // This will not find values in the "head node"
    // If the value is in head the you will not find a previous node.
    // You need to take into account this special case at the bottom.
    while(node-> next != node2)
    {
      node = node->next;
    }
    if(node->next == node2)
    {
      prevNode2 = node;
      nextNode2 = node2->next;
    }

    // HERE YOU HAVE some issues.
    // prevNode1 or prevNode2 or node1 or node2 may be nullptr
    // If any of these values are null the code below will be UB.
    prevNode1->next = node2;
    Node* tmp       = node2->next;
    node2->next     = node1->next;
    prevNode2->next = node1;
    node1->next     = tmp;
  }