Writing a hyperlink to a cell with Apache POI

Some thoughts:

Use methods! Break out complexities where you can to make it easier on readers of your code.
Avoid statics. There's no reason for it. Make a reusable class instead.
It also helps to rearrange the member variables so they're declared right before they're used.
You really shouldn't have your three static instance variables as static instance variables.
To my knowledge, no, POI does not support anything other than reading in the whole file, making your change, and then writing the whole file.
If you're going to make lots of these calls, create an object that holds the four relevant pieces of information (label, link, row, column), then create them and stick them in a queue. When you've got all of them, open the workbook once and add them all. Might not be worth the complexity - are you sure you have a real performance bottleneck, or are you guessing?

The exception handling needs work, and it only probably compiles, but this might get you pointed in a good direction. Note that it is not thread-safe! An interesting addition might be to make it implement AutoCloseable so that clients could use it in a try-with-resources block, and have it write automatically when they were done with it. Just add a close() method that calls flush, and a check in all public methods to make sure close() hasn't been called yet.

public final class ExcelFileEditor {

    private final File file;
    private final List<HyperlinkAddition> hyperlinkAdditions = new LinkedList<>();

    public ExcelFileEditor(final File file) {
        this.file = file;
    }

    public void setHyperlink(
            final String label,
            final String hyperlink,
            final int row,
            final int column)
    throws IOException {
        this.hyperlinkAdditions.add(new HyperlinkAddition(label, hyperlink, row, column));
    }

    public void flush()
    throws IOException {
        final XSSFWorkbook workbook = this.loadWorkbook();
        for (final HyperlinkAddition hyperlinkAddition : this.hyperlinkAdditions) {
            this.setHyperlink(
                    workbook,
                    hyperlinkAddition.label,
                    hyperlinkAddition.hyperlink,
                    hyperlinkAddition.rowIndex,
                    hyperlinkAddition.columnIndex);
        }
        this.hyperlinkAdditions.clear();
        this.writeWorkbook(workbook);
    }

    private void setHyperlink(
            final XSSFWorkbook workbook,
            final String label,
            final String hyperlink,
            final int rowIndex,
            final int columnIndex) {

        final CreationHelper createHelper = workbook.getCreationHelper();
        final XSSFHyperlink url = createHelper.createHyperlink(XSSFHyperlink.LINK_URL);
        url.setAddress(hyperlink);

        final XSSFFont hyperlinkFont = workbook.createFont();
        hyperlinkFont.setColor(IndexedColors.BLUE.getIndex());

        final XSSFCellStyle hyperlinkStyle = workbook.createCellStyle();
        hyperlinkStyle.setFont(hyperlinkFont);

        final XSSFSheet sheet = this.getSheet(workbook);
        final XSSFCell cell = this.getCell(sheet, rowIndex, columnIndex);
        cell.setCellType(XSSFCell.CELL_TYPE_STRING);
        cell.setHyperlink(url);
        cell.setCellValue(this.buildCellLabel(label));
        cell.setCellStyle(hyperlinkStyle);
    }

    private XSSFWorkbook loadWorkbook()
    throws IOException {

        if (!this.file.exists()) {
            return new XSSFWorkbook();
        }

        try (FileInputStream fis = new FileInputStream(this.file)) {
            return new XSSFWorkbook(fis);
        }
    }

    private XSSFSheet getSheet(final XSSFWorkbook workbook) {
        final XSSFSheet sheet = workbook.getSheetAt(0);
        if (sheet == null) {
            return workbook.createSheet();
        }
        return sheet;
    }

    private XSSFCell getCell(final XSSFSheet sheet, final int rowIndex, final int columnIndex) {
        final XSSFRow row = this.getRow(sheet, rowIndex);
        final XSSFCell cell = row.getCell(columnIndex, XSSFRow.CREATE_NULL_AS_BLANK);
        if (cell == null) {
            return row.createCell(columnIndex);
        }
        return cell;
    }

    private XSSFRow getRow(final XSSFSheet sheet, final int rowIndex) {
        final XSSFRow row = sheet.getRow(rowIndex);
        if (row == null) {
            return sheet.createRow(rowIndex);
        }
        return row;
    }

    private String buildCellLabel(final String label) {
        if (label.isEmpty()) {
            return "Empty String";
        }
        return label;
    }

    private void writeWorkbook(final XSSFWorkbook workbook)
    throws IOException {
        final FileOutputStream fileOutputStream = null;
        try (FileOutputStream fos = new FileOutputStream(this.file)) {
            workbook.write(fos);
        }
    }

    private static final class HyperlinkAddition {
        public final String label;
        public final String hyperlink;
        public final int rowIndex;
        public final int columnIndex;

        public HyperlinkAddition(
                final String label,
                final String hyperlink,
                final int rowIndex,
                final int columnIndex) {
            this.label = label;
            this.hyperlink = hyperlink;
            this.rowIndex = rowIndex;
            this.columnIndex = columnIndex;
        }
    }
}


I would just name the variable for Bluebird promises as Promise as it mostly acts like the standard Promise object in ES6. That way, if you happen to run an ES6-compatible Node.js, you can just remove the import, and you'll be set.
In the promise constructor, you need not do a return. The code will also feel awkward to a new developer, thinking Promise needs a return. You can simply do:

jwt.verify(token, req.app.config.api.secret, function(err, decoded) {
  if (err) reject(err);
  else resolve(decoded);
});

Bluebird has a static method called Promise.promisify which converts callback-style APIs into promise-returning ones. Just make sure you follow it's guidelines in that:

  function should conform to node.js convention of accepting a callback as last argument and calling that callback with error as the first argument and success value on the second argument.

If your operation needs to return a promise, but it's not async, then you can simply return a resolved or rejected promise instantly using Promise.resolve and Promise.reject static methods, respectively.

var validateEmptyFields = function() {
  var token = req.body.token || req.param('token') || req.headers['x-access-token'];
  return token ? Promise.resolve(token) : Promise.reject('Please provide the token parameter')
};

In getEvents, I suggest you resolve with events. Then assemble results in the same way you assembled errors in catch. The idea is that your promise-generating functions should not be causing side-effects. It should only be aware of the fact that you called it with some arguments, and it resolves or rejects and nothing more.
Move out that SQL query from the logic. It's messy.

And so, without further ado:

var Promise = require('bluebird');
var jwt = require('jsonwebtoken');

var EVENT_QUERY = '\
SELECT e.* FROM events e \
INNER JOIN event_to_groups etg ON e.id=etg.event_id \
INNER JOIN user_to_groups utg ON utg.group_id=etg.group_id \
WHERE utg.user_id=?';

exports.events = function(req, res) {
  var results = {};
  var errors = [];

  var validateEmptyFields = function() {
    var token = req.body.token || req.param('token') || req.headers['x-access-token'];
    if (!token) Promise.reject('Please provide the token parameter');
    else Promise.resolve(token);
  };

  var getUser = function(token) {
    return new Promise(function(resolve, reject) {
      jwt.verify(token, req.app.config.api.secret, function(err, decoded) {
        if (err) return reject(err);
        else resolve(decoded);
      });
    });
  };

  var getEvents = function(user) {
    return new Promise(function(resolve, reject) {
      req.app.db.getConnection(function(err, connection) {
        if (err) return reject(err);

        connection.query(EVENT_QUERY, user.id, function(err, events) {
          if (err) return reject(err);
          else resolve(events);
        });

        connection.release();
      });
    });
  };

  validateEmptyFields()
    .then(getUser)
    .then(getEvents)
    .then(function(events) {
      results.events = events;
    }, function(err) {
      errors.push(err);
    })
    .finally(function() {
      res.json({
        results: results,
        errors: errors
      });
    });
};


Could this be considered a valid mergesort?

No, it is not a merge sort. It never accounts for the fact that list1 is already sorted. Instead it performs len(list1) insertions, every time traversing list2 from the very beginning.

Each call to mymerge is quadratic with respect to the length of the list). At each recursion level \$r\$ there are \$2^r\$ fragments of length \$\dfrac{n}{2^r}\$, so each recursion level will take \$O\left(r\left(\dfrac{n}{2^r}\right)^2\right)\$ time, and summing up for \$r\$ from \$1\$ to \$\log{n}\$ yields the total complexity \$O\left( n^2 \log{n}\right)\$.

The expected runtime of merge sort shall be \$O(n\log{n})\$ (or \$O(n \log^2{n})\$ if done in place).


Determining the state of matter for some substances

Works well!

This:

const liquidType = this.state.liquidType;
const temperature = this.state.temperature;

Can be written as:

const { liquidType, temperature } = this.props;

This:

function LiquidState(props){
  var liquid = props.liquidType;
  if (props.temperature >= liquidInventory[liquid].boiling){
    return
 Boiling {liquid}

  } else if (props.temperature <= liquidInventory[liquid].freezing){
    return
 Frozen {liquid}

  } else {
    return
 You have liquid {liquid}

  }
}

Can be written as:

const LiquidState = ({ liquidType, temperature }) => {
  if (temperature >= liquidInventory[liquidType].boiling){
    return
 Boiling {liquidType}

  } else if (temperature <= liquidInventory[liquidType].freezing){
    return
 Frozen {liquidType}

  } else {
    return
 You have liquid {liquidType}

  }
}

It's not much, but it's been useful to me.

I think lifting the state up is mainly important, if you're actually using the state in the high level component or one of its child components.

In this case, the value in the input is passed on to every input. If you instead keep state local to the component, you can type different values for each liquid.

I've just made my own attempt to learn something myself. Maybe there's one more useful thing hiding in there:

var liquids = {
  ethanol: {
    name: "Ethanol",
    states: [
      {
        minTemperature: 173.1,
        maxTemperature: Infinity,
        state: 'Boiling'
      },
      {
        minTemperature: -173.2,
        maxTemperature: 173.1,
        state: 'Liquid'
      },
      {
        minTemperature: -(Infinity),
        maxTemperature: -173.2,
        state: 'Frozen'
      }
    ]
  },
  water: {
    name: "Water",
    states: [
      {
        minTemperature: 212,
        maxTemperature: Infinity,
        state: 'Boiling'
      },
      {
        minTemperature: 0,
        maxTemperature: 212,
        state: 'Liquid'
      },
      {
        minTemperature: -(Infinity),
        maxTemperature: 0,
        state: 'Frozen'
      }
    ]
  }
}

class TemperatureInput extends Component {
  constructor(props) {
    super(props)
    this.state = {
      temperature: 0
    }
  }

  onChangeTemperature(event) {
    this.setState({ temperature: parseFloat(event.target.value) })
  }

  renderLiquidState(liquid, temperature) {
    for(var i = 0; i < liquid.states.length; i++) {
      if(liquid.states[i].minTemperature < temperature && temperature <= liquid.states[i].maxTemperature) {
        return {liquid.states[i].state} {liquid.name}
      }
    }
  }

