Array Duplicate Item Filtering by Element Value

If the sole purpose was to have a resultant array of objects that did not have a duplicated id then I would be tempted with the below:

// Indexes keyed by item id
$indexes = array();

// Cast to array of objects
$items = current((array)$items);

foreach ($items as $index => $item) {
    $id = ((array)$item)['id'];

    if (isset($indexes[$id])) {
        // Unset this item
        unset($items[$index]);
        // Unset the original instance
        unset($items[$indexes[$id]]);
    } else {
        $indexes[$id] = $index;
    }
}

// List names of items that doesn't have an id that is duplicated
foreach ($items as $item) {
    // Still have original SimpleXml object to work with
    echo $item->name . "\n";
}


Your solution requires that you create a new Vector for every combination. You are right that there is no better algorithm. The way you have it implemented though, is not as efficient as it should be.

Float should be a primitive.... float. Using a Float object instead of the primitive float will require a lot more memory than you should need.

The Java Vector class is a synchronized implementation. Use of the Vector class is discouraged. If you need synchronization then use one of the java.util.concurrent.* classes. I would also use an array-of-primitives for the input population too):

private static void distribuzioneInBlocco(int n, int firstElementConsidered, float[] population, float[] sample){
    // not sure what this is.....
// exit condition, when n equals 0 the function doesn't self-calls
    //if(n==0){
    //    JOptionPane.ShowMessageDialog(null, campione);
    //    return:
    //}

    // for every element of the population the function adds this element
    // at the previous combination
    for(int x = firstElementConsidered; x < population.length; x++) {
        float[] aggiunta = Arrays.copyOf(sample, sample.length + 1);
        aggiunta[aggiunta.length - 1] = population[x];
        distribuzioneInBlocco(n-1, x+1, population, aggiunta);
    }
}

So, using an array of primitive will make a big difference for your performance.

I note that you are not keeping any of these samples. If you do not need to actually keep the agguinta array, it is possible that you can save a lot of time by moving the initialization to be outside the loop:

private static void distribuzioneInBlocco(int n, int firstElementConsidered, float[] population, float[] sample){
    // not sure what this is.....
// exit condition, when n equals 0 the function doesn't self-calls
    //if(n==0){
    //    JOptionPane.ShowMessageDialog(null, campione);
    //    return:
    //}

    // for every element of the population the function adds this element
    // at the previous combination
    // move the array initialization outside the loop, and reuse it for each
    // recursion at this depth.
    float[] aggiunta = Arrays.copyOf(sample, sample.length + 1);
    for(int x = firstElementConsidered; x < population.length; x++) {
        aggiunta[aggiunta.length - 1] = population[x];
        distribuzioneInBlocco(n-1, x+1, population, aggiunta);
    }
}


Iterating over an object that contains arrays

To directly answer your question, yes, there is a better way: template literals and using array methods.

In the following snippet, it uses Object.keys and array.reduce to concatenate all arrays in the object into one array, array.map to generate an array of name strings from that array, and array.forEach to ultimately loop through the names array and print names.

const users = {
  'Students': [
    {first_name:  'Michael', last_name : 'Jordan'},
    {first_name : 'John', last_name : 'Rosales'},
    {first_name : 'Mark', last_name : 'Guillen'},
    {first_name : 'KB', last_name : 'Tonel'}
  ],
  'Instructors': [
    {first_name : 'Michael', last_name : 'Choi'},
    {first_name : 'Martin', last_name : 'Puryear'}
  ]
}

Object.keys(users)
  .reduce((names, userType) => names.concat(users[userType]), [])
  .map(userObject => `${userObject.first_name} ${userObject.last_name}`)
  .forEach(name => console.log(name));

If you're not into ES6, here's the ES5 equivalent:

const users = {
  'Students': [
    {first_name:  'Michael', last_name : 'Jordan'},
    {first_name : 'John', last_name : 'Rosales'},
    {first_name : 'Mark', last_name : 'Guillen'},
    {first_name : 'KB', last_name : 'Tonel'}
  ],
  'Instructors': [
    {first_name : 'Michael', last_name : 'Choi'},
    {first_name : 'Martin', last_name : 'Puryear'}
  ]
}

Object.keys(users)
  .reduce(function(names, userType) {
    return names.concat(users[userType]);
  }, [])
  .map(function(userObject) {
    return ((userObject.first_name) + " " + (userObject.last_name));
  })
  .forEach(function(name) {
    return console.log(name);
  });

As for your code:

Indentation needs to be more consistent.
Names in JS follow the camelCase convention.
Most of JS code I've seen use the "egyptian braces" (collapsed braces).
Note that variables declared with var is function-scoped. Loops don't scope vars locally.
for-in loops should be guarded with an object.hasOwnProperty check.


Some comments on your code:

