Getting the remaining days of the current week

First of all, never calculate dates yourself. If possible, always defer to a library that's built by people who know more about dates, who keeps rules up to date, and has more eyes on it to spot bugs than you and your code. For that, I forward you to moment.js. With that, calculating the remaining week days would be as simple as finding today's day number with day and subtracting it from 6 (Saturday's number).

const daysUntilWeekend = 6 - moment().day()

For work days (week days sans holidays) you simply need at least 3 moment instances, the first representing the start of the week, the second representing the end of the week, and the third (or more) representing the holidays. Then you can use isBetween to check if any of your holiday dates fall between the first two, and subtract how many match from 6 accordingly.

// May fail when today's saturday or sunday. Adjust this code accordingly.
const start = moment().day(1).startOf('day')
const end = moment().day(6).startOf('day')
const holidayMoments = [moment(), moment()] // Holiday dates in moments
const holidays = holidayMoments.filter(h => h.isBetween(start, end)).length
const today = moment().day()
const remainingWorkDays = 6 - (today + holidays)


Using Models and Entities in MVP pattern

It's not clear exactly what you're referring to as Model classes, I think you're over-thinking it.

I'd go with the else snippet, the POCO (Plain Old CLR Object) that does nothing but exposing auto-properties. The snippet that exposes a public Advance field doesn't look right. Do not expose public fields; a class should expose properties, not fields.

Your remark about only using VS isn't clear either: if you're not using EF, that's fine, but this means your data access code is using some data access library - Visual Studio isn't one, it's your IDE; if you're using things under System.Data, you're using ADO.NET.

If I understand correctly what you're doing, you have a bunch of tables/entities that have columns/properties in common, and you're wondering if composition would be better than repeating the properties on all classes. You forgot an option: inheritance.

Composition is normally favored over inheritance, but in the case of POCO classes composition can greatly complicate matters, and if you're instantiating your POCO's from an SqlReader it doesn't really matter how that's done, since you completely own the process.

Things are different with EF - composition would lead to a database model similar to this:

With inheritance, you have this (I hope I got the UML right):

Which involves 3 classes, but works off only 2 tables: Advance isn't really an entity, it's just a base class with properties that are common to DeductionInfo and AdvanceInfo.

Hence, if what you intend to do is to model 2 tables, I'd do this:

public abstract class AdvanceBase
{
    public int AdvanceID { get; set; }
    public decimal AdvanceAmount { get; set; }
    public DateTime AdvanceEnteredDate { get; set; }
    public DateTime AdvanceProcessDate { get; set; }
}

The class is made abstract, to enforce the concept that such a class shouldn't be instantiated and serve as a base class for derived types instead:

public class AdvanceInfo : AdvanceBase
{
    public int EmployeeID { get; set; }
    public string NameWithInitials { get; set; }
    public string BankAccountName { get; set; }
    public string BankAccountNumber { get; set; }
}

The AdvanceInfo class inherits the AdvanceID and everything else from AdvanceBase, so you don't need to specify them again.

Then you'll have:

public class DeductionInfo : AdvanceBase
{
    /* DeductionInfo members */
}

And here also, the class will inherit the AdvanceBase members so you only need to code the DeductionInfo-specific members in that class.

And if/when you switch to EF, you can reuse the exact same POCO classes as entities, without changing anything.

Side note, I think the naming of the classes is somewhat bad - I'd call AdvanceInfo just Advance, and DeductionInfo would be simply Deduction.


Program to delete directories that do not contain a file

I didnt check the correctness of code, but...

Small tips on comments:

Don't write #end if. You have identation. Why do you need it?
Comments for functions should look like

def hasFile(p_path):
    """Returns true if the given directory or any of its children directories have a file in them"""
    for r, d, f in os.walk(p_path):

https://saddlebackcss.github.io/tutorials/python/basic/2016/01/14/python-basics-4

Methods should be called like folder_cleanupand has_file. See https://visualgit.readthedocs.io/en/latest/pages/naming_convention.html

Do not name variables like this for r, d, f in os.walk(p_path):. Make names more meaningfull

Try to reduce nesting, may be  using early return


Optimization of region of interest (ROI) drawing in the image

Well, you could try literally darkening the outside of the image by 25%, not by creating a 25%-opaque black area but just by calculating the pixel color values of the same color 25% darker, without the need to create a new 32bbp bitmap.

This might help: Formula to determine brightness of RGB color (StackOverflow). Based on this, let's say you choose Y = 0.2126 R + 0.7152 G + 0.0722 B as your luminance formula and 0.75 and the new brightness of the outside part of the image -- each pixel should be changed to:

Y = 0.75 * (0.2126 * R + 0.7152 * G + 0.0722 * B)
(R, G, B)' = (R - Y * 0.2126, G - Y * 0.7152, B - Y * 0.0722)

(Twice I realized that the formula I put here was quite wrong... this time I'm more confident, but it might be that this makes no sense when painted, I haven't tested it.)

This would require iterating through each individual pixel outside the central square, so not sure if it will be faster in the end... But as will all things performance, only measurements will tell!


You're right, you can cut down on the repetition of code. Although bundling all of the functions into one like you mention would work, you lose a bit of the readability that keeping them as class methods gives. Instead, you could just have an internal _command method that collects all of the repeated code:

def _command(self, command_name, required, **kwargs):
    if not any(arg in required for arg in kwargs):
        raise InvalidParameters("Missing object of types: " + ", ".join(required))
    return self._request(json={kwargs, {"command": command_name }})

Note that I've corrected a syntax error in the last line: your parameter used to read json={**kwargs, **{"command": command_name }}.

This makes your Chaos class a lot shorter:

class Chaos(object):
    """This class allows access to the Andrews & Arnold API.

    Note that it is based on trial and error, there is very little
    official documentation about this API yet, so use at your own risk.
    """

    def __init__(self, username, password):
        """Initialize the class.

        Use the same credentials as on control.aa.net.uk.

        Args:
            username: username like xx00@x
            password: self-explanatory
        """
        self.session = requests.session()
        self.session.headers["User-Agent"] = "Python Chaos Client"
        self.session.auth = (username, password)

    def _request(self, **kwargs):
        """Make an API request, lets Requests check the HTTP status code
        then checks if the "error" string is present in the response
        and raises an exception if that's the case.

        Args:
            **kwargs: will be passed as-is to python-requests
        Returns:
            a dict representation of the APi'S JSON reply
        Raises:
            Exception: the remote server returned an error
        """

        resp = self.session.post(BASE_URL, **kwargs)

        if resp.status_code != requests.codes.ok:
            resp.raise_for_status()

        resp = resp.json()

        if "error" in resp:
            raise APIError(resp["error"])

        return resp

    def _command(self, command_name, required, **kwargs):
        """Make an API request, checking that the arguments are valid

        Args:
            command_name: the command name to be passed to the API
            required: a list of names of required arguments
            **kwargs: will be passed as-is to python-requests
        Returns:
            a dict representation of the APi'S JSON reply
        Raises:
            InvalidParameters: the wrong set of arguments was given
        """

        if not any(arg in required for arg in kwargs):
            raise InvalidParameters("Missing object of types: " + ", ".join(required))

        return self._request(json={kwargs, {"command": command_name }})

    def info(self, **kwargs):
        return self._command('info', [], **kwargs)

    def change(self, **kwargs):
        return self._command('change', ["broadband", "sim", "voip"], **kwargs)

    def check(self, **kwargs):
        return self._command('check', ["order"], **kwargs)

    def preorder(self, **kwargs):
        return self._command('preorder', ["order"], **kwargs)

    def order(self, **kwargs):
        return self._command('order', ["order"], **kwargs)

    def usage(self, **kwargs):
        return self._command('usage', ["broadband", "sim", "voip"], **kwargs)

    def availability(self, **kwargs):
        return self._command('usage', ["broadband"], **kwargs)

Since _request only ever gets called by _command you could compress this further by making them one function, but it's fine as is.

As a side note, this code only checks that the minimum set of arguments is given. Depending on your API, it might be a problem if you give extra arguments that aren't required or supported.


Here is how I would rewrite your code, comments to follow.

simulated_annealing <- function(func, s0, niter = 10, step = 0.1) {

   # Initialize
   ## s stands for state
   ## f stands for function value
   ## b stands for best
   ## c stands for current
   ## n stands for neighbor
   s_b <- s_c <- s_n <- s0
   f_b <- f_c <- f_n <- func(s_n)
   message("It\tBest\tCurrent\tNeigh\tTemp")
   message(sprintf("%i\t%.4f\t%.4f\t%.4f\t%.4f", 0L, f_b, f_c, f_n, 1))

   for (k in 1:niter) {
      Temp <- (1 - step)^k
      # consider a random neighbor
      s_n <- rnorm(2, s_c, 1)
      f_n <- func(s_n)
      # update current state
      if (f_n < f_c || runif(1, 0, 1) < exp(-(f_n - f_c) / Temp)) {
         s_c <- s_n
         f_c <- f_n
      }
      # update best state
      if (f_n < f_b) {
         s_b <- s_n
         f_b <- f_n
      }
      message(sprintf("%i\t%.4f\t%.4f\t%.4f\t%.4f", k, f_b, f_c, f_n, Temp))
   }
   return(list(iterations = niter, best_value = f_b, best_state = s_b))
}

sol <- simulated_annealing(schaffer, s0 = c(0, 2))
#  It   Best    Current Neigh   Temp
#  0    0.5722  0.5722  0.5722  1.0000
#  1    0.1054  0.1054  0.1054  0.9000
#  2    0.1054  0.1922  0.1922  0.8100
#  3    0.1054  0.1922  0.3579  0.7290
#  4    0.1054  0.1922  0.9059  0.6561
#  5    0.1054  0.6428  0.6428  0.5905
#  6    0.1054  0.8893  0.8893  0.5314
#  7    0.1054  0.1597  0.1597  0.4783
#  8    0.1054  0.6489  0.6489  0.4305
#  9    0.1054  0.7535  0.7535  0.3874
#  10   0.1054  0.2236  0.2236  0.3487

sol
# $iterations
# [1] 10
#
# $best_value
# [1] 0.1053682
#
# $best_state
# [1] -0.3203791  1.7080835

Now the comments, in no particular order:

when defining your function, you meant to name the first argument  func, not schaffer. That was a bug.
niter and steps are the kind of arguments that could use an optional value so I made it so. And once an argument has an optional value, it is recommended to move it to the end of the argument list, hence function(func, s0, niter = 50, step = 0.1).
I renamed T to Temp for 1) it is more descriptive and more likely to suggest that this is the annealing's temperature variable, but mostly 2) R provides T as a shortcut for TRUE, although you can overwrite it like you just did here. This is a horrible feature of the R language and you should avoid using T both for TRUE or as your own variable.
message is probably a more appropriate tool for logging. I also transformed the code so it prints one row per iteration. I hope you'll agree the log is much easier to look at this way.
Keeping track of the best state is an improvement over the "vanilla" version simulated annealing process which only reports the current state at the last iteration. If you want it that way, then you need to use three states: best, current, neighbor. Which I implemented here.
In addition to keeping track of the current state and best state, it is recommended to keep track of their function values, so you do not have to make unnecessary function calls to re-compute them at each iteration.
Like the matlab function you referred to, it is preferable to return a list so you can provide more outputs than just the best state.
Always, it is important to comment your code to make it easier to understand and maintain.