  render() {
    const { liquid } = this.props
    const { temperature } = this.state

    return (

        <fieldset>
          <legend>
            Enter Temperature for {liquid.name}:
          </legend>
          <input
            value={temperature}
            onChange={this.onChangeTemperature.bind(this)}
          />

          {this.renderLiquidState(liquid, temperature)}
        </fieldset>

    )
  }
}

class Temperature extends Component {
  render() {
    return (

        <TemperatureInput liquid={liquids.water} />
        <TemperatureInput liquid={liquids.ethanol} />

    )
  }
}


Interesting question,

there are few things that could be improved:

Read up on the revealing module pattern, it would be excellent to

Reduce your usage of this
Make your class look like 1 piece of code

Something like this:

// main particle constructor class
function Particle(position) {

  var velocity = new PVector(random(-0.1, 0.1), random(-0.1, 0.1)),
      acceleration = new PVector(random(-0.01, 0.01), random(-0.01, 0.01)),
      lifeTime = 300,
      position = position.get();

  function update() {
    velocity.add(acceleration);
    position.add(velocity);
    lifeTime--;
  }

  function render() {
    strokeWeight(2);
    stroke(161, 153, 153, lifeTime);
    fill(140, 135, 140, lifeTime);
    ellipse(position.x,position.y, 15, 15);
  };

  return {
    update : update,
    render: render;
  }
};

I obviously did not rewrite the whole thing, but you should catch my drift.
You keep using random(-0.1, 0.1), I would create a helper function for this
fill(140, 135, 140, lifeTime); <- I would put a comment as to what color this should be
Do not use an if statement to determine true or false like you do :

// check if the particle is dead
Particle.prototype.particleDead = function() {
    if(this.lifeTime > 0) {
        return false;
    } else {
        return true;
    }
};

do this instead:

// check if the particle is dead
Particle.prototype.particleDead = function() {
    return this.lifeTime > 0
};

If you have time, read up on falsy values, you could also simply do return !this.lifetime
I am still playing with the code, I managed to fix the right hand side bounce with this:

if(this.position.x >= 385) {
  this.acceleration.x = random(-0.02, -0.01);
  this.velocity.x = random(-0.1, -0.01);
}

In essence you have to solve both the acceleration and the velocity.

I have to wonder, how do you access random? I can only access random as a function under the instance of Processing.

It is too bad that the snippets will now allow for localStorage access, so I can only give you a link to jsbin with my refactored version and the source code here in case jsbin ever dies:

var canvas = document.getElementById('partikals'),
    pjs = new Processing(canvas),
    width = 400,
    height = 400,
    padding = 15;

function Particle2(position) {

    var velocity = new PVector(pjs.random(-0.1, 0.1), pjs.random(-0.1, 0.1)),
        acceleration = new PVector(pjs.random(-0.01, 0.01), pjs.random(-0.01, 0.01)),
        lifeTime = 300;

    position = position.get();

    function update() {
        velocity.add(acceleration);
        position.add(velocity);
        lifeTime--;
    }

    function render() {
        pjs.strokeWeight(2);
        //Each particle is grey
        pjs.stroke(161, 153, 153, lifeTime);
        pjs.fill(140, 135, 140, lifeTime);
        pjs.ellipse(position.x, position.y, 15, 15);
    }

    function isDead() {
        return !lifeTime;
    }

    //I wonder if just *= -1 would work
    function bounce() {
        if (position.x > width - padding) {
            acceleration.x = -Math.abs(acceleration.x);
            velocity.x = -Math.abs(velocity.x);
        }
        if (position.x < padding) {
            acceleration.x = Math.abs(acceleration.x);
            velocity.x = Math.abs(velocity.x);
        }
        if (position.y > height - padding) {
            acceleration.y = -Math.abs(acceleration.y);
            velocity.y = -Math.abs(velocity.y);
        }
        if (position.y < padding) {
            acceleration.y = Math.abs(acceleration.y);
            velocity.y = Math.abs(velocity.y);
        }
    }

    return {
        update: update,
        render: render,
        isDead: isDead,
        bounce: bounce
    };
}

// array containing particles
var particles = [];

pjs.setup = function() {
    pjs.size(width, height);
    pjs.frameRate(24);
};

pjs.draw = function() {

    //Clear by drawing the background and push a new particle
    pjs.background(11, 100, 209);
    particles.push(new Particle2(new PVector(pjs.mouseX, pjs.mouseY)));

    // iterate through particles and run their methods
    for (var p = particles.length - 1; p >= 0; p--) {
        var particle = particles[p];
        particle.bounce();
        particle.update();
        particle.render();
        if (particle.isDead()) {
            particles.splice(p, 1);
        }
    }
};

pjs.setup();


BigDecimal money = scan.nextBigDecimal();

The specification said

  reads a double value representing a monetary amount.

However, BigDecimal is the correct type to represent a monetary amount. There's a case to be made for using scan.nextDouble() to comply with the spec and then converting it to BigDecimal. There's also a case to be made that you should talk to the person who set the task and suggest improving the spec.

    BigDecimal tenDollarNext = money.divideToIntegralValue(tenDollar);
    System.out.println(tenDollarNext.intValue() + " Ten Dollar Bills");

    BigDecimal fiveDollarNext = money.subtract(tenDollar.multiply(tenDollarNext));
    BigDecimal i = fiveDollarNext.divide(fiveDollar);

Why the inconsistencies? tenDollarNext and fiveDollarNext aren't analogues of each other, and one uses divideToIntegralValue(...) where the other uses divide(...).intValue().

There are seven chunks of code dealing with seven values of token which are virtually identical. DRY: use a loop.


Find a file in current or parent directories

Handling Path and PathBuf types correctly;

My concern is that you recreate PathBuf every time, I don't see the point to have a buffer if you don't use it.

  Performance;

I think it's ok, you search one file in particular the time you take creating the string is cheap compare to system call. So I don't think read_dir is better on your case. This could be benchmarked.

  Rust writing style in general.

You are using return, on your case maybe use break to make your function SESE (single entry single exit).

Path::new(&RUSV_FILENAME); the reference is not needed Path::new(RUSV_FILENAME);.

fn find_rusv_file(starting_directory: &Path) -> Option<PathBuf> {
    let mut path: PathBuf = starting_directory.into();
    let file = Path::new(RUSV_FILENAME);

    loop {
        path.push(file);

        if path.is_file() {
            break Some(path);
        }

        if !(path.pop() && path.pop()) { // remove file && remove parent
            break None;
        }
    }
}


Renaming all files/folders in first children folders but not sub-children

You should rethink your solution in terms of regexes:

#!/usr/bin/env python3

import re
from os import scandir, rename, path

def rename_children(parent):
    n_renamed = 0
    re_fname = re.compile('(IMG|PANO|VID)_')

    for child_dir in scandir(parent):
        if child_dir.is_dir():
            for child in scandir(child_dir):
                renamed = re_fname.sub('', child.name)
                if renamed != child.name:
                    new_path = path.join(child_dir.path, renamed)
                    print(f'Renaming {child.path} to {new_path}')
                    rename(child.path, new_path)
                    n_renamed += 1
    print(f'{n_renamed} files renamed')

Note the following changes:

Only one if to check whether the regex matches
Use scandir instead of listdir
Do not call chdir; there's no point
Don't call replace; the pattern check and the replacement operation can be combined by using sub
Don't store a list of all_subfolders; simply iterate over the results


Adding Combinations of Numbers in an Array

The code is fine, and asymptotically optimal. There is a potential speedup by preallocating the output list to the correct size, but it's at best a factor of 2. VisualMelon's comment is unnecessarily pessimistic: List<T>.Add has an amortised cost of \$O(1)\$, although to show that it's necessary to rely on implementation details which are not in the API documentation.

There are some small improvements which could be made. The spec asks for "a list" rather than "a List", so I see no reason not to follow the principle of coding to the interface. I would prefer to return IList<int> or IReadOnlyList<int>.

The other thing is names. The return in returnSums doesn't tell me anything useful. How about pairwiseSums? And instead of x and y I would use i and j, which are de facto standard variable names for array indices for reasons going back to FORTRAN's type system.


Taking some JSON data, converting the date format and calculating a user average

This answer is by no means complete but I would like to give you a few hints.
Use for-loops sparingly, prefer combinators - map, flatMap, filter, zip etc.
For example in the last snippet, instead of iterating over sessions using for loop, try something like:
val filtered = session.filter(session.get()...)
val sessionSize = filtered.size
val sum = filtered.map(_.get("Score").asInstanceOf[Double]).sum

Always think twice before writing for-loop, it is very likely you can achieve the same using combinators.
Of course, common sense applies, don't try to pack all your code into one long line of combinators - split it into many lines and use indentation and local variables to keep it readable.
You don't have to declare types when defining variables
It is quite typical in Scala code not to declare types for local variables, so try:
val date = utcFormat.parse(session.get("UTCStartTime").toString)

without declaring type :Date
However, if variable has wider scope or providing type would improve readability then, of course, you can still do it. I encourage you to declare return types on public methods.
Learn about different implementations of list in Scala
Most popular ones below.
Mutable:

ListBuffer - quick sequential access
ArrayBuffer - quick random access (like Java's ArrayList you mentioned)

Immutable:

List - implemented as linked list

Prefer immutable ones if you want to code in FP style. Read about "structural sharing" if you have doubts about performance of immutable data structures
Don't use return keyword - it is redundant and potentially dangerous
In your examples you can remove all occurrences of return, read more about usage of return here: Don't use return in Scala
Bonus
Here is a talk from Scala's author where he presents his definition of idiomatic Scala - Scala with Style
Hope this will help.


First a few minor points:

You should give the definition of split-on-first-char since it is an important function in this context.
You should use equal instead of equalp to compare a value with a string (assuming that you cannot use string= to allow the first argument not to be a string).
The second parameter of parse-netstring could be defined as &optional, so that the function could be called with only the first parameter, and the second is automatically initialized with the empty list.

Then, let’s go to the main point: your function does not check many error conditions, and this is very bad for a function like this, that could get its input from the outside of the system (for instance, from a stream or a file). So, I think that you should do much more checks, for instance:

when the string does not start with a number,
when the first string part is less than the size,
when the size is greater than the whole string, etc.

The objective is to catch all the possible errors arising from calling primitive functions.

So I propose to rewrite the function in the following way, and in rewriting it I propose also a different approach to the recursion: use an auxiliary function, and recur only on the start index of the string, this make the code simpler and avoid a lot of costly subseq calls. Moreover, working with the indexes allow to get rid of the function split-on-first-char (again, with costly subseq calls). This is made possible also by the use of parse-integer with the junk-allowed parameter, which stops on the first non-numeric character, and by the fact that parse-integer returns two values, the number (which is NIL if it is not present), and the first position after the number. Here is the function:

(defun parse-netstring (netstring &optional acc)
  "recursively parses netstring of the form
   size1:string1,size2:string2,size3:string3,
   acc can be any list, or nil
   returns -> (string3 string2 string1)"
  (check-type netstring string "a string")
  (check-type acc list "a list")
  (let ((end (length netstring)))
    (labels ((parse-aux (start acc)
               (if (= start end)
                   acc
                   (multiple-value-bind (string-size semicolon-position)
                       (parse-integer netstring :start start :junk-allowed t)
                     (let ((comma-position
                             (when string-size (+ string-size semicolon-position 1))))
                       (unless (and string-size
                                    (< comma-position end)
                                    (<= string-size end)
                                    (char= (char netstring semicolon-position) #\:)
                                    (char= (char netstring comma-position) #\,))
                         (error  'malformed-netstring-error :netstring netstring))
                       (parse-aux
                         (1+ comma-position)
                         (cons (subseq netstring (1+ semicolon-position) comma-position) acc)))))))
      (parse-aux 0 acc))))


You're right, it is a bit repetitive. I believe you could boil it down to the following:

var door = id2 + id3.substr(1);
$("g" + door).show().siblings("g:not(#BG," + id + ")").hide();

or even:

$("g" + id2 + id3.substr(1)).show().siblings("g:not(#BG," + id + ")").hide();

ALSO if you change:

var doorColorChoice = String($('input[name=radiosColor]:checked', '#myFormFront').val());
var id3 = String("#" + doorColorChoice);

to

var id3 = String($('input[name=radiosColor]:checked', '#myFormFront').val());

you could have:

$("g" + id2 + id3).show().siblings("g:not(#BG," + id + ")").hide();

(provided the rest of your code doesn't need the "#" (hash) in id3. That would be faster than using substr)


Pomodoro countdown timer synced to the clock

Bug

There is an off chance that the interval event that you start at the bottom of the script with setInterval(startTime, 1000); will fire before the page has fully loaded, causing the first run to throw an error at document.getElementById("message").innerHTML =
However it is a minor bug and will fix itself in the next interval.

Some coding points

Avoid putting code in the HTML. eg you have   which can be done in the script with addEventListener("load",startTime) But its not really needed as you have the interval call the function anyway.
You can access elements directly via their id as long as you ensure that the id is unique on the page. If you use the same name for any other id or name element property then it will not work. Refer to answers to this SO post for more context.
When adding text only (no HTML) to an element it is more efficient to add it via the textContent property. For simple stuff it's not a major issue, it is when you start to add lots of content that it will be noticeable.

Regarding time
The value of a Date object is an integer that counts the milliseconds since 1 January 1970 UTC.
Since you are not interested in the specific time, but rather half hour periods it can be simpler to work in milliseconds rather than the more complex minutes, seconds format.
To get the millisecond value you can use Date.now() and to change that value to half hour chunks you get the remainder of dividing by 30 * 60 * 1000ms using the remainder operator %
The  remainder operator % is great when you need to get cyclic values.
Example snippet
The example below show how it can be done using milliseconds alone.

addEventListener("load", displayPeriod);  // start on page load

const second = 1000;          // length of second in ms
const minute = 60 * second;   // length of minute in ms
const halfHour = 30 * minute; // length of half hour in ms

function displayPeriod() {
     const halfHourTime = Date.now() % halfHour;
     var nextPeriod = 25 * minute;

     if (halfHourTime <= nextPeriod) {
         message.textContent = "WORK TIME";
     } else {
         message.textContent = "BREAK TIME";
         nextPeriod = halfHour;
     }
     const min = Math.floor((nextPeriod - halfHourTime) / minute);
     const sec = Math.floor((nextPeriod - halfHourTime) / second) % 60;

     countDown.textContent = min + ":" + ("" + sec).padStart(2,"0");

     var time2Second = second - halfHourTime % second;
     if (time2Second < 50) { // if too close delay a littl
         time2Second += 50;
     }
     setTimeout(displayPeriod, time2Second);
}
div{
   font-family : arial;
   font-size : 32px;
   width : 100%;
   text-align : center;
}

Or using interval and shortening the naming as I find long names hard on the eyes. Also I use a shortcut for Math.floor the bitwise | 0  which is handy for rounding down positive numbers. I also used the ms times expressed with the exponent as I happen to know them (3e5 is 5 minutes in milliseconds)
I would consider the second snippet of lower quality, but for simple projects less code can be better.

addEventListener("load", () => setInterval(displayPeriod,1000));  // start on page load

function displayPeriod() {
     const time= Date.now() % 18e5;
     var nextP = 15e5;
     var mes = "WORK TIME :(";

     if (time > nextP) {
         mes = "BREAK TIME :)";
         nextP = 18e5;
     }

     const m = (nextP - time) / 6e4 | 0;
     const s = ("" + ((nextP - time) / 1e3 | 0) % 60).padStart(2,"0");

     message.textContent = mes;
     countDown.textContent = m + ":" + s;
}
div{
   font-family : arial;
   font-size : 32px;
   width : 100%;
   text-align : center;
}

setInterval V setTimeout
Personally I prefer using setTimeout rather than the setInterval as it give finer control over when the next event will fire. In the example I use the ms time to workout how long it is till the next second starts, if too close to ensure the timer will fire (browsers may throttle timers) I offset it a little.
This method sets the event for the closest coming second, and will skip any missed seconds.
But setInterval is just as good but if the system is busy the countdown can skip displaying seconds more often than using setTimeout


How can I optimize my Von Neumann neighborhood algorithm?

Set vs. dict
So far as I can tell, you aren't really using the value in is_counted, so it is better represented as a set than a dictionary. Also, it shouldn't be global - this prevents re-entrance and hampers testing; instead, make it a return value of find_von_neumann, merged in turn into another set in populate_dict that is returned.
Iteration
This is both very dense and re-executes a number of things that can be pre-computed:
    for i in range(curr_i + min((-n), rows), curr_i + min((n + 1), rows)):
        for j in range(curr_j + min((-n), cols), min(curr_j + (n + 1), cols)):

instead consider something like
i0 = curr_i + min((-n), rows)
i1 = curr_i + min((n + 1), rows)
j0 = curr_j + min((-n), cols)
j1 = min(curr_j + (n + 1), cols)

for i in range(i0, i1):
    for j in range(j0, j1):

Combined inequalities
You did the right thing here:
n >= dist >= -n

though I would find it more intuitive as
-n <= dist <= n

You should do the same for i and j:
0 <= i < rows and 0 <= j < cols


Language switcher, consulting browser's localStorage

The rewrite of LocalStorage is normal practice because of a rewrite time ~equal check time.

You can change the code.

localStorage.setItem('lang', language);

By the way JSON.parse and  JSON.stringify is unnecessary actions in your code because language is already string.

I only considered the code associated with your the question.


If you are using the standard library classes of the same name, I would give the following names the correct namespace qualifier: std::string, std::stringstream, std::hex.

In C++, this works just as well, IMHO it's mildy more idiomatic.

uint32 hexform[ITEMLINKGROUPCOUNT] = {};

ebx, edi, ecx, eax are not good variable names, if you can give them more meaningful names, then do.

    uint32 ecx = (hexform[i] + 1) * hexsum,
           eax = ecx * hexform[i];

Personally, I think this is clearer:

    uint32 ecx = (hexform[i] + 1) * hexsum;
    uint32 eax = ecx * hexform[i];

The comment is really bad because it talks about hexform[i]^2 + hexform[i] * hexsum whereas ecx gets the value hexform[i] * hexsum + hexsum and eax gets the value hexform[i]^2 * hexsum + hexform[i] * hexsum. I think the comment needs a pair of parentheses if the code is doing what you meant.

To be robust, you should check whether the parse worked.

parseitemlink >> hex >> hexform[i];

You can trivially combine the first two for loops as well.


Completely untested psuedo-code, but the key is to realize f = number of days from March 22 to Orthodox Easter.

(* f gives Easter as the number of days since March 22 *)

easter = f+22+(year<1918)*13

month = "March"; # default
if f > 31 {month="April"; day=f-31}
if f > 61 {month="May"; day=f-61}

You might also post to http://codegolf.stackexchange.com


As for the architecture it seems good to me.

As for the TypeScript I have a few minor suggestions:

Avoid using var, use const or let instead.

function randomIntString(min: number, max: number): string {
    const chance = require('chance').Chance();
    const randomVar: number = chance.integer({
      min: min,
      max: max
    });

    return randomVar.toString();
}

It is also preferable to use let for for-cycle control variables.

for (let x = 0; x < sel.length; x++) {
   // body
}

It would help readability and maintainability if you specified the types of all the arguments of all your functions.

function randomIntString(min: number, max: number): string {
    // body
}

Also prefer using lower case type names for built-in primitive types (e. g. number over Number) when specifying the type of something.

You could specify the IP option type more precisely (asuming you use TypeScript >= 2.0). This will help you prevent typos and also improves readability (the code is more self-documenting):

type IpAddressType = 'ipv4' | 'ipv6';
function randomIP(option?: IpAddressType): string{
    // body stays the same
}

When the property of the object being initialized has the same name as the variable assigned to it you can shorten it like so (see the chance.integer call):

var randomVar: number = chance.integer({
      min,
      max
    });


Using separate functions for Project Euler 1

Here's some superficial review. More for testing the site and some comment formatting than anything, but: do create main functions (helps us benchmarkers a lot) and do think that your module can be imported, so docstrings and local variables help.

# Finds...
###-^ Put this in a docstring

def find_multiples():
    """Finds sum of all multiples of 3 and 5 from 0 to 999 """
###-^ This allows you to "from x import find_multiples,  help(find_multiples)"
    numbers = []
###-^ Avoid globals
    for i in xrange(1000):
###-^ Use xrange if Python 2.x, no need to start at 0 (it's the default)
       if not (i % 3) or not (i % 5):
###-^ Add spaces around operators, simplify
###-^ the boolean/numeric checks
           numbers.append(i)
###-^ Remove trailing ;
    return numbers

###-^ Removed global

def main():
###-^ Allows calling main many times, e.g. for benchmarking
    numbers = find_multiples()
    print sum(numbers)

if __name__ == '__main__':
    main()


Extracts marks of all students in class from website

Style

Your code looks good but you might like to know that there is a Style Guide for Python Code called PEP 8. If you are interested, you'll find tools to check your code automatically (pep8) and to fix it (autopep8).

In your case, I can see straight-away that you are sometimes missing spaces around your '+' operator.

String format

You'll find various more pythonic ways to format your number with leadings 0s.

Also, in case you want to keep your current logic, comparison can be written pretty succintly in Python so that you can simply write : if 1 <= roll < 10. (Please note that in Python 2.x, range returns a list so checking if x in range(whatever) is not efficient in time (it has to check all elements if the elements you are looking for is not in the list) nor in memory (a list is built for no reason)).

Using context managers

Opening files and remembering to close them is a bit tedious. Good thing is that Python has a clean solution to this : the with keyword. In a nutshell, you use with when you open your file, you add a level of indentation and the magic to close your file will happen automaticaly.


JUnit - Test whether object was persisted or not

I'm going to assume that you have a standard DAO setup so you should try the following.

@Test
public void testCreated(){
    ConfirmationTypeEntity confirmationTypeEntity = confirmationTypeDao.find(1L);
    UserEntity userEntity = userDao.find(1L);

    ConfirmationEntity confirmationEntity = new ConfirmationEntity();
    confirmationEntity.setConfirmationTypeEntity(confirmationTypeEntity);
    confirmationEntity.setUserEntity(userEntity);
    confirmationEntity.setConfirmationString("5374a74e9542f");
    confirmationEntity.setConfirmationStringValidUntil(new LocalDateTime());

    int countPreSave = confirmationDao.count();

    confirmationDao.create(confirmationEntity);

    /* This call has the advantage of getting Hibernate to flush the session
     * to prevent you reading stale data in your count call.
     */
    int countPostSave = confirmationDao.count();

    assertEquals("The number of confirmations doesn't match what was expected",
                  countPostSave,
                  countPreSave + 1);

There, you've just ensured that your object was saved correctly, and only 1 record was inserted. You can do similar things for update (ensure countPreUpdate and countPostUpdate match) and delete (ensure countPostDelete = countPreDelete - 1)

If you don't have a count() method, here is the Hibernate criteria implementation:

@Override
public int count() {
    Criteria criteria = getCurrentSession().createCriteria(type);
    criteria.setProjection(Projections.rowCount());
    return (Integer) criteria.uniqueResult();
}


Count the number of vowelgroups in a string

Using the itertools recipe pairwise you can directly use sum to calculate the number of vowel groups by iterating over pairs of values.

In addition I would make the vowels a global constant and a set, because building the string every time is going to cost some time. Also, sets have very fast membership testing.

With these changes you would get:

from itertools import tee, izip

VOWELS = set("aeiouy")

def pairwise(iterable):
    """s -> (s0,s1), (s1,s2), (s2, s3), ..."""
    a, b = tee(iterable)
    next(b, None)
    return izip(a, b)

def count_vowelgroups(words):
    words = words.lower()
    return sum(c_1 not in VOWELS and c in VOWELS for c_1, c in pairwise(words))


Should I split class or keep it all in one?

This class has a well defined role and by keeping it intact you are satisfying the Single Responsibility Principle. So, I would leave it like that. Perhaps you might want to look into how you could refactor some common code out of each method and into a separate utility class, but that's all.


Looks sort of like you're trying to accomplish a singleton pattern, using the App class to control them all. Try this approach instead:

<?php
// Base / abstract class that defines a basic singleton pattern
abstract class SingletonProvider
{
  // Singleton pattern
  protected static $_instance;
  public static function getInstance()
  {
    if(static::$_instance == null)
    {
      static::$_instance = new static();
    }
    return static::$_instance;
  }

  // Private constructor
  private function __construct() { }
}

// A specific provider class definition that inherits the singleton pattern
class MyProvider extends SingletonProvider
{
  // Class-specific instance reference
  protected static $_instance;

  // --- CLASS INSTANCE-SPECIFIC PROPERTIES AND METHODS BELOW HERE ---

  // Class properties
  public $FieldX;

  protected function __construct()
  {
    $this->FieldX = "Hello World!";
  }
}

// Another specific provider class definition that inherits the singleton pattern
class MyOtherProvider extends SingletonProvider
{
  // Class-specific instance reference
  protected static $_instance;

  // --- CLASS INSTANCE-SPECIFIC PROPERTIES AND METHODS BELOW HERE ---

  // Class properties
  public $FieldY;

  protected function __construct()
  {
    $this->FieldY = "Foo";
  }

  public function MakeMoreExciting($sentence)
  {
    return $sentence . "!!!!!!!!";
  }
}

// Usage examples
echo MyProvider::getInstance()->FieldX; // Hello World!
echo MyOtherProvider::getInstance()->FieldY; // Foo
echo MyOtherProvider::getInstance()->MakeMoreExciting("Hi there"); // Hi there!!!!!!!!

The "static" keyword is used for late static binding, which basically means that when you run MyOtherProvider::getInstance(), all the "static" references like "static::$_instance" resolve to the calling class, so it's like automatically determining either MyOtherProvider::$_instance or MyProvider::$_instance, depending on which class is being called.

The protected static $_instance is there to ensure that each class has its own property to hold the class instance.

In theory, you could even shorten all of this up into nothing but static methods and properties, too:

abstract class MyOtherProvider
{
  // Class properties
  public static $FieldY;

  public static function MakeMoreExciting($sentence)
  {
    return $sentence . "!!!!!!";
  }
}

echo MyOtherProvider::MakeMoreExciting("Hi there"); // Hi there!!!!!!

Although sometimes you might want an actual instance rather than just being completely static.


Sorry for being late, but had no time to study your code until today.
The results are the same which AmirHossein presented before.

After you conditionally swap the input arrays:

    if m > n:
        A, B, m, n = B, A, n, m

you have m <= n, so

    half_len = (m + n + 1) // 2

(after the fix by AmirHossein) is not less than m. That makes

    j = half_len - i

greater than zero if i < m, so j > 0 and i < m is redundant.

Of course half_len is also is not greater than n, so similary j < n if i > 0.

As for the complexity, the code bisects the A array in each iteration, so the complexity is actually \$\mathcal{O}(\log m)\$ where m is the length of A after the conditional swap, or \$\mathcal{O}(\log (\min(m,n)))\$ in terms of input values of m,n. And this can be bounded by \$\mathcal{O}(\log (m+n))\$.


Mutex implementation for a uniprocessor bare metal embedded OS

Does this really work?  You call cpu_atomic_cmpxchg without taking any notice of its return value. I guess the function must return true or false (1 or 0 etc) according to whether the lock was already taken or not and it seems likely that you should take notice of that.

Also, if it were my code I'd drop all the unlikely() and likely() calls.  For my money, they just obscure the code and I doubt they are necessary.

I haven't read the functions in detail, so maybe I misunderstood the code...

EDIT: Read it again and have some comments:

Your point 10: "Mutex MUST not be freed without calling mutex_deinit." is
strange.  Isn't there a difference between freeing the mutex (lock/free is
what you normally do, no?) and de-initialising it (which you would do when
it is no longer needed, if at all)?
'restrict' used in functions with a single parameter has no purpose
Reviewers and readers would be more likely to understand what is going on if
your functions had some commets as to their intended purpose/use/return
values etc.
How do the 'atomic' functions wait for mutex availability?
Shouldn't mutex_init fail on an already-initialised mutex?
How do you know when it is safe to deinit a mutex?
Your mutex flags are confusing.  You have DEAD, BUSY, LOCKED, SUCCESS,
READY.  Seems likely to me that there is some redundancy here.  Or
conflating state flags and return values.
What is the point in all those MUTX flags if you assume the value of one of
them (in  if(unlikely(ret))) - assuming the atomic function returns one.
What is the difference between BUSY and LOCKED?
mutex_acquire_timeout doesn't tell the caller whether a timeout occurred!
(or whether enquing falied!)
So if the mutex has an owner already in mutex_acquire_timeout, you put the
thread onto a queue, with a timeout.  Presumably thread_queue_enqueue
returns either when awoken by thread_queue_wake_highest_priority in
mutex_release, or when there is a timeout.   But you carry on and
replace the mutex owner whatever the case...
Your point 4 says a mutex can only be released by its owner, and yet
mutex_release goes ahead and plays with the mutex queue whoever calls it.
Also sets state (ie releasing the local lock) before playing with the queue;   surely there will be a race condition there.

Sorry, but I don't believe this code 'works' in a meaningful way.  Why are
you writing these primitives anyway?  Why not use an existing kernel?  It is
generally a mistake to write your own (although I've worked at several that
have done, with bad consequences).


Concatenating results in a comma separated list

Concatenating strings from rows in to a single field is an age-old quandary among the SQL Server community unfortunately.

In SQL Server 2017, Microsoft introduced the STRING_AGG function which has performance benefits over the "stuff XML" method you're using above. It also looks a lot cleaner, which is nice. Example:

SELECT
    i.Rn_Interaction_Id,
    STRING_AGG(e.Full_Name, ', ') WITHIN GROUP (ORDER BY e.Full_Name) as Employees
FROM Rn_Interactions i
    LEFT JOIN Rn_Int_Employee ie ON i.Rn_Interactions_Id = ie.Rn_Interactions_Id
    LEFT JOIN Employee e1 ON ie.Employee_Id = e1.Employee_Id
GROUP BY Rn_Interaction_Id

(Haven't actually tested that, but it shows you how you might use STRING_AGG)

If you haven't got and can't get SQL Server 2017 though, tough luck unfortunately. One solution might be to tackle the root of the problem: Create a field on the Rn_Interactions table that is meant to store this string, then re-write the string to the table every now and then (maybe when your app saves the interaction or changes the employees it's linked to). Then when you want a list of employees, it's right there already in the table, rather than having SQL re-generate it every time you select. It's far from a normalised and perfect solution, but hey, life is neither of those things.


How to use smart pointers with SDL2 (SDL_RWops)?

Your idea to wrap the result of SDL_RWFromFile in a smart pointer is a good idea. I recommend a few improvements:

Factor out the opening-and-wrapping operations into a named function. For example:
auto OpenFile(const char *fname, const char *mode) {
    return std::shared_ptr<SDL_RWops>(SDL_RWFromFile(fname, mode), SDL_RWclose);
}

if( saveFile.get()  == NULL ){

Your whitespace is all messed up here; and also, you should generally treat smart pointers the same way you'd treat regular pointers. Avoid using .get() and .reset() and so on, unless you have a specific reason you need to emphasize the "object-ness" of the smart pointer. Keep it simple by writing:
saveFile = OpenFile("data/save.txt", "r");
if (saveFile == nullptr) {
    printf("Warning: Unable to open savefile! SDL Error: %s\n", SDL_GetError());
    Highlevel = 0;
    saveFile = OpenFile("data/save.txt", "w+");
    if (saveFile == nullptr) {
        printf("Error: Unable to create savefile! SDL Error: %s\n", SDL_GetError());
    } else {
        printf("New save file created!\n");
        SDL_RWwrite(saveFile.get(), &Highlevel, sizeof(Highlevel), 1);
    }
} else {
    printf("Reading save file...!\n");
    SDL_RWread(saveFile.get(), &Highlevel, sizeof(Highlevel), 1);
}

I notice that you are not checking the return value of SDL_RWread for errors. That's not great.
Have you considered throwing an exception on failure, instead of using printf to report directly to the user? This would certainly streamline your code:
if (auto f = OpenFile("data/save.txt", "r")) {
    printf("Reading save file...\n");
    if (SDL_RWread(f.get(), &Highlevel, sizeof(Highlevel), 1) != 1) {
        throw std::runtime_error(std::string("Save file format error: ") + SDL_GetError());
    }
} else if (auto f = OpenFile("data/save.txt", "w+")) {
    printf("Writing new save file...\n");
    Highlevel = 0;
    SDL_RWwrite(f.get(), &Highlevel, sizeof(Highlevel), 1);
} else {
    throw std::runtime_error(std::string("Unable to create save file: ") + SDL_GetError());
}

Finally, shared_ptr is overkill here because you never have more than one "owner" of the open file. You should certainly rewrite OpenFile to return a unique_ptr — a type which you can still implicitly convert to shared_ptr if you do ever need shared ownership of the file. See "OpenSSL client and server from scratch, part 1"; it's basically this:
struct RWCloser { void operator()(SDL_RWops *p) const { SDL_RWclose(p); } };

using UniqueRWops = std::unique_ptr<SDL_RWops, RWCloser>;

UniqueRWops OpenFile(const char *fname, const char *mode) {
    return UniqueRWops(SDL_RWFromFile(fname, mode));
}


Given a sorted array nums, remove the duplicates in-place

This is a job for itertools.groupby:

i = 0
for key, _ in groupby(nums):
    nums[i] = key
    i += 1
return i

A look at the implementation of groupby shows that it allocates \$O(1)\$ extra space, as required by the problem.

The i += 1 could be avoided using enumerate, like this:

i = -1 # in case nums is empty
for i, (key, _) in enumerate(groupby(nums)):
    nums[i] = key
return i + 1

but the need for an exceptional case to handle empty input is rather inelegant.


Using File.Replace() still seems the best option to me. As you mentioned on SO, the following might give a problem:

  If the sourceFileName and
  destinationFileName are on different
  volumes, this method will raise an
  exception. If the
  destinationBackupFileName is on a
  different volume from the source file,
  the backup file will be deleted.

To prevent this exception from being thrown, can't you first check whether you can serialize the temp file directly to the desired volume? If this isn't possible, further processing will fail as well, so you can already show a message that the volume isn't writeable.

Afterwards, call the Replace function, creating a backup file. When it fails, handle appropriately and check in which state your files are, indicate to the user when something is 'corrupt' (so point to the backup file). In the finally check whether the backup file exists and remove.


Minimizing string length checker in C# + format(ish) function

Is it a good practice to keep that

No

  or should I change it to my idea

Yours is better but it could be better.

The if..else could just be simplified like

return part1.Length == 3 && part2.Length == 8 && part3.Length == 3;


You need to decide on the Domain Objects that represent concepts in your current model.

A Route object should encapsulate the data to do with a route. If you look at Symfony's Route you'll see that it is simply an object with some properties, getters and setters, and that's about it (apart from a few select helper functions). This is also known as an Entity, the end object that you get back.

So, now you know that you want to get back some Route entities (@return Route[] in phpdoc), you should:

Create a Route object which merely represents a route
Take a look at the Factory Pattern and create a factory for these

The object API I would then expect to be using would be:

$router = new Router(new RouteFactory);
/** @var Route $route */
$route = $router->createRoute('/', 'PageController', 'showHome');

Somewhere in the Router, it would call RouteFactory::create($param1, $param2 ...) to actually make a Route object.

Don't expect the user to remember to call createRoute() followed by runRoute(). If one can't be run before the other, then it looks like you're trying to implement the builder creational pattern (which is for optional parameters). Your createRoute() method should return a Route object.

In the context of routing itself, you'll likely want something called a Resolver. That is, something you pass a Route to, and it instantiates the thing you are routing to. In an 'MVC' framework, you have a ControllerResolver - so you would create a Route, call ControllerResolver::resolve(Route $route) and that would contain the logic to decide what controller to create based on the contents of the Route object (so it'd do things like class_exists($controllerName) etc.

It looks like you're trying to design some generic router, but it is doing too many things. Focus on making the following seperately:

An object representing your route (Route)
An object responsible for creating a route from $_POST etc (RouteFactory::createFromGlobals($_POST) (or similar))
An object responsible for taking your Route and doing what you want to do with it (ControllerResolver (or similar))

Separate the actions out that you want to do, contextually, and you'll achieve better SoC.

Also, you shouldn't be accessing any superglobals ($_*) within this class, you should pass them in instead. This means that during testing you fake (or 'mock') the data you pass in with relative ease and test that your object still functions as you expect over different scenarios.


Thread safe Parameters class (follow up)

I agree with the comments.  I don't see the advantage of your code over something more like below.  If there is a use case you have in mind, please clarify.

public class Parameters
{
    public int ConnectionTimeout {get; private set;} // or a readonly field if you prefer
    public int ResponseTimeout {get; private set;}

    public Parameters(int ct, int rt)
    {
        ConnectionTimeout = ct;
        ResponseTimeout = rt;
    }
}

Threading concerns often disappear when you can use immutable data structures.


How about using

IS, LTV, EMAIL, TIME, userID, URL  = map(\
    qs.get, ['vID', 'channelID', 'uEmail', 'Time', 'uID', 'contentUrl'])

channelID, uEmail, ytID, uTime, uID, contentUrl = map(\
    lambda x : str(x)[2:-2], [LTV, EMAIL, ID, TIME, userID, URL])

for i in (channelID, uEmail, ytID, uTime, uID, contentUrl):
    print i

ytURL = str("https://www.youtube.com/tv#/watch?v=%s" % ytID)
print ytURL

instead of

ID = qs.get('vID')
LTV = qs.get('channelID')
EMAIL = qs.get('uEmail')
TIME = qs.get('Time')
userID = qs.get('uID')
URL = qs.get('contentUrl')
channelID = str(LTV)[2:-2]
print channelID
uEmail = str(EMAIL)[2:-2]
print uEmail
ytID = str(ID)[2:-2]
print ytID
ytURL = str("https://www.youtube.com/tv#/watch?v=%s" % ytID)
print ytURL
uTime = str(TIME)[2:-2]
print uTime
uID = str(userID)[2:-2]
print uID
contentUrl = str(URL)[2:-2]
print contentUrl

The first one just prints ytURL at the end but it can be changed easily if you really want. Other than that they do the same thing. But I am sure the first one is much easier to modify and maintain.

Other than that I can only say after I know what this program is about.

It might also be a good idea to keep os-specific functions(like you are doing after checking for the os) into separate functions. It would make maintaining and modifying the code much easier.

You should also read PEP8, particularly the part about code-layout. Your indentation is not good.

What I meant was that this can be converted into

if sys.platform == "darwin":
      subprocess.Popen('./killltv', shell=True)
      sleep(1)
      subprocess.Popen('./killltv', shell=True)
      sleep(1)
      subprocess.Popen('./test.py %s'%ytURL, shell=True)
elif sys.platform == "linux2":
      subprocess.Popen('./killltv', shell=True)
      sleep(1)
      subprocess.Popen('./test.py %s'% ytURL, shell=True)

this equivalent structure

OS_DETAIL = { 'darwin' : 2, 'linux2' : 1}
for i in xrange(OS_DETAIL[sys.platform]):
    subprocess.Popen('./killltv', shell=True)
    sleep(1)
else:
    subprocess.Popen('./test.py %s'% ytURL, shell=True)

It doesn't solve the complete problem because I am not sure whether you'll need those commented statements or not. If the sleep(2) is actually needed in case of linux2 then you can store a tuple in the OS_DETAILS dictionary. But the problem with this approach is your win32 part. It is totally different. It can be taken care of using an structure like this.

if sys.platform in ['darwin', 'linux2`]:
    #place the code I have just suggested for these 2
elif sys.platform == "win32"
    #place your code for win32

But as you can see this isn't the best way. It is better than the current solution but if the code for win32 can be refactored in some way (I don't know its functionality so don't ask) to fit the same pattern then it all comes down to a simple dictionary and a loop structure.


Adding two numbers represented as linked lists

A bit of scaffolding

In order to test/review your code, I had to write a bit of additional code. In case it can be relevant to you or other reviewers, here it is:

# Definition for singly-linked list.
class ListNode:
    def __init__(self, x):
        self.val = x
        self.next = None

    def __eq__(self, other):
        ret = other is not None and self.val == other.val and self.next == other.next
        # print(self, other, ret)
        return ret

    @classmethod
    def from_list(cls, l):
        ret = ln = cls(l.pop(0))
        while l:
            e = l.pop(0)
            ln.next = cls(e)
            ln = ln.next
        return ret

    def to_list(self):
        l = [self.val]
        return l if self.next is None else l + self.next.to_list()

class Solution:
    ...

    @staticmethod
    def ListNodeFromInt(n):
        return ListNode.from_list([int(d) for d in reversed(str(n))])

    @staticmethod
    def testAddTwoNumbersUsingNumbers(n1, n2):
        l1 = Solution.ListNodeFromInt(n1)
        l2 = Solution.ListNodeFromInt(n2)
        expected_add = Solution.ListNodeFromInt(n1 + n2)
        add = Solution().addTwoNumbers(l1, l2)
        print(n1, n2, n1 + n2, expected_add.to_list(), add.to_list())
        assert expected_add == add

    @staticmethod
    def unitTests():
        # Edge cases
        Solution.testAddTwoNumbersUsingNumbers(0, 0)
        Solution.testAddTwoNumbersUsingNumbers(342, 0)
        Solution.testAddTwoNumbersUsingNumbers(0, 342)
        # Same length
        Solution.testAddTwoNumbersUsingNumbers(342, 465)
        # Different length
        Solution.testAddTwoNumbersUsingNumbers(342, 46)
        # Return longer than input
        Solution.testAddTwoNumbersUsingNumbers(999, 999)

Solution.unitTests()

This is pretty poorly organised but it is quick and dirty.
Now starts the actual review

Overall review

Your code looks good. The API is a bit awkward but it is a limitation from the programming challenge platform.

A few details can be improved anyway.

Remove non-required checks

Instead of:

        if remainder != 0:
            digit += remainder

You can write:

        digit += remainder

Use builtins

The builtin divmod is not the most famous but it is convenient for a pretty usual task: compute both the quotient and the remainder.

Instead of:

        remainder = digit // 10
        digit = digit % 10

You can write:

        remainder, digit = divmod(digit, 10)

Different strategy

Instead of having a function to perform all the steps in one go, you could split the problem: define a function computing the sum of the 2 list as an integer and a function to convert that number into a list. Adding values bigger than 9 may be what we are trying to avoid though...


Simple console application that changes text color based on user input

Review

Whitespace
Use whitespace between the method name and opening parenthesis: Main (string[] args) instead of Main(string[] args). The same convention applies to statements such as while: while (Continue) instead of while(Continue). And also to curly braces: new string[4] { instead of new string[4]{.

New Line
Prefer using the new line of the system over a fixed format: use Environment.NewLine instead of \n.

Comments
Avoid useless comments such as //strings. We all know these are string instances: "Hello!", "Enter a color\n1 = blue\n2 = red\n3 = Magenta", "Render numbers". Don't comment out code that you don't use, remove it entirely: //string Nums = "";.

Naming conventions
Use pascalCase for variable names: string[] arrays instead of string[] Arrays. But what does arrays mean? Use a meaningful instead: string[] promptMessages for instance.

Using an array or not
There is no reason to wrap the messages in an array. Console.WriteLine(Arrays[1]); is a disaster for readability. Console.WriteLine("Enter a color .."); is much cleaner. On the other hand, string[] color could have been declared as ConsoleColor[] colors. This way, you could have avoided all that repetitive code. You should try to write DRY code.

var colors = new ConsoleColor[] {
    ConsoleColor.Blue,
    ConsoleColor.Red,
    ConsoleColor.Magenta
};

// NOTE: this is a trivial parsing, you should perform some validation..
// 0 for Blue, 1 for Red, 2 for Magenta
char userColor = int.Parse(Console.ReadKey().KeyChar.ToString());

Console.ForegroundColor = colors[userColor];
Console.WriteLine("Do you want to continue? y/n");
var nextTask = Console.ReadKey().KeyChar;
Continue = nextTask == 'y';

Console input
Don't read an entire line when you only need a single character: string NextTask = Console.ReadLine(); if (NextTask == "y") { ... You can read a single character: string NextTask = Console.ReadKey().KeyChar;. Unlike ReadLine, ReadKey does not wait for Enter key to be pressed, but immediately returns the pressed key.


I have gone over the code briefly and looked at a couple optimizations, but haven't come up with any drastic changes. I will try to go over it again when I find time.
What is good
I like how the various functions are generally short. And the CSS/HTML is very simple too! It is a nice use of the canvas.
Suggestions
Iterations
Anytime you iterate over an array using a for loop, consider using a functional approach like .forEach(), .map(). That way, you won't have to handle the bookkeeping of iterating the variable (e.g. var i) and indexing into the array. For more information, I recommend going through these exercises. Though be aware that functional approaches are not always optimal/faster.
Creating board:
Inspired by the comment from Longfei Wu on this question, the function to create the board could take on a functional approach using Array.fill() and Array.map()
function createBoard(width, height) {
  return Array(width).fill(0).map(function() {
    return Array(height).fill(0);
  });
}

And if you are open to using ES-6 arrow functions, that can be even shorter:
function createBoard(width, height) {
  let board = Array(width).fill(0).map(() => Array(height).fill(0));
  return board;
}

See comparison in this jsPerf. When I ran it in Chrome the array fill-map approach was faster, though the opposite was true in Firefox, Mobile Safari and emphasized textEdge.
Drawboard:
.forEach() can be used here instead of the for statements:
function drawBoard(arr) {
  ctx.clearRect(0, 0, canvas.width, canvas.height)
  arr.forEach(function(innerArray, i) {//  for (let i = 0; i < canvasWidth; i++) {
    innerArray.forEach(function(cell, j) {//for (let j = 0; j < canvasHeight; j++){
      if (cell === 1) {
        ctx.fillStyle = "#012345";
        ctx.fillRect(i*3, j*3, 3, 3);
      }
    });
  });
}

And the same is true for nextGene().
deadOrAlive()
Because checkSurrounding() checks 3-9 spaces around the given cell, I see cases where it returns values greater than 3. Should deadOrAlive() have logic in those cases? It appears that it only has logic for return values of 2 and 3.
Updated snippet:

const canvas = document.querySelector('.gameOfLife');
const ctx = canvas.getContext('2d');

// create an array
const canvasWidth = 100;
const canvasHeight = 100;
canvas.width = 3 * canvasWidth;
canvas.height = 3 * canvasHeight;
let gameBoard = createBoard(canvasWidth, canvasHeight);
let gameBoard2 = createBoard(canvasWidth, canvasHeight);
let gameBoard3 = createBoard(canvasWidth, canvasHeight);

function createBoard(width, height) {
  return Array(width).fill(0).map(function() {
    return Array(height).fill(0);
  });
}

function randomNumber(max) {
  return Math.floor(Math.random() * max);
}

function randomPos() {
  const x = randomNumber(canvasWidth);
  const y = randomNumber(canvasHeight);
  return [x, y];
}

function randomBoard(arr) {
  for (let i = 0; i <= 0.2 * canvasHeight * canvasWidth; i++) {
    const [x, y] = randomPos();
    arr[x][y] = 1;
  }
}

function drawBoard(arr) {
  ctx.clearRect(0, 0, canvas.width, canvas.height)
  arr.forEach(function(innerArray, i) {//  for (let i = 0; i < canvasWidth; i++) {
    innerArray.forEach(function(cell, j) {//for (let j = 0; j < canvasHeight; j++){
      if (cell === 1) {
        ctx.fillStyle = "#012345";
        ctx.fillRect(i*3, j*3, 3, 3);
      }
    });
  });
}

// calculate new cycle

function checkSurrounding(x, y) {
  let sum = 0;

  startX = x-1 < 0 ? x : x-1;
  stopX = x+1 >= canvasWidth ? x : x+1;
  startY = y-1 < 0 ? y : y-1;
  stopY = y+1 >= canvasHeight ? y : y+1;

  for (let i = startX ; i <= stopX; i++) {
    for (let j = startY ; j <= stopY; j++) {
      if (i !== x || j !== y) {
        sum += gameBoard[i][j];
      }
    }
  }

  return sum;
}

function deadOrAlive(x, y) {
  const surround = checkSurrounding(x, y);

  if (gameBoard[x][y] === 1 && (surround === 2 || surround === 3)) return 1;
  else if (gameBoard[x][y] === 0 && surround === 3) return 1;
  else return 0;
}

function nextGene() {
  let newBoard = createBoard(canvasWidth, canvasHeight);

  newBoard.forEach(function(innerArray, i) {//  for (let i = 0; i < canvasWidth; i++) {
    innerArray.forEach(function(cell, j) {//for (let j = 0; j < canvasHeight; j++){
      newBoard[i][j] = deadOrAlive(i, j);
    });
  });

  gameBoard = newBoard;
  drawBoard(newBoard);

}

randomBoard(gameBoard);
drawBoard(gameBoard);

setInterval(nextGene, 150);
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Game of Life - Canvas</title>
</head>
<body>
  <canvas class="gameOfLife" width="400" height="400"></canvas>
  <script type="text/javascript" src="scripts.js"></script>
</body>

<style>
  body {
    background-color: #ffc600;
  }
  .gameOfLife{
    margin: 15px auto;
    background-color: #ff6c00;
    display: block;
  }
</style>
</html>


Returning all possible English dictionary words that can be formed out of a string

As a general advice, you may want to organize your code into functions - say

One function to receive user input and process it
One function to generate all possible permutations for a string passed in less than a value (here 3).
Another function to filter this based on whether the string passed in is in us or uk dictionaries
At the end, you can combine these as a list comprehension.

Regarding your problem of performance, time the program with the itertools permutation output alone (without dict checking). My guess would be that the permutations is taking the time, but it would be nice to verify.

You may also want to check where the valid words are getting filtered. (Since you say that not all the words are being output). My guess is that permutation produces them but is not present in the enchant dictionary. But please verify.
Here is a possible rewriting of your code. It removes the redundant sorts

import enchant
import itertools

MIN_LEN = 3
uk = enchant.Dict("en_UK")
us = enchant.Dict("en_US")

def get_input():
  return sorted(set(input('enter the word: ').rstrip('\r\n')))

def gen_permutations(ent):
  tuples = map(lambda i: itertools.permutations(ent,i), range(MIN_LEN,len(ent)+1))
  arrr= [["".join(j) for j in i] for i in tuples]
  return list(itertools.chain(*arrr))

def filter_dict(words):
  return [x for x in words if uk.check(x) or us.check(x)]

for i in filter_dict(gen_permutations(get_input())):
  print i


Looks good! :)

The only thing I can spot is that the second condition for your if statement is unnecessary, as the first condition is all that is required. Therefore:

if (toSum.length % 2 == 1) {
    sumPairs[sumPairs.length - 1] = toSum[toSum.length - 1];
}


Is this code efficient?

Probably... not.

Efficiency can mean different things. Efficiency could mean "fast running code" or "use the least amount of memory" - this can only be determined by running the code through a profiler. Efficiency could also mean "I can use it easily" or "works reliably" or "handles edge cases well" - this can only be determined by having other people use it.

  Are there any reasons this shouldn't be used in the wild?

Yes.

Does the code really run on a variety of objects? What if I put things like Arrays, Dates, RegExps, Maps, Sets, etc. in my object? Does it handle circular references? This is a naive implementation of deep-copy which is fine in small apps and prototypes where you know what the data looks like. But in more general cases, this will probably not hold.

If you'd like to see how a general-purpose deep-copy function looks like, see how jQuery.extend or lodash.assign is implemented.

  Is there a way I can make it shorter?

Wrong question. Code size is irrelevant in JS, you have minifiers for that.


Fastest way to remove/hide a lot of elements from a list

A couple notes:

display: none does everything you're trying to do with your existing CSS class; it hides and completely removes the element from the layout. So instead of adding the zero class you would set display to none, and instead of removing it you would set display to block.
As far as optimization goes, one thing you could do is iterate the list items and store all the strings in an array as part of the initialization for your function. Then when you're iterating self.list, fetch the string from your cached array with the current index instead of calling $(this).html(). That would most likely be faster because it eliminates a DOM lookup.


Comparing database values with values from a GridView

It looks like what you want is ArrayList.Contains.

string rowHostName = row.Cells["HostName"].Value.ToString();
string rowUsers = row.Cells["Users"].Value.ToString();
string rowPSName= row.Cells["PS_NAME"].Value.ToString();

if (arrHostName.Contains(rowHostName)
    || arrUsers.Contains(rowUsers)
    || arrPSName.Contains(rowPSName))
{
    row.Appearance.BackColor = Color.Yellow;
    row.Appearance.FontData.Bold = Infragistics.Win.DefaultableBoolean.True;
}

And if you only use the collections above to check if they contain some values, you should prefer HashSet over ArrayList.

Of course, you should then change the names of the local variables accordingly, from arrHostName to hostNames and so on. It is always better not to clutter variable names with type information in C#, whose type system is good enough.


Formatting a date range, with shortening if the interval falls entirely within a calendar month

This is a self-contained problem, with well-defined inputs and outputs.  To be maintainable, the code should reside in a function.

You have three distinct cases, and maybe more:

Start and end dates are the same day
Start and end dates fall in the same calendar month
Start and end dates span calendar months

Your solution should therefore be written to make it obvious that there are more than two cases.

Bugs in your implementation

intval($dateDiff->d) != 0 is an invalid check.  You would be treating the range from 2015-01-22 to 2015-03-22 as if it were one day.

Similarly, $d1->format('m') != $d2->format('m') is not quite right either.  It would be deceptive to format the range from 2014-12-26 to 2015-12-25 as 26. – 25.  December.  It might be acceptable to say 26. December – 25. December.  But really, it would be clearest to include the years as well.

Suggested solution

function formatDateRange($d1, $d2) {
    if ($d1->format('Y-m-d') === $d2->format('Y-m-d')) {
        # Same day
        return $d1->format('d. F');
    } elseif ($d1->format('Y-m') === $d2->format('Y-m')) {
        # Same calendar month
        return $d1->format('d.') . $d2->format(' – d. F');
    } elseif ($d1->format('Y') === $d2->format('Y')) {
        # Same calendar year
        return $d1->format('d. F') . $d2->format(' – d. F');
    } else {
        # General case (spans calendar years)
        return $d1->format('d. F Y') . $d2->format(' – d. F Y');
    }
}


Find the minimum value that data could have had before it was rounded

You can firstly change by difference != 0 and then use na.locf to replace NAs by last available value recursively.

minimum_new <- function(data) {
  answer <- rep(NA, length(data))
  difference <- c(0, diff(data, lag = 1, differences = 1)) / 2
  answer[1] <- data[1]
  answer[difference != 0] <- data[difference != 0] - difference[difference != 0]
  answer <- zoo::na.locf(answer, na.rm = FALSE)
  answer
}

This version is faster for me by at least 2 times.

> data <- sample(10, 10000, replace = TRUE)
> check <- function(values) all(sapply(values[-1], function(x) identical(values[[1]], x)))
> bench <- microbenchmark::microbenchmark(loop = Minimum(data), vectorised = minimum_new(data), check=check)
Unit: microseconds
       expr      min       lq     mean   median       uq      max neval cld
       loop 1401.959 1415.552 1665.816 1457.274 1586.407 4620.835   100   b
 vectorised  742.325  758.183 1111.202  796.507 1383.268 2587.940   100  a

With check it's also checks the equality of output.


Two similar factory classes to instantiate services

Problem is that you prefer static methods. This way you effectively throw away benefits of polymorphism.

Also, when ever you find duplicated code you should carefully think if it might belong into a class of its own.

If you could open your mint to an OO approach you could move common behavior into a (non static) utility class and inject that common behavior into the concrete Factories. Or you go the usual OO way to create an abstract factory having the common code and have the concrete factories inheriting from it.

  but why do static methods throw away polymorphism benefits?  – Thufir

Static method imply early binding. All accessors to a method are known at compile time of the method implementation. Also all implementors of a static method are known at compile time of the accessors. You cannot provide a new behavior of a method unless you compile the accessors needing this new behavior.

class A {
  static void method(){
     System.out.println("static method in A");
  }
}

class B extends A {
  static void method(){
     System.out.println("static method B");
  }
}

class  C {
  static void main(String[] args){
     A.method(); // outputs "static method in A"
     B.method(); // outputs "static method in B"
     A[] a = {new A(), new B()};
     a[0].method();  // outputs "static method in A"
     a[1].method();  // outputs "static method in A" although instance is f type `B`
  }
}

  And, is polymorphism really so beneficial? – Thufir

Polymorphism is no value as such.

But if you doubt the value of polymorphism in general you might rather use a programing language that does not bother you with such  gratuitous  concepts...


Optimize the split of a String from console

This is probably not your bottleneck, but you could achieve the same result by:

ditching the StringTokenizer in favour of String.split()
replacing the while loop with a call to Collections.addAll(T...)

Like so:
while ((currentLine = bufferedReader.readLine()) != null) {
    Collections.addAll(arrayList, currentLine.split(" ")));
}

The static method Collections.addAll() is preferable to arrayList.addAll(Arrays.asList()):

public static <T> boolean addAll(Collection<? super T> c, T... elements)
Adds all of the specified elements to the specified collection. Elements to be added may be specified individually or as an array. The behavior of this convenience method is identical to that of c.addAll(Arrays.asList(elements)), but this method is likely to run significantly faster under most implementations.


Query of attributes of mobile phone models, using several UNIONs to find distinct values

This is a pet peeve of mine, and others have disagreed with me about it, so please take it with a grain of salt. I really just can't stand single letter aliases. I mean, is cpu really so long that you can't just use the table name? Do you really need to shorten it to c?

It's lazy and it's the worst kind of lazy. It's the kind of lazy that creates more work. Now, instead of plainly seeing series_attr.attr_name, I have to keep in my mind that saa means "series attribute attribute", and ma means "just plain model attribute" and a is a "model attribute attribute" and... Do you see where this is going? Imagine you're brand new to this code base. Would you be able to easily map the alias names to useful meanings? No. You wouldn't, but you shouldn't have to because alias names should be meaningful.

That said, I do like that you've consistently formatted your code. I especially like that you put some whitespace around your UNION statements. However, I really prefer to see subqueries indented one level. It just makes it easier to follow the logic.

You've also hardcoded C79 into your query. What if I want to find info on D82? I have to change the query in at least 4 places. You should be using a variable for this. Better yet, wrap the query in a stored procedure and use a parameter.


Heap Sort implementation time complexity

correctNode() looks like an (algorithmic) code-smell: its not needed. The only routines required to implement heap sort are:

swap
maxHeapify for maintaining the max-heap invariant; the topmost invocation must run in \$\mathcal{O}(\log n)\$.
buildMaxHeap, Introduction to Algorithms has a funky proof that this runs in linear time. Since, it is called only once, linear time is OK.
The actual heap sort routine: builds the max heap and pops in order until sorted.

The length argument of your heap sort is not needed. You can alwasy ask array.length.

I had this in mind:

public static void sort(final int[] array) {
    buildMaxHeap(array);
    int heapSize = array.length;

    for (int i = array.length - 1; i > 0; --i) {
        swap(array, 0, i);
        maxHeapify(array, 0, --heapSize);
    }
}

private static void buildMaxHeap(final int[] array) {
    for (int i = array.length / 2; i >= 0; --i) {
        maxHeapify(array, i, array.length);
    }
}

private static void maxHeapify(final int[] array,
                               final int index,
                               final int heapSize) {
    final int leftChildIndex = (index << 1) + 1;
    final int rightChildIndex = leftChildIndex + 1;

    int largestIndex;

    if (leftChildIndex < heapSize
            && array[leftChildIndex] > array[index]) {
        largestIndex = leftChildIndex;
    } else {
        largestIndex = index;
    }

    if (rightChildIndex < heapSize
            && array[rightChildIndex] > array[largestIndex]) {
        largestIndex = rightChildIndex;
    }

    if (largestIndex != index) {
        swap(array, largestIndex, index);
        maxHeapify(array, largestIndex, heapSize);
    }
}

private static void swap(final int[] array,
                         final int index1,
                         final int index2) {
    final int tmp = array[index1];
    array[index1] = array[index2];
    array[index2] = tmp;
}

Hope that helps.


A few stylistic comments :

I'd change the while loop for a for loop. It doesn't matter at all but I feel it better that way.
You could perform len--; before the while (or for) loop so that you can go til len instead of len - 1.

Then, as duplicates don't need to be close to each other (from what I understand), wouldn't it be easier to do something like (NOT TESTED AT ALL) :

private static String removeDuplicates(char[] chars) {
    if(chars == null)
        return null;
    int len = chars.length;
    int idx = 0;
    for (int i = 0; i < len; i++) {
        char c = chars[i];
        bool dup = false;
        for (int j = 0; j < idx; j++) {
            if (c == chars[j]) {
                dup = true;
                break;
            }
        }
        if (!dup) {
            chars[idx] = c;
            idx++;
        }
    }

    return new String(chars, 0, idx);
}

The point would be to go through the string and for each characters, try to see if we have seen it already. If we haven't we store it, otherwise, we don't.


There is no need for brackets in class Matrix(): .... It can be just class Matrix: .... See docs for class definition syntax.
In self.rows = [[0]*width for i in range(height)] you should replace i by _ that we usually use for throwaway variables.
In the same line 0 is a magic number. You could make it a default parameter:

def __init__(self, height, width, fill_value=0):
    self.rows = [[fill_value] * width for _ in range(height)]

Regarding __str__:

def __str__(self):
    s = "\n" + "\n".join([str(i) for i in [rows for rows in self.rows] ]) + "\n"
    return s

Having those "\n" on both ends seems unnecessary. Just return the middle part and let user decide if he wants more blank lines between output.
[rows for rows in self.rows] is the same as self.rows. That leaves us:

def __str__(self):
    s = "\n".join([str(i) for i in self.rows])
    return s

i is a bad name. row is better.
Removing unnecessary s:

def __str__(self):
    return "\n".join([str(row) for row in self.rows])

And making it more concise:

def __str__(self):
    return "\n".join(map(str, self.rows))

Regarding __repr__:

def __repr__(self):
    return (f'{self.__class__.__name__} ({self.height!r} , {self.width!r})')

The brackets are unnecessary here, and spacing is a bit weird. It should be like this:

return f'{self.__class__.__name__}({self.height!r}, {self.width!r})'

As you probably already know, with __repr__ you should be able to pass the returned string to Python interpreter so that it could recreate the object. But in your case information about the values in your matrix would be lost. What you return is just something like Matrix(5, 5). Would this be OK? Probably it would be better if the values would be returned as well, but then the current logic of the class won't allow you to recreate the matrix as you separated filling (fill_matrix) from initializing. Maybe it would be better to be able to do both at the same time?

len method should be called __len__.
As with current implementation its value is constant, you could use lru_cache(1) so to calculate it only once and then reuse the cached value:

from functools import lru_cache

...

@lru_cache(1)
def __len__(self) -> int:
    return self.height * self.width

You have some not implemented yet methods. Instead of returning nothing:

def __add__(self, matrix2):
    return

raise a NotImplementedError:

def __add__(self, matrix2):
    raise NotImplementedError

Regarding fill_matrix:

def fill_matrix(self, fill_list):
    index = 0
    for i in range(len(self.rows)):
        try:
            for j in range(len(self.rows[i])):
                self.rows[i][j] = fill_list[index]
                index += 1
        except IndexError:
            print (f"Matrix not filled \nMatrix fill stopped at: row {i}, Column {j}")
            break
    return fill_list[index:]

Add a docstring. It is not clear at the first sight why this method should return anything. Something like:

def fill_matrix(self, fill_list):
    """
    Fills matrix by `fill_list`
    and returns what didn't fit in it.
    """

You are catching IndexError but this case seems impossible as indices are always taken from the ranges defined by shape of the matrix. You can remove it.
Why recalculating len(self.rows) and len(self.rows[i]) if you already have self.height and self.width?
The idea of iterating the index doesn't seem Pythonic. How about something like this instead:

from itertools import product

...

def fill_matrix(self, fill_list):
    fill_values = iter(fill_list)

    indices = product(range(self.height), range(self.width))

    for (i, j), value in zip(indices, fill_values):
        self.rows[i][j] = value

    return fill_values

This can accept iterators or sequences and will return an iterator with "overflow". So if you need to use those leftovers, you get them like this:

myMat = Matrix(5, 5)
overflow = myMat.fill(range(30))
print(list(overflow))
>>> [25, 26, 27, 28, 29]

It would be better to rename fill_matrix as fill and its argument fill_list as values.

Regarding add_value. I think it's better to name it replace instead.
This method is too complicated and doesn't follow Single responsibility principle. Catch the errors outside, and use this method just for replacing one value. If you need to replace multiple values, then put the function call inside the loop. See this post for a better explanation. In the end it should be as simple as that:

def insert(self, row_index, column_index, value):
    self.rows[row_index][column_index] = value

And you could call it, and catch and save the errors like this:

import traceback

...

values = [(-1, 3, 500),
          (0, 0, 3),
          (51, 5, 7),
          (1, 2, 667),
          [3, 4, 676],
          (1),
          [3, 4, 676, 123],
          (1, "a", 1),
          (1, 1, "£")]

errors = []
bad_values = []

for value in values:
    try:
        myMat.insert(*value)
    except (IndexError, TypeError):
        errors.append(traceback.format_exc())
        bad_values.append(value)

for error, value in zip(errors, bad_values):
    print(f'Error occurred for value {value}:\n'
          f'{error}')

And the output is:

Error occurred for value (51, 5, 7):
Traceback (most recent call last):
  File "C:/Users/Georgy/SO_CR/main.py", line 82, in <module>
    myMat.insert(*value)
  File "C:/Users/Georgy/SO_CR/main.py", line 55, in insert
    self.rows[row_index][column_index] = value
IndexError: list index out of range

Error occurred for value 1:
Traceback (most recent call last):
  File "C:/Users/Georgy/SO_CR/main.py", line 82, in <module>
    myMat.insert(*value)
TypeError: insert() argument after * must be an iterable, not int

Error occurred for value [3, 4, 676, 123]:
Traceback (most recent call last):
  File "C:/Users/Georgy/SO_CR/main.py", line 82, in <module>
    myMat.insert(*value)
TypeError: insert() takes 4 positional arguments but 5 were given

Error occurred for value (1, 'a', 1):
Traceback (most recent call last):
  File "C:/Users/Georgy/SO_CR/main.py", line 82, in <module>
    myMat.insert(*value)
  File "C:/Users/Georgy/SO_CR/main.py", line 55, in insert
    self.rows[row_index][column_index] = value
TypeError: list indices must be integers or slices, not str

You might be interested in Python logging module as well.
Though, I find it strange that you decided to pay so much attention to catching the errors.

Some other notes:

Don't forget about naming conventions. myMat should be my_matrix, Errors should be errors. See PEP 8: for more.
Consider using type hints.

In the end your code could look like this:

from functools import lru_cache
from itertools import product
from typing import (Any,
                    Iterable,
                    Iterator)

class Matrix:
    def __init__(self,
                 height: int,
                 width: int,
                 fill_value: Any = 0) -> None:
        self.height = height
        self.width = width
        self.rows = [[fill_value] * width for _ in range(height)]

    def __str__(self) -> str:
        return "\n".join(map(str, self.rows))

    def __repr__(self) -> str:
        return f'{self.__class__.__name__}({self.height!r}, {self.width!r})'

    @lru_cache(1)
    def __len__(self) -> int:
        return self.height * self.width

    def __add__(self, matrix2):
        raise NotImplementedError

    def __mul__(self, matrix2):
        raise NotImplementedError

    def remove(self, item):
        raise NotImplementedError

    def fill(self, values: Iterable[Any]) -> Iterator[Any]:
        """
        Fills matrix by `fill_values`
        and returns what didn't fit in it.
        """
        values = iter(values)

        indices = product(range(self.height), range(self.width))

        for (i, j), value in zip(indices, values):
            self.rows[i][j] = value

        return values

    def replace(self,
                row_index: int,
                column_index: int,
                value: Any) -> None:
        """Replaces a value by given indices by a new one."""
        self.rows[row_index][column_index] = value


"Heads or Tails?" guessing game in Python

Why are you mixing raw_input() with easygui?  That's a suboptimal user experience.

sys.exit(0) at the end is superfluous, but harmless.


Avoid using Active*

You can use Worksheets collection to access a specified Worksheet object represents a worksheet.

Worksheets("YOUR SHEET NAME")

This can be useful to do explicit job, without changing the active sheet. The same way for ActiveCell, ActiveChart and ActiveChart, you can always access the target object by the collection.

Use With rather than Selection

Aside from error-raising macro problems, a recorded macro is less efficient, because it mimics all the mouseclicks and keystrokes (every cough and camera flash) that occurred while the recording was taking place. A recorded macro clicks on every object to select it, then performs an action on the selection:

Columns("A:A").Select
Selection.FormatConditions.AddColorScale ColorScaleType:=3
Selection.FormatConditions(Selection.FormatConditions.Count).SetFirstPriority

If you have two or more property or method statements that work on the same object, wrap them in a With / End With block:

With Worksheets("Sheet1").Columns("A")
    ' read / write object's properties here
    ' e.g. add new color scale rule
    .FormatConditions.AddColorScale ColorScaleType:=3
End With

This block can increase the code efficiency and readability.

Check the existence of target object

The macro record is powerful, but it's more difficult to understand whether something exists already. For example, we may not want to apply 10 rules of color scale to the column A.

' drop color scale if exists
For Each fc In .FormatConditions
    If fc.Type = xlColorScale Then
        fc.Delete
    End If
Next

Here's just an example, there must be better logic for treating existing object.

As for your script, here's my suggest edits.

Public Sub Stats2()
'
' Stats Macro
' Give stats to column A and draw chart with trendline.
'
' Modified by Mincong HUANG
'

    ' declarations
    Dim wsName As String
    Dim chartName As String
    Dim srcRange As Range

    ' initialization
    wsName = "Sheet1"
    chartName = "Fancy Chart"
    Set srcRange = Worksheets(wsName).Columns("A")

    ' set format conditions at target column
    With srcRange

        Debug.Print .Address

        ' drop color scale if exists
        For Each fc In .FormatConditions
            If fc.Type = xlColorScale Then
                fc.Delete
            End If
        Next

        ' add new color scale
        With .FormatConditions
            ' add
            .AddColorScale ColorScaleType:=3
            With .Item(.Count)

                .SetFirstPriority

                ' advanced setting (optional)
                ' Optional because these values are the default setting
                ' but you can add other desired color

                .ColorScaleCriteria(1).Type = xlConditionValueLowestValue
                .ColorScaleCriteria(1).FormatColor.Color = 7039480
                .ColorScaleCriteria(1).FormatColor.TintAndShade = 0

                .ColorScaleCriteria(2).Type = xlConditionValuePercentile
                .ColorScaleCriteria(2).FormatColor.Color = 8711167
                .ColorScaleCriteria(2).FormatColor.TintAndShade = 0
                .ColorScaleCriteria(2).Value = 50

                .ColorScaleCriteria(3).Type = xlConditionValueHighestValue
                .ColorScaleCriteria(3).FormatColor.Color = 8109667
                .ColorScaleCriteria(3).FormatColor.TintAndShade = 0

            End With
        End With
    End With

    ' drop log chart if exists
    Debug.Print Worksheets(wsName).ChartObjects.Count & " charts"
    For Each c In Worksheets(wsName).ChartObjects
        If c.Name = chartName Then
            c.Delete
        End If
    Next

    ' add log chart
    With Worksheets(wsName).Shapes.AddChart2(227, xlLine)
        .Chart.Parent.Name = chartName
        .Chart.HasTitle = True
        .Chart.ChartTitle.Text = chartName
        .Chart.SetSourceData Source:=srcRange
        .Chart.FullSeriesCollection(1).Trendlines.Add _
            Type:=xlMovingAvg, _
            Period:=2, _
            Forward:=0, _
            Backward:=0, _
            DisplayEquation:=0, _
            DisplayRSquared:=0, _
            Name:="2 per. Mov. Avg. (Series1)"
        .Chart.ClearToMatchStyle
        .Chart.ChartStyle = 233
        With .Chart.FullSeriesCollection(1).Trendlines(1).Format.Line
            .Visible = msoTrue
            .ForeColor.ObjectThemeColor = msoThemeColorAccent2
            .ForeColor.TintAndShade = 0
            .ForeColor.Brightness = -0.25
            .Transparency = 0
        End With
    End With

    ' release memory
    Set srcRange = Nothing

End Sub

By the way, I'm using Excel 2016. So I'm not sure the code compatibility. Please tell me if there's any error.

References

Peltier Tech Blog - Quick Excel Chart VBA Examples
Peltier Tech Blog - Naming an Excel Chart
MSDN - Worksheets Object (Excel)


Advent of Code 2018 Day 1 in OCaml: Find length of cycles when accumulating deltas

I won't give it all away, since that would take away some of the fun of Advent of Code, but I'll point out:

First, yes, List.mem takes time proportional to the length of your list, which means if you're calling it over and over again it can be quite slow indeed. There might be faster structures you could use if you want to track if a previous value has been seen before, like Sets. Also, you should not be using == for equality here but rather =; I recommend learning the difference between = and ==, you will want to know it.

Second, your code is not very idiomatic OCaml; in general, if you're doing things like nesting lots of ifs and using List.hd instead of pattern matching, you may not be doing things quite right. This won't impact your performance but might impact readability and correctness. (For example, the match l with | [] -> ... pattern will warn you if a pattern match isn't exhaustive, which avoids nasty bugs.)


Certainty of two comparative values (A/B results certainty)

The code below doesn't reproduce your code entirely, it just illustrates what I mentioned earlier in the comments:

function example() {
    var values = [0.0498673470,
                  0.0211410061,
                  0.0032776263,
                  0.0000380036,
                  0.0000488906,
                  0.0000053830];
    function sum(a, b) { return a + b; }
    function sqdiff(a, b) { return (b - a) * (b - a); }
    function avg(data) {
        return data.reduce(sum) / data.length;
    }
    function curry(f) {
        var args = [].slice.call(arguments);
        args.shift();
        return function () {
            return f.apply(null, args.concat([].slice.call(arguments)));
        };
    }
    function std(data) {
        var a = avg(data);
        return Math.sqrt(data.map(curry(sqdiff, a)).reduce(sum) /
            data.length);
    }
    console.log("Standard deviation: " + std(values));
}

You, most likely, won't want to write functions like curry yourself though. There are libraries out there which already do such (and many more) useful things. I believe that Lodash already has one.