def initialize max, current, target. The community consensus seems to be to put always parenthesis on method definitions. I'd definitely do it.
return @current == @max. It's not idiomatic to put explicits return, the last expression of a block/method is returned.
MAX_STEPS = 12. Isn't this kind of cheating?
raise 'max.length must equal init.length' if max.length != init.length. I wouldn't lose a second validating inputs. If the input data is wrong it's the caller's problem.
[Lots of imperative code which, frankly, I don't understand] When you are dealing with mathematics-related problems (some would argue all computation is a mathematics-related problem) you'll get better algorithms with functional programming.

I'd write it with a depth-first algorithm in functional style. Note that I've created two generic abstractions, Enumerable#map_detect (Facets has it) and Array#merge, so the main algorithm remains as clean and declarative as possible. Granted, it may be difficult to grasp at first if you have only experience with imperative programming, ask if you don't understand something (also, reviews of the review welcomed):

require 'facets/enumerable/map_detect'

class Array
  # [:a, :b, :c, :d].merge_from_hash(1 => :bb, 3 => :dd) #=> [:a, :bb, :c, :dd]
  def merge_from_hash(hash)
    map.with_index { |x, idx| hash.fetch(idx, x) }
  end
end

class PitchersProblem < Struct.new(:total)
  def solve(current, final, solution = [])
    if current == final
      solution + [current]
    else
      (candidates(current) - solution).map_detect do |candidate|
        solve(candidate, final, solution + [current])
      end
    end
  end

  def candidates(current)
    (0...total.size).to_a.permutation(2).map do |i1, i2|
      free2 = total[i2] - current[i2]
      if current[i1] > 0 && free2 > 0
        moved = [current[i1], free2].min
        current.merge_from_hash(i1 => current[i1] - moved, i2 => current[i2] + moved)
      end
    end.compact
  end
end

p PitchersProblem.new([10, 7, 3]).solve([10, 0, 0], [5, 5, 0])
#=> [[10, 0, 0], [3, 7, 0], [0, 7, 3], [7, 0, 3], [7, 3, 0],
#    [4, 3, 3],  [4, 6, 0], [1, 6, 3], [1, 7, 2], [8, 0, 2],
#    [8, 2, 0],  [5, 2, 3], [5, 5, 0]]

Notes on my code:

solve can be read as: "If the current state is the final, add it to the path solution and we are done. Otherwise, for each permutation of the pitchers, move water from one to the other if possible, and try to find a solution recursively (unless that state is already in our solution path)".
This algorith returns the first solution it gets (size 13), which is not the optimal (size 10?), that's because it's a depth-first algorithm, you can transform it into a breadth-first algorithm to get the shortest solution first.
Ideally solution should be an insertion-ordered data-structure with O(1) lookup (because of solution.include?(new_current)), something like an OrderedSet. An array has O(n) lookup, but anyway, let's leave it just to keep it simple.


You might want to create a service that accepts the spreadsheet data as method argument instead.

And maybe the columns could be configured to make it more flexible.

Also no need to do 5 times the same again, instead use a loop.

class SpreadsheetTillsConverter
{
  private int $modelColumn;
  private int $versionColumn;

  /** @var array<int, int> Map nameColumn => ipAddressColumn */
  private array $columns;

  public function __construct(int $modelColumn, int $versionColumn, array $columns)
  {
    $this->modelColumn = $modelColumn;
    $this->versionColumn = $versionColumn;
    $this->columns = $columns;
  }

  public function getTills(array $data): array
  {
     if (!isset($data[$this->modelColumn])) {
        throw new \InvalidArgumentException('Model column not found.');
     }
     $model = $data[$this->modelColumn];

     if (!isset($data[$this->versionColumn])) {
        throw new \InvalidArgumentException('Version column not found.');
     }
     $version = $data[$this->versionColumn];

     $result = [];
     foreach ($this->columns as $nameColumn => $ipAddressColumn) {
        if (isset($data[$nameColumn], $data[$ipAddressColumn])) {
          $result[] = [
            'model' => $model,
            'name' => $data[$nameColumn],
            'ip_address' => $data[$ipAddressColumn],
            'version' => $version,
          ];
        }
     }
     return $result;
  }
}

$converter = new SpreadsheetTillsConverter(17, 7, [
  40 => 41,
  42 => 43,
  44 => 45,
  46 => 47,
  48 => 49
]);

$tills = $converter->getTills($spreadsheetData);


AngularJS Todo List - too much controller logic?

This is a funny question because

One of the most readable Angular submissions on CR
There is probably too much logic in the controller indeed

Some observations:

It seems the controller knows too much, it should not know that 5 is the maximum amount of items, or that 1 is the minimum amount of items to be kept
It seems silly to pass the list to list every single time to listEdit, it is not DRY.
I know alert in this case is used because it is a prototype, but still..

I would counter propose something where listEdit is aware of the list after you make a connection, listEdit also knows about limits and gives feedback ( in the form of a string ) whenever it does something to the list.

The controller this way is very small, and easy to understand:

//Controller methods
toDo.controller('main', ['$scope', 'listEdit', function($scope, listEdit) {

  $scope.list = [];
  listEdit.linkList( $scope.list ); //<- Magic happens here

  $scope.addToList = function() {
    $scope.feedback = listEdit.add($scope.todo);
  };

  $scope.remove = function(index) {
    $scope.feedback =  listEdit.remove(index);
  };

}]);

listEdit is then a little bigger:

toDo.factory('listEdit', function() {
  var _list = [],
      maxLength = 5,
      minLength = 1;

  return {
    add: function(item) {
      if( _list.length >= maxLength )
        return 'Too many list items';
      _list.push(item);
      return item + ' is added';
    },
    remove: function(index) {
      if( _list.length == minLength )
        return 'You can\'t delete this last item';
      var item = _list.splice(index, 1)[0];
      return item + ' has been deleted';
    },
    count: function() {
        return internalList.length;
    },
    linkList: function(list){
      _list = list;
    }
  };
});

I consciously chose for immediate return with feedback in case of a problem, then the intended activity and then giving positive feedback. My evil twin whispered this hackish alternative:

    add: function(item) {
      return _list.length >= maxLength ?
        'Too many list items' :
        _list.push(item), item + ' is added';
    }

Also, you will find me railing against people using underscore to indicate that it is private when it is not. In this case, _list is actually private, so that is fine.

In order to show the feedback you would need to add div:

<!DOCTYPE html>

  <meta charset="utf-8">
  <title>JS Bin</title>

{{feedback}}&nbsp;

    <input type="text" ng-model="todo">
    <button ng-click="addToList()">Add to List</button>

    {{todo}}

I used the &nbsp; trick to make sure the elements dont reflow after the first element is added, probably not best practice, HTML is not my forte.

In the end, it was fun to play with this in jsbin: http://jsbin.com/vesomu/2/edit

Also, check this : a simple todo app by Angular pro's.


How to write a cleaner code for this piece of php snippet?

if ($this->form_validation->run() == true)

is redundant, just use...

if ($this->form_validation->run())

Also, you can move the whole if (empty($user_id)) block outside to the end to avoid duplicating it:

$code = $this->uri->segment(3);

if (!$code) {
    // validation
    $this->form_validation->set_rules('code', 'PassCode',
        'required|trim|max_length[100]|xss_clean');

    // run validation to check if validation rules are satifised
    if ($this->form_validation->run()) {
        $code = $this->input->post('code');
        $user_id = $this->user_model->getUserId($code);
    }
} else {
    $user_id = $this->user_model->getUserId($code);
}

if (empty($user_id)) {
    $data['errorMessage'] = 'Your code is not valid.';
} else {
    redirect('user/profile');
}


Remove multiple array elements by indices

The main concern with this implementation is not its complexity but the fact that you transform ranges into arrays of indices. It works fine for basic cases, but what if the range is huge? For example,

array_except(a, 1..100000000)

works with the significant delay on my laptop already, and infinite range will obviously cause your implementation to never terminate.

But you don't need to iterate over all the numbers within the range to check if the index belongs to it, right? It's enough to just check the boundaries. So, my suggestion is

def array_except(array, *indexes)
  array.reject.with_index do |_, i|
    indexes.any? do |index|
      index.is_a?(Range) ? index.cover?(i) : index == i
    end
  end
end

pry(main)> array_except(a, 1..Float::INFINITY) # => ["a"]

UPD. Please, note: it doesn't work with the negative ranges as is, but can be adjusted if you decide to go in this direction - for example, via converting ranges with the negative boundaries into "equivalent" ones with the proper positive boundaries:

def array_except(array, *indexes)
  array.reject.with_index do |_, i|
    indexes.any? do |index|
      if index.is_a?(Range)
        start = index.begin > 0 ? index.begin : array.length + index.begin
        stop = index.end > 0 ? index.end : array.length + index.end
        start <= i && i <= stop
      else
        index == i
      end
    end
  end
end

The final version is more verbose than your initial implementation, but its performance doesn't depend on the size of the ranges provided as an input...

UPD2. If you don't care about the predictable performance and is just interested in a concise implementation, it can be made as short as

def array_except(array, *indexes)
  array.reject.with_index { |_, i| indexes.any? { |ind| Array(ind).include?(i) } }
end

UPD3. Good point raised in the comment. The second implementation works terribly bad in the cases when indexes parameter is a huge list of something (integers or ranges) applied to a large list. In this case we get stuck with O(m*n)... To beat this we need something more sophisticated. For example, we can first iterate over all indexes and fill some auxiliary data structure (with O(1) read access) with some "flags" (defining what to keep/delete) and then iterate over the array itself and clean it up. Very dirty implementation:

def array_except4(array, *indexes)
  to_delete = Array.new(array.size)

  indexes.each do |index|
    case index
    when Range
      start, stop = [index.begin, index.end].sort
      start = start < 0 ? [0, start + array.length].max : [start, array.length - 1].min
      stop = stop < 0 ? [stop + array.length, array.length - 1].min : [stop, array.length - 1].min

      (start..stop).each { |k| to_delete[k] = true }
    else
      to_delete[index] = true
    end
  end

  array.reject.with_index { |_, i| to_delete[i] }
end
```


Make Node generic

The problem description uses node values like A, B, C, ..., yet your Node class can only store int values. There's no need to choose, you can make Node generic:

class Node<T> {
    Node<T> left, right;
    Node<T> neighbor;
    T data;

    Node(T d) {
        left = null;
        right = null;
        data = d;
        neighbor = null;
    }
}

Bug

This implementation doesn't work for the given example data:

        A
     /     \
    B       C
 /    \      \
D      E       F

The neighbor of E should be F, but this implementation will give null.
This is because the only place you set the neighbor is this code:

if (parent.left != null && parent.right != null) {
    parent.left.neighbor = parent.right;
}

This only works for nodes in left position. It doesn't for nodes in right position that have a neighbor.

But you're not too far off. With a few simple changes to the main loop, this can work:

        Node<T> prev = null;
        for (Node<T> node : parents) {
            if (node.left != null) {
                current.add(node.left);
            }
            if (node.right != null) {
                current.add(node.right);
            }
            if (prev != null) {
                prev.neighbor = node;
            }
            prev = node;
        }

Initializing generic types

There are several issues here:

ArrayList<Node> current = new ArrayList<BinaryTree.Node>();

The type of left-hand size is ArrayList<Node> but the right-hand side is ArrayList<BinaryTree.Node>. This only compiles if Node and BinaryTree.Node are the same class. But if they are the same class, then it would be better to refer to them the same way consistently.

...except you don't actually need to specify the generic type of the right-hand side, you can use the diamond operator <> and let the compiler figure out the correct type:

ArrayList<Node> current = new ArrayList<>();

Lastly, it's recommended to declare variables with their interface type rather than the implementation type. So this will be better:

List<Node> current = new ArrayList<>();

Alternative implementation

The current implementation tries to avoid adding null values in the list. The consequence of that is multiple null checks:

Before adding the root
Before adding a left child
Before adding a right child

Instead of having 3 places to check for nulls, you could allow null values in the list, and move the check inside the loop, in one place. Rearranging the code to work that way, the code becomes:

    List<Node<T>> level = new ArrayList<>();
    level.add(root);

    do {
        List<Node<T>> prevLevel = level;
        level = new ArrayList<>();
        Node<T> prevNode = null;
        for (Node<T> current : prevLevel) {
            if (current == null) {
                continue;
            }
            level.add(current.left);
            level.add(current.right);
            if (prevNode != null) {
                prevNode.neighbor = current;
            }
            prevNode = current;
        }
    } while (!level.isEmpty());

I also renamed some variables to slightly more intuitive names.


So, I looked at the problem spec, expecting to see a 3-word description o the title of the problem, and not much else, followed by 'Looking for optimizations, and confirmation that compelxity is O(n log(n) ).
Fortunately, I was disappointed ;-) Your description is improved over previous questions, and I can actually follow it without having to google-search for references and hints. It would have been improved slightly if you had spelled out carefully that diagonally touching 1 values combine to form an island... but this is a nit-pick.
Then, I did the normal-for-me task of thinking 'How would I solve this', and I thought for a moment, and decided I would:

scan the matrix cell-by-cell
if you encounter a 1, use recursion to follow all it's adjacent 1 values
mark all visited cells as 'seen'
consider that process a 'hit' for an island
scan the remaining unseen cells for the next unseen island. (go to 1).

So, I looked through your code, and, it took me a moment, but I found all of those processes in your solution.
So, you have solved this the same way I would have tackled it. The algorithm is 'good', and all that is then left, is to look at how you have implemented it...

I like the Enum for the directions. It is a good solution.
I think your variable names have improved recently. I much prefer seeing row and col instead of x and y, etc. It is more descriptive, and it helps.
count() could be countIslands() because that is what is being counted.

That's a pretty short list of nit-picky things. In all, this is a good program.
There is one suggestion I have for your recursion, and that is that there are multiple 'styles' of recursive methods. If you choose one method, and use it consistently (except for those times the other methods are better), it helps. My suggestion is that you should settle on what I call optimistic recursion.... which is the opposite case of what Wikipedia calls 'short-circuit recursion'. What I am saying, is that 'standard' recursion checks the recursive state, and, if it is valid, it does it's work, and it then calls recursion. The short-circuit system does the state-check of the new state before recursing in to that new state.
By way of example, a standard (what I call optimistic) recursion for this problem would be:
private static void dfs(int row, int col, int[][] m, boolean[][] visited) {
    // check recursion state... and expect it to have failures.
    if (row < 0 || row >= m.length || col < 0 || col >= m[0].length) {
        // invalid state, index-out-of-bounds
        return;
    }
    // OK, row/column are valid... more checks
    if (visited[row][col]) {
        // already seen this valid position.
        return;
    }
    // mark the position seen
    visited[row][col] = true;
    // if it's not an island....
    if (0 == m[row][col]) {
       return;
    }
    // OK, we are still on the island, let's optimistically search around....
    for (Direction direction : Direction.values()) {
        dfs(row + direction.getRowDelta(), col + direction.getColDelta(), m, visited);
    }
}

This optimistic approach simplifies the call structure significantly.... (and eliminates the isValid() method).
Food for thought.
Finally, I don't like calling your method dfs.... it's not a depth-first-search.... since that applies to a tree. The 'cells' in the 'landscape' are not linked in a tree structure, as one cell could be a neighbour to many other cells. A better name would be scan, or even just search.


JavaScript style

Delimit cod blocks with {}. Eg if (foo) bar = 0; should be if (foo) { bar = 0; }

Use semicolons consistently!

Avoid Array.unshift as it is much slower than Array.push. If you know the size of the array pre-allocate the array new Array(size) and then pput items on the array via an index. (See example)

Be wary of destructuring as it can sometimes be rather slow (engines converting the right side to array (like) before assigning to the left). As destructuring becomes more main stream and JS engines stabilize new features destructuring has and will continue to improve in terms of performance.

Complexity.
Your function is too complex!
The complexity of this function is \$O(n)\$ where \$n\$ is the number of digits in the result. A well written function should thus have a performance that is related linearly to \$n\$ however your functions performance does not have this relationship, demonstrating a logarithmic performance (approx) \$O(n^2)\$ making it very slow for large numbers.
The reason is your use of Array.unshift. Each time you unshift a value to the array each item on the array needs to be moved up by one item. This is compounded every time the array size doubles as jS will then create a new array, and copy all the items to that array. As JS is a managed environment and memory is not cleaned up until the function exits or is forced by low memory your function not only has high time complexity but on theoretically infinite memory machines also has a storage complexity of \$O(n^2)\$
Rewrites
The rewrites are both \$O(n)\$ time and space complex, where \$n\$ is number of digits in the result (including leading zeros).
rather than revers the digits the code pre-allocates the result array with the required number of digits and then works from the least significant digit up.
Note that when the index into the strings a or b is less than 0 the coercion forced by the bitwise OR 0 | 0 will convert undefined to the number 0.
Ignoring leading zeros (assumes that there are no leading zeros for values over 0)
"use strict";
function sumStrings(a, b) {
    var carry = 0, i = a.length, j = b.length, k = i > j ? i : j;
    const res = new Array(k);
    while (i > 0 || j > 0) {
        const sum = (a[--i] | 0) + (b[--j] | 0) + carry;
        res[--k] = sum % 10;
        carry = (sum > 9 && 1) || 0;
    }
    return (carry ? carry : "") + res.join("");
}

The next version will accept leading zeros truncating the result string if there is no carry on the last digit. The truncation is at the last non zero digit encountered.
"use strict";
function sumStrings(a, b) {
    var carry = 0, i = a.length, j = b.length, k = i > j ? i : j, lastNonZero = k;
    const res = new Array(k);
    while (i > 0 || j > 0) {
        const sum = (a[--i] | 0) + (b[--j] | 0) + carry;
        lastNonZero = sum ? k : lastNonZero;
        res[--k] = sum % 10;
        carry = (sum > 9 && 1) || 0;
    }
    return carry ? carry + res.join("") : res.join("").slice(lastNonZero -1);
}

BigInt?
You could also have just parsed the two strings as BigInt but that is not the point of the exercise.
The summing algorithm is a basic component of computing, the algorithm will also work on any number base. Eg Binary base 2 Hex base 16.
With only minor modifications the function will handle any base and never actually add any numbers


Simple integer range for C++11 range-based for loops

You can make the class template with trivial changes (add template<typename T> and change int by T in your classes), then make a construction function that deduces integer types:

template<typename T>
LoopRange<T> range(T from, T to)
{
    static_assert(std::is_integral<T>::value,
                  "range only accepts integral values");

    return { from, to };
}

That will even allow you to explicitly tell what kind of integer you want to loop with if needed:

for (auto i: range<unsigned>(0, 5))
{
    std::cout << i << " ";
}

If you need to generate indices to iterate through a std::vector, this can be useful since std::vector<T>::size_type is probably bigger than int. While the static_assert avoids some potential problems with floating point values, it also inhibits the use of integer-like classes (for example, a hypothetical BigNum class).

You can simplify some of your functions thanks to list initialization. For example, used in a return statement, it sallows you not to explicitly repeat the return type (unless the return type's constructor is explicit):

LoopRangeIterator begin() const
{
    return { from };
}

LoopRangeIterator end() const
{
    return { to };
}

On a side note, such a range utility would also be interesting if it worked with floating point numbers, and maybe decimal numbers in the future (akin to Python's numpy.arange). However, you would have to special-case the class for those types if you want to avoid problems: if you repeatedly add the same floating point (say 0.01), you will accumulate rounding errors. Computing every value from the base value with a multiplication could be away to circumvent such a problem.


Creating 3 sublists based on unique conditions

No much room for improvement here. The code is clear, readable, maintainable, short and nice. You could get rid of the three iterations by using a loop and filling three lists all in one iteration, but you'd sacrifice maintainability for a few microseconds saved. Don't do this unless you are in a real critical spot. For real world applications, keep it as it is.

One thing however is the PersonUtil. From an OO perspective, the Person should probably know whether it is underaged or senior or whatever and contain that business logic itself, so that you don't have to resort to a util-class. However, if the Person is an entity, eventually generated, you basically have no other choice.


Cycling through sibling elements on button click and assigning a class to the “active” element

You are doing a lot of DOM traversal. I'll show you the updated code and explain it.

HTML

Item 1

Item 2

Item 3

Item 4

  <button type="button" class="btn-toggle">Toggle Next</button>

CSS

.d-none {
  display: none;
}

JAVASCRIPT

$(document).ready(() => {
  const toggleButton = $('.btn-toggle');
  const items = document.querySelectorAll('.items > li');
  let index = 0;
  toggleButton.on('click', () => {
     $(items[index]).toggleClass('d-none');
     index = index + 1;
     if(index === items.length){
       index = 0;
     }
     $(items[index]).toggleClass('d-none');
  });
});

I updated the HTML so that the li's after the first have display none. In your previous code this was the initial state, so its better to set it in the HTML than using JavaScript to do it.

What i have done in JavaScript is that i store all
 and an associated index, then when you press Toggle Next, i just toggle the
 at the current index, and increment index by 1, if index === items.length, then it must mean we are out of bounds, because items[4] would be undefined, so we have to reset it to 0.

After increment, we toggle d-none on the new index.


Create file path and filename in JSON and send it to Discord

There's comments above report which should really be a docstring,
since they explain the function's workings.
The default parameters for report are a bit suspect:

The expression payload if payload else None is redundant, can just
be payload then.
str(reason) for the default value None for reason is odd,
maybe that also needs special casing and could be left out of the
JSON body?

Does the value from payload["store"] need escaping / is it safe?
E.g. if it's coming from the server you'd have to validate it before
using it as part of a filename to prevent attacks.
I feel it's a bit over-commented.  Consider "Create file path and
filename" - that's basically what I can discern from the block below,
same as "Check if the path already exists", that's basically the same
as the line if not os.path.exists(file_path).  Consider splitting
off smaller functions that have descriptive names instead of one huge
function, that way you wouldn't have to comment on blocks of code (and
would instead use the function names as descriptors).
with is used, good.
os.makedirs won't do anything if the path already exists, so the
check before it is redundant.
Consider making webhook and embed (global) constants, they
otherwise don't seem to add anything to the function.
After writing the JSON to the file, it's immediately being read back
for the webhook.add_file - avoid that unnecessary computation and
reuse the in-memory representation of the data.
Again, consider splitting the setup phase and the while True loop
into separate functions to help understanding and, potentially,
testability.
The only thing I'd have to complain about in the loop is the fetching
of the retry timeout value: Be conservative in what you expect.  The
server doesn't have to send that value and if it doesn't you'll get
exceptions.  Consider providing a default value and a maximum sleep
amount to not open yourself up to a malicious server (yes, that's a
stretch, but still).
Just noticed:  You're importing typing.List just to check
isinstance - AFAIK you can just use isinstance(response, list)
without the need to import the typing module.  Of course using
typing is great, you'd just have annotate your functions most likely
and use mypy or a similar type-checker ...


The first thing to do is to incorporate some basic notions of organization and design into your program, for example, a maxWord function.

package main

import (
    "fmt"
    "regexp"
)

var re = regexp.MustCompile(`[A-Za-z]+|[*?()$&.,!]`)

func maxWord(s string) string {
    matches := re.FindAllString(s, -1)
    var count int
    for i := 0; i < len(matches); i++ {
        if (i+1)%len(matches) > 0 {
            if len(matches[(i+1)%len(matches)]) > len(matches[i]) {
                count = (i + 1) % len(matches)
            }
        }
    }
    return matches[count]
}

func main() {
    for _, s := range []string{
        "I love dogs",
        "fun&!! time",
        loremipsum,
    } {
        fmt.Printf("%q\n", maxWord(s))
    }
}

var loremipsum = `
Lorem ipsum dolor sit amet, consectetur adipiscing elit,
sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.
Ut enim ad minim veniam,
quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.
Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.
Excepteur sint occaecat cupidatat non proident,
sunt in culpa qui officia deserunt mollit anim id est laborum.
`

Output:

"love"
"time"
"laborum"

Test your code. Your result for the loremipsum text doesn't look right.

Consider writing a simple, efficient word parser. For example,

package main

import (
    "fmt"
    "unicode"
)

func maxWord(s string) string {
    var word string
    inWord := false
    j, k := 0, 0
    for i, r := range s {
        if !unicode.IsLetter(r) {
            if inWord {
                k = i
                if k-j > len(word) {
                    word = s[j:k]
                }
            }
            inWord = false
        } else if !inWord {
            inWord = true
            j = i
        }
    }
    if inWord {
        k = len(s)
        if k-j > len(word) {
            word = s[j:k]
        }
    }
    return word
}

func main() {
    for _, s := range []string{
        "I love dogs",
        "fun&!! time",
        loremipsum,
    } {
        fmt.Printf("%q\n", maxWord(s))
    }
}

var loremipsum = `
Lorem ipsum dolor sit amet, consectetur adipiscing elit,
sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.
Ut enim ad minim veniam,
quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.
Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.
Excepteur sint occaecat cupidatat non proident,
sunt in culpa qui officia deserunt mollit anim id est laborum.
`

Output:

"love"
"time"
"reprehenderit"

Go programmers often write reasonably efficient programs. The Go standard library testing package provides a benchmark facility.

For example,

$ go test maxword_test.go -bench=. -benchmem
BenchmarkPeterSO-4    24316906      47.7 ns/op      0 B/op     0 allocs/op
BenchmarkMannu-4        557594    2022 ns/op      448 B/op    10 allocs/op

maxword_test.go:

package main

import (
    "regexp"
    "testing"
    "unicode"
)

func maxWordP(s string) string {
    var word string
    inWord := false
    j, k := 0, 0
    for i, r := range s {
        if !unicode.IsLetter(r) {
            if inWord {
                k = i
                if k-j > len(word) {
                    word = s[j:k]
                }
            }
            inWord = false
        } else if !inWord {
            inWord = true
            j = i
        }
    }
    if inWord {
        k = len(s)
        if k-j > len(word) {
            word = s[j:k]
        }
    }
    return word
}

func BenchmarkPeterSO(b *testing.B) {
    for N := 0; N < b.N; N++ {
        for _, s := range []string{"I love dogs", "fun&!! time"} {
            maxWordP(s)
        }
    }
}

var re = regexp.MustCompile(`[A-Za-z]+|[*?()$&.,!]`)

func maxWordM(s string) string {
    matches := re.FindAllString(s, -1)
    var count int
    for i := 0; i < len(matches); i++ {
        if (i+1)%len(matches) > 0 {
            if len(matches[(i+1)%len(matches)]) > len(matches[i]) {
                count = (i + 1) % len(matches)
            }
        }
    }
    return matches[count]
}

func BenchmarkMannu(b *testing.B) {
    for N := 0; N < b.N; N++ {
        for _, s := range []string{"I love dogs", "fun&!! time"} {
            maxWordM(s)
        }
    }
}

var benchTexts = []string{"I love dogs", "fun&!! time"}


Making the basic accumulator in Real World OCaml use Async

It is totally idiomatic and pretty code. My personal style is to put the pipe operators to the end, as they are, at their essence, just functional semicolons, e.g.,

let read_and_accumulate () =
  Reader.lines (Lazy.force Reader.stdin)  |>
  Pipe.filter ~f:(Fn.non String.is_empty) |>
  Pipe.map ~f:Float.of_string |>
  Pipe.fold ~init:0. ~f:(fun x y -> return (x +. y))

With such approach every line starts with a word, not the punctuation that helps the readability.

What concerning the compose function, it didn't work for you because (+.) is binary (in fact it is not binary, but it is a function that returns a function). So, when you compose a return function that has type 'a -> 'b, with some function f : 'c -> 'c -> 'c, then you actually has a type ('c -> 'c) -> 'b, where ('c -> 'c) is the return type of function f. Note, the parenthesis. The ('c -> 'c) -> 'b is not equivalent to 'c -> 'c -> 'b. The first type describes a function, that takes a function and returns a value (i.e., apply-style function), and the latter type describes a function that take a value, and returns a function, that takes another value and computes the result (the curried binary function).


Proper and consistent indentation would improve the readability a lot. Here is mine:

<?php
    $Sql = new mysqli("localhost", "root", "*******", "serveradmin");
    if ($Sql->connect_error) {
        die("Sorry, Could not connect (" . $Sql->connect_errno . ") " . $Sql->connect_error);
    }
    $Data = $Sql->query("SELECT * FROM trial");
    while ($q = $Data->fetch_assoc()) {
        $Start = $q['Start'];
        $Stop = $q['Stop'];
        $Steam = $q['Steam'];
        $Result = $Start - $Stop;
        $Time = time();
        if ($q['Expired'] == "True") {
            echo "All expired \n";
        } else {
            if ($Stop <= $Time) {
                echo "Deleted " . $Steam . " From trial Reason: Expired";
                $Sql->Query("DELETE FROM `sm_admins` WHERE `identity` = '" . $Steam . "'");
                $Sql->Query("UPDATE trial SET `Expired` = 'True' WHERE `Steam` = '" . $Steam . "'");
            } else {
                echo "All ok, 0 deleted";
            }
        }
    }
?>

These conditions are good candidates for guard clauses:

if ($q['Expired'] == "True") {
    echo "All expired \n";
} else {

and

if ($Stop <= $Time) {

Here is the modified version:

while ($q = $Data->fetch_assoc()) {
    $Start = $q['Start'];
    $Stop = $q['Stop'];
    $Steam = $q['Steam'];
    $Result = $Start - $Stop;
    $Time = time();
    if ($q['Expired'] == "True") {
        echo "All expired \n";
        continue;
    }
    if ($Stop > $Time) {
        echo "All ok, 0 deleted";
        continue;
    }
    echo "Deleted " . $Steam . " From trial Reason: Expired";
    $Sql->Query("DELETE FROM `sm_admins` WHERE `identity` = '" . $Steam . "'");
    $Sql->Query("UPDATE trial SET `Expired` = 'True' WHERE `Steam` = '" . $Steam . "'");
}

References: Replace Nested Conditional with Guard Clauses in Refactoring: Improving the Design of Existing Code; Flattening Arrow Code
Furthermore, if you are not interested in those records whose Expired flag is True and Stop attribute is bigger than the current time you could modify the SQL query to filter those records, for example:

$Data = $Sql->query("SELECT * FROM trial WHERE Expired != `True` AND Stop > " . $Time);

(If you are using string concatenation to create SQL commands be careful about SQL injections attacks. The value of $Time comes from the time() function so it can't contain any malicious data here.)
I'd consider using MySQL's datetime attributes for storing the date informations and using MySQL's date and time functions for the comparison. I'd improve the database structure and make the raw data readable. You might want to prepare for situations when the current time is different between the webserver and the database server.
$mysql->query has a return value. You might want to check whether it's FALSE and print a proper error message.
PHP functions are not case sensitive, but according to this answer you might want to modify ->Query(...) to ->query(...).
This line seems unnecessary, since the $Result variable is not used:

$Result = $Start - $Stop;

The delete and update statement uses the $Steam variable as the part of the query without escaping it. I think it could cause 2nd order SQL attacks.


It's fine for your strings - and scraped web content - to be localised in French; but ensure that your variables are in English (groupe -> group) for consistency
Prefer tuples over lists when you have immutable data
Add PEP484 type hints when possible
Do not leave those first four variables in global scope; move them to a function
Consider using f-strings instead of format calls
Always check to see if your requests calls fail; the easiest way is via raise_for_status
Tell requests when you're done with a response via context management
Use actual integers for your department numbers instead of stringly-typed data
Consider using an intermediate dataclass for your agency data instead of implicit tuples
Consider using generator functions (yield) to simplify your iterative code

First Suggested
from dataclasses import dataclass, astuple
from typing import Iterable, Collection

import pandas as pd
import requests
from lxml import html
from lxml.html import HtmlElement

@dataclass
class Agency:
    name: str
    street: str
    postal_code: str

    @classmethod
    def from_block(cls, block: HtmlElement) -> 'Agency':
        return cls(
            name=block.xpath("div/div[1]/h4")[0].text,
            street=block.xpath("div/div[1]/p[1]")[0].text,
            postal_code=block.xpath("div/div[1]/p[2]")[0].text,
        )

def get_nb_pages(group: str, department: int) -> int:
    """ Return nb_pages ([int]): number of pages containing banks information .
    Args:
        groupe ([string]): bank groupe ("credit-agricole",...)
        department ([string]): departement ("01",...)
    """
    url = f"https://www.moneyvox.fr/pratique/agences/{group}/{department}"
    with requests.get(url) as req:
        req.raise_for_status()
        raw_html = req.text

    xpath = "/html/body/div[2]/article/div/div/div[3]/div[2]/nav/a"
    tree = html.fromstring(raw_html)
    return len(tree.xpath(xpath)) + 1

def get_agencies(group: str, department: int, page_num: int) -> Iterable[Agency]:
    """ Return agencies ([List]): description of agencies scrapped on website target page.
    Args:
        groupe ([string]): bank groupe ("credit-agricole",...)
        department ([string]): departement ("01",...)
        page_num ([int]): target page
    """
    url = f"https://www.moneyvox.fr/pratique/agences/{group}/{department}/{page_num}"
    with requests.get(url) as req:
        req.raise_for_status()
        raw_html = req.text

    xpath = '//div[@class="lh-bloc-agence like-text"]'
    tree = html.fromstring(raw_html)
    for block in tree.xpath(xpath):
        yield Agency.from_block(block)

def get_all(groups: Iterable[str], departments: Collection[int]):
    """Return all_agencies ([List]): description of agencies scrapped.
    Args:
        groupes ([List]): target groups
        departments ([List]): target departments
    """
    for group in groups:
        for department in departments:
            nb_pages = get_nb_pages(group, department)
            for page in range(1, nb_pages + 1):
                yield from get_agencies(group, department, page)

def main():
    group = "credit-agricole"
    department = 21
    groups = ("credit-agricole",)
    departments = (53, 44,)  # ...  56, 35, 22, 49, 72, 29, 85)

    n_pages = get_nb_pages(group, department)
    agencies = tuple(get_agencies(group, department, page_num=1))

    all_agencies = get_all(groups, departments)
    df_agencies = pd.DataFrame(
        (astuple(agency) for agency in all_agencies),
        columns=('agence', 'rue', 'code_postale'),
    )

if __name__ == '__main__':
    main()

All of that being the case, your approach using xpath selectors is very fragile. Here is an alternate approach that uses named elements with classes and IDs where available. It is incomplete because I think the site rate-limited my IP, which is of course a direct risk of scraping and totally within the rights of the website.
BeautifulSoup Alternate
import re
from dataclasses import dataclass, astuple
from typing import Iterable, Dict, ClassVar, Pattern
from bs4 import BeautifulSoup, Tag

import pandas as pd
from requests import Session

ROOT = 'https://www.moneyvox.fr'

@dataclass
class Branch:
    name: str
    street: str
    city: str
    postal_code: str
    path: str

    @classmethod
    def scrape_all(cls, session: Session, path: str) -> Iterable['Branch']:
        page = ''
        while True:
            with session.get(ROOT + path + page) as response:
                response.raise_for_status()
                doc = BeautifulSoup(response.text, 'xml')

            body = doc.select_one('div.main-body')
            city = None

            for head_or_cell in body.select('h2, div.lh-bloc-agence'):
                if head_or_cell.name == 'h2':
                    city = head_or_cell.text
                elif head_or_cell.name == 'div':
                    street, postal_code = head_or_cell.select('p')
                    yield cls(
                        name=head_or_cell.h4.text,
                        street=street.text,
                        city=city,
                        postal_code=postal_code.text,
                        path=head_or_cell.select_one('a.lh-btn-info')['href'],
                    )

            # perform depagination here

@dataclass
class Department:
    name: str
    code: str
    path: str
    n_branches: int

    re_count: ClassVar[Pattern] = re.compile(r'\d+')

    @classmethod
    def from_li(cls, li: Tag) -> 'Department':
        return cls(
            name=li.strong.text,
            path=li.a['href'],
            code=cls.re_count.search(li.a.text)[0],
            n_branches=int(cls.re_count.search(li.em.text)[0]),
        )

@dataclass
class Agency:
    name: str
    category: str
    path: str

    @classmethod
    def scrape_all(cls, session: Session) -> Iterable['Agency']:
        with session.get(ROOT + '/pratique/agences') as response:
            response.raise_for_status()
            doc = BeautifulSoup(response.text, 'xml')

        body = doc.select_one('div.main-body')
        category = None
        for head_or_cell in body.select('h2, a.lh-lien-bloc-liste'):
            if head_or_cell.name == 'h2':
                category = head_or_cell.text
            elif head_or_cell.name == 'a':
                yield cls(
                    name=head_or_cell.text,
                    category=category,
                    path=head_or_cell['href'],
                )

    def get_departments(self, session: Session) -> Dict[str, int]:
        with session.get(ROOT + self.path) as response:
            response.raise_for_status()
            doc = BeautifulSoup(response.text, 'xml')

        for li in doc.select('#tabs-departement li'):
            yield Department.from_li(li)

    def __str__(self):
        return self.name

def main():
    pd.set_option('display.max_columns', None)
    pd.set_option('display.width', None)

    with Session() as session:
        agencies = {a.name: a for a in Agency.scrape_all(session)}
        agency_df = pd.DataFrame(
            (astuple(a) for a in agencies.values()),
            columns=('Nom', 'Catégorie', 'Lien'),
        )
        print(agency_df)

        agency = agencies['Crédit Agricole']
        departments = {d.name: d for d in agency.get_departments(session)}

        department = departments['Ardennes']
        branches = {b.name: b for b in Branch.scrape_all(session, department.path)}

if __name__ == '__main__':
    main()


Powershell remote script execution pattern

A couple of things I see, if it is as simple as you suggest. First is the $using: context, where you can use local variables in remote execution. For example, you could remove the parameters from your scriptblock, and not have to pass arguments to the Invoke-Command call by doing this:

$scriptBlock = {
    Import-Module C:\CreateNewObject.psm1
    CombineBothStanzas -firstStanza $using:firstStanza -secondStanza $using:secondStanza
}

Second is that if your .psm1 file has but one purpose, and that is a singular function, why not just make it a script with parameters? Then you don't have to first import it then execute it.

Contents of remote script on server c:\CreateNewObject.ps1:

Param([Parameter(Mandatory=$true)]$firstStanza,[Parameter(Mandatory=$true)]$secondStanza)
return ($firstStanza + $secondStanza).GetEnumerator() | sort -Property name

Putting both of those into use, you end up with something like:

$firstStanza=@{
    a = "Mary had"
    b = "a little"
    c = "lamb"
}

$secondStanza=@{
    d = "its fleece"
    e = "was white"
    f = "as snow"
}

$scriptBlock = {
    . C:\CreateNewObject.ps1 -firstStanza $using:firstStanza -secondStanza $using:secondStanza
}

Invoke-Command -ComputerName serverName.internalDomain.com -ScriptBlock $scriptBlock


First a special problem: Unicode 0 is a terminator char in strings in C/C++.
Modified UTF (i.e. UTF-8) deals with this by also doing the encoding for what officially should be one byte 0. As decoding poses no problem. You might consider this. For instance simply requiring modified UTF-16 on input as you check the terminator.
    if (codepoint <= 0x007F && codepoint != 0) {

Now the actual review:

(Optional) To cope with modified (*str) UTF-16, generating modified UTF-8:
  if (codepoint <= 0x007F && codepoint != 0) {

You are now giving the result to cout using an extra nul byte as terminator.

There should be a byte output stream. An output stream parameter could be appended to per byte, without intermediate arrays; and only at the end might need a NUL byte. If str occupies N UTF bytes, then the result will at most need 2N UTF bytes. _N UTF-16 bytes ~ to N/2 code points ~ max 2N UTF-8 (N/2 * 4-byte sequences)._
That terminator should be added outside the loop.

Creating arrays is superfluous, immediately return the single bytes. (This would be the case for delivering the result somewhat like cout << ((codepoint >> 6) & 0x1F) | 0xC0)

You nicely validate the input for illegal UTF-16 chars above the max. In java one would throw an exception, you just discard the char.

(A matter of taste) Maybe consider an API with a string length as input parameter instead of relying on a NUL terminator. If the area of application is file based, that
would even be more natural.


As you said that you will always have the right number of elements in the array, I would suggest the following:

public class Airport
{
    public string Id { get; set; }
    public string Ident { get; set; }
    public string Type { get; set; }
    public string Name { get; set; }
    public string Latitude { get; set; }
    public string Longtitude { get; set; }
    public string Elevation { get; set; }
    public string Continent { get; set; }
    public string CountryIso { get; set; }
    public string RegionIso { get; set; }
    public string Municipality { get; set; }
    public string ScheduledService { get; set; }
    public string GPSCode { get; set; }
    public string DataCode { get; set; }
    public string LocalCode { get; set; }
    public string HomeLink { get; set; }
    public string WikipediaLink { get; set; }
    public string Keywords { get; set; }

    public static Airport CreateFromData(string[] data)
    {
        if (data.Length != 18) {
            throw new ArgumentException("...");
        }
        return new Airport
                   {
                       Id = data[0],
                       Ident = data[1],
                       Type = data[2],
                       Name = data[3],
                       Latitude = data[4],
                       Longtitude = data[5],
                       Elevation = data[6],
                       Continent = data[7],
                       CountryIso = data[8],
                       RegionIso = data[9],
                       Municipality = data[10],
                       ScheduledService = data[11],
                       GPSCode = data[12],
                       DataCode = data[13],
                       LocalCode = data[14],
                       HomeLink = data[15],
                       WikipediaLink = data[16],
                       Keywords = data[17]
                   };
    }
}

Depending on usage I would suggest that you alter the accessibility of the setters on the properties and consider making the default constructor protected (if you only want to create via a data array).

Why am I making this suggestion?

Keeps it simple
It's about 30 times faster than your method
You can view the code as a schema for the data array. I.e. Type is the third element

Edit

As RufusL notes in the comments, it would be a good idea to add a null check for the data array:

public static Airport CreateFromData(string[] data)
{
    if (data == null) {
        throw new ArgumentNullException("data");
    }
    if (data.Length != 18)
    {
        ...

Further to my comment about my proposed solution being faster - it's not because your code is slow in any way. If you want a dictionary of mappings of property -> index in data array your code will be slower but that probably wont matter.

You could just move your array of property mappings to a field. Just change the signature to Action<Airport,string>[] you'd then populate it like:

Action<Airport, string>[] PropertyMappings =
{
     (a, s) => a.Id = s,
     // ...
}

public static Airport CreateFromData(string[] data)
{
    // Guards omitted.
    var result = new Airport();
    for (var i = 0; i < data.Length; i++)
    {
        PropertyMappings(result, data[i]);
    }
    return result;
}

(all of the code in the edit has just been typed directly in the browser, if it doesn't compile, hopefully it should be close enough to correct.)


Program to insert, search for and delete an element from an array

The easy stuff first...

You should format your code nicer. It makes it easier to read for everyone who uses the same standard formatting style. Use your IDE's reformatting function (Control + Shift + f in Eclipse, Alt + Control + l in IntelliJ) to reformat before posting on forums.

Remove pointless comments. The auto-generated TODO has no place in working code. And this one for example is really stating the obvious:

// array initialization
int[] arr = { 5, 10, 12, 22, 4 };

In general, try to not write comments. If your code is not self-explanatory without comments, try to rewrite it. A common technique is to extract a few lines of code into a method, and the name of the method will explain what those lines do instead of a comment.

You probably you know you're reinventing the wheel, but just for the record, there is an ArrayList<T> class that can do all the things you're doing in your code.

Object-oriented design

The code in the main method is doing all kinds of things, all of them centered around an array, and various manipulations on it, such as:

find the index of an element
remove an element, if exists
print elements

It would make sense to encapsulate all these by a class to keep track of the array and its size. Maybe something like this:

public class ArraysDemo {

    private final int[] values;
    private int size;

    public ArraysDemo(int... values) {
        this.values = values.clone();
        this.size = values.length;
    }

    int indexOf(int value) {
        for (int i = 0; i < size; i++) {
            if (values[i] == value) {
                return i;
            }
        }
        return -1;
    }

    boolean remove(int value) {
        for (int i = 0; i < size; i++) {
            if (values[i] == value) {
                --size;
                for (; i < size; ++i) {
                    values[i] = values[i + 1];
                }
                return true;
            }
        }
        return false;
    }

    void print() {
        System.out.print("Elements in the array: ");
        for (int i = 0; i < size; ++i) {
            System.out.print(values[i] + " ");
        }
        System.out.println();
    }
}

I tried to mimic the methods in ArrayList<T>. This is a good idea to do when you're reinventing the wheel. For example indexOf to find the index of an element, or return -1 if not found. A remove method that returns true if something was removed.

Using this class, you can rewrite the main method like this:

ArraysDemo arr = new ArraysDemo(5, 10, 12, 22, 4);
arr.print();

int index = arr.indexOf(11);
if (index < 0) {
    System.out.println("Element not found");
} else {
    System.out.println("Element found in the position " + index);
}

if (!arr.remove(5)) {
    System.out.println("Element not found");
}
arr.print();

As a final step, the class can be generalized to work with any type, not only integers. When you do that, remember to change all the conditions with == to use the .equals method instead, for example:

public class ArraysDemo<T> {

    private final T[] values;
    private int size;

    // ...

    int indexOf(int value) {
        for (int i = 0; i < size; i++) {
            if (values[i].equals(value)) {
                return i;
            }
        }
        return -1;
    }
}


Validating credit card numbers - Haskell

TL;DR:

toDigits can be expressed with toDigitsRev and vice-versa.
If you use both div and mod, use divMod to get both at the same time.
You can pattern match on two elements in a list with (x:y:xs). That way you only need a single doEveryTwo.
sumDigits is sum . map (sum . toDigits).
doubleEveryOther can be written with mapAccumR, but that might be a little bit too advanced.

All in all, your code will work, but we can improve it.

Write functions in terms of other functions

You have written both toDigits as well as toDigitsRev. However, you only need one of them. The other one is the reversed variant:

toDigits :: Integer -> [Integer]
toDigits = reverse . toDigitsRev

Use divMod if you need both results

You can think of divMod as

divMod x y = (div x y, mod x y)

but it's usually faster. Even better, if all your numbers are guaranteed to be positive, use quotRem, since div and mod have some constraints on their result:

toDigitsRev :: Integer -> [Integer]
toDigitsRev x
  | x <= 0 = []
  | otherwise = r : toDigitsRev q
 where
  (q,r) = x `quotRem` 10 -- x guaranteed to be positive

Use pattern matching to your advantage

You can match on multiple elements in a list at once. That way, you can write doEveryTwo without a helper that skips:

doEveryTwo :: (t -> t) -> [t] -> [t]
doEveryTwo f (x:y:xs) = f x : y : doEveryTwo f xs
doEveryTwo _ [x]      = f x
doEveryTwo _ []       = []

Note that a worker-wrapper approach is usually used here for performance:

doEveryTwo :: (t -> t) -> [t] -> [t]
doEveryTwo f = go
  where
    go (x:y:xs) = f x : y : go xs
    go [x]      = f x
    go []       = []

That way we don't have to carry f along. (Exercise: write doEveryTwo with zipWith. Have a look at cycle if you get stuck).

Use higher order function to your advantage

When you do the same for all elements in a list, it's usually time to use map. If we take a look at sumDigits, we can see that it uses toDigits for all numbers and then sums it:

sumDigits :: [Integer] -> Integer
sumDigits [] = 0
sumDigits (x:xs) = sum (toDigits x) + sumDigits xs

If we write that as list comprehension, it gets more obvious:

sumDigits xs = sum [sum (toDigits x) | x <- xs]

That's the same as

sumDigits xs = sum (map (sum . toDigits) xs)

or

sumDigits = sum . map (sum . toDigits)


Find if a word with wildcard exists in dictionary

At first: This is a really nice question for an interview. You can show off your knowledge of data structures and algorithms here, but you can also demonstrate how familiar you are with your programming language and concepts like test driven development for example.

So, what went wrong here? At the first sight, your solution looks "ok". If you look a little closer, there are some issues:

Data Structures

You were pretty spot on when choosing a tree here. You could have done a little better by calling it with its common name, Trie. That comes from retrieval and is described in detail over here.

This data structure in its simplest form (we don't need any more for solving your problem) consists of trie nodes that have 1.) children where each child is assigned a character and 2.) a marker if this node is the last character of a word (so that we can distinguish a prefix of a word and a complete word).

You tried printing a graph as an example, which unfortunately got lost in formatting. Here is one from Wikipedia:

In your solution, you have used two HashSets (of TreeNodes and chars). I don't understand what the Index set is for, as you didn't include your code for adding nodes. The bigger problem I see here is the type HashSet itself: They describe unordered lists of stuff ("sets"), and you are trying to access them using an indexer (e.g. root.Nodes[str[currentIndex]]). This will not only give unpredicted results, it won't even compile. There is no indexer on HashSet.

What you actually want to use here is a Dictionary. Looking at the graph above, we seem to be navigating along using characters. That means, in every node, having one character we can determine the next node to go to. A dictionary can do that for us.

The whole thing

Rather than trying to come up with some working code during the interview, I would have talked about the architectural and algorithmic features of the to-be-built solution. I guess, if you had written out some unit tests that specify the behavior of the system it would have come out better than writing code that obviously won't even compile.

Let's see how we can easily build the whole thing using TDD (Test Driven Development), writing tests first and then bringing them from red to green by developing and refactoring our Trie.

Please create an empty Unit Test Project and create a new file in there. Add the NuGet package "FluentAssertions". You can paste each method stepwise to see how the solution matures. If there is a [TestMethod] attribute above, add it to the TrieTests class. If there is no attribute, add or update the method in TrieNode.

We start with:

[TestClass]
public class TrieTests
{
    private readonly TrieNode trie = new TrieNode();

    [TestMethod]
    public void AddingDoesntThrow()
    {
        this.trie.Add("word");
    }
}

public class TrieNode
{
    public void Add(string blah)
    {
        throw new NotImplementedException();
    }
}

Ok. We need to add stuff to the trie, so we have an Add. Test will be red. Update Add method:

    public void Add(string blah)
    {
    }

Bam, test is green now. Next one! (Don't do more that you need to make your test green. Deleting the NotImplementedException is enough for now.)

    [TestMethod]
    public void FindEmptyString()
    {
        this.trie.Add("");
        this.trie.Find("").Should().BeTrue();
    }

    public bool Find(string query)
    {
        throw new NotImplementedException();
    }

Test is red.

    public bool Find(string query)
    {
        return true;
    }

Test is green! But wait. What if there is nothing in the trie?

    [TestMethod]
    public void FindInEmptyTrieReturnsFalse()
    {
        this.trie.Find("").Should().BeFalse();
    }

Test is red, because we have no logic at all. Let's add the isWord boolean field and use it:

public class TrieNode
{
    private bool isWord;

    public void Add(string s)
    {
        if (s.Length == 0)
        {
            this.isWord = true;
        }
    }

    public bool Find(string query)
    {
        if (query.Length == 0)
        {
            return this.isWord;
        }

        return false;
    }
}

Okay, our trie works with empty strings! What happens if somebody passes null?

    [TestMethod]
    public void FindWithNullQueryThrows()
    {
        Action find = () => this.trie.Find(null);
        find.ShouldThrow<ArgumentNullException>();
    }

Test is red. We need to check the argument and throw an exception:

    public bool Find(string query)
    {
        if (query == null)
        {
            throw new ArgumentNullException("query");
        }

        if (query.Length == 0)
        {
            return this.isWord;
        }

        return false;
    }

Let's add support for real words now:

    [TestMethod]
    public void FindWordReturnsTrue()
    {
        this.trie.Add("word");
        this.trie.Find("word").Should().BeTrue();
    }

This is the tricky part. To make this work, we have to add the aforementioned dictionary of child nodes. Adding "word" creates child nodes for each character; finding "word" checks if the next child node exists and recurses down the tree: A trie node finds "word" if it has a child node "w" and this child node finds "ord".

public class TrieNode
{
    private readonly Dictionary<char, TrieNode> children
        = new Dictionary<char, TrieNode>();

    private bool isWord;

    public void Add(string s)
    {
        if (s.Length == 0)
        {
            this.isWord = true;
            return;
        }

        var c = s[0];
        var child = GetOrCreateChild(c);

        child.Add(s.Substring(1));
    }

    private TrieNode GetOrCreateChild(char c)
    {
        TrieNode child;
        if (!children.TryGetValue(c, out child))
        {
            child = new TrieNode();
            children.Add(c, child);
        }

        return child;
    }

    public bool Find(string query)
    {
        if (query == null)
        {
            throw new ArgumentNullException("query");
        }

        if (query.Length == 0)
        {
            return this.isWord;
        }

        var c = query[0];
        var child = this.GetChild(c);

        return child != null && child.Find(s.Substring(1));
    }

    private TrieNode GetChild(char c)
    {
        TrieNode child;
        return this.children.TryGetValue(c, out child) ? child : null;
    }
}

We can even add further tests to check if everything works as expected:

    [TestMethod]
    public void FindLongerWordReturnsTrue()
    {
        this.trie.Add("word");
        this.trie.Add("wording");
        this.trie.Find("wording").Should().BeTrue();
    }

    [TestMethod]
    public void FindPrefixReturnsFalse()
    {
        this.trie.Add("word");
        this.trie.Find("wor").Should().BeFalse();
    }

Both green already! Now we still have something to do: We need the wildcard support.

    [TestMethod]
    public void FindWithWildcardReturnsTrue()
    {
        this.trie.Add("word");
        this.trie.Find("w??d").Should().BeTrue();
    }

Instead of looking for one child node, a "?" means looking in all child nodes. We can generalize that: GetChild(char) gets renamed to GetChildren(char) and returns an IEnumerable:

public class TrieNode
{
    private readonly Dictionary<char, TrieNode> children
        = new Dictionary<char, TrieNode>();

    private bool isWord;

    public void Add(string s)
    {
        if (s.Length == 0)
        {
            this.isWord = true;
            return;
        }

        var c = s[0];
        var child = GetOrCreateChild(c);

        child.Add(s.Substring(1));
    }

    private TrieNode GetOrCreateChild(char c)
    {
        TrieNode child;
        if (!children.TryGetValue(c, out child))
        {
            child = new TrieNode();
            children.Add(c, child);
        }

        return child;
    }

    public bool Find(string query)
    {
        if (query == null)
        {
            throw new ArgumentNullException("query");
        }

        if (query.Length == 0)
        {
            return this.isWord;
        }

        var c = query[0];
        var child = this.GetChildren(c);

        return child.Any(x => x.Find(query.Substring(1)));
    }

    private IEnumerable<TrieNode> GetChildren(char c)
    {
        if (c == '?')
            return this.children.Values;

        TrieNode child;
        return this.children.TryGetValue(c, out child)
            ? new[] { child }
            : Enumerable.Empty<TrieNode>();
    }
}

You could add additional features like a collection of values for each trie node or prefix search, but I guess this simple implementation would have solved your question.


Your current code, if I understand it, starts by sieving each target without recognizing that if the target is less than the highest cache (or _base) then it is prime if and only if it in the cache.

One option is to keep your primes in a single cache (_base), make sure that the cache is high as your target, and check if your target is in your cache.

The rough code would have only two functions:  one ensures that base array is high enough, and the other returns the value.   Something like:

const primes = [2, 3, 5];

function ensure_primes(until_n) {
    let n = primes.slice(-1) + 1;
    while (n <= until_n) {
        if (primes.every(prime => n % prime != 0)) {
            primes.push(n)
        }
        n += 1;
    }
}

function is_prime(target) {
    ensure_primes(target);
    return target in primes
}

Is this what you were asking?


I don't like that the FuselageSections silently discards out of
bounds values, throwing an exception would be better.
Maybe there are shorter ways, but Fuselage can use AddRange as
well:

if (diamondShape)
{
    fuselage.AddRange(upDesigns);
    fuselage.AddRange(downDesigns);
}
else
{
    fuselage.AddRange(downDesigns);
    fuselage.AddRange(upDesigns);
}

wantDiamond can just be

bool wantDiamond = sections % 2 == 0;

and that (foo ? true : false or the reverse) is something I'll
always fix if I see it somewhere.
ToString can just be

return String.Join(Environment.NewLine, rocketPartsList);

instead.
Nose, Booster can all just create a copy with the List
constructor, i.e.

return new List<string>(BoosterParts);

and so on.

Otherwise looks fine; if it was actually part of a larger program I'd
move the parts itself into classes and have them output (ToString)
themselves instead.


It seems to me that this would be equivalent but shorter:

def get_sha():
    repo = os.listdir('.')[0]
    sha = subprocess.check_output(['git', 'rev-parse', 'HEAD'], cwd=repo).decode('ascii').strip()
    return sha

Because, . is essentially the same as os.environ['PWD'],
with the difference that it's not an absolute path.
Since subprocess.check_output(..., cwd=...) works fine with relative paths too,
I don't see the reason to use an absolute path, and so no need for PWD.

But more importantly,
I find it a bit odd that this script assumes that the first entry in the directory listing is a Git repository.
This setup seems a bit fragile.
It would be better to pass the repo path as a parameter to this function:

def get_sha(repo):
    sha = subprocess.check_output(['git', 'rev-parse', 'HEAD'], cwd=repo).decode('ascii').strip()
    return sha

Then you'd have something simple, clear, no questions asked.


Create directories for outputs based on setting

Any time there's a repeating pattern that's very obvious like this you
might consider using another loop, or a function, or some other
abstraction mechanism available.  To me this also looks like example
code - please post the actual code you're using!

So first a few comments:

x is True isn't very idiomatic unless you really want to check for
specifically one of the true values, True.  Otherwise just write
that as x (keeping in mind that some values like the empty tuple or
list are actually falsy.
Some expressions are repeated in the if test and the body of the
if - in those cases you likely want to have a variable to only
evaluate the expression once for better readability.
Consider using some functional idioms like
map to make
the code more succinct too.
Take a look at PEP8 for
variable naming - in Python it's usually
snake case.

So how with that said, how could this all look like?

for path in map(os.path.dirname, file_path_list):
    x = os.path.join(path, settings['outputDirNameOut1'])
    if not os.path.exists(x):
        os.makedirs(x)

    y = os.path.join(path, settings['outputDirNameA'])
    if settings['A'] and not os.path.exists(y):
        os.makedirs(y)

    z = os.path.join(path, settings['outputDirNameB'])
    if settings['B'] and not os.path.exists(z):
        os.makedirs(z)

    a = os.path.join(path, settings['outputDirNameC'])
    if settings['C'] and not os.path.exists(a):
        os.makedirs(a)
        os.makedirs(os.path.join(path, settings['outputDirNameOut2']))

    b = os.path.join(path, settings['outputDirNameOut2'])
    if settings['D'] and not os.path.exists(b):
        os.makedirs(b)

Now you just have to come up with more sensible variable names.  Also I
have the feeling that the double makedirs in the fourth case is a
copy&paste error?

Going with that assumption this can be simplified further:

names = ['outputDirNameOut1', 'outputDirNameA', 'outputDirNameB',
         'outputDirNameC', 'outputDirNameOut2']
dirs = [settings[name] for name in names]
for path in map(os.path.dirname, file_path_list):
    for dir in dirs:
        x = os.path.join(path, dir)
        if not os.path.exists(x):
            os.makedirs(x)

At that point I can't see any more obvious changes.

Edit: That assumption doesn't hold and I also skipped some part of the
logic.  Therefore I'd suggest writing and using a local function:

def foo(name):
    x = os.path.join(path, settings[name])
    if not os.path.exists(x):
        os.makedirs(x)

for path in map(os.path.dirname, file_path_list):
    foo('outputDirNameOut1')

    if settings['A']:
        foo('outputDirNameA')

    if settings['B']:
        foo('outputDirNameB')

    if settings['C']:
        foo('outputDirNameC')
        foo('outputDirNameOut2')

    if settings['D']:
        foo('outputDirNameOut2')


I'm not pretend to full review, but I guess better so than nothing.

Golang allow swapping in one-line, so you can just do so:

arr[i-1],arr[i] = arr[i],arr[i-1]
Go does not have optional parameters nor does it support method overloading.So if you want implement more "usually" version of this sort - provide utility function which will take arguments for range:

// merge sort algorithm
func merge_sort(arr []int, l, r int) {
    if l < r {
        m := (l + r) / 2
        mergeSort(arr, l, m)
        mergeSort(arr, m+1, r)
        merge(arr, l, m, r)
    }
}

func mergeSort(arr []int) {
    merge_sort(arr, 0, len(arr)-1)
}

In your current code very often used function append, it's not very effective. As example I just re-write C code from here and get:

func merge(arr []int, l, m, r int) {

    i := 0
    j := 0
    k := 0

    n1 := m - l + 1
    n2 := r - m
    L := make([]int, n1)
    R := make([]int, n2)
    for i < n1 {
        L[i] = arr[l+i]
        i++
    }
    for j < n2 {
        R[j] = arr[m+1+j]
        j++
    }

    i = 0
    j = 0
    k = l

    for i < n1 && j < n2 {
        if L[i] <= R[j] {
            arr[k] = L[i]
            i++
        } else {
            arr[k] = R[j]
            j++
        }
        k++
    }

    for i < n1 {
        arr[k] = L[i]
        i++
        k++
    }

    for j < n2 {
        arr[k] = R[j]
        j++
        k++
    }
}

About concurrent implementation - read this question and answers
and this one.


Apply stock quote changes using observer pattern

1. If you are implementing this pattern for learning, then it is OK.

Otherwise, you can use built-in Observer Pattern of C#.

2. Think about readable:

    public void UnRegister(IObserver o)
    {
         int idx = observers.IndexOf(o);

         observers.RemoveAt(idx);

     }

 }

There are some redundant empty lines in your code. Inaddition, "o" is not a good variable name. I think you can change it to "observer".

3.You don't need to retrieve index of an object and then you remove it via the index. It will reduce the performance:

      public void UnRegister(IObserver o)
      {
          int idx = observers.IndexOf(o);

          observers.RemoveAt(idx);

       }

You can use Remove() method to remove an object from the list directly:

    public void UnRegister(IObserver o)
    {
        observers.Remove(o);
    }


Using Threading.Event to signal main thread

Yes and no. Your approach works, and it is easy to understand. If, however, you want to keep track of what type of exception was raised, it could be improved. What if you have some super complex function that can raise 10 different exceptions, and you need access to the exception traceback if something goes wrong? You'd need 10 threading.Event instances. In that case, you should use a queue.Queue instead, which is thread-safe (untested snippet):

import queue
import threading

def dividebyzero(first, second, exc_queue):
    try:
        result = first / second
    except ZeroDivisionError as exc:
        exc_queue.put(exc)
    else:
        print(result)

excq = queue.Queue()
t = threading.Thread(target=dividebyzero, args=(10, 0, excq))
t.start()
t.join()
if excq.qsize() != 0:
    print(excq.get())

No, it is not mandatory to use threading.Event.wait(). Your observation is right: calling event.wait() might make the thread hang indefinitely.
goto 1;


Assign a unique number to duplicate items in a list

As you've already implemented Curtain.__eq__, if you also implement Curtain.__hash__ you can use it as a dictionary (or collections.Counter...) key, or a set member:

def __hash__(self):
    return hash(self.type) ^ hash(self.fabric)

Now make_unique is trivial:

def make_unique(self, original_list):
    return set(original_list)

(Note: if you require order to be retained, this will need additional work.)

This also allows you to easily determine how many of each distinct Curtain you have:

>>> from collections import Counter
>>> Counter(curtains)
Counter({<__main__.Curtain object at 0x02A15190>: 3,
         <__main__.Curtain object at 0x031A0CF0>: 2,
         <__main__.Curtain object at 0x031A0ED0>: 2,
         <__main__.Curtain object at 0x0329EA30>: 1})

(Note: implementing Curtain.__repr__ would make this more readable!)

As pointed out in the comments, the __hash__ implementation I suggest has an issue - if either attribute type or fabric is changed, the hash will be different. You could protect these attributes by making them "read-only" using properties:

class Curtain(object):

    def __init__(self, type, ...):
        self._type = type # note leading underscore on attribute

    @property # defining setter but no getter
    def type(self):
        return self._type

Alternatively, you can implement Curtain.__lt__ etc., then sort the list and use itertools.groupby to get your groups of "equal" Curtains.

Either way, I would not implement CreatSet as a class, there's no need (as should be clear from the fact that there is no __init__ and no class or instance attributes). Just have one class, and two functions:

class Curtain(object):
    ...

def create_set(curtains):
    ...

def make_unique(curtains):
    ...

Your code is generally compliant with the style guide (well done!) but you could do with some explanatory docstrings.


It looks fine overall, but...

A few pointers

You should make private String value final too though, to clearly indicate that they cannot be modified after instantiation.
One thing to note for values() is that it always returns a new array, so for that reason, sometimes it may be recommended to also construct a lookup Map<String, SecurityClassification> to avoid the extra arrays creation.
Also, is it really OK to just return null if an invalid security classification is specified here? Depending on your implementation, you may want to consider whether you should throw an IllegalArgumentException here to have a slightly better modelling of such cases.
How is hasValue() used? In fact, can it be used in enumForValue() for a case-insensitive comparison?
Finally, enumForValue() may seem like a mouthful, you can consider a shorter name like of(). The other thing to consider is that you don't really need to express that it's an enum this method is returning.


Image-processing filters using decorator pattern in Python 3

First of all, since Python is dynamically typed, there is not really a need for interfaces. That’s why there is no such language concept. So your IImage type does not really serve any need.

Similarly, the base type ImageDecorator is not really that useful. In statically typed language you are using these design patterns, and ultimately such a base type, because you need to interact with some common base type. Since we have duck typing in Python, this is not really necessary.

Following the Zen of Python, “Simple is better than complex”; and looking at those classes you wrote, it looks somewhat complex to me considering what it does. Compare it with the following solution:

#!/usr/bin/python3
import PIL.Image, PIL.ImageFilter, PIL.ImageOps

def blur(image, radius):
    return image.filter(PIL.ImageFilter.GaussianBlur(radius))

def flip(image):
    return PIL.ImageOps.flip(image)

im_obj = PIL.Image.open('lena.gif')
im_obj = im_raw.convert('L')
im_obj_flipped = flip(im_obj)
im_obj_flipped_blurred = blur(im_obj_flipped, 5)

im_obj.show('original')
im_obj_flipped.show('flipped')
im_obj_flipped_blurred.show('flipped and blurred')

I think this is a lot more to the point, and it shows exactly what’s going on without unnecessarily wrapping the image in an object that does not really serve any purpose.

Of course, I don’t know if your BaseImage is actually needed for something; but if it’s just what you’re showing here, then it’s just a wrapper that doesn’t do anything on its own. You should avoid creating types that don’t have any behavior, especially if they only contain a single object. It’s much easier to just use that actual object then instead.

That being said, if the BaseImage actually is more complicated, then you can still keep your filters simple:

def blur(image, radius):
    rawImage = image.get_img_obj()
    modifiedImage = rawImage.filter(PIL.ImageFilter.GaussianBlur(radius))
    return BaseImage(modifiedImage)

def flip(image):
    rawImage = image.get_img_obj()
    modifiedImage = PIL.ImageOps.flip(rawImage)
    return BaseImage(modifiedImage)

Now you retain your image type, even after the transformation.


Finding solutions on GitHub and Stack Overflow

Selenium
Selenium imposes a lot of overhead and complexity that you don't need to deal with. If you needed to scrape, use requests + beautifulsoup; but you don't: StackExchange has a good API, so you should strongly prefer using that. It will get you results more efficiently and the results will be more accurate and less fragile.
PEP8
class github :

should be
class Github:


Count digits in a given number using recursion

pro:

code is clean and easy to understand

con:

a recursive solution may not be optimized to a loop by your interpreter so there might be a lot of memory (stack) waste because of the recursion overhead. (So you could implement it as a loop instead of a recursion)
You do not need the if(abs(x) / 10 == 0) branch. So to simplify your code you could remove it.

Simplified recursive code:

def ndigits(x):
    # Assume for the input 0 the output is 0
    if(x == 0):
        return 0
    else:
        return 1 + ndigits(abs(x) / 10)

Simplified tail-recursive code:
end-recursive methods are likely to be detected by the interpreter and transformed to a loop. So this code might be faster and may nor waste memory.
For more information see wikipedia Tail call

def ndigits(x):
    return ndigits_(0, abs(x))

def ndigits_(s,x):
    if(x == 0):
        return s
    else:
        return ndigits(s+1, x / 10)


I avoid using namespace std;.

cout << "Enter Number Of Persons:";
int n;     //This is the number of objects that the user wants to make.
cin >> n;

Personally, I always use getline to capture a line at a time when using std::cin for interactive input. The fact that >> stops at whitespace means that it is very easy for the user to enter two fields in a single line and then the second field gets used at a subsequent point in the program without the user being able to respond to a later prompt.

Also you should always check whether the input operation succeeded.

std::string inputline;
if( std::getline( cin, inputline ) )
{
    std::istringstream iss( inputline );
    if( iss >> n )
    {
        // success
    }
    else
    {
    }   // fail
}
else
{
    // fail
}

catch(bad_alloc xa)
{
    cout<<"Sorry,Program Can Not Continue";
    cin.get();
    exit(1);
}

For all that you actually do in the exception handler, you may as well let the expection propogate. The runtime might actually give a more meaningful error message for bad_alloc. Also, unless you have a good reason, always catch exception by const reference. e.g. catch( const std::bad_alloc& ba ).

Looking at your definition of Persons, I think that Person is a better name for the class. I see one name and one address member, if the class represented multiple people (e.g. a household) you would need at least multiple names, I would have thought.

Always try and avoid needing to use delete[] explicitly. Here a vector would be much simpler and safer.

std::vector<Person> persons(n);

int Persons count;//initializing the static member

Class static variables are normally not advisable. This isn't valid, it should be:

int Persons::count;

In this program it isn't giving you anything that n isn't so I would just remove it.

Persons::Persons()
{
    name_="";
    address_="";
    id_number_=0;
    count++;
}

Always prefer to initialize member variables. Assigning "" to a newly constructed std::string is redundant so you could do either.

Persons::Persons()
    : name_()
    , address_()
    , id_number(0)
{
    count++;
}

or even this (although some people prefer an explicit initializer for all members and bases).

Persons::Persons()
    : id_number(0)
{
    count++;
}

for(int i = 0; i< n; i++)
{
    ptr[i].getData(n);
}
for(int j = 0; j< n; j++)
{
    ptr[j].displayData( n );
}

Why do getData and displayData take an int? They don't use the parameter, and I don't understand why you are passing n.

cin.get();

This seems redundant.

void Persons::getData(int n)
{

        cout<<"Enter Name (Press '$' To Exit):";
        getline(cin,name_,'$');
        cout<<endl<<"Enter Address (Press '$' To Exit):";
        getline(cin,address_,'$');
        cout<<endl<<"Enter Identitiy Card Number:";
        cin>>id_number_;

}

Again, my comments about the unused parameter, always using getline and always checking the success of input operations all apply.


Filtering out illegal moves from a map of available moves

You can iterate once by using remove in combination with a set of illegal moves:

(defn- filter-moves [moves can-split? can-double?]
  (let [illegal? (cond-> #{}
                   (not can-split?) (conj :split)
                   (not can-double?) (conj :double))]
    (into {} (remove #(illegal? (second %)) moves))))

What's more, If I understand correctly that moves is the map mapping keys to moves. In my opinion, this map has no place in your core game logic: have your filter-moves function manipulate only sets of moves and keep any notion of user input at the edge of your system.


Optimize the CSV Upload function in Ruby On Rails

The following code is not tested, maybe some minor changes will be necessary: I'm not 100% sure it will work as is, don't hesitate to tell me if there is anything wrong with the code

Refactoring the existing code

The first thing I did was to set the headers option to true it will enable the parsing of the first line of the CSV and instead of giving you an array for each row it will return an hashmap with keys extracted from the header. It replace the code you wrote to parse the header of the file.

Then I replace the imbricated ternary operations to use a case when expression for the business_type_id which is far more readable.

Next I made two small function to extract all the needed values, I use reduce to automatically fill a hashmap from an array of symboles.

At least I merge all the hashmap in the constructor of the target_model before saving.

CSV.parse(csv_file, {headers: true, header_converters: :symbol}) do |row|
  business_type_id =  case row[:business_type_id]
                        when 'Online' then 1
                        when 'Local' then 2
                        else 3
                      end

  target_model.new( {business_type_id: business_type_id} + extract_required_fields(row) + extract_optionals_fiels(row) )
              .save()

end

def extract_required_fields(row)
  [:user_id, :name, :country_id, :free_shipping, :category_ids, :style_ids, :shipping_country_ids]
    .reduce({}) do |carry, item|
      carry[item] = row[item]
  end
end

def extract_optionals_fiels(row)
  [:homepage, :telephone, :email, :address, :facebook, :twitter, :google, :instagram, :pinterest, :ship_details]
    .reduce({}) do |carry, item|
      carry[item] = row[item] ||= ''
  end
end

Bulk update

But this code, even if it has a better separation of concern and less duplication will not really speed your import process because your performance bottleneck is in the insert operation performed for each item by the save method.

So the solution is to make a bulk update instead of saving each row separately: you'll group the insert !

To do so, you can use the https://github.com/zdennis/activerecord-import gem which will allow you to do something like this :

entities = []
CSV.parse(csv_file, {headers: true, header_converters: :symbol}) do |row|
  business_type_id =  case row[:business_type_id]
                        when 'Online' then 1
                        when 'Local' then 2
                        else 3
                      end

  entities << target_model.new( {business_type_id: business_type_id} + extract_required_fields(row) + extract_optionals_fiels(row) )
  target_model.import entities if entities.size == 100
end

#don't forget to save the remaining entities:
target_model.import entities unless entities.size == 0

In this case we proceed the save operation each 100 row, which will make the import process way faster !

Getting the Thread's ID

To collect the thread's Id, I suggest to use the inspect method of the current_thread, you'll get more information than only the thread's id but you'll be able to have all the needed informations about which thread processed the insert operation.

thread_identifier = Thread.current.inspect


Your implementation looks good to me.  From the NSCopying reference:

Your options for implementing this protocol are as follows:
Implement NSCopying using alloc and init... in classes that don’t inherit copyWithZone:.
Implement NSCopying by invoking the superclass’s copyWithZone: when NSCopying behavior is inherited. If the superclass implementation might use the NSCopyObject function, make explicit assignments to pointer instance variables for retained objects.
Implement NSCopying by retaining the original instead of creating a new copy when the class and its contents are immutable.
If a subclass inherits NSCopying from its superclass and declares additional instance variables, the subclass has to override copyWithZone: to properly handle its own instance variables, invoking the superclass’s implementation first.

So you just need to know that if you are going to have classes that inherit from your MTSound, they will need to call [super copyWithZone] first, and then initialize their own instance variables after that.
You may also want to consider the first option of simply using alloc and init.  If it is okay with Apple, then it should be alright for you to do it too, if you want.
Looking at the reference examples, it also seems perfectly fine to ignore the NSZone argument that is passed into copyWithZone.  It seems to be common practice to ignore that argument.  This Stack Overflow answer talks more about NSZone if you are interested.
I have just a couple more comments about the code.  It seems to me that these comments:
// Initializers
// Class factory methods
// NSCopying protocol

Would be more useful as pragmas, or could be removed completely.  If you do this instead:
#pragma mark - Initializer

Then you will get a bold heading in the method browser in Xcode, which can be useful for finding specific methods in a class.  This is definitely a matter of preference, but simple comments like you have are not that useful and are a bit redundant.
Is there a reason that your properties such as @property (nonatomic) float frequency; are not readonly?  From reading the code, I cannot tell if they will be modified later, or if the values will always stay the same.  If they will always stay the same, I think readonly would be appropriate.
Overall the code is very clean and easy to understand.


Functional Sieve of Eratosthenes in Clojure

Is there a way to avoid the cond dispatch in naïve-prime??

You could do naive-prime? this way:

(defn naive-prime? [n]
  (and
       (>= n 2)
       (->> n
            (inc)
            (Math/sqrt)
            (range 2)
            (not-any? #(zero? (rem n %))))))

This gets rid of the special cases 1 and 2. The trick is to increment before applying Math/sqrt, so that the edge case 2 works correctly.

I've also elided the not into the some to produce not-any?.

  I'd mainly like recommendations for speeding this up.

Try

(defn sieve-primes [n]
  (loop [p 2 ; First prime
         marked #{} ; Found composites
         primes []]
    (let [mults (range (* p p) (inc n) p)
          next-p (->> p
                      (inc)
                      (iterate inc)
                      (remove marked)
                      (first))

          new-primes (conj primes p)]

      (if (>= (* next-p next-p) n)
        (into new-primes (remove marked (range next-p (inc n)))

There are a couple of changes here.

Generate  mults as a range, starting at (* p p) - the first
number that needs to be tested with prime factor p.
Stop testing when the prime you would use, next-p, squared is
bigger than the limit n.

I don't like the idea of building a massive set of composites. Better turn the algorithm inside out and test each number as it occurs against only the necessary prime factors. But that's a quite different algorithm.


I agree that it is too long. I find a good place to start is to try breaking it up into methods that are short and each do a single thing. While I'm doing this I usually see opportunities to make things DRY.

My code might look like:

content_tag(:table, ...) do
  header_row + week_rows
end

def week_rows
  num_rows = (first_day + last_day) % 7
  rows = num_rows.times.map { |i| week_row(i) }
  content_tag(:tbody) do rows.join('')
end

A couple of things I noticed:

Instead of hard-coding html like "<table class='table-condensed table-bordered table-striped'><thead><tr>" use the Rails content_tag helper
Instead of date.at_end_of_month.strftime('%w').to_i use the wday method. There is also a day method that you can use instead of %d.
Have your method return a string that is already html_safe


I don't understand why encryption would be "hard" - the code above looks straightforward enough although I'm not sure you need the padding (never tried the new crypto APIs).

Do note that if you want to secure your UUIDs (why?), you probably want to add a random IV to your UUIDs otherwise you'll probably expose too much information - UUIDs have some bits very static. Generally speaking, rolling your own crypto protocol is fraught with error; I would use an existing library like Hashids (https://hexdocs.pm/hashids/Hashids.html) because that protocol has been analyzed and you're probably better off with the mild known weaknesses in such a library than some huge unknown weakness lurking in roll-your-own :).

But for all practical purposes, generating v4 UUIDs using a cryptographically strong RNG should be all you need.


I would strongly recommend creating a class.

class Student:
    def __init__(self, id, graduated):
        self.id = id
        self.graduated = graduated

Then your problem is easier.

graduatedchemistry = [student for student in chemistry if student.graduated]

To cleanly get graduates from all classes then you can make a function

def getgraduates(students):
    return [student for student in students if student.graduated]

graduatedchemistry = getgraduates(chemistry)
graduatedmath = getgraduates(math)


No, this method cannot be improved because it is completely wrong I am afraid.

Fact: Sessions are not thread safe, don't try make them thread safe, because you don't know how to do it and there are reasons why they are not thread safe.You can simply return the Session from the factory like this

public static Session getHibernateSession() throws SQLException{
   Session session = HibernateUtil.getSessionFactory().openSession();
   return session;
}

The main problem in your code is this

 catch(Exception e){
            LOGGER.error("Exception: ", e);
            session.close();
            session = HibernateUtil.getSessionFactory().openSession();
  }

What you trying to do here? Forcing the code to get a connection?You can't do that. If you fail to open a connection first time, I doubt you will get it in 2 nanoseconds time.
If you don't want to create too many instances, then you should let your IoC container manage it for you. You don't have an IoC container? Then get a Session object every time you need it and don't forget to close it when you are done

  try(Session session = getHibernateSession()){
   // use it
  }


Arguably a better variant for DeflateArray:

private decimal[] DeflateArray(decimal[] items, decimal deflateRate)
{
    return items
        .Select((item, index) => item /= PowerOf(1 + deflateRate, index))
        .ToArray();
}

It's better in a way it helps avoiding OBOE.

And by the way, another thing you can do is define it as an extension method in a separate static class, and will be able to invoke it as myArrayOfDecimals.DeflateArrayWithRate(1.5m):

public static class DecimalArrayExtensions
{
    public static decimal[] DeflateArrayWithRate(this decimal[] items, decimal deflateRate)
    {
        return items
            .Select((item, index) => item /= PowerOf(1 + deflateRate, index))
            .ToArray();
    }

    private static decimal PowerOf(decimal x, decimal y)
    {
        return (decimal)Math.Pow((double)x, (double)y);
    }
}