I hope it helps.


First of all I think you meant:

a = ["a","1","one"]; // instead of [a, 1, one]

I handle these rare kind of issues as follow:

Open your browser (the following code is tested against Chrome)
Open the JavaScript console [Control -Shift -J (Chrome:Windows/Linux)]
Copy/paste your own code into the console

and then paste the following code

copy('abcde'.split('').map(function(varName){
return 'var ' + varName + ' = ' + JSON.stringify(window[varName])+';';
}).join('\n'));

If your variable names are more than 1 character use this code instead: (of course the following code won't work with the file example you specified, I changed the variable names for demonstration purpose)

copy(['var1', 'myVar2', 'blablabla'].map(function(varName){
return varName + ' = ' + JSON.stringify(window[varName])+';';
}).join('\n'));

Hit enter

the above code will copy the following JavaScript code into your clipboard:

a = ["a","1","one"];
b = ["b","2","two"];
c = ["c","3","three"];
d = ["d","4","four"];
e = ["e","5","five"];

Paste it into your file, save it and that's all!


Square root calculation in Scheme (SICP Exercise 1.7)

In change-in-precision, you can avoid the negation by swapping the operands for the subtraction.

In sqrt, if the guess is already close enough, why not just return guess?

To eliminate the repeated call to change-in-precision, use a let to define a variable delta.

The two branches of the if should be indented.


Optimize Cython code with np.ndarray contained

As a general rule for optimizing with cython, try to avoid python function calls if possible, i.e. replace pythonic sum with numpy sum or explicit for loop, replace bit number table with numpy array, and try to declare types for all variables.

You can also precalculate most of the variables used in distance calculation and use a separate array to hold minimum distances for each block. I quickly put something together and got the code below.

Just wondering, what is the rationale for normalizing the distance with the number of set bits?

import cython
import numpy as np
cimport numpy as np

cdef bitCount(unsigned char value):
    cdef count = 0
    while(value):
        value &= value - 1
        count += 1
    return(count)

def compare(np.ndarray[np.uint8_t, ndim=1, mode='c'] a,
            np.ndarray[np.uint8_t, ndim=1, mode='c'] b):

    cdef int nblocksA = int(a.size/256)
    cdef int nblocksB = int(b.size/256)
    cdef int i, j, k

    cdef double partial_hamming_distance

    # Prepare a bit number table for fast query
    cdef np.ndarray[np.uint8_t, ndim=1] bits = np.zeros(256, dtype=np.uint8)
    for i in range(256):
        bits[i] = bitCount(i)

    cdef np.ndarray[np.float_t, ndim=1] min_distances = np.ones(nblocksB,
                                                                dtype=np.float)
    min_distances *= 1000000

    cdef np.ndarray[np.float_t, ndim=1] set_bitsA = np.zeros(nblocksA, dtype=np.float)
    for i in range(nblocksA):
        for k in range(256):
            set_bitsA[i] += bits[a[k + 256 * i]]

    cdef np.ndarray[np.float_t, ndim=1] set_bitsB = np.zeros(nblocksB, dtype=np.float)
    for i in range(nblocksB):
        for k in range(256):
            set_bitsB[i] += bits[b[k + 256 * i]]

    for i in range(nblocksB):
        for j in range(nblocksA):
            partial_hamming_distance = 0

            for k in range(256):
                partial_hamming_distance += (bits[b[i*256+k] ^ a[j*256+k]]
                                          / (set_bitsB[i] + set_bitsA[j]))

            if partial_hamming_distance < min_distances[i]:
                min_distances[i] = partial_hamming_distance

    return np.sum(min_distances)


Javascript: Canvas drawing - storing mouse coordinates

Firstly, I want to give you a thumbs up for a clear description of your code. It really helps with reading.

And another before-we-begin thing: you've got a missing . in your longest line of the code, near the end: -  thisoffsetTop };.

Main changes

Indeed, as you do not need to store all the coordinates, it's not efficient to save them all.
To draw a line between the current and previous point, all you need are those two points.
So, the first thing we can do with the code is to refactor that away: use prevCoord instead of an array.

Get rid of the array

First, we remove the coords declaration and replace it with a prevCoord.
Without adding initialization, it'll stay at undefined for the first round.
We're fine with that.

// old
var coords = [];

// new
var prevCoord;

Slightly different condition

We do not need to compute the max anymore -- the original code uses it to grab the "current" and "previous" coordinate, but we're moving away from that.
Also, the condition is now different.
We just need to ask if prevCoord is undefined.

// old
var max = coords.length - 1;
if (typeof coords[max - 1] !== "undefined") {

// new
if (typeof prevCoord !== "undefined") {

Simplify the contents of if

Let's see what happens inside.
Before we incorporate our change, let's notice that in your first line within if, you've got an expression coords[max].
That's actually the element you've just push'd, right?
So we can replace coords[max] with just coord (the current coordinate).

Then, we also not need the prev = coords[max - 1] part because we already have the previous coordinate stored in prevCoord.

In other words, that line's a goner because we have the refs we need at hand.

// old
var curr = coords[max], prev = coords[max - 1];

// new
// not needed: curr is coord and prev is prevCoord

Now, the drawing commands become the following:

// old
context.moveTo(prev.x, prev.y);
context.lineTo(curr.x, curr.y);

// new
context.moveTo(prevCoord.x, prevCoord.y);
context.lineTo(coord.x, coord.y);

Store the current as previous

Now, the main part.

The idea is not that far from what you have here.
Instead of pushing into array, you can just overwrite the prevCoord:

prevCoord = coord

Of course, you cannot do it as soon as you grab the coord from the event and offset stuff -- you need the prevCoord to draw the line.
So, just overwrite it after drawing.

// old
coords.push(coord);
if (typeof prevCoord !== "undefined") {
    // ...
}

// new
if (typeof prevCoord !== "undefined") {
    // ...
}
prevCoord = coord;

See -- just after using the prevCoord to draw a line between previous and current, we don't need the prevCoord anymore.
We can use this variable to prepare for the next cycle: on next mouse move, the "current" will become "previous"... meaning that when we run this function the next time, prevCoord will be just what it needs to be: the coordinate that was "mouse overed" the previous time.

Polish up

There's one more place let to change: the click handler.
Just as you reset your array, you should reset the prevCoord back to undefined.

// old
coords = [];

// new
prevCoord = undefined;

Full code

Here's the complete deal.

var draw = false;
var prevCoord;
var canvas = document.getElementById('canvas');
var context = canvas.getContext('2d');
canvas.addEventListener('click', function (event) {
    prevCoord = undefined
    draw = !draw;
});
canvas.addEventListener('mousemove', function (event) {
    if (draw) {
        context = canvas.getContext("2d");
        var coord = { 'x': event.x - this.offsetLeft, 'y': event.y - this.offsetTop };
        if (typeof prevCoord !== "undefined") {
            context.beginPath();
            context.moveTo(prevCoord.x, prevCoord.y);
            context.lineTo(coord.x, coord.y);
            context.stroke();
        }
        prevCoord = coord
    }
});
<canvas id="canvas" style="border: 1px solid red"></canvas>

More suggestions

A couple of things...

Redefining context

You have, on your fourth line, in the global scope a var context = ..., and then inside the if (draw) you have a context = ....
There's no need to run that each time.
The context doesn't change.

// old
if (draw) {
    context = canvas.getContext("2d");

// new
if (draw)

Check for undefined

You don't need to use typeof x != 'undefined' here.
It's used when you're not sure if x has been declared.
A simple check would do.

// old
if (typeof prevCoord !== "undefined") {

// new
if (prevCoord !== undefined) {

That's all!


Using [ChildActionOnly] for generating links

This would appear to be an abuse of child actions. Child Actions are meant to compose smaller items of your interface that you would need to re-use and load up part (albeit a small part) of the MVC pipeline to provide this functionality.

Furthermore, it is giving your Controller responsibility for a unit of work that you may eventually want to reuse elsewhere. Can you really not see a need to work out a full path to a file in the future?

You mention this:

  in my controller I can easily access to context and fetch the result, That why I didn't use HTML helpers.

I can understand you not wanting to use HTML Helpers for this, as you need to make a request to a service to find out information about the user and the filename. Fine, but your reference to requiring access to a context, what context? Your service? This doesn't seem to warrant, at least in my eyes, a full controller action.

In my opinion, and this is an opinion-based "how is best to do this" question rather than code review, this method is best suited on your model. Extending your model to have a method that would return a path to the file that you can subsequently output seems like a much more logical place for this type of method. That way, should you need to get a path again in a different controller, you do not need to duplicate code and/or refactor the method into another location at a later date.

Another option would be to construct a ViewModel for each item in your (current) Model, which contains this URL for output. That way you can have a normal method on your controller, and call it whilst constructing the VM in the main Action.

Finally, have your models where the filename is sourced from a different column implement an interface that allows you to get a filename, and fallback to using URL Helpers.

Something as simple as below would suffice:

interface IFileNameProvider
{
    GetFileName();
}

Each implementation would return the filename from its appropriate property as an attempt at model-level (not DB-level) normalisation (of course you could normalise the filename at DB level). That way you can use standard URL helpers after getting your filename from this method, and your username through a similar method.


My suggestions:

Move type_count from being a public member

type_count plays an important role in the event manager. Making such a crucial part of the event management system a publically accessible member variable seems risky to me.

I would make that accessible only as a protected member function.

struct BaseEvent
{
   virtual ~BaseEvent() {}
   protected:
      static size_t getNextType();
};

size_t BaseEvent::getNextType()
{
   static size_t type_count = 0;
   return type_count++;
}

Of course, change Event appropriately.

template <typename EventType>
struct Event : BaseEvent
{
   static size_t type()
   {
      static size_t t_type = BaseEvent::getNextType();
      return t_type;
   } //; You don't need this semi-colon. Remove it.
};

Change the implementation of EventManager to simply event classes

Instead of

struct PLAYER_LVL_UP : Event<PLAYER_LVL_UP>
{ int new_level; };

struct PLAYER_HIT : Event<PLAYER_HIT>
{ int damage; };

struct COLLISION : Event<COLLISION>
{ Entity entity1; Entity entity2; };

it's cleaner to have:

struct PLAYER_LVL_UP
{ int new_level; };

struct PLAYER_HIT
{ int damage; };

struct COLLISION
{ Entity entity1; Entity entity2; };

You can accomplish that by updating EventManager to:

struct EventManager
{
   template <class EventType>
      using call_type = std::function<void(const EventType&)>;

   template <typename EventType>
      void subscribe(call_type<EventType> callable)
      {
         // When events such as COLLISION don't derive
         // from Event, you have to get the type by
         // using one more level of indirection.
         size_t type = Event<EventType>::type();
         if (type >= m_subscribers.size())
            m_subscribers.resize(type+1);
         m_subscribers[type].push_back(CallbackWrapper<EventType>(callable));
      }

   template <typename EventType>
      void emit(const EventType& event)
      {
         // Same change to get the type.
         size_t type = Event<EventType>::type();
         if (type >= m_subscribers.size())
            m_subscribers.resize(type+1);

         // This a crucial change to the code.
         // You construct a temporary Event object by
         // using the EventType object and use Event.
         // This requires a change to Event, which follows below.
         Event<EventType> eventWrapper(event);
         for (auto& receiver : m_subscribers[type])
            receiver(eventWrapper);

      }

   template <typename EventType>
      struct CallbackWrapper
      {
         CallbackWrapper(call_type<EventType> callable) : m_callable(callable) {}

         void operator() (const BaseEvent& event) {
          // The event handling code requires a small change too.
          // A reference to the EventType object is stored
          // in Event. You get the EventType reference from the
          // Event and make the final call.
          m_callable(static_cast<const Event<EventType>&>(event).event_); }

         call_type<EventType> m_callable;
      };

   std::vector<std::vector<call_type<BaseEvent>>> m_subscribers;
};

The updated Event class:

template <typename EventType>
struct Event : BaseEvent
{
   static size_t type()
   {
      static size_t t_type = BaseEvent::getNextType();
      return t_type;
   }
   Event(const EventType& event) : event_(event) {}
   const EventType& event_;
};


Remove the first N elements from an array while reducing the N variable

Code style

Variable names

Make sure that your variable names are descriptive of what they contain. In particular $max1 and $max2 use a poor naming style as it is unclear what you expect them to contain.

Whitespace

Make sure to keep whitespace around your operators, even in a for-loop. This increases readability, and thus decreases the chance for bugs.

Unneeded bookkeeping

You currently use $offset--; but do not use the result. Remove code you do not use.

Bugs

Your current code only works once, because you keep the keys. Considering the following code:

$offset = 3;
$elements = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13];

$max1 = $offset;
$max2 = count($elements);
for ($i=0; ($i<$max1 && $i<$max2); $i++) {
    unset($elements[$i]);
    $offset--;
}

$max1 = $offset;
$max2 = count($elements);
for ($i=0; ($i<$max1 && $i<$max2); $i++) {
    unset($elements[$i]);
    $offset--;
}

var_dump($elements);

// Result: array(11) { [3]=> int(3) [4]=> int(4) [5]=> int(5) [6]=> int(6) [7]=> int(7) [8]=> int(8) [9]=> int(9) [10]=> int(10) [11]=> int(11) [12]=> int(12) [13]=> int(13) }

You would expect it to remove the first 3 elements twice, but because the keys are not reset, the second iteration of your code will try to remove key 0, 1 and 2, while the first key is 3.

Algorithm

Your current code modifies an array in-place while keeping the keys. Modifying arrays while looping over them is aweful in any language, as you need to be mindful that conditions in loops may be pre-calculated, and element pointers may skip elements.

Since you use a for-loop, I can assume you use an array with numeric keys, which makes it odd that you would want to keep the current keys.

Alternative creating a new array

In php you can use array_slice to obtain a new array with only a slice of the original array. This will reset the keys of the array.

$elements = array_slice($elements, $offset);

No loop required.

Alternative deleting elements

You can use array_splice to modify an array in-place by deleting a consecutive chunk of array elements. It returns the deleted elements and the original array has a few less elements. This will also reset the keys.

array_splice($elements, 0, $offset);

Again, no loop required.

Alternative with a loop

You can also use a loop and use array_shift to remove the first element of the array repeatedly. For numeric keys the keys are reset, while literal keys are left untouched.

for ($i = 0; $i < $offset; $i++) {
  $result = array_shift($elements);
  if (is_null($result)) {
    // The array is empty, so safe us some time
    break;
  }
}

Filter to keep keys

If we want to keep keys, we can use array_filter. The following code works exactly like your own code, as in: It works the first time you invoke it, and then it breaks.

$elements = array_filter(
  $elements,
  function ($item, $index) use ($offset) {
    return $index >= $offset;
  },
  ARRAY_FILTER_USE_BOTH
);

You can improve that code by using and checking against $offset + $first_key.

reset($elements);
$first_key = key($array);


How long a PID has been running (taking multiple inputs)

GNU long options are not POSIX, so instead of ps --pid "$1" --format etime=, write ps -p "$1" -o etime=.
kill -s 0 "$1" >/dev/null 2>&1 is much faster than ps --pid "$1" > /dev/null 2>&1, partly because kill is a builtin in most shells. Signal 0 is used to test for the existence of a process without sending it a signal.
Consider redirecting the echo messages to the appropriate output streams, i.e. stdout and stderr.
is_this_a_number, does_pid_exist: these are used directly in if clauses, so it'd read more naturally if they are renamed to is_a_number and pid_exists.
A minor point here, but I'd reverse the if-else statements to remove the ! negations.
Another minor point: during the short time span between testing the existence of a PID and querying the elapsed time since the process with that PID was started, the process with that PID could have finished running or even been substituted with a newly spawned one. You could avoid that by running the second command first, saving the output in a variable and then check for nullness, like thus:

echo "Process ID $arg_val"
running_time=$(how_long_pid_has_been_running "$arg_val" 2>/dev/null |
    trim_leading_and_trailing_spaces)
if [ -z "${running_time}" ]
then
    echo "This process does not exist."
else
    echo "${running_time}"
fi

I've seen you write printf "\\n" in another post also, so I'm curious: is it any different from printf "\n"? And in any case, an echo would do the job just as well.


int biggestChldIndx;
        if(getRgtChldIndx(i) <= end) {//check if node has right child
            if(heap[getLftChldIndx(i)] > heap[getRgtChldIndx(i)]) {
                biggestChldIndx = getLftChldIndx(i);
            } else {
                biggestChldIndx = getRgtChldIndx(i);
            }
        } else {//only has left child so use it
            biggestChldIndx = getLftChldIndx(i);
        }

You can simplify this somewhat.

        int biggerChildIndex = getLftChldIndx(i);
        int rightChildIndex = getRgtChildIndx(i);
        if (rightChildIndex <= end && heap[biggerChildIndex] <= heap[rightChildIndex]) {
            biggerChldIndx = rightChildIndex;
        }

The compiler would probably do most of that.  The basic point is that there are only two possible values for biggerChildIndex.  Since we need to fetch both values to pick the right one, we might as well assign one of them optimistically.  Then we only have to check for the one path where it would be the other value.

I renamed it to biggerChildIndex because when you have two things, one is bigger than the other.  Biggest implies that there are at least three.  If interested, look up the difference between comparatives (e.g. bigger) and superlatives (e.g. biggest).  A rather pedantic difference, but one that I happen to know.

I also prefer not to elide out letters.  The minor savings in typing are outweighed by the cognitive increase in reading in my opinion.  Since most code is read more than it is written, it makes more sense to optimize for reading.

You also might want to consider this pattern:

        for (int childIndex = getBiggerChildIndex(i); childIndex <= end && heap[i] < heap[childIndex]; childIndex = getBiggerChildIndex(i)) {
            swap(i, childIndex);
            i = childIndex;
        }

Some people prefer to iterate (which is what is happening here) with for loops rather than while loops.  In this case, it simplifies the logic somewhat by allowing us to combine the two iteration checks.  Previously you had to use a break because the second check was separated.

What you really want to know is that the child is inside the heap, not that i doesn't point to a leaf.  The other logic works because when i is a leaf, there is no child (and therefore the loop has to stop iterating).

An argument against this is that it adds a method call to each iteration of the loop.  Of course, the method might be inlined.  As I suspect that the calls to getLftChldIndx and getRgtChldIndx are.  Note that your original made at least two calls to those methods and possibly four on every iteration plus a call to isLeaf.  This version makes exactly three method calls, the same as the minimum in the original version.

Possible implementation:

    int getBiggerChildIndex(final int parentIndex) {
        int leftChildIndex = getLftChldIndx(parentIndex);
        int rightChildIndex = getRgtChildIndx(parentIndex);
        if (rightChildIndex <= end && heap[rightChildIndex] >= heap[leftChildIndex]) {
            return rightChildIndex;
        }

        return leftChildIndex;
    }

It's possible to write this with the ternary operator as well, but the condition is long enough that I think the if is worth it for readability.

This is also slightly more readable in that it doesn't guess which one is bigger so as to save an unnecessary variable assignment.  It returns instead.

Extraneous comment

            //if it is, then swap

Considering that this appears in an if statement and the next statement is swap, this is unnecessary.

Note that I actually removed all the comments.  I believe that my code structure makes them obvious enough to be unnecessary.  It's more borderline on the other two though.


Demonstration of the Largest Square Submatrix

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

Do you need <iostream>?

bool check_Same_Length(std::vector< std::vector<int> > maximalSquareInput)

Space in the typename isn't required since c++11.

Not thrilled with the naming.  The function could be better named to signal that you are checking the column counts.  The parameter doesn't have to be your maximal input, but any 2D container.

You copy the vector of vectors every time you call a function.  Pass your matrix by reference (and to const if immutable).

bool has_equal_column_counts(const std::vector<std::vector<int>>& matrix)

    size_t length = maximalSquareInput[0].size();

size_t is missing its std:: namespace prefix.  Consider auto.

What happens if maximalSquareInput is empty?  If you are not going to check the preconditions yourself, you should at least document them.

    for (int i = 0; i < maximalSquareInput.size(); ++i) {
        if (length == maximalSquareInput[i].size()) {
            state = true;
        } else {
            state = false;
            return state;
        }
    }
    return state;

When you are accessing elements by an index and you are not using any index arithmetic, consider using range-based for.

    for (const auto& row : maximalSquareInput) {
        if (length == row.size()) {
            state = true;
        } else {
            state = false;
            return state;
        }
    }
    return state;

If you are returning false the first time you encounter an invalid length, just return false.

    for (const auto& row : maximalSquareInput) {
        if (length != row.size()) {
            return false;
        }
    }
    return true;

It turns out, the standard library has two functions that will do what you want here. You could use std::find or std::all_of, but std::adjacent_find works as well.

    auto not_equal_size = [](const auto& v1, const auto& v2) {
        return v1.size() != v2.size();
    };
    return matrix.end()
        == std::adjacent_find(maximalSquareInput.begin(),
                              maximalSquareInput.end(),
                              not_equal_size)

bool only_1_And_0(std::vector< std::vector<int> > maximalSquareInput)

Function should be named all_are_one_or_zero.

    for (int i = 0; i < maximalSquareInput.size(); ++i) {
        if (!(std::all_of(maximalSquareInput[i].begin(), maximalSquareInput[i].end(),
                          [] (int digit) { return digit == 1 || digit == 0; })))
        {
            return false;
        }
    }
    return true;

Again, range-based for would be better than index-based for.

Consider adding more tools to your toolbox to reduce repetition (DRY - Don't repeat yourself).  You have a couple functions iterating over collections of iterables.  An iterator that chains those collections (essentially "flattening" the collection) would allow you to simplify your function.  Consider the following code (exposition-only):

bool all_are_one_or_zero(const std::vector<std::vector<int>>& matrix) {
    return std::all_of(make_flatten_iterator{matrix},
                       make_flatten_iterator{},
                       [](int digit) { return digit == 1 || digit == 0; });
}

auto find_biggest_element(const std::vector<std::vector<int>>& matrix) {
    return std::max_element(make_flatten_iterator{matrix},
                            make_flatten_iterator{});
}

int findBiggestElement(std::vector< std::vector<int> > maximalSquareOutput)

Be consistent with your formatting/style.  You're function names have mixed snake_Camel_Case and camelCase.  Pick one, stick with it.

If this was meant to be a generalized max element finder for a matrix, you should consider (a) what happens if the matrix is empty, and (b) is 0 the minimum element value for type int?

std::string findLargestSubmatrix(const std::vector< std::vector<int> > maximalSquareInput)

Why return a string? Consider just returning either the square length or the square area and let the caller convert it to a string if they want it formatted.

You've used "Biggest" and "Largest" but you've always called the input parameter "maximal" (for maximum).  Just call it maximum and you can cut down on the parameter name.

std::size_t max_length_of_square_submatrix(const std::vector<std::vector<int>>& matrix)

    if(check_Same_Length(maximalSquareInput) && only_1_And_0(maximalSquareInput))

Back to being consistent, you have spaces to distinguish between language constructs (if, for) and functions and in this instance you don't.

Avoid unnecessary code nesting by returning early.

    if (!check_Same_Length(maximalSquareInput) || !only_1_And_0(maximalSquareInput))
    {
        return 0;
    }

    for (...)

Do you even need to check? Should that be the responsibility of some other function?

        for (int row = 0; row < maximalSquareInput.size(); ++row)
        {
            for (int column = 0; column < maximalSquareInput[row].size(); ++column)
            {
                if (row == 0 || column == 0 || maximalSquareInput[row][column] == 0)
                {

You check to see if you are on either the first row or first column.  When in either the first row or first column, you already know you can't make a square towards the northwest.  Therefore, you can just copy those values into your matrix of sums before calculating the entire matrix.  Then you check from [1,row][1,col].

std::size_t max_area_of_square_submatrix(const std::vector<std::vector<int>>& matrix)
{
    auto sums = matrix;

    for (std::size_t row = 1; row < matrix.size(); ++row)
    {
        for (std::size_t col = 1; col < matrix.size(); ++col)
        {
            if (matrix[row][col]) {
                sum[row][col] = 1 + std::min({sum[row-1][col],
                                              sum[row][col-1],
                                              sum[row-1][col-1]});
            }
            else
            {
                sum[row][col] = 0;
            }
        }
    }
    auto max_length = find_maximum_element(sums);
    return max_length * max_length;
}

std::string MaximalSquare(std::string strArr)
{
    auto matrix = to_matrix2i(strArr);
    if (!has_equal_column_counts(matrix) ||
        !all_are_one_or_zero(matrix))
    {
        return "0";
    }
    return std::to_string(max_area_of_square_submatrix(matrix));
}


Output strings from a set in lexicographical order

Just formal way :

Use TreeSet<String> ts to store S = {S1 U S2} :

if String is already stored, it returns false,
you can use ts.toString() to print all values of the Set, separated by ', ' between '[]'
you have addAll(..), containsAll(..), retainAll(..), ... ready made [and optimized] other tools.
You can put in Collections.synchronizedSet(s) if you have multi threaded concurrrent jobs.

You can rebuilt/combine your code from JVM, not only from mathematical constraints. ... wheels exist from long time.


Good job checking the input for validity and breaking up the logic into simple functions! However, some improvements can be made.

Avoid using namespace std

This can cause name collisions because it adds every name in the std namespace to the global namespace. For a small program like this one it's unlikely that you'll run into any problems (then again, maybe not) but it's best to get into the habit of using the std:: prefix on names in the std namespace.

Alternatively, you can introduce using declarations like using std::cout; to add specific names to the global namespace.

Avoid std::endl in favor of \n

std::endl flushes the stream, which can cause a loss in performance. In some cases you can also reduce calls to operator<< (e.g. cout << endl << "Finished!" << endl; becomes cout << "\nFinished!\n";).

Simplify your boolean expressions

You can remove some of your explicit return true and return false statements by returning the expression in the if condition. For example, you can shorten isEven() like so:

bool isEven(int num) {
  return num % 2 == 0;
}

Similarly, you can shorten isValid().

Don't mix logic and writing to cout in calculate()

Currently calculate() is not very reusable since it writes to cout. What if you wanted to write to a different stream, or if you just wanted to calculate the next term in the sequence without writing to any stream? I suggest redefining calculate() to simply return the next term in the sequence:

int next(int prev) {
  if (isEven(prev))
    return prev / 2;
  else
    return prev * 3 + 1;
}

Then in main() you can output each number returned by next() to cout, as well as check for the condition in which the term equals 1. You would replace the calculate(input); statement in main() with something like this:

while (input != 1) {
  input = next(input);
  std::cout << input << " ";
}

std::cout << "\nFinished!\n"


Checking whether two strings are isomorphic

Looking at your isomorphism helper function…

The flow of control is kind of nasty.  In particular, burying an unless in here…

if …
  raise Exception.new(…) unless …
elsif …
  raise
end

… is too tricky, because:

You already have an if-elsif expression, and it would be better to work it into the same chain.
It's at the end of a very long line, where it is barely visible.
unless, being a negation, is automatically less preferable to an affirmative if.

Switching the naming convention from string_a, string_b to char_one, char_two is not ideal.  Why not char_a, char_b?  Or better yet, just a, b?

Doing Hash lookups in reverse using value? is not efficient.  You would be better off making a "forward" map and an "inverse" map.  See below for an even better way to decompose the problem.

As for the use of exceptions internally, I think it's a bad idea.  It's just a cumbersome way to return false with commentary.  You could just write a comment to avoid the overhead.  Better yet, if you write the code well, I don't think there is a need for any comment.  For example, in the implementation below, b != expected_b is pretty self-explanatory.

module Isomorphism

  def self.isomorphic?(string_a, string_b)
    surjective?(string_a, string_b) && surjective?(string_b, string_a)
  end

  protected
  def self.surjective?(string_a, string_b)
    return false if string_a.size != string_b.size
    surjection = {}

    string_a.chars.zip(string_b.chars).each do |a, b|
      expected_b = surjection[a]
      if expected_b && (b != expected_b)
        return false
      end
      surjection[a] = b
    end
    true
  end

  # Alternate implementation: shorter, but won't detect failure as quickly
  def self.surjective?(string_a, string_b)
    return false if string_a.size != string_b.size
    pairs = string_a.chars.zip(string_b.chars)
    surjection = Hash[pairs]
    pairs.all? { |a, b| surjection[a] == b }
  end

end


We're missing any documentation or template constraints, but it appears that this code parses only decimal integers, and silently ignores anything after the first non-digit.  There are other departures from the interface of the functions provided in <charconv>:

a leading + is accepted and ignored
not all out-of-range values are detected.

Worse, there's no prevention of signed integer overflow, so there's undefined behaviour on certain inputs.
The avoidance of signed overflow is fragile and could be made clearer to the reader (with suitable static_assert() if requires isn't palatable, for instance).

I think that writing a function to multiply by 10 is taking functional decomposition a step too far.  I would say the same for subtracting '0', but that could be arguable if it were home for a comment explaining how C++ guarantees that the characters '0'..'9' are encoded as contiguous values.

There are no tests for any of the failure cases, and all the tests have to be checked externally.  It's better to make main() return an error status unless all the tests pass (and diagnostic output should go to std::clog or std::cerr as appropriate, rather than std::cout).


If it were me, I'd reduce the boiler plate by only putting what's actually changing into the switch statement, and putting everything else outside of it. So here you would only set the texture names in the switch statement. Something like this:

var selectedTextureName : String
var normalTexture1Name : String
var normalTexture2Name : String
var node1Name : String
var node2Name : String
switch node.name!
{
    case "level_1":
        selectedTextureName = "level_1_selected"
        normalTexture1Name = "level_2_normal"
        normalTexture2Name = "level_3_normal"
        node1Name = "level_2"
        node2Name = "level_3"

    case "level_2":
        selectedTextureName = "level_2_selected"
        normalTexture1Name = "level_1_normal"
        normalTexture2Name = "level_3_normal"
        node1Name = "level_1"
        node2Name = "level_3"

    case "level_3":
        selectedTextureName = "level_3_selected"
        normalTexture1Name = "level_1_normal"
        normalTexture2Name = "level_2_normal"
        node1Name = "level_1"
        node2Name = "level_2"
}

pushd(node: node)
node.run( sk_Action.animate(with: [skTexture(imageNamed:selectedTextureName)], timePerFrame: K1_4.f64_t) )

temp1 = childNode(withName: node1Name)!
temp1.run( sk_Action.animate(with: [sk_Texture(imageNamed: normalTexture1Name) ], timePerFrame: K1_4.f64_t) )
popd(node:temp1)

temp1 = SKSpriteNode()
temp1 = childNode(withName: node2Name)!
temp1.run( sk_Action.animate(with: [sk_Texture(imageNamed: normalTexture2Name) ], timePerFrame: K1_4.f64_t) )
popd(node:temp1)


"Up" script for moving up directories quickly

This is a decent concept, but by looping on the cd you loose some of the value of the $OLDPWD function in the shell. For example, I often use the special construct cd - in a shell, and that changes directory to the one you were in before.

Your code will make that impossible.

I would instead recommend that you instead build up a chain of ../ string values, like ../../../../ for 4 directories, and then just call cd once, which will preserve the cd - function, and the $OLDPWD.

Additionally, this would be a good feature to include as a function in your code, rather than a script. Bash shell likes functions, and they make life easier.

Finally, if someone supplies a non-number as an argument, it will do odd things.

I played with your code, and came up with:

up () {
    local count=$1
    if [ -z "$count" ]; then
        cd ..
        return
    fi

    test "$count" -eq "$count" || return 1

    local todir=""
    for i in `seq 1 $count`;
    do
      todir="../$todir"
    done
    cd $todir
}

The features of the above code I like are:

it is a function of the shell, so there's no additional script called.
it checks the value is a number, by doing a numeric comparison on the value: test "$count" -eq "$count" (That will throw an error if the inputs are not integers)
it only does a single 'cd', so things like cd - still work.

I would add that to my ~/.bashrc file, or source it in to my current shell.


Function to take a positive integer and return the next bigger number formed by the same digits

I know whatever program codewars uses does not care about readability (most computer programs don't), but in the real world readability is important.

The first step to refactoring should be creating tests. This way you can easily figure out if you've broken something:

let test1 = getNextNumberOfGreaterSize(12);
let test2 = getNextNumberOfGreaterSize(513);
let test3 = getNextNumberOfGreaterSize(2017);

assertEquals(21, test1);
assertEquals(531, test2);
assertEquals(2071, test3);

function assertEquals(expected, actual) {
  if (expected !== actual) {
    throw new Error("expected: " + expected + " but was: " + actual);
  }
}

While designing tests, you may discover other edge cases such as:

What if the number given is already the highest?
What if the number doesn't have any other combinations (such as 11)?
What if a single digit number is given (1)?

You didn't provide a function name but assuming it wasn't descriptive I suggest you change it. It's tricky coming up with a name for such a function (Functions like these probably wouldn't exist in the 'real world'), but something like getNextNumberOfGreaterSize(originalNumber) with a comment describing what it does.

Set otherNumber (Note I changed the name to be more readable. Cutting off 3 letters isn't saving you, or the interpreter any time) outside of the while loop and get rid of your if statement:

let otherNum = originalNumber;
while (originalNumber > newNum) {
if (....

Whatever you are doing inside the if statement deserves a comment. Better yet, you should also put it inside a function (especially when you know you'll refactor it later!):

function numbersContainSameDigits(number1, number2) {
  return String(number1)
        .split("")
        .sort()
        .join("") ===
      String(number2)
        .split("")
        .sort()
        .join("");
}

Now that we got the important stuff out of the way, let's move onto what you're actually asking for. How can we shave a few milliseconds off each run / Why is coderank telling us the methods too slow?

Computers suck at computing Strings. However they rock at computing numbers. Let's see if we can cut down on the amount of String computing.

The way we check if the two numbers contain the same letters can be changed. First we get an array containing the characters, then compare the two arrays after sorting:

function numbersContainSameDigits(number1, number2) {
  return checkIfTwoArraysAreEqual(getArrayContainingDigits(number1), getArrayContainingDigits(number2));
}

function checkIfTwoArraysAreEqual(array1, array2) {
  return JSON.stringify(array1.sort()) === JSON.stringify(array2.sort());
}

function getArrayContainingDigits(number) {
    let arrayOfDigits = [];
    while (number >= 1) {
        arrayOfDigits.push(Math.floor(number % 10));
      number /= 10;
    }

    return arrayOfDigits;
}

Edit:

You are going through a much wider range of numbers than needed. You could instead get all available combinations of a number, and select the permutation 1 index greater than the input.


main guard

Put the parts of your code that are the ones calling for execution behind a if __name__ == "__main__": guard

if __name__ == "__main__":
    def my_add(a, b):
        first = a
        second = b

        return first + second
    print_co_obj_fields(my_add.__code__)

This way you can import this python module from other places if you ever want to

Documentation

There is a python convention (docstring) to document the behaviour of a method: PEP-257

def print_co_obj_fields(code_obj):
    """prints all the instance variables of the code object that start with 'co_'"""

Indentation

To decrease the levels of indentation, you can reverse the test of startswith, and continue when it fails:

def print_co_obj_fields(code_obj):
    # Iterating through all instance attributes
    # and calling all having the 'co_' prefix
    for name in dir(code_obj):
        if not name.startswith('co_'):
            continue
        co_field = getattr(code_obj, name)
        print(f'{name:<20} = {co_field}')

An alternative if using the builtin filter:

def print_co_obj_fields(code_obj):
    # Iterating through all instance attributes
    # and calling all having the 'co_' prefix
    for name in filter(lambda field: field.startswith("co_"), dir(code_obj)):
        co_field = getattr(code_obj, name)
        print(f'{name:<20} = {co_field}')

Presentation

Separate the generation of the results from the presentation. The easiest way to do this is to have print_co_obj_fields yield the name and co_field instead of printing them

def co_obj_fields(code_obj):
    """generator that yields the fields in a code_object and their value"""
    for name in filter(lambda field: field.startswith("co_"), dir(code_obj)):
        co_field = getattr(code_obj, name)
        yield name, co_field

def print_co_obj_fields(fields):
    for name, co_field in fields:
        print(f"{name:<20} = {co_field}")

The main part then changes to:

if __name__ == "__main__":

    def my_add(a, b):
        first = a
        second = b

        return first + second

    fields = co_obj_fields(my_add.__code__)
    print_co_obj_fields(fields)


Let's start with extractVideoID().
Your regex /^.*((youtu.be\/)|(v\/)|(\/u\/\w\/)|(embed\/)|(watch\?))\??v?=?([^#\&\?]*).*/ doesn't guarantee the URL has a YouTube format. For example, the URL www.google.com/watch?v=01$@T$89h does match the regex and has the following groups: ["www.google.com/watch?v=0123456", "watch?", undefined, undefined, undefined, undefined, "watch?", "01$@T$89h"], where the 7th group 01$@T$89h isn't a valid YouTube video ID.
I suggest you replace your regex with /^((?:https?:)?\/\/)?((?:www|m)\.)?((?:youtube\.com|youtu.be))(\/(?:[\w\-]+\?v=|embed\/|v\/)?)([\w\-]+)(\S+)?$/ (source). This regex only matches valid YouTube URLs format, and the 5th group is the ID of the video. Notice that a valid YouTube URL along with a video ID doesn't guarantee that the video exist. You can use YouTube.Videos.list() to test if the video for the given ID exists.
  if ( match && match[7].length == 11 ){
    return match[7];
  }
  else if (!( match && match[7].length == 11 )){ // equivalent of else {}
    // multiple attempts to replace
    return trimmedVideoID;
  }

The if..else if block is bad. If you find a match, you return the ID. Done. So extractVideoID() has only one purpose: if the URL has a valid format, return the ID. Otherwise, i.e., if it doesn't find a match, then extractVideoID() should return null.
if (match && match[5])
  return match[5];

In your code, the else if block is opposite of the first if, so it is actually an else block. This also means that, altought you couldn't find any match, you are returning anything anyway, even if url is garbage like Lorem ipsum dolor sit amet, consectetur adipiscing elit..
Now, with addVideoToYouTubePlaylist().
pageToken = res.nextPageToken || "";
The nextPageToken is a string for the next page, so unless YouTube.PlaylistItems.list() fails - and thow an error, stopping everything - it won't evaluate to false. And if it does, you are restarting all over again, possibly heading to the same falsy value thus creating an infinite loop.
for (var d=1,l=data.length; d<l; d++) {
You can test d < data.length directly for improved reading.
  var videoId = extractVideoID(data[d][0]);
  if (!obj[videoId]) {
  YouTube.PlaylistItems.insert({

You may want to test if the video with the given ID exists before of inserting it in the playlist.
  resourceId: {
    kind: "youtube#video",
    videoId: extractVideoID(videoId)
  }

Without chaning extractVideoID() and passing a valid ID to it returns null.
sheet.deleteRow(d+1); // delete row after video is checked
When you delete row number d+1, what was in row (d+1)+1 now is in row d+1. Because of that, you need a counter of deleted rows, say r, and delete the row number d+1-r to compensate the upward "shift".


Batch file to copy specific folders and to delete the folder which is not copied

It seems you're not taking the advices from a previous reviews,
which gave very good points:

Always use SETLOCAL, unless you really really really want variables to affect the environment of the calling process
It's good to use @ECHO even if you set ECHO OFF at the top, in case you might want to temporarily disable the ECHO OFF for debugging purposes
It's good to add some blank lines to separate related blocks and improve readability

Now on to this new code.

The path D:\backup\test\swift appears twice in this statement:

set /P SOURCEPATHPATH=Enter SOURCEPATH example:D:\backup\test\swift (default SOURCEPATH path=D:\backup\test\swift):

It's good to avoid repeating yourself, because you might want to change the value later, and then you'll have to change every occurrence, and risk the mistake of forgetting to change one of them.
Extract duplicated strings into a variable, for example:

set DEFAULT_SOURCEPATH=D:\backup\test\swift
set /P SOURCEPATH=Enter SOURCEPATH example:%DEFAULT_SOURCEPATH% (default SOURCEPATH path=%DEFAULT_SOURCEPATH%):

Btw in the original code SOURCEPATHPATH looks like a typo (the ...PATHPATH at the end).

All the else blocks here look utterly pointless:

if "%SOURCEPATH%"=="" (
    ...
) else (
    set SOURCEPATH=%SOURCEPATH%
)
if "%DESTPATH%"=="" (
    ...
) else (
    set DESTPATH=%DESTPATH%
)
if "%folder%"=="" (
    ...
) else (
    set folder=%folder%
)

In all these examples, you set a variable to itself. That does nothing at all.
It would be better to completely omit these else statements,
and the code will be shorter.

A blank line between the treatment of SOURCEPATH, DESTPATH, folder would be nice for visual separation and readability.

Finally, I don't have a Windows with me now,
but I think this would work and be a better way of implementing those if conditions:

if not defined SOURCEPATH (
    ...
)

if not defined DESTPATH (
    ...
)

if not defined folder (
    ...
)


Check if an array value exists as part of the url

If you can use ES6 Features in your code, use a Set for constant lookup time:
const urlsToIgnore = new Set([
  'boldchat.com',
  'pinimg.com',
  'responsetap.com',
  'facebook.net',
  'dwin1.com',
  'bing.com',
  'google-analytics.com',
  'googletagmanager.com',
  'hotjar.com',
  'pinterest.com',
]);

// later
if (uslstoIgnore.has(event.request.url) { ... }

Otherwise, just use a simple object as a map:
const urlsToIgnore = {
  'boldchat.com': 1,
  'pinimg.com': 1,
  'responsetap.com': 1,
  'facebook.net': 1,
  'dwin1.com': 1,
  'bing.com': 1,
  'google-analytics.com': 1,
  'googletagmanager.com': 1,
  'hotjar.com': 1,
  'pinterest.com': 1,
};

// later
if (uslstoIgnore[event.request.url]) { ... }

Both these options offer constant time lookup, as opposed to the linear time of your current solution.
The actual performance gain depends on the size of the list with ignored items, but since this list can be added to, I'd opt for an O(1) lookup.


Advice 1

mergeSort(v, v.begin(), v.end() - 1);

So your implementation requires the actual vector + two iterators; this is an anti-pattern, you should strive for the following API:

mergeSort(v.begin(), v.end());

Note v.end() instead of v.end() - 1, since end() points to the one element past the last element; this is the STL approach.

Advice 2

Same applies to the merge.

Summa summarum

If you want to improve your coding, you could start by investigating the following:

#include <iostream>
#include <iterator>
#include <algorithm>
#include <vector>

void mergeSort(std::vector<int>::iterator begin,
               std::vector<int>::iterator end);

void merge(std::vector<int>::iterator begin,
           std::vector<int>::iterator middle,
           std::vector<int>::iterator end);

void print(const std::vector<int> &v);

int main()
{
    std::ios_base::sync_with_stdio(false);

    std::vector<int> v;

    int temp = 0;
    while (std::cin >> temp) {
        v.push_back(temp);
    }

    // Sort
    mergeSort(v.begin(), v.end());
    // Print the vector after sorting.
    print(v);

    return 0;
}

void mergeSort(std::vector<int>::iterator begin, std::vector<int>::iterator end) {
    auto distance = std::distance(begin, end);

    if (distance < 2) {
        return;
    }

    auto middle = begin;
    std::advance(middle, distance / 2);
    mergeSort(begin, middle);
    mergeSort(middle, end);
    merge(begin, middle, end);
}

void merge(std::vector<int>::iterator begin,
           std::vector<int>::iterator middle,
           std::vector<int>::iterator end) {
    auto distance = std::distance(begin, end);
    std::vector<int> aux(distance);

    auto left = begin;
    auto left_bound = middle;
    auto right = middle;
    auto right_bound = end;
    size_t aux_index = 0;

    while (left != left_bound && right != right_bound) {
        if (*right < *left) {
            aux[aux_index++] = *right;
            ++right;
        } else {
            aux[aux_index++] = *left;
            ++left;
        }
    }

    std::copy(left, left_bound, &aux[aux_index]);
    std::copy(right, right_bound, &aux[aux_index]);
    std::copy(aux.begin(), aux.end(), begin);
}

void print(const std::vector<int> &v) {
    for (const auto &i : v) {
        std::cout << i << " ";
    }

    std::cout << std::endl;
}

Advice 3

Making the sort more idiomatic (a template) and efficient (double buffer strategy) is not too hard:

template<typename RandomIter1, typename RandomIter2>
void merge(RandomIter1 begin,
           RandomIter1 middle,
           RandomIter1 end,
           RandomIter2 aux) {
    RandomIter1 left = begin;
    RandomIter1 right = middle;
    RandomIter1 left_bound = middle;
    RandomIter1 right_bound = end;

    while (left != left_bound and right != right_bound) {
        if (*right < *left) {
            *aux = *right;
            ++right;
        } else {
            *aux = *left;
            ++left;
        }

        ++aux;
    }

    std::copy(left, left_bound, aux);
    std::copy(right, right_bound, aux);
}

template<typename RandomIter1, typename RandomIter2>
void merge_sort(RandomIter1 source_begin,
                RandomIter1 source_end,
                RandomIter2 target_begin,
                RandomIter2 target_end) {
    auto distance = std::distance(source_begin, source_end);

    if (distance < 2) {
        return;
    }

    RandomIter1 source_middle = source_begin;
    RandomIter2 target_middle = target_begin;
    std::advance(source_middle, distance >> 1); // distance >> 1 is the same as
                                         // distance / 2
    std::advance(target_middle, distance >> 1);

    merge_sort(target_begin,
               target_middle,
               source_begin,
               source_middle);

    merge_sort(target_middle,
               target_end,
               source_middle,
               source_end);

    merge(source_begin,
          source_middle,
          source_end,
          target_begin);
}

template<typename RandomIter>
void merge_sort(RandomIter begin, RandomIter end) {
    auto distance = std::distance(begin, end);

    if (distance < 2) {
        return;
    }

    using value_type = typename std::iterator_traits<RandomIter>::value_type;
    value_type* aux = new value_type[distance];
    std::copy(begin, end, aux);
    merge_sort(aux, aux + distance, begin, end);
    delete[] aux;
}

When I compare the above to your version (demo here), I get the following figures when using -O3 optimization flag:

OP time: 377 milliseconds.
coderodde time: 144 milliseconds.
Algorithms agree: true

Hope that helps.


Handling thread interruptions in a directory iterator

Overall your code looks fine to me, however some remarks:

I would log the IOExceptions that may happen during walkFileTree. Otherwise, if there are problems with the tree walk, it's hard to find out the reason later (e.g., if the baseDir does not exist). Perhaps you should perform also some sanity checks (i.e, baseDir is not null and baseDir exists) before submitting the Runnable.
When catching the IOException, it would be also possible to just throw a RuntimeException that has the IOException as its cause. But this is just a matter of taste.
However, in both cases if an IOException is thrown you need to be aware that the ExecutorService has still an idle thread (that may prevent the shutdown of your app) until you call the close method on LayzDirectoryIterator. Maybe using a custom ThreadFactory that creates daemon threads (and neat thread names) is an option here? I like to use Guava's ThreadFactoryBuilder for this purpose.
I'm generally not a fan of spawning a new Thread within the constructor, I would add an additional start method to submit the tree walk Runnable.
Your Thread.currentThread().interrupt() within the CustomVisitor is fine.


Finding anagrams in a word list using Python

Good that you tagged with Python 3, as it kinda works in Python 2.7
with a bit different behaviour.

All the time reminder to format according to
PEP8; here I'd note that
there should be spaces between names, i.e. key, val and
print(key, input_word).

Firstly, it's good that there are functions to split the logic up.
However part of that is negated by using globals.  In general using
globals is a bad pattern - here in particular it makes more sense to
pass the word list through to the individual functions.

Edit: And I forgot to update it to not use globals, shame on me ...

Most of the comments can also be docstrings instead.

Now, for the globals.  Just pass them through to the functions:

def simplify_entered_word(input_word):
    "Lowercase and sort the user input word."
    word = input_word.lower().strip()
    return word, "".join(sorted(word))

This function can now also be reused easily by returning two results,
the lowercased word and the sorted result.

Next I'd move the word list reading its own function:

def read_word_list(filename):
    """Open file and create a dictionary of {"word":"sorted word"}."""
    with open(filename, "r") as word_file:
        word_list = {}
        for text in word_file:
            word = text.lower().strip()
            simple_text = "".join(sorted(word))
            word_list.update({word: simple_text})
        return word_list

However this can also be much easier in terms of simplify_entered_word:

def read_word_list(filename):
    """Open file and create a dictionary of {"word":"sorted word"}."""
    with open(filename, "r") as word_file:
        return {simple[0]: simple[1]
                for simple in map(simplify_entered_word, word_file)}

N.b. there might be a better way to write that dictionary
comprehension.  Note also that I used with as to not leak the file
handle from open.

And then call that with the filename:

if __name__ == "__main__":
    word_list = read_word_list("word_list(1).txt")
    while True:
        input_word = input("Input the word for anagram checking: ")
        find_in_dict(word_list, simplify_entered_word(input_word)[1])

Just in case this will only run as a script and not if the file is
imported somewhere else, which is good practice.

One problem that still remains is the iteration in find_in_dict.  It'd
be much simpler if the data structure is slightly changed by collecting
all words for one anagram into a list:

from collections import defaultdict

def read_word_list(filename):
    """Open file and create a dictionary of {"word":"sorted word"}."""
    with open(filename, "r") as word_file:
        word_list = defaultdict(list)
        for word, simplified in map(simplify_entered_word, word_file):
            word_list[simplified].append(word)
        return word_list

def find_in_dict(word_list, entered_word):
    """Compare the sorted user input with the values of the dictionary to find
    the anagrams."""
    for name in word_list.get(entered_word, []):
        print(name, entered_word)

Note the use of defaultdict to simplify the automatic creation of the
list.


Rather than using a list, consider approaching the problem from a graph perspective.  Build a tree from the root directory using the existing directories, then traverse it with the new directories, and output a result line each time you have to add a leaf to the graph.  This should be a little faster than comparing your two sets.


In the way you show that you create each Skill instance, you really have anything than the Description to distinguish them from each other.

I read your Skill class as merely an advanced flag that defines a small set of properties. In the below I further anticipate, that each skill type doesn't change throughout the game. If that is correct, then I would make the Skill class as a "singleton" per Skill type (onehanded, twohanded etc.) and let a static Factory method create/return the right Skill according to a Skill Type enum:

public class Skill
{
  public string Description { get; private set; }
  public bool Advanced { get; private set; }
  public int PointsToLearn { get; private set; }
  public SkillType Type { get; private set; }

  private Skill()
  {
  }

  private static Dictionary<SkillType, Skill> s_skills = new Dictionary<SkillType, Skill>
  {
    { SkillType.OneHanded, new Skill { Type = SkillType.OneHanded, Description = "Skill needed for the use of one handed weapons", Advanced = false, PointsToLearn = 1, } },
    { SkillType.TwoHanded, new Skill { Type = SkillType.TwoHanded, Description = "Skill needed for use of two handed weapons", Advanced = false, PointsToLearn = 2, } },
    { SkillType.Polearm, new Skill { Type = SkillType.Polearm, Description = "Skill needed for use of polearms", Advanced = false, PointsToLearn = 3, } },
    { SkillType.Shield, new Skill { Type = SkillType.Shield, Description = "Skill needed to use shields", Advanced = false, PointsToLearn = 1, } },
    { SkillType.ResistMagic, new Skill { Type = SkillType.ResistMagic, Description = "Negates the first spell cast at the character", Advanced = true, PointsToLearn = 0, } },
  };

  public static Skill Factory(SkillType type)
  {
    return s_skills[type];
  }
}

public enum SkillType
{
  OneHanded,
  TwoHanded,
  Polearm,
  Shield,
  ResistMagic
}

If their role is more advanced than that with methods and state, it IMO calls for at class hierarchy in some way like:

public abstract class Skill
{
  public string Description { get; set; }
  public bool Advanced { get; set; }
  public int PointsToLearn { get; set; }
  public SkillLevel SkillLevel { get; set; }
}

public class OneHanded: Skill
{

}

public class TwoHanded : Skill
{

}
...

which of cause requires a lot more work.

Update

If you want to filter a list of skills by SkillLevel, it can be done like this:

List<Skill> skills = new List<Skill> { new OneHanded(), new TwoHanded(), ... etc. }

foreach (Skill skill in skills.Where(s => s.SkillLevel == SkillLevel.Basic))
{
  Console.WriteLine(skill.GetType().Name);
}

Beside that I would change the Advanced flag to an enum too, because you can then distinguish between more levels like:

enum SkillLevel
{
  Basic,
  Medium,
  Advanced,
}


Project Euler 5: Smallest multiple in Functional Programming (fp)

Well, this is Code Review, so let's be picky.  First, remember that superLongVariableNamesThatTakeSeveralMinutesToWrite are for IDE-assisted object-oriented enterprise programming in Java where a recursive call is so unusual you'd record it as a Very Special Day in your diary.

Functional programmers don't have time for that nonsense, so start by writing:

const gcd = (a,b) => 0 === b ? a : gcd(b, a % b)

When it comes to writing lcm, a functional programmer probably wouldn't write a version that calculates the (1) least common multiple of (2) several values produced by (3) iterating over integers because that's three different concepts, and functional programmers' heads are so crammed with greek letters and category theory that they can only concentrate on one thing at a time.  So, we'll have to be content with an lcm function that operates on only two numbers:

const lcm = (a,b) => a * b / gcd(a,b)

Second, no self-respecting functional programmer would be caught dead without a fold function (AKA reduce), whether she needed it or not, so let's be sure to write one now and worry about finding a way to use it later:

const reduce = (f,xs) => 1 === length(xs) ? xs[0]
      : f(xs[0], reduce(f,xs.slice(1)))

A couple tests ensure it's working:

> reduce((x,y) => x+y, [1,2,3,4,5])
15
> reduce((x,y) => x*y, [1])
1
> reduce((x,y) => x*y, [])
RangeError: Maximum call stack size exceeded
   at reduce (repl:1:72)
   at reduce (repl:1:60)
   ...

Oh, well, close enough.  we'll leave unit testing to some junior programmer (or an intern, who would probaly be clever enough to realize that Array.reduce is already vanilla JS).

Third, since we agree that explicit iteration is for imperative programming chumps, we'll write a tail recursive function for generating arrays of integer ranges:

const seq = (m,n) => m > n ? [] : [i].concat(step(m+1,n))

and a few tests:

> seq(5,10)
[5,6,7,8,9,10]
> seq(1,20)
[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]
> seq(1,1000000)
RangeError: Maximum call stack size exceeded
>

Oh, yeah, we forgot to make it tail recursive...  Again, we really need to hire that junior programmer.

ANYWAY, armed with this selection of functions:

const gcd = (a,b) => 0 === b ? a : gcd(b, a % b)
const lcm = (a,b) => a * b / gcd(a,b)
const seq = (m,n) => m > n ? [] : [m].concat(seq(m+1,n))
const reduce = (f,xs) => 1 === xs.length ? xs[0]
      : f(xs[0], reduce(f,xs.slice(1)))

the program really writes itself:

> console.log(reduce(lcm, seq(1, 20))
232792560
>

And seriously, while I was writing this up a little tongue-in-cheek, this is really how functional programming is supposed to work.

Instead of writing a function leastCommonMultiple with a long name that tries to do multiple things:

count up from 1 to max
maintain an accumulator of results
calculate pairwise LCMs using the greatestCommonDivsor helper

you:

write functions with short names like lcm that do simple things like calculating the LCM of two numbers
take algorithms like folding a list of values into an accumulator using a binary operator and abstract them into higher order, reusable functions like reduce
compose these simple functions together to write more complex programs

As a side note, from a practical standpoint, my seq and reduce leave much to be desired.  In Javascript, building an array recursively with concat is not a sane way to create an array of sequential integers (and my reduce is really no better).  Of course, that's why we have libraries like Lodash, to provide optimized implementations of these common building blocks.

Which brings me to my last point.  If you're an FP beginner, I don't think you're likely to benefit much from trying to write FP code in vanilla Javascript without any external libraries.  The main reason these external libraries exist is that FP programming in vanilla Javascript is tedious, inefficient, error-prone, unpleasant, and a host of other distasteful adjectives.

A programmer who is already experienced with FP can write decent FP programs in vanilla Javascript (but is probably smart enough not to try).  Programmers who are trying to improve their FP skills are better off using an FP-friendly library that will encourage writing good FP code.

If you want to get better at FP in Javascript, install a library that supports FP programming, work through its tutorials, and make heavy use of it:

// Euler 1
var _ = require('lodash')
console.log(_.sum(_.filter(_.range(1000),
    (x) => (x % 3 === 0) || (x % 5 === 0))))
console.log("Awesome!")


Initial thoughts:
This code looks very ... compressed without strictly needing to. Another thing that I notice is the level of nesting that shows in here.
Generally speaking it doesn't particularly make a difference how you decide to handle Promises, in the vast majority of cases it's just a matter of personal preference.
One thing you do not need to worry about is specially handling a promise rejection, since express automatically converts thrown errors into an appropriate response. That is what login takes advantage of to look so clean.
One final initial thing I notice is the inconsistency that shows in the code.
Inconsistencies:
Compare the use of spaces in the following example:
const  user   = await User.existLogin(req.body.login);
const isPassword = await User.isPassword(user.dataValues.password, req.body.password);

Or compare the use of braces as well as whitespace for these examples:
if(!token) return res.status(401).json('Unauthorized');
if (!user) { return res.status(400).json({result: 'Login is wrong '});}
if(!user){
    return res.status(404).json('User not Found');
}

Compare also the use of newlines and indentation levels in the following examples:
User.create({
    name, email, login, password }).then(result => {
    res.status(201).json({Results: result.dataValues})
})
return jwt.sign(payload,
    config.secretToken
           )
return {
    sub: usuario.id,
    // ....
    exp: moment().add(10, 'minutes').unix()
}

All this is to say: Pick one style and stick to it. Whichever style you decide on, it makes it easier to read if the style is consistent.
Personally I prefer a style with more space than you've shown here for most cases.
Indentation:
You're using a strange mix of indentation styles and you're making lots of use of early returns, except in some small cases where I don't understand it. I personally prefer to almost always return early inside the request handler and if there's more complex logic I'd consider extracting that into a separate function. That yields code which will look a lot like this:
function addUsers(req, res) {
    const name = req.body.name;
    const email = req.body.email;
    const login = req.body.login;

    const exists = await User.existLogin(login);
    if (exists) {
        return res.status(409).json({ message: 'Login already exists' });
    }

    const password = bcrypt.hashSync(req.body.password, 10);
    const created = User.create({ name, email, login, password });
    res.status(201).json({ results: created.dataValue });
}

Note that I removed the use of await with hashSync (should be clear why).
Also note that I lower-cased the member results in the returned JSON result.
Obviously this doesn't quite have the same error behaviour as the code presented in the question, but it nicely shows how to avoid deeply nesting blocks.
HTTP / web standard authorization patterns
As a minor point I'd like to add that the auth middleware shown here is not quite following the common header authorization pattern. It's missing a response header indicating the expected authorization type. Since you're working with a token here, usually the header would be 'WWW-Authenticate: "Bearer"', but that would imply the expected Authorization header should start with "Bearer", which is not the case here.
To be more ... standard-conform I'd expect a proper bearer-token Authentication scheme to specifically define the authorization type used in the scheme. An option could be to explicitly specify you expect a jwt-token as type resulting in the following headers:
'WWW-Authenticate: "jwt-token"'
---
'Authorization: "jwt-token <jwt_token_goes_here>"'

Note that this suggestion of course would require an adjustment to the way the token is obtained, adding another way the request can be malformed :)
Conclusion:
All in all this is a solid start, to get this code to the next level just requires a few tweaks, mostly around being consistent in how the code is structured in itself.
Well done :)


Handling HTTP requests and saving user to database

I know that PersonRepository#create returns a Future[A] as that is the only signature that can make the map call at the end of register actually compile. I'll assume it returns a Future[UserInser], and therefore has a signature equivalent to :

class PersonRepository {
  def create(email: String, provider: String, uid: String, facebook_token: String, display_name: String, photo_url: String):Future[UserInsert] = ???
}

That I have to make this assumption at all shows a first issue in your code : the name i used in

personRepository.create(user.email, user.provider, user.uid, user.facebook_token, user.display_name, user.photo_url).map(i => {
      Ok(Json.toJson(i))
    })

expresses no intent and forces the reviewer to go and check the signature of create to know what's going on.

Assuming I am right that it returns the inserted user, it would be nice to improve the naming as such:

personRepository.create(user.email, user.provider, user.uid, user.facebook_token, user.display_name, user.photo_url).map(savedUser => {
      Ok(Json.toJson(savedUser))
    })

Apart from that, your code definitely doesn't do what you want as it will try to insert an empty user in the database if the request is incorrect.

This could be avoided along with the whole pattern matching by delegating to play using a form such as :

val userRegisterForm = Form(
      mapping(
        "email"->text,
        "provider"->text,
        "uid"->text,
        "facebook_token"->text,
        "display_name"->text,
        "photo_url"->text
      )(UserInsert.apply)(UserInsert.unapply)
    )

Your controller then becomes  :

  /**
    * Login/register action.
    */
  def register = Action.async { implicit request =>
      val maybeUser: Form[UserInsert] = userRegisterForm.bindFromRequest()
    maybeUser.fold(
      errors => Future.successful(BadRequest("Bad Request: " + play.api.http.Status.BAD_REQUEST)),
      user => personRepository.create(user.email, user.provider, user.uid, user.facebook_token, user.display_name, user.photo_url).map(savedUser => {
        Ok(Json.toJson(savedUser))
      })
    )
  }

I would also argue that

errors => Future.successful(BadRequest("Bad Request: " + play.api.http.Status.BAD_REQUEST))

doesn't make sense. It is just repeating bad request all over the place without providing any useful information. Just replace it with

errors => Future.successful(BadRequest)

or provide a meaningful error message

errors => Future.successful(BadRequest("Unable to parse request" + Json.prettyPrint(errors.errorsAsJson)))

which gives you :

  /**
    * Login/register action.
    */
  def register = Action.async { implicit request =>
      val maybeUser: Form[UserInsert] = userRegisterForm.bindFromRequest()
    maybeUser.fold(
      errors => Future.successful(BadRequest),
      user => personRepository.create(user.email, user.provider, user.uid, user.facebook_token, user.display_name, user.photo_url).map(savedUser => {
        Ok(Json.toJson(savedUser))
      })
    )
  }

Regarding the remainder of your code :

def userModel(json: JsValue) = {
    new UserInsert((json \ "email").as[String], (json \ "provider").as[String], (json \ "uid").as[String], (json \ "facebook_token").as[String], (json \ "display_name").as[String], (json \ "photo_url").as[String])
  }

should probably be made private.

Last but not least, the scala style guide says All public methods should have explicit type annotations. This should definitely be applied to PersonRepository#create

It can probably be improved further but that's a start.


Your math was wrong, but don't worry it was a simple fix. And I have provided an easier way to do it on top of that.

The key to this review is that we're going to take advantage of the .Net libraries, which you should remember can practically do anything you want them to. That is IF you know how to use them.

in C#.Net

double percent = 40d / 60d;
var newValues = myList.Where((value, index) => index % (1 / percent) < percent).ToList();

in VB.Net

Dim percent As Double = 40.0 / 60.0
Dim newValues = myList.Where(Function(value, index) index Mod (1 / percent) < percent).ToList()

They are practically the same. But now let me explain how this works a bit now.

List<T> in .Net inherits from the IEnumerable<T> class which has the Where()  overloaded extension method from the Linq library. Using linq in combination with a lambda expression Function(value, index) index Mod (1 / percent) < percent I was able to specify to the Where method exactly what values to give back. I specifically did this with some math involving the index of the item that was being iterated over internally. Suffice to say, the Where method loops over given list, and returns all values which meet the criteria given in that lambda expression. At the end I convert the IEnumeral<double> to a List<double> to work like the data you had before.


When I run your code in Octave I see the following:

>> a=Enum.test()
a =

<object Enum>

Simply overloading the disp operator will solve this issue:

       function disp(this)
           disp(['Enum with value ',this.value])
        end

Now:

>> a=Enum.test()
a =

Enum with value test

You created a handle class to define your enumerator object. I don't see the benefit of using a handle class for this. Handle classes are meant as an interface to resources (a file, memory) that cannot (or should not) be copied. The handle class is always passed by reference, and the assignment operator causes the new variable to refer to the same object rather than making a copy.

This means that a=Enum; function(a) can modify a. Also, b=a; b.Value='foo' will change the value of a. This is highly uncommon and unexpected behavior in the MATLAB language. In general, MATLAB/Octave data is never a handle class, and I think an enumerator class should not be a handle class either.

I'm not sure what problem enumConstructor is avoiding. I'm running Octave 5.1 and don't have any issues overloading the constructor. A static function is a good workaround. I'm not sure why it is marked private though, since this makes it impossible to create an object of the class (I'm assuming the method test is just for show, not actually meant as part of the class).

Octave has a few additions to the MATLAB language that I feel are unfortunate. I always suggest to people not to use these additions. In particular, comments should start with %, not with #, and you should use end rather than endfunction, endif, etc. I don't feel that these additions improve the language sufficiently to break comparability between the two systems.

When you define a function with a single output argument, the square brackets around the output are superfluous. Thus, instead of writing

function [out] = getValue (this)

you can write

function out = getValue (this)

The use of a private property to hold data, and a public, dependent property to read and write from it, adds unnecessary complexity. It is possible to define accessor functions to protect public properties. For example, if the class only had a public value property, then the function set.value(this, value) can prevent the user from changing the value to an illegal value. A function value = get.value(this) likewise can control the reading of the property. The advantage is that one does not need to define the reading property if it's not necessary (there are default property reading and writing functions if one doesn't explicitly define them).

Putting all these things together, I would implement an enumerator class this way:

classdef Enum
   properties
      value
   end

   methods
      function this = Enum(value)
         if nargin > 0
            this.value = value;
         else
            this.value = 'none';
         end
      end

      function this = set.value(this, value)
         if ~ischar(value) || ~any(strcmp(value, {'foo','bar','baz','none'}))
            error(['Illegal value! ', value])
         end
         this.value = value;
      end

      function out = eq(this, other)
         out = strcmp(this.value, other.value);
      end

      function disp(this)
         disp(['Enum with value ',this.value])
      end
   end
end

You can use it as follows:

a = Enum;
b = Enum('foo');
c = Enum('foo');
>> a==b
ans = 0
>> c==b
ans = 1

Alternatively, if you don't want to allow the user to change the value of the enumerator (which, I gues, is not really necessary at all), then it is possible to keep the value property as read-only (SetAccess=private), or even completely private (Access=private), and remove the set.value function. With a private value property, the Enum class can still be copied, examined (using disp) and compared.


Your ID is a long created from 2 ints, so you can fit both ints inside this one long side by side:

long key = (long)nums[i] << 32 | i;

You have a lot of unnecessary if statement evaluations. You could get rid of them by adding the first k elements from the array into the list in a separate loop, and then starting a second loop from i = k that can safely do med.Remove and med.Add without ifs.

k never changes, so instead of evaluating k % 2 == 0 and k / 2 and k / 2 - 1 in every iteration, you can store the final value in a variable before the loop begins. Then in the loop you only need to call

res.Add(med[med.Keys[medianIndex]]);

or

res.Add( ((long)med[med.Keys[medianIndex]] + med[med.Keys[medianIndex2]])/2.0 );

Making res a list and in the end converting it into an array slows your code down a lot. You can make it an array (of size nums.Length - k + 1). Lists come with the overhead of their extra functionality, so you waste time not only on the conversion to an array but also on every time you add a number to the list.


finished Josephus-Problem in C#, how to make this more efficient?

List<int> list = new List<int>();
        int iCounter = 1; //always count till the size of the list
        int iWatcher = 1; //always count till the size of k
        for (int i = 1; i <= n; i++)
        {
            list.Add(i);
        }

You can initialize list more elegantly:

List<int> list = Enumerable.Range(1, n).ToList();

For n = 2; k = 1 it runs infinitely?

Your counting and indexing seem ok, but are a little difficult to comprehend. It can be done a lot easier using modular operations:

static int JosSurvivor(int n, int k)
{
  List<int> positions = Enumerable.Range(1, n).ToList();
  int index = k % n - 1; // %n is important for k > n

  while (positions.Count > 1)
  {
    if (index < 0) index += positions.Count;  // when (index + k) % poisitons.Count == 0 then index becomes -1 from the line below
    positions.RemoveAt(index);
    index = (index + k) % positions.Count - 1;
  }

  return positions[0];
}

Another approach building on the same principle is to maintain a fixed array of indices and then left-shift the reminder of the indices for each found index while decrement n by 1:

static int JosSurvivor(int n, int k)
{
  int[] positions = Enumerable.Range(1, n).ToArray();
  int index = k % n - 1;

  while (n > 1)
  {
    if (index < 0) index += n;
    Array.Copy(positions, index + 1, positions, index, n - index - 1);
    n--;
    index = (index + k) % n - 1;
  }

  return positions[0];
}

There seems to be a little performance gain - but not significant.

Yet another version that uses a fixed array of flags, that are set for each found index:

static int JosSurvivor(int n, int k)
{
  int counter = 0;
  int index = -1;
  int runner = 0;
  bool[] positions = new bool[n];

  while (counter < n - 1)
  {
    runner += k;
    int temp = 0;
    do
    {
      index = (index + 1) % n;
    } while (positions[index] || ++temp < k);

    if (runner > 0 && runner % k == 0)
    {
      positions[index] = true;
      counter++;
    }
  }

  for (int i = 0; i < n; i++)
  {
    if (!positions[i])
      return i + 1;
  }

  throw new InvalidOperationException("No last position found");
}

This is very fast for small ks - even for large ns - but becomes slower when k increases.


First of, yes, prepared statements are the way to go to prevent SQL injection (and you are using them correctly).

Reducing Code Length

The assignment of POST values to a variable as well as an array takes a lot of space, and it makes your code hard to read. There are a lot of solutions for this, one would be to move the assignment before bind, and then use the array values for binding:

$mail_params['email'] = $_POST['email'];
$mail_params['issue'] = $_POST['issue'];
[...]
if (!$stmt->bind_param("sssssss", [...], $mail_params['email'], $mail_params['issue'], [...])) {
    [...]
}

If you create one more function, it might also be a bit better structured:

submitCommentForm() {
    [extract POST values]
    insertComment([extracted post values]);
    sendMail([same extracted post values]);
    [render result]
}

insertComment($db, $comment_values) {
    [the database stuff]
}

sendMail($comment_values) {
    [send mail]
}

Misc

Your spacing and indentation isn't ideal, which makes your code a bit hard to read. You can probably use any IDE to fix this.
Don't echo in a function (it makes your code very inflexible). Just throw an exception.
Don't create your mysqli object in each function you need it, but pass it to the function as an argument (that way, you avoid duplicate code, and you make your functions more flexible and testable).


Shortcuts You can use 2 special regex syntax rules to make the pattern more concise:

When a token may or may not be matched, instead of {0,1}, it can be done with ? instead - they're exactly equivalent.

When you want to match a digit from 0 to 9, rather than writing out [0-9], you can use \d instead (they're exactly equivalent):

Typo? Regular expressions in JS are delimited by forward slashes, not backslashes.
Prefer const - Unless you plan on reassigning the regExp variable name, better to use const - only use let when you need to warn readers that the variable may be reassigned.
Missing semicolon Unless you're an expert and can avoid the pitfalls of Automatic Semicolon Insertion, I'd highly recommend using semicolons whenever appropriate, else you will occasionally run into hard-to-understand bugs.
Bug? You probably only want to match digits if they fulfill all the rules - I doubt you want to match the 30 part of 300, for example. I'd expect that you want a line that ends with 300 to not match at all, right? Fix it by adding a word boundary at the end:
const regExp = /exp[0-2]?\d{1,2}\b/;

Or, if the digits will always come at the end of the line, use $ and the m flag instead:
const regExp = /exp[0-2]?\d{1,2}$/m;

https://regex101.com/r/udp9BX/7