Generate a matrix of booleans from another one Let's say that I have a bool[,] with random values

FFFFFFFF
FFFFFTTT
TTTTTTTT
FFFFFFFF

What would be the smartest way to create a new bool[,] that build on top of the previous one. That means, that it can have random values where the previous one was true, but that it preserves the falses from the original?

So this could be a possible result

FFFFFFFF
FFFFFTFT
TTFFFTTT
FFFFFFFF

But this not...

TTTTTFFF
TTTTTFFF
TTTTTTTT
FFFFFFFF

So far I have come with the classical solution. First create a matrix of random values, and the overwrite them.

for (int x = 0; x < cols; x++)
    for (int y = 0; y < rows; y++)
        if (matrix1[x, y] == false)
            matrix2[x, y] = false;

But I was wondering if there is a better way.

You can make this function more generic so that you can use reuse it where necessary and with any type. Currently your code is doing three things:

Loop over the matrix.
Checking a condition.
Modifying the elements.

This can be separated and encapsulated. You first create a general-purpose extension that just loops over any matrix, checks the passed predicate and calls the action:

public static T[,] ForEach<T>(
    this T[,] m,
    Func<T, bool> predicate,
    Action<T, int, int> action
)
{
    for (int x = 0; x < m.GetLength(0); x++)
        for (int y = 0; y < m.GetLength(1); y++)
            if (predicate(m[x, y])) action(m[x, y], x, y);

    return m;
}

Example:

Assuming you have these two matrices

var m1 = new[,]
{
    { false, false, false, false },
    { false, true, false, true },
    { true, true, false, false },
    { false, false, true, true }
};

var m2 = new[,]
{
    { false, true, true, false },
    { false, true, false, true },
    { true, true, false, false },
    { false, false, false, false }
};

you call the new ForEach extension like this where you first filter the items with !m so that you get only those where m = false, then you update the second matrix at the coordinates [x, y] with the value m of the first matrix.

m1.ForEach(m => !m, (m, x, y) => m2[x, y] = m);


Pair programming matrix At work, we have a "pair programming ladder" where you can keep track of who is pairing with whom (based on check-ins).  The idea is to promote "promiscuous pairing" where each developer eventually pairs with every other developer.

In our team, this was being updated manually, so I thought of writing a script that will parse the logs and generate a table.

Given these are the names of the developers:

  "Adam", "Bill", "Carl", "David", "Eddie", "Frank", "George"

The output would look like so:

       |Adam
Bill   |0      |Bill
Carl   |0      |2      |Carl
David  |1      |0      |0      |David
Earl   |0      |0      |3      |0      |Earl
Frank  |0      |0      |0      |2      |1      |Frank
George |0      |0      |0      |0      |2      |0      |George
Solo   |1      |0      |0      |0      |0      |1      |0      |Solo
Other  |1      |0      |0      |0      |0      |2      |1      |0      |Other

This is my script:

from git import *
import re
from collections import Counter

list = ["Adam", "Bill", "Carl", "David", "Eddie", "Frank", "George"]

def build():
    repo = Repo("/home/developer/work/commerce-git/commerce-project")
    master = repo.heads.master
    pairsDict = {}
    for commit in repo.iter_commits(master, since='2013-02-06+14:00', reverse=True):
        for person in list:
            if person not in pairsDict:
                pairsDict[person] = Counter()
            if person in commit.message:
                pairedWith = ""

                m = re.search('(\w+)/(\w+)\s', commit.message)
                if not m:
                    pairedWith = "Solo"
                else:
                    if m.group(1) == person:
                        pairedWith = m.group(2) #pair is right of slash
                    else:
                        pairedWith = m.group(1) #pair is left of slash
                    if pairedWith not in list:
                        pairedWith = "Other"
                pairsDict[person][pairedWith] += 1
                if pairedWith not in pairsDict:
                    pairsDict[pairedWith] = Counter()
                pairsDict[pairedWith][person] += 1
                break;

    return pairsDict

def print_table():
    pairsList = list + ["Solo", "Other"]
    pairsDict = build()
    str = ""
    for index,person in enumerate(pairsList):
        if (index == 0):
            str += '|'.rjust(8) + person.ljust(7) + '\n'
        else:
            str += person.ljust(7) + '|'
            for paired in pairsList[:index]:
                count  = pairsDict[person][paired]
                str += '{:<7}|'.format(count)
            str +=  person.ljust(7)+'\n'
    print str
    return str

if __name__ == "__main__":
    print_table();

The scripts parses the git logs using GitPython, where a commit message is expected to look like this:

  "Adam/David - Refactored app to be more polyglot-y"

From there it constructs a HashMap of Counters to keep track of who has paired with whom. I'm going to eventually feed this data structure into a simple Django web-app so people can view it in a browser.

Do you have any suggestions for this script?  Could it be more "pythonic"?  Is there anything I could do to refactor it to be simpler to read, or better performance-wise?

1. Comments on your code

No docstrings! What do these functions do and what kind of values do they return?
Python statements don't need to be terminated with a semicolon: they finish at the end of a line.
Is it really necessary to do from git import * given that you only actually use git.Repo?
There's a built-in function called list, so it's a bad idea to use that as the name of a variable. Also, list is a vague name: list of what? I suggest something like users.
Similarly, build is a vague name. Build what? I suggest something descriptive like count_commit_pairings.
It's conventional (following PEP8) for Python variables to use lower case with underscores. If you plan to collaborate with other Python programmers, use variable names like pairs_dict and paired_with instead of pairsDict and pairedWith.
Constants like '2013-02-06+14:00' shouldn't be buried deep in the code, but should be pulled out to become global variables or function parameters.
You could avoid having to write these lines:

if person not in pairsDict:
    pairsDict[person] = Counter()

and these lines:

if pairedWith not in pairsDict:
    pairsDict[pairedWith] = Counter()

if you made pairsDict into a defaultdict(Counter). See collections.defaultdict.
Since you're going to be looking up users to see whether they need to be replaced with 'Other', it's good practice to convert the list of users into a set, so that looking up a name can be done in constant time.
It's wasteful to iterate over the users and try to match each one against the commit message. Why not do a regular expression match against the commit message just once and then figure out which users are mentioned?
You use the line

if person in commit.message:

to determine if person is the committer. But what if someone makes a commit without writing their name in the commit message (false negative)? What if someone's name appears in the commit message by coincidence (false positive)? It seems to me that looking at commit.committer.name would be more reliable.
Backslash is an escape character in Python strings, so you should generally use the r modifier in front of strings where you want to preserve the backslashes. So write:

m = re.search(r'(\w+)/(\w+)\s', commit.message)

It's better to use the regular expression \b (word boundary) rather than \s (whitespace) to detect the end of a word. This is because \b matches if the word is followed by punctuation, or by the end of the string, whereas \s would fail in those cases.
If the name of the pairing is supposed to be at the start of the commit message, you should use re.match to ensure this. But if it is allowed to be anywhere in the commit message you should write:

m = re.search(r'\b(\w+)/(\w+)\b', commit.message)

to ensure that the match starts at the beginning of a word.
Each time you call re.search it has to compile the regular expression. Since you're going to do this for each commit, it makes sense to compile the regular expression just once by calling re.compile.
In the section of code

if m.group(1) == person:
    pairedWith = m.group(2) #pair is right of slash
else:
    pairedWith = m.group(1) #pair is left of slash

you assume that if person is in the message, and not to the left of the slash, then they must be to the right of the slash. But that doesn't follow at all. Suppose Gabrielle commits a change with the message

Gabrielle/Frank -- fixed bug 123 found by Alice

it looks to me as though your code will incorrectly deduce that this is a change committed by Alice and Frank. So I think it would be worth taking more care to detect (and perhaps report?) errors in the commit messages. People make mistakes!

2. Revised build function

Addressing all the issues discussed above yields the following code. But beware: I haven't tested this, so most likely there are mistakes.

from git import Repo
import re
from collections import Counter, defaultdict
import sys

def count_commit_pairings(repository = '/home/developer/work/commerce-git/commerce-project',
                          since = '2013-02-06+14:00',
                          users = 'Alice Bill Clare David Emma Frank Gabrielle'.split()):
    """
    Count the number of times each pair of users has made a commit.

    `repository` is the git repository to examine.
    `since` is the date at which to start looking at the commits.
    `users` is a list of users to count commits for.

    Return the counts in the form of a dictionary mapping user name to
    a dictionary mapping partner name to count of commits by that
    pair. Commits not made by a pair are filed as if by the committer
    and the fake user 'Solo'. User names not found in `users` are
    replaced by 'Other'.
    """
    repo = Repo(repository)
    pairs = defaultdict(Counter)
    users = set(users)
    pair_re = re.compile(r'(\w+)/(\w+)\b')

    def username(name):
        """Return the username to use for `name`."""
        return name if name in users else 'Other'

    def partner(commit):
        """Return the partner of the committer, or 'Solo' if none found."""
        m = pair_re.match(commit.message)
        if not m:
            return 'Solo'
        if commit.committer.name not in m.groups():
            sys.stderr.write("Bad commit {0.hexsha}: committer {0.committer.name} "
                             "missing from pair {1}."
                             .format(commit, m.group(0)))
            return username(m.group(1))
        partner = set(m.groups()).difference([commit.committer.name])
        if len(partner) != 1:
            sys.stderr.write("Bad commit {0.hexsha}: duplicate pair {1}."
                             .format(commit, m.group(0)))
            return 'Solo'
        return username(partner.pop())

    for commit in repo.iter_commits(repo.heads.master, since=since, reverse=True):
        u1 = username(commit.committer.name)
        u2 = partner(commit)
        pairs[u1][u2] += 1
        pairs[u2][u1] += 1

    return pairs

(This seems like plenty for one answer. Maybe some other person can look at print_table.)


Find Triangle Triplets from a list of given numbers If a triplet of segments A, B and C are triangle triplets if and only
if

A + B > C
A + C > B
B + C > A

Is there a better implementation for this problem?
#include<vector>
#include<iostream>

void findTriangleTriplets( std::vector<int>& vec_input, std::vector<std::vector<int>>& triplets)
{
    int size =  vec_input.size();
    for(int i = 0; i < size; ++i)
    {
        for(int j = i+1; j < size; ++j)
        {
            for(int k = 0; k < size; ++k)
            {
                if( ( ( vec_input.at( i ) + vec_input.at( j ) ) > vec_input.at( k ) ) &&
                    ( ( vec_input.at( i ) + vec_input.at( k ) ) > vec_input.at( j ) ) &&
                    ( ( vec_input.at( j ) + vec_input.at( k ) ) > vec_input.at( i ) ) )
                {
                    std::vector<int> temp;
                    temp.emplace_back( vec_input.at( i ) );
                    temp.emplace_back( vec_input.at( j ) );
                    temp.emplace_back( vec_input.at( k ) );
                    triplets.emplace_back( temp );
                }
            }
        }
    }
}

int main()
{
    std::vector<std::vector<int>>  triplets;
    std::vector<int> vec_input { 1, 2, 3, 4, 5, 6 };

    findTriangleTriplets( vec_input,  triplets);
    for ( auto &x : triplets)
    {
        std::cout<<x.at(0)<<" "<<x.at(1)<<" "<<x.at(2)<<"\n";
    }

    return 0;
}

First thing to comment on after copying and pasting into my IDE, the following line gives a warning:

int size = vec_input.size();

  Implicit conversion loses integer precision: 'size_type' (aka 'unsigned long') to 'int'

Apparently, the size() method of Vector returns an unsigned long, and we should use this type for our size, rather than int.

unsigned long size = input.size();

Functions that return void but accept (and modify) an argument passed by reference are always a warning sign for me.  Here, I don't think there's a particularly good reason to do so.

Here, I can't see any good reason to be doing so.  We create and return a vector within the function, and only accept the input argument.

Another problem I see: the result we're giving the caller is a vector of vectors, and the inner vectors are supposed to always have exactly 3 values in it.  Why don't we create a struct to represent the triplets?

struct Triplet {
    int a;
    int b;
    int c;
}

Now we can return a vector of these.

I would also abstract that complex conditional into its own function.

bool isTriplet(int a, int b, int c) {
    return ((a + b) > c) && ((a + c) > b) && ((b + c) > a);
}

Now, putting all that together, without changing the algorithm or any of the logic, the code looks like this:

#include<vector>
#include<iostream>

struct Triplet {
    int a;
    int b;
    int c;
};

bool isTriplet(int a, int b, int c) {
    return ((a + b) > c) && ((a + c) > b) && ((b + c) > a);
}

std::vector<Triplet> findTriangleTriplets(std::vector<int> input) {
    std::vector<Triplet> triplets;
    unsigned long size = input.size();

    for(int i=0;i<size;++i) {
        for(int j=i+1;j<size;++j) {
            for(int k=0;k<size;++k) {
                int a = input.at(i);
                int b = input.at(j);
                int c = input.at(k);

                if(isTriplet(a, b, c)) {
                    Triplet t = Triplet{a,b,c};
                    triplets.emplace_back(t);
                }
            }
        }
    }

    return triplets;
}

int main()
{
    std::vector<Triplet> triplets;
    std::vector<int> vec_input { 1, 2, 3, 4, 5, 6 };

    triplets = findTriangleTriplets(vec_input);
    for ( auto &x : triplets)
    {
        std::cout<<x.a<<" "<<x.b<<" "<<x.c<<"\n";
    }

    return 0;
}


Non-recursive BFS Maze Solving with Python I wrote this program to help me understand how BFS and Queues work. (Also DFS if I replace the queue with a stack).

It works, but I'm curious how well I implemented the algorithm.

Are there any obvious improvements?

For example, I notice that there are duplicate values in the Queue. I understand that I should avoid visiting already visited positions. However the queue contains only "prospective" positions which are yet to be visited. Should I modify the algorithm to not enqueue positions which it already contains?

My agenda is to understand Data Structures and Algorithms and write reasonable quality code to implement the basic concepts.

from os import system
from random import randint

class Queue:
    def __init__(self):
        self.list = []

    def enqueue(self, item):
        self.list.append(item)

    def dequeue(self):
        temp = self.list[0]
        del self.list[0]
        return temp

    def isEmpty(self):
        return not self.list

    def empty(self):
        self.list = []

def create_maze(n):
    maze = []
    for row in range(n):
        row = []
        for col in range(n):
            if randint(0,3) == 0:
                row.append(1)
            else:
                row.append(0)

        maze.append(row)

    maze[0][0] = 0
    maze[n-1][n-1] = 2
    return maze

def print_maze(maze):
    for row in maze:
        print((row))

def is_valid_pos(tup):
    (col, row) = tup
    if col < 0 or row < 0 or col >= MAZE_SIZE  or row >= MAZE_SIZE :
        return False
    return maze[row][col] == 0 or maze[row][col] == 2

def solve(maze, start):
    q = Queue()
    (col,row) = start
    print('Enqueueing ({},{})'.format(col,row))
    q.enqueue((col,row))

    while not q.isEmpty():
        print('Queue contents: {}'.format(q.list))
        input('Press Enter to continue: ')
        print('Dequeueing')
        (col, row) = q.dequeue()
        print('Current position: ({}, {})'.format(col,row))

        if maze[row][col] == 2:
            print('Goal reached at ({}, {})'.format(col,row))
            return
        if maze[row][col] == 0:
            print('Marking ({}, {})'.format(col,row))
            maze[row][col] = 3
        print_maze(maze)
        print('Enqueueing coordinates of valid positions in 4 directions.')
        if is_valid_pos((col+1, row)): q.enqueue((col+1, row))
        if is_valid_pos((col, row+1)): q.enqueue((col, row+1))
        if is_valid_pos((col-1, row)): q.enqueue((col-1, row))
        if is_valid_pos((col, row-1)): q.enqueue((col, row-1))

    print("Goal can't be reached.")

while True:
    system('cls')
    maze = create_maze(4)
    MAZE_SIZE = len(maze)
    solve(maze, (0,0))
    input('Press Enter to restart: ')

Feedback in mostly top-down order

"""Doc strings""".  You should get in the habit of adding these at the top of your file, the top of every class, and the top of every (public) function.

class Queue.  I'm certain you know that Python comes with everything including the kitchen sink, so it should come as no surprise that there exists a deque already builtin.  I'll assume you implemented your own for practice.  ;-)

self.list The list member should not be accessed outside of the Queue class; it is an internal private detail.  To indicate this, you should name the member with a leading underscore, referencing it as self._list.  Python does not enforce public/private semantics, but many code-review tools (such as pylint) will check for and complain about these violations.  Also, leading underscores can "hide" members from autogenerated documentation.

You actually do reference it outside the Queue class, to print the queue's contents.  You should instead implement the method which converts the object to a string, for printing.  It is called __str__, and you could implement it like:

class Queue:
    # ... your other methods here

    def __str__(self):
        return str(self._list)

Then instead of .format(q.list), you could write .format(q).

    def dequeue(self):
        temp = self.list[0]
        del self.list[0]
        return temp

This is verbose code to retrieve an item from the start of a list, remove the item from the list, and return the item.  The list has a builtin method to do this: pop(0).

    def dequeue(self):
        return self.list.pop(0)

    maze = []
    for row in range(n):
        row = []
        ...
        maze.append(row)

The variable row is created in the for loop, and assigned the value 0 (an integer).  Then, the next statement reassigns row to [] (a list).  Fortunately, when the loop returns for the next value, it doesn't try to add 1 to row, but rather retrieves the next value from the range(n), and the loop works properly.  But this is still poor coding.  pylint will complain that the type of row (not that python has typed variables) changes between an int and a list.

Better would be to use a different variable names, or since the int value of row is never used, to use no variable name at all.  A single underscore is by convention the "throwaway" variable, used when you need a variable but will never use it.

    maze = []
    for _ in range(n):
        row = []
        ...
        maze.append(row)

row.append(0)
row.append(1)
maze[n-1][n-1] = 2
maze[row][col] = 3

Magic numbers!  What is 0?  What is 1?  What is 2?  What is 3?

Help maintain the code by giving names to these numbers.  For example, you could add:

EMPTY = 0
BLOCKED = 1
GOAL = 2
VISITED = 3

at the top of your program, and then use:

maze[n-1][n-1] = GOAL

Readers/maintainers of your program will understand more quickly what is meant by GOAL than by 2.

But, just assigning values to variable names is slightly dangerous.  They are variables can therefore can be changed.  Better would be to create an Enum:

from enum import Enum
class Position(Enum):
    EMPTY = 0
    BLOCKED = 1
    GOAL = 2
    VISITED = 3

Then you can write:

maze[n-1][n-1] = Position.GOAL

And the value of Position.GOAL cannot be changed.

def is_valid_pos(tup):
    (col, row) = tup
    if col < 0 or row < 0 or col >= MAZE_SIZE  or row >= MAZE_SIZE :
        return False
    return maze[row][col] == 0 or maze[row][col] == 2

You always call is_valid_pos((..., ...)), constructing a tuple to pass to the function, which immediately unpacks the tuple into col and row.  Why not simply use col and row as parameters?

The tests for whether row and col are within the valid range is more complex than it needs to be.  Python allows for chained comparisons.  The compound test:

if 0 <= row  and  row < MAZE_SIZE:

can be written as:

if 0 <= row < MAZE_SIZE:

Python evaluates 0 <= row, then row < MAZE_SIZE, then the and of the two values.  So the function may be rewritten as:

def is_valid_pos(col, row):
    if  0 <= col < MAZE_SIZE  and  0 <= row < MAZE_SIZE:
        return (maze[row][col] == Position.EMPTY  or
                maze[row][col] == Position.GOAL)
    return False

As of Python 3.6, we have "f-strings".  This means instead of:

print('Enqueueing ({},{})'.format(col,row))

where you need to match the format() arguments to the correct {} codes positions, we can write:

print(f'Enqueueing ({col},{row})')

which is shorter and may be simpler to understand.

    if is_valid_pos((col+1, row)): q.enqueue((col+1, row))
    if is_valid_pos((col, row+1)): q.enqueue((col, row+1))
    if is_valid_pos((col-1, row)): q.enqueue((col-1, row))
    if is_valid_pos((col, row-1)): q.enqueue((col, row-1))

This code style is error prone.  You probably copied the first line, and pasted it 3 times, and then changed the +1's to -1's, and moved them from col to row.  Did you make the same change to corresponding the is_valid_pos() and q.enqueue() calls?

Better might be:

    enqueue_if_valid(q, col+1, row)
    enqueue_if_valid(q, col, row+1)
    enqueue_if_valid(q, col-1, row)
    enqueue_if_valid(q, col, row-1)

and write an enqueue_if_valid() function:

def enqueue_if_valid(q, col, row):
    if is_valid_pos(col, row):
        q.enqueue((col, row))

  I notice that there are duplicate values in the Queue. I understand that I should avoid visiting already visited positions. However the queue contains only "prospective" positions which are yet to be visited. Should I modify the algorithm to not enqueue positions which it already contains?

Since we have moved the 4 enqueue operations into a call to one function, it would now become easier to implement this improvement.  One way would be to search the queue for the tuple you are about to add, but an easier way would be to mark maze[col][row] with Position.ENQUEUED, if it was Position.EMPTY.  Then the next time you are about to enqueue that position, instead of that position being valid, it would return invalid and not be enqueued a second time.

What is maze?  Is it a local variable, and passed to solve(maze, ...) and print_maze(maze)?  Or is it a global variable that is_valid_pos() automatically knows about?

Pick one.

MAZE_SIZE is also a global.  Do you need it?  Or could you just use len(maze) when it is required?


Mocking dependencies when unit testing AngularJS services with QUnit I'm trying to unit test an AngularJS service that is dependent on another service, using QUnit as my testing framework. The first test I'm writing is one to verify that my service calls another service under specific circumstances.

Below is a runnable example. I'm mainly looking to get feedback on the contents of the second main closure (which represents a QUnit module). Things I'm particularly interested in:

Conventions around unit testing AngularJS services with QUnit (e.g. I'm unsure when it's common to prefix variables with a $);
I'm following this advice (which was for Jasmine though) on mocking a dependent service, but am unsure if I can improve that approach or even need a different one (heck, perhaps I even need / should use a mocking framework?);
Whether I'm using the injector features of Angular correctly.

Here's a runnable snippet with promised code:

(function() {
    var app = angular.module('demoApp', []);

    app.factory('myService', ['anotherService', function(anotherService) {
        return {
            getTheTruth: function() { return anotherService.someFunction(); }
        };
    }]);
})();

(function() {
    // Looking to get feedback on this closure...

    'use strict';

    var $injector, anotherService;

    QUnit.module('myServiceTests', {
        beforeEach: function() {
            anotherService = {};
            angular.module('demoApp').factory('anotherService', function() {
                return anotherService;
            });
            $injector = angular.injector(['ng', 'demoApp']);
        }
    });

    QUnit.test('Calling getTheTruth relays to anotherService', function(assert) {
        var service = $injector.get('myService');
        anotherService.someFunction = function() {
            assert.ok(true);
        };
        assert.expect(1);
        service.getTheTruth();
    });

    // More tests here
})();
<link href="https://cdnjs.cloudflare.com/ajax/libs/qunit/1.16.0/qunit.min.css" rel="stylesheet"/>

e.g. I'm unsure when it's common to prefix variables with a $

A quick Google and I found a StackOverflow thread about this,

The accepted answer had this to say:

  It's a common reference to a jQuery wrapped object. It makes reading the code easier to know which variables are jQuery wrapped.

I would say that you don't need to use $ prefix in your code at all, at least what you have posted.

If you were using $scope that would be different as noted by this answer

  $scope variables bind to the view where as var does not and is local to the function it was declared in!

also noted in the comments

  The $ prefix is used as a naming convention identifying native AngularJS services

▼▼▼

  Do not use $ to prepend your own object properties and service identifiers. Consider this style of naming reserved by AngularJS and jQuery.

From Google's AngularJS Style Guide


"Block a website" script with vanilla JavaScript I use this script to block access to a one or more websites with vanilla JavaScript. I find that it helps me avoid some addictive news websites that make me depressed. (Credit to Marat Tanalin for helping me with the event handling.)

The script is aimed to be an all vanilla JavaScript imperative small script for personal usage, hence it's not modular (there isn't a HTML/CSS/JS file distribution on purpose).

To use the script please change news_website_1.com to a given news website you hate.

My personal main problem with the script is that it doesn't block websites right away or almost right away such as happens with BlockSite Google Chrome extension:
For example, the script first loads a website, then about 5 seconds pass, then it gets blocked; for some reason, listening to the sooner DOMContentLoaded event sometimes works and sometimes doesn't and a reviewed version might show an improvement in that point.

How would you revise this script?

// ==UserScript==
// @name         New Userscript
// @match        *
// ==/UserScript==

window.addEventListener('load', ()=> {
  let sitesToBlock = [
      'news_website_1.com'
  ];
  let regexToMatchTLD = /\..+/;
  let href = window.location.href;
  for (let i = 0; i < sitesToBlock.length; i++) {
      if (href.includes(sitesToBlock[i])) {
          let domain = sitesToBlock[i].replace(regexToMatchTLD, '');
          document.body.innerHTML =`

                  The website ${domain} successfully blocked !

        `;
      }
  }
}, false);

The main suggestion I have is to take the values from sitesToBlock and put them in the @match metadata key instead of detecting when to update the document content. There is an extensive guide about match patterns here. With this approach there should not be any need to wait for the DOM to be loaded and check if the URL contains elements in sitesToBlock, though maybe that “news_website_1” loads slower than the one I tested with and that won’t work.

Other review points:

default to using const instead of let when declaring variables unless re-assignment is mandatory. This helps avoid accidental re-assignment.
use for...of loops when possible- e.g. for iterating through sitesToBlock and there is no need for a counter variable (e.g. i) other than accessing the current element


Find positive integer with a minimum number of binary 1's such that its bitwise AND with all array elements is not 0 Task

  You have an array of positive integers. Your task is to find an
  integer x such that the following are true:

  Bitwise AND between x and each array element is non-zero.
  Number of ones in the binary expression of x is minimum.
  If there are many such x, you should find smallest of them.

  Input Format

  The first line contains a single integer n, the number of elements
  in the array. The second line contains n space-separated integers.

  Constraints

  1<=n<=10,000
  array elements are in range [1; 2^26)

Please find a full description of the problem here.

My Effort

Count a number of binary 1's for each number from 1 to \$2^{26} - 1\$.
Sort each number from 1 to \$2^{26} - 1\$ by its number of binary 1's. Use a normal std::sort(). Unfortunately, the counting sort is not an option here as its space complexity is too high for Hackerrank environment.
Check each sorted number from the previous step against the array numbers. If its AND with all of them is not 0 - we've found the answer.

This approach has a \$O(m \cdot \log(m) \cdot n)\$ time and \$O(m)\$ space complexity where m - maximum value of an array element and n - size of the array. So, it produces a timeout error for every test case. It produces the correct result, though - I ran it locally for a couple of test cases.

I've tried a \$O(m \cdot n)\$ time and \$O(2 \cdot m)\$ space complexity solution (using the counting sort)  but it didn't work due to a segmentation fault. As stated before, there's a limit as to how much memory one can use for this problem and that one was exceeded.

Code

#include <vector>
#include <iostream>
#include <algorithm>
#include <bitset>

uint32_t solve(std::vector<uint32_t>& array) {
    const uint32_t upperBoundValue = (1 << 26);

    std::vector<uint32_t> candidateNumbers(upperBoundValue);
    for (uint32_t i = 0; i < upperBoundValue; i++) {
        candidateNumbers[i] = i;
    }

    // sort all possible x's by their binary 1's in ascending order
    std::sort(candidateNumbers.begin(), candidateNumbers.end(), [](const auto& a, const auto& b) {
        std::bitset<26> bitSet1(a);
        std::bitset<26> bitSet2(b);

        size_t count1 = bitSet1.count();
        size_t count2 = bitSet2.count();

        if (count1 < count2) {
            return true;
        } else if (count2 < count1) {
            return false;
        } else {
            return a < b;
        }
    });

    // exclude duplicates from the array to reduce its size
    std::sort(array.begin(), array.end());
    array.erase(unique(array.begin(), array.end()), array.end());

    uint32_t candidateIndex;
    for (candidateIndex = 0; candidateIndex < upperBoundValue; candidateIndex++) {
        bool candidateFound = true;

        for (uint32_t index = 0; index < array.size(); index++) {
            if (!(candidateNumbers[candidateIndex] & array[index])) {
                candidateFound = false;
                break;
            }
        }

        if (candidateFound) {
            break;
        }
    }

    return candidateNumbers[candidateIndex];
}

int main() {
    //read an array size
    uint32_t size;
    std::cin >> size;

    //save each value into the corresponding array position
    std::vector<uint32_t> array(size);
    for (auto& element : array) {
        std::cin >> element;
    }

    uint32_t bestMask = solve(array);
    std::cout << bestMask << "\n";

    return 0;
}

Question

Is there a way to improve the time complexity of this solution without exceeding the space limitation? Should a completely different approach be used here?

Is there a way to improve the time complexity of this solution without
  exceeding the space limitation?

Yes, there's a way. We don't actually need any additional array of numbers because we can check all numbers from 1 to the maximum possible mask for given elements of the array. Then, we will perform AND of the current number candidate with all array elements only if its 1's count lower than that of the current best candidate. Please check the code for more details.

  Should a completely different approach be used here?

I've come up with a similar brute force approach that requires only additional O(1) space. It's quite simple and also passes all the tests.

Remove duplicates from the original array

We can safely do it because duplicate elements do not influence the final answer. It also helps us to reduce the size of the array and thus improve the time complexity of the algorithm.

Sort the array by 1's count

By doing so, we won't perform a bitwise AND for most of best mask candidates with ALL array elements and thus save a lot of execution time.

Perform AND only for candidate numbers having fewer 1's

That's another important optimisation. Before checking a candidate against the array elements make sure it has fewer 1's than the current best candidate.

Code

#include <vector>
#include <iostream>
#include <algorithm>
#include <bitset>

uint8_t popCount(const uint32_t& number) {
    std::bitset<26> bitSet(number);

    return bitSet.count();
}

uint32_t solve(std::vector<uint32_t>& array) {
    // exclude duplicates from the array to reduce its size
    std::sort(array.begin(), array.end());
    array.erase(unique(array.begin(), array.end()), array.end());

    // sort array elements based on their 1's count in ascending order
    std::sort(array.begin(), array.end(), [](const auto& a, const auto& b) {
        uint8_t count1 = popCount(a);
        uint8_t count2 = popCount(b);

        if (count1 == count2) {
            return a < b;
        }
        return count1 < count2;
    });

    // Initially, bestMask is the maximum possible mask
    uint32_t maxPossibleMask = 0;
    for (const auto& element : array) {
        maxPossibleMask |= element;
    }

    uint32_t bestMask = maxPossibleMask;
    for (uint32_t bestMaskCandidate = 1; bestMaskCandidate < maxPossibleMask; bestMaskCandidate++) {
        if (popCount(bestMaskCandidate) < popCount(bestMask)) {

            bool candidateFound = true;
            for (uint32_t index = 0; index < array.size(); index++) {
                if (!(bestMaskCandidate & array[index])) {
                    candidateFound = false;
                    break;
                }
            }

            if (candidateFound) {
                bestMask = bestMaskCandidate;
            }
        }
    }

    return bestMask;
}

int main() {
    //read an array size
    uint32_t size;
    std::cin >> size;

    //save each value into the corresponding array position
    std::vector<uint32_t> array(size);
    for (auto& element : array) {
        std::cin >> element;
    }

    uint32_t bestMask = solve(array);
    std::cout << bestMask << "\n";

    return 0;
}


Optimize method to iterate to over Map> I have a Map<String, List<Object>> multiFieldMap and I need to iterate over its value set and add the value to multiFieldsList:

public List<Object> fetchMultiFieldsList() {
    List<Object> multiFieldsList = new ArrayList<>();
    for (Entry<String, List<Object>> entry : multiFieldMap.entrySet()) {
        String entityName = entry.getKey();
        List<Object> ids = entry.getValue();
        for (Object id : ids) {
            Object entity = queryService.query(entityName, queryService.property("id").eq(id));
            multiFieldsList.add(entity);
        }
    }
    return multiFieldsList;
}

Can this method be simplified further?

You can accomplish this using Java 8 streams.

public List<Object> fetchMultiFieldsList() {
    return multiFieldMap.entrySet().stream()
      .flatMap(e -> {
          String entityName = e.getKey();
          List<Object> ids = e.getValue();
          return ids.stream()
            .map(id -> queryService.query(entityName, queryService.property("id").eq(id)));
      }).collect(Collectors.toList());
}

I think the code itself is relatively self-explanatory. The important bit is the usage of flatMap instead of map for the first mapping operation so that the resulting streams are concatenated, ending up with a flat list of objects rather than a list of lists.

It is unfortunate that Java does not support destructuring assignment, which would allow the first lambda expression to be a single expression of the form (k, v) -> ..., but it does not, so I've left the statements in for clarity.

If you are willing to omit the inner declarations, the above code can be simplified further.

public List<Object> fetchMultiFieldsList() {
    return multiFieldMap.entrySet().stream()
      .flatMap(e -> e.getValue().stream()
          .map(id -> queryService.query(e.getKey(), queryService.property("id").eq(id)))
      ).collect(Collectors.toList());
}

Whichever one you prefer is a matter of personal preference. The former has more descriptive variable names, while the latter is simpler and more functional.


Python breadth first search algorithm Any pointers, or any advice on how to clean up my code/make more pythonic would be appreciated.

graph = {'A': ['B','Y','D', 'E',],
         'B': ['F','F'],
         'C': ['F'],
         'D': [],
         'E': ['F','G'],
         'F': ['F','A'],
         'G': ['E','K'],
         'K': ['M','L']
         }

def bfs(graph,start,end):
    vertex = [start]
    history = []

    #  create new node to be iterated through
    #  update history
    #  update vertex

    while vertex:  #  while vertex is not empty. len(li) == 0:

        node = vertex[0]  #  get the 0th element of the vertex
        history.append(node)
        print(node)

        vertex.pop(0)  #  pop the 0th element of the vertex
        if node == end:
            return end

      #  iterate through the graph. gather all of the values per node

        for i in graph.get(node, '/'): #  if key does not exist, print '/'

            if i:  #if i is not empty
                vertex.append(i)
                # append the dict values into vertex list
                print('vertex',vertex)

            if i in history:
               vertex.pop(-1)

1. Bug

A correct implementation of breadth-first search visits each node at most once, but the code in the post visits some nodes multiple times. In this example, \$C\$ gets visited twice:

>>> graph = {'A': 'BC', 'B': 'C', 'C': 'A'}
>>> bfs(graph, 'A', 'Z')
A
vertex ['B']
vertex ['B', 'C']
B
vertex ['C', 'C']
C
vertex ['C', 'A']
C
vertex ['A']

The problem is that a node is only added to the history list after you pop it from the vertex list. But that means that if there are multiple paths to a node, then it can be added to the vertex list multiple times (as in the example above, where node \$C\$ gets added twice).

Instead, a node should be added to the history list at the same time as you add it to the vertex list.

2. Review

The name queue would be better than vertex (it's a queue of nodes that have been visited in the search but whose neighbours have not yet been considered for visiting).
The queue is implemented using a list. But this is inefficient because popping the leftmost element of a list takes time proportional to the length of the list (because the other items in the list get moved down in the list to fill the space). It is better to use a collections.deque, which has an efficient popleft method.
The name visited would be better than history (it's a collection of nodes that have been visited in the search).
The collection of visited nodes is implemented using a list. But this is inefficient because finding an element in a list takes time proportional to the length of the list (because the element gets compared against each member of the list in turn). It is better to use a set, which has efficient membership determination.
The name neighbour would be better than i (it's a neighbour of node in the graph).
It's pointless to add a node to the queue and then immediately remove it again:

    if i:  #if i is not empty
        vertex.append(i)
    if i in history:
       vertex.pop(-1)

Instead of testing for node == end after popping the node from the queue, it would be better to test before adding it to the queue. That way you wouldn't have to wait for the end node to move all the way up the queue.

3. Revised code

from collections import deque

def bfs(graph, start, end):
    """Return True if there is a path from start to end in graph, False if
    not. graph must be a dictionary mapping a node to a collection of its
    neighbours.
    """
    if start == end:
        return True
    queue = deque([start])
    visited = set(queue)
    while queue:
        node = queue.popleft()
        for neighbour in graph.get(node, ()):
            if neighbour not in visited:
                if neighbour == end:
                    return True
                queue.append(neighbour)
                visited.add(neighbour)
    return False


trash script to alias rm This script implements a command line level trashcan system.

Designed to work around rm doing the bits needed to implement a trashcan system at command line level. Any user flags hands the request over to rm. This means rm -f will still delete a file with no recovery. Prevents execution by root as too many dependencies at superuser level. Deployment by adding aliases rm=trash and rmoops=untrash. Only implemented on files, does not cater for directories.

Appreciate any and all suggestions from formatting, expansion of the idea to glaring issues. Looking for an experienced eye to pin point potential issues.

/usr/local/bin/trash

#!/bin/bash
#
# Trashcan script
# alias rm=trash
#

error() {
  echo $1
  exit 1
}

bypass() {
  exec rm $*
}

file="$1"
trash=~/.trash
keep=5

## bypass scenarios
# root user
[ "$(id -u)" = "0" ] && error "Please do not run as root user."
# special cases
case $file in
  -*) bypass $* ;;
  $trash/* ) bypass $* ;;
esac
# only single filename supported
[ $# -gt 1 ] && bypass $*
# can we access the file?
[ -f "$file" ] || error "File not specified."

# move existing versions out of the way
ls $trash/$file.version.* 2>/dev/null | tac | while read name; do
  version=$((${name##*.}+1))
  # keep the only the last number of versions
  if [ $version -gt $keep ]; then
    rm $name || error "Unable to remove file $name."
  else
    mv $name $trash/$file.version.$version || error "Unable to move version $version."
  fi
done

# move file into trash (volume friendly)
cp --preserve $file $trash/$file.version.1 || error "Unable to trash your file."
rm -f $file || error "Unable to cleanup the file."

exit 0

/usr/local/bin/untrash

#!/bin/bash
#
# Restore files from Trashcan
# alias rmoops=untrash
#

error() {
  echo $1
  exit 1
}

file="$1"
trash=~/.trash
keep=5

## bypass scenarios
# root user
[ "$(id -u)" = "0" ] && error "Please do not run as root user."

# any flags so rm -rf actually does it
case $file in
  -*) error "Flags are not supported." ;;
  $trash/*) error "You cant restore from trash directly." ;;
esac

# only single filename supported
[ $# -ne 1 ] && error "File not specified."

version=0
# find latest version
for name in `ls $trash/$file.version.* 2>/dev/null | tac`
do
  version=${name##*.}
  break
done
[ $version -gt 0 ] || error "Sorry I cannot find your file in the trash."

echo "I have versions 1 to $version, 1 being the most recent."
echo -n "Which would you like to restore? [1]:"
read user
[ -n "$user" ] || user=1

# check we have the actual file
[ -f $trash/$file.version.$user ] || error "Sorry I cannot find that version."
# move existing file out of the way
[ -f $file ] && mv $file $file.old
# restore the file
cp $trash/$file.version.$user $file || error "Unable to restore file."
echo Version $user restored.

exit 0

Overall
I'm not really convinced of the value of this "trashcan" idea.  If deleting files doesn't actually delete them, then what's the point?  Trying to create free space would be ineffectual.  Worse, encouraging users to lean on an "undelete" facility will likely leave them in trouble when they move to a conventional system without such a crutch.  (Plus, it's a Good Thing to have an occasional minor accident - otherwise it's very easy to just assume that your backups are working, and never think to verify that you can actually restore from them!  I'm certainly guilty of that...)
Quoting issues
Much of your code doesn't quote expanded variables when it should.  One example:
case $file in
  -*) bypass $* ;;
  $trash/* ) bypass $* ;;
esac

This is unsafe, and needs to be written
case "$file" in
  -*) bypass "$@" ;;
  "$trash"/* ) bypass "$@" ;;
esac

There are many more similar instances; I won't list them all.
Testing for file-ness rather than existence
[ -f "$file" ] || error "File not specified."

Do you really want this error when you ask to trash a symlink?  In fact, I think the wording of the message is poor, even for the case you think you're testing.
Pathname matching
You test whether the argument is in the "trash" directory with
case $file in
  $trash/* )
esac

There's other ways to refer to the same directory as "$trash" - in particular, a relative name from the working directory.  You'll need to canonicalise path name if you're doing this kind of comparison; possibly you might want to compare device and inode numbers for real robustness if you might have bind mounts and the like.
Echo and read
This code:
echo -n "Which would you like to restore? [1]:"
read user

is usually written
read -p "Which would you like to restore? [1]: " user

(I'm not sure that user is a good name for the version number, either).


Movement code from a game Could you suggest ways of writing this code better?

bool success = true;

if(x == 0)
{
    if(do_up)
        run_do_up();
    else if(do_a)
        run_do_a();
    else if(do_n)
        run_do_n();
    else
        success = false;
}
else if(x == 1)
{
    if(do_n)
        run_do_n();
    else if(do_a)
        run_do_a();
    else
        success = false;
}
else//x == 2
{
    if(do_a)
        run_do_a();
    else if(do_n)
        run_do_n();
    else
        success = false;
}

I think I'd encode this into something on the order of a state machine--a table holding the conditions and actions associated with each, and a tiny bit of code to walk through those to carry out the tests:

#include <iostream>
#include <functional>

#ifdef TEST
bool do_n, do_a, do_up;
bool success;
bool T = true;

void run_do_up() { std::cout << "did up\n"; }
void run_do_a() { std::cout << "did a\n"; }
void run_do_n() { std::cout << "did n\n"; }
#endif

struct conditional_action {
     bool const &condition;
     std::function <void()> action;

     template <class F>
     conditional_action(bool const &b, F &a) : condition(b), action(a) {}

     conditional_action() : condition(T), action([&]{success = false; }) {}
};

conditional_action actions[4][3] {
    { { do_up, run_do_up }, { do_a, run_do_a }, { do_n, run_do_n } },
    { { do_n, run_do_n }, { do_a, run_do_a } },
    { { do_a, run_do_a }, { do_n, run_do_n } }
};

void exec(size_t x) {
    for (auto const &a : actions[x])
        if (a.condition) {
            a.action();
            return;
        }
}

#ifdef TEST

int main() {
    do_n = true;
    exec(0);

    do_a = true;
    exec(2);
}
#endif

Depending on viewpoint, you might want to add a { T, [&]{success = false; }} to the end of each row in the actions table. That's what the default ctor will fill those entries with anyway, but there's a fair argument to be made that since it was explicit in the original logic, it should remain explicit here as well.

There is probably at least a little argument to be made that this is kind of a borderline case. A case where there were more conditions and actions would favor this technique more strongly. Whether really it makes sense when you have only three conditions and actions may be open to a little more question.


Dumping output from template_init() I have a Drupal site with roughly the following in my template.php hook_init block:

function mytemplate_init() {
    if (request_path() == "widgets_json") {
        drupal_json_output(_get_widgets());
        exit;
    }
    if (request_path() == "people_json") {
        drupal_json_output(_get_people());
        exit;
    }
}

Are there any problems with this approach?

On the face of it, the two main problems are that it's going to break if URL's ever change, and it's impossible to theme the output of those functions using an appropriate page--widget_json.tpl.php or page--people_json.tpl.php template. On the other hand, adding a content type just for a few JSON output pages that are never going to change paths seems like overkill.

What do you think of this approach?

From what I see, you could use two different methods: Ternaries and switches:

From a switch point of view, you could use the following to proceed:

function mytemplate_init() {
    switch(request_path()) {
       case "widgets_json":
           drupal_json_output(_get_widgets());
       break;
       case "people_json":
           drupal_json_output(_get_people());
       break;
    }
}

Or, one can replace that with a ternary to shorten it:

if (request_path() == "widgets_json") {
    drupal_json_output(_get_widgets());
    exit;
}
if (request_path() == "people_json") {
    drupal_json_output(_get_people());
    exit;
}

into:

request_path() == "widgets_json" ? drupal_json_output(_get_widgets()) : (request_path() == "people_json" ? drupal_json_output(_get_people()) : "" )
exit;

The shortside to ternaries is that you sacrifice readability for effectiveness.

However, if you can move past that, ternaries are an effective part of a Programmer's Toolbelt(TM)

Or, as I've since come to understand, we can use objects!

$functions = [
       "widgets_json" => _get_widgets,
       "people_json"  => _get_people
     ];
$functions[request_path()]();

Unfortunately, with such a small amount of code supplied, very little can be reviewed.


Sleep until specified time It's sometimes useful to pause until a specified time (but inconvenient to use at or the like), so I wrote a tiny script to wait until a user-specified time point is reached.

I use this when I want to keep the output of preceding and subsequent commands together, but I don't mind blocking the current terminal.  Quite often, this would be M-xcompile when I want to wait until after new source code/data have been uploaded, but still have the results in a compilation-mode buffer.

Although it's a very short script, my time at Code Review has taught me that almost any program has something that can be improved, so please make your suggestions!

#!/bin/sh

# Sleep until the specified time

# Accepts any date/time format accepted by 'date'

# Assumes GNU date and GNU sleep

die() {
    echo "$@" >&2
    exit 1
}

usage() {
    echo "Usage: $0 TIME"
}

test $# = 1 || die $(usage)

case "$1" in
    --version)
        echo "sleep_until version 1.0"
        exit 0
        ;;
    --help)
        usage
        exit 0
        ;;
    -*)
        die "Unrecognised option: $1"
        ;;
    *)
        end=$(date -d "$1" +%s.%N)
        now=$(date +%s.%N)
        test ${end%.*} -gt ${now%.*} || die "$1 is in the past!"
        exec sleep $(echo $end $now - p | dc )
        ;;
esac

Notes:

We need GNU date for its -d option and a good range of input formats.
GNU sleep handles fractional seconds; we could remove .%N from the date formats to work with traditional/POSIX sleep.
I've used dc for the arithmetic so we can use plain sh rather than requiring a more heavyweight shell.

In a program comment it is said that the program

# Accepts any date/time format accepted by 'date'

That information should be printed with the usage help, plus one or two examples. Something like

$ ./sleep_until.sh --help
Usage: ./sleep_until.sh TIME

    TIME can be any date/time as accepted by date(1).

Examples:

    ...

That'll save me from looking into the source code (and possibly from
looking up man date) in order to figure out the correct parameters.

Due to the truncation in

test ${end%.*} -gt ${now%.*} || die "$1 is in the past!"

there is a (albeit small) chance that a valid date is not recognized.
This can be avoided by computing the delay first, and then checking
it to be positive (e.g. as in How to compare to floating point number in a shell script):

end=$(date -d "$1" +%s.%N)
now=$(date +%s.%N)
delay=$(echo $end - $now | bc)
test 1 -eq $(echo "$delay > 0" | bc) || die "$1 is in the past!"
exec sleep $delay

Note: I'm using bc rather than dc here just because I needed it for the check $delay > 0 and found a bc-based solution first (and then I did not want to use two different tools). Also I am a little bit more familiar with bc. Some criteria are given in the Unix & Linux question How is bc different from dc?, such as “bc is standardised by POSIX and so is probably the more portable of the two.”


jQuery eye candy for a WordPress site This is a follow-up to this question my code has evolved since so I'm reposting my question.

What is the best way to tidy this up? How can this be refined? I am finding it's thrashing the layout quite a lot and the scroll function seems to lag.

;(function ($, window) {
var main = $("#swab"),
    sbContainer = $("#sb-container"),
    sbContainerDiv = sbContainer.find("div"),
    tblcontents = $('#tblcontents'),
    tblcontentstwo = $('#tblcontents_2'),
    button = $('#wrap_return, .thumb, #tblcontents'),
    slideele = $('.site, .menu-panel'),
    slideele2 = $('.site, .menu-panel_2');

function animate() {
    sbContainerDiv.css({
        "transform": "rotate(0deg)",
            "-webkit-transform": "rotate(0deg)",
            "-ms-transform": "rotate(0deg)",
            "-moz-transform": "rotate(0deg)",
            "-o-transform": "rotate(0deg)"
    });

    main.animate({
        "right": "1%",
            "left": "auto",
            "top": "4px"
    }, "slow");
}

function toggletwo() {

    var toggleStatetwo = true;
    $(tblcontents).on("click", function () {
        if (toggleStatetwo) {
            animate({
                "top": "15%"
            });
            main.fadeOut(1000);
        } else {
            animate();
            main.fadeIn(1000);
        }
        toggleStatetwo = !toggleStatetwo;
    });

}

function toggleone() {
    $(tblcontents).on("click", function () {
        main.stop(true, true).animate();
    });

}

var $window = $(window);
$window.resize(function () {
    if (this.resizeTO) clearTimeout(this.resizeTO);

    this.resizeTO = setTimeout(function () {
        $(this).trigger('resizeEnd');
    }, 500);
});

$window.on('resizeEnd', function () {
    var winWidth = $window.width();

    if (winWidth < 960) {
        toggletwo();
        animate();
    } else {
        toggleone();
    }
});

$(document).scroll(function () {
    animate();
});
var toggleState = true;
$('#toggle_div').on("click", function () {
    if (toggleState) {
        main.animate({
            "right": "50%"
        }, "slow");
    } else {
        main.animate({
            "right": "1%",
                "top": "4px"
        }, "slow");
        main.css("left", "auto");
    }
    toggleState = !toggleState;
});

$(tblcontents).effect("pulsate", {
    times: 100
}, 2000).on('click', function () {
    $(this).effect().stop(true, true);
    $(this).animate({
        "opacity": "1"
    }, "fast");
});
$(button).on("click", function () {
    animate({
        "top": "4px"
    }, "slow");
});
main.draggable()

$(function () {

    sbContainer.swatchbook({
        center: 6,
        angleInc: 20,
        speed: 700,
        easing: 'ease',
        proximity: 120,
        neighbor: 20,
        onLoadAnim: true,
        initclosed: true,
        closeIdx: 11,
        openAt: -1

    });
});

var toggleStatemenu2 = true;
$(tblcontentstwo).on("click", function () {
    if (toggleStatemenu2) {
        $(slideele2).animate({
            top: '+=171'
        }, 458, 'swing', function () {});
    } else {
        $(slideele2).animate({
            top: '-=171'
        }, 458, 'swing', function () {});
    }
    toggleStatemenu2 = !toggleStatemenu2;
});
var toggleStatemenu = true;
$(tblcontents).on("click", function () {
    if (toggleStatemenu) {
        $(slideele).animate({
            left: '+=240'
        }, 458, 'swing', function () {});
    } else {
        $(slideele).animate({
            left: '-=240'
        }, 458, 'swing', function () {});
    }
    toggleStatemenu = !toggleStatemenu;
});

})(jQuery, window, document);

Interesting question:

Naming

JavaScript uses lowerCamelCase variable and function names. ( tblcontentstwo -> TblContentsTwo or TabelContents2
Some of your prefixes like sb are not adding anything. I would drop those prefixes.
Names like slideele2 are unfortunate, ideally the name should reflect what is being slided (slid?)

Comments

You have no comments whatsoever, fortunately the code reads well
Still, in some places, like sbContainer.swatchbook(, I have no clue what you are trying to accomplish

JSHint.com

Your code passes all checks, except for 1 semicolon, well done ;)

Readability

You don't use newlines consistently, more specifically you need more newlines in a few spots
Also your indentation is off in places, I would use a site like http://jsbeautifier.org/

Don't Repeat Yourself

This looks like copy pasted code:

var toggleStatemenu2 = true;
$(tblcontentstwo).on("click", function () {
if (toggleStatemenu2) {
    $(slideele2).animate({
    top: '+=171'
    }, 458, 'swing', function () {});
} else {
    $(slideele2).animate({
    top: '-=171'
    }, 458, 'swing', function () {});
}
toggleStatemenu2 = !toggleStatemenu2;
});
var toggleStatemenu = true;
$(tblcontents).on("click", function () {
if (toggleStatemenu) {
    $(slideele).animate({
    left: '+=240'
    }, 458, 'swing', function () {});
} else {
    $(slideele).animate({
    left: '-=240'
    }, 458, 'swing', function () {});
}
toggleStatemenu = !toggleStatemenu;
});

you could try to make a helper function there.

var toggleStates = {};

function createSlider( button, slider, animation1, animation2 ){
  toggleStates[button.id] = true;
  $(button).on("click", function () {
    if (toggleStates[button.id]) {
      $(slider).animate(animation, 458, 'swing', function () {});
    } else {
      $(slider).animate(animation2, 458, 'swing', function () {});
    }
    toggleStates[button.id] = !toggleStates[button.id];
  }
}
createSlider(tblcontentstwo, slideele2, {top: '+=171'}, {top: '-=171'} );
createSlider(tblcontents, slideele, {left: '+=240'}, {left: '-=240'} );


Initiating Child ViewController from UIStoryBoard in iOS I'm trying to use inheritance in UIViewController where base class has XIB in storyboard. I'm troubling with initiating different children classes with that XIB.
I cannot use XIB file separately instead of storyboard because it has static UITableViewCells.

So here is how I'm managing it currently using object_setClass method in SWIFT:
Parent Class:

class MeetingViewController: UITableViewController {

    private(set) var project: CDProject?
    private(set) var meeting: CDMeeting?

    static func initWith(project: CDProject?, meeting: CDMeeting?) -> MeetingViewController {
        let storyboard = UIStoryboard(name: "Meeting", bundle: nil)
        let meetingVC = storyboard.instantiateViewController(withIdentifier: "MeetingVCId") as! MeetingViewController
        meetingVC.project = project
        meetingVC.meeting = meeting
        return meetingVC
    }
}

Child Class-1:

class MeetingInfoViewController: MeetingViewController {

    static func initWith(meeting: CDMeeting) -> MeetingInfoViewController {
        let meetingVC = MeetingViewController.initWith(project: nil, meeting: meeting)
        object_setClass(meetingVC, MeetingInfoViewController.self)
        return meetingVC as! MeetingInfoViewController
    }
}

Child Class-2:

class MeetingCreateViewController: MeetingViewController {

    static func initWith(project: CDProject) -> MeetingCreateViewController {
        let meetingVC = MeetingViewController.initWith(project: project, meeting: nil)
        object_setClass(meetingVC, MeetingCreateViewController.self)
        return meetingVC as! MeetingCreateViewController
    }
}

This is working very fine, not any issue; but I'm just curious if:
1 there's any other way to handle this scenario?
2 this approach has any side-effects?
3 this can be improved somehow?

Also feel free to point out other things than initialisation!

There isn't another way to handle this scenario. Storyboard VC's can't be subclassed without replicating the UI also.
I'm surprised this works at all. object_setClass just changes the isa pointer, so the memory is still set up for the parent class, not the child. It will probably crash if you try to set an instance variable that doesn't exist in the parent.
Refactor the two VC's into one (since the UI is the same after all), and use composition for the differences instead.


What percentage of down votes are users responsible for? I put together this simple query to calculate the percentage of downvotes each user is responsible for and displaying them in order of downvote percentage. It's generating the desired results, but I am uncertain about style and best practices.

WITH DownVoteCount AS (
SELECT DownVoteCount = CAST(SUM(DownVotes) AS float)
FROM Users
), DownVoteWeight AS (
SELECT DisplayName, UpVotes, DownVoteWeight = ROUND(DownVotes / (SELECT DownVoteCount from DownVoteCount) * 100, 4)
FROM Users
Where Users.DownVotes > 0
)

SELECT DisplayName, DownVoteWeight
FROM DownVoteWeight

ORDER BY DownVoteWeight DESC, UpVotes

I read about the capitalization of keywords, and decided it would be useful in case of working with SQL inside strings, where syntax highlighting wouldn't be available.

SQL casing shouldn't matter (much)
Every SQL developer I know writes their queries a bit differently. Case/style shouldn't matter much or at all, if the SQL code works but it's a bit sloppy. Favor substance over style. For example, these 3 queries are identical, as far as the database engine cares:
/* These are all exactly the same in SQL: */
SELECT FOO, BAR FROM TEST;
Select Foo, Bar From Test;
select foo, bar from test;

That being said...
...there are a few things we could probably improve in your own query...
Some indentation would feel nice, especially in the subqueries/CTEs. Some indentation will make your code much easier to read:
WITH foo AS (
    ...
),
bar AS (
    ...
)
--etc

Lines breaks
Line breaks...also feel nice, especially for breaking down business logic, which DownVoteWeight is (for instance), where it can be broken down into meaningful functions/operations. This one might deserve a bit more documentation.
SELECT
    DisplayName,
    UpVotes,
    DownVoteWeight = ROUND(
        DownVotes / (SELECT DownVoteCount from DownVoteCount) * 100, 4
    )


Knockout first-timer Looking at knockout for the first time, would like to know if I'm approaching it correctly.

Here's a live example:
http://jsfiddle.net/fergal_doyle/xhAe8/1/

I have a "car" select, and an "other" input to allow values not present in the select box. When "other" is populated, it over-rides "car" by disabling it and a computed observable is set to the actual chosen car. Only when "other" is emptied, will "car" become enabled again.

HTML:

Car
<select id="car" data-bind="options: cars, value: selectedCar, enable: checkCar"></select>

Other
<input id="other" type="text" data-bind="value: other, valueUpdate:'afterkeydown'"/>

Chosen value:

JS:

function viewModel(){
    var self = this;

    self.cars = ko.observableArray(["Chrysler", "Chevrolet", "Ford", "Lincoln"]);
    self.other = ko.observable("");
    self.selectedCar = ko.observable("");

    self.chosenCar = ko.computed(function() {
        return self.other() || self.selectedCar();
    });

    self.checkCar = ko.computed(function(){
        if(self.other())
            return false;
        else
            return true;
    });
}

ko.applyBindings(new viewModel());

It looks fine to me.  My only real criticism is your checkCar implementation.  It ought to be written out as:

self.checkCar = ko.computed(function(){
    return !self.other();
});

On a minor note, you should case your view model name in PascalCase.  By making constructors like that, they stand out better.  Everything else should be in camelCase.

Other than that, you've made great use of the computed observables.  A big mistake I see a lot on Stack Overflow IMHO is when I see people putting all that logic in the view.

I might change the name of the properties however to be more descriptive of what they represent.  In particular, change checkCar to isSelectedCarOverridden.

Personally, I'd change it around a bit.  I'd add an "Other" option in the cars list and make the Other car input enabled/visible based on that value.

Also, consider making cars not observable. If this is going to be a fixed list and you won't be dynamically adding to it, making it observable may be unnecessary.  In fact, I'd pull that array out of the view model as it appears to be a constant value.  That way if you have multiple view models instantiated in the future, they all can share the same instance.

var constants = {
    cars: ["Chrysler", "Chevrolet", "Ford", "Lincoln"]
};

function ViewModel() {
    var self = this;
    self.cars = constants.cars;
    // ...
}


Print a "shebang" line, or prepend it to a file This is a sort-of-useless "utility" I wrote to learn my way around shell programming better.

My concerns are:

Is the code readable? Could it be more efficient, or just simpler? The logic ends up being a little complicated and I have a lot of nested if statements. Should I use 4 tabs instead of 2?
Is the interface itself (the flags, arguments, etc) intuitive? Is the documentation clear?
How easily this could be ported to Bash? As far as I remember, the only Zsh-specific feature I use here is zparseopts, but I've been casually using Zsh for a while and I could have forgotten some of the inconsistencies between shells.

# shebang [-iv] [-t interpreter] [-I extension] [-J [extension]] [filename]
#
# If no filename is given, print a shebang. If a filename is given, append a shebang to the file and print its contents. If a filename is given and the -I or -J options are specified, append a shebang to the file in place.
#
# OPTIONS
#   -i
#     Interactive mode; ask for confirmation first.
#   -I
#     Modify "filename" in place (as in `sed -i`) using specified extension. Extension is mandatory.
#   -J
#     Same as -I, but extension is mandatory only if the string "gsed" cannot be found in the output of `which sed`. Overridden by -I.
#   -t
#     Specify an interpreter, e.g. `shebang -t zsh` produces "#!/usr/bin/env zsh"
#   -v
#     Print (to stderr) the interpreter being used.

shebang () {
  local interpreter
  local inplace
  local inplace2
  local verbose
  local interactive
  local input_shebang
  local shebang
  local continue
  local sed_command
  local gsed_avail
  zparseopts -D t:=interpreter I:=inplace J::=inplace2 v=verbose -i=interactive
  (( $? )) && return 1

  if [[ -n $1 ]]; then
    input_shebang=$(sed -n '1 { /^#!/ p; }' "$1")
    if (( $? )); then
      echo "Unable to read $1." >&2
      return 1
    fi
    if [[ -n "$input_shebang" ]]; then
      echo "$1 already has a shebang." >&2
      return 1
    fi
  fi

  if [[ (-z "$interpreter") && (-z "$1") ]]; then
    echo "The -t option is mandatory if no argument is supplied." >&2
    return 1
  fi

  if [[ (-z "$interpreter") && (-n "$1") ]]; then
    interpreter=$(filename=$(basename "$1"); [[ "$filename" = *.* ]] && echo "${filename##*.}" || echo '')  # grab extension
    interpreter=${interpreter:#(* *|* | *)}  # "extensions" with whitespace probably aren't legit
    interpreter=${interpreter:-sh}  # assume sh if no extension and no -t option
  else
    interpreter="$interpreter[2]"
  fi

  shebang="#!/usr/bin/env $interpreter"

  if [[ -n $verbose ]]; then
    echo "Using interpreter '$interpreter'" >&2
  fi

  if [[ -n $interactive ]]; then
    read -q "continue?Shebang will be '$shebang'. Ok? y/n: "
    [[ $continue == n ]] && return 1
  fi

  if [[ -z "$1" ]]; then
    echo $shebang
  else
    gsed_avail=$(command which -s gsed && echo 1)
    echo $gsed_avail

    if [[ -n $gsed_avail ]]; then
      sed_command="1 i\\$shebang\n"
      if [[ -n $inplace ]]; then
        gsed "${inplace/-I/-i}" "$sed_command" "$1"
      elif [[ -n $inplace2 ]]; then
        gsed "${inplace2/-J/-i}" "$sed_command" "$1"
      else
        gsed "$sed_command" "$1"
      fi
    else
      sed_command='1 i\
REPLACEME\n'  # need to use single quotes to preserve the line break
      sed_command=${sed_command/REPLACEME/$shebang}  # work around the single quotes
      if [[ -n $inplace ]]; then
        sed "${inplace/-I/-i}" "$sed_command" "$1"
      elif [[ (-n $inplace2) && (-z ${inplace2#-J}) ]]; then
        echo "'-J' was given without an argument, but 'gsed' is unavailable. Specify an explicit extension or use -I."
      elif [[ -n ${inplace2#-J} ]]; then
        sed "${inplace2/-J/-i}" "$sed_command" "$1"
      else
        sed "$sed_command" "$1"
      fi
    fi
  fi
}

Is the code readable? Can this code be simpler?

Basically readable, although I prefer early returns and things like that.

Ported to bash but testing limited:

# shebang [-iv] [-t interpreter] [-I extension] [-J [extension]] [filename]
#
# If no filename is given, print a shebang. If a filename is given, append a
# shebang to the file and print its contents. If a filename is given and the -I
# or -J options are specified, append a shebang to the file in place.
#
# OPTIONS
#   -i
#    Interactive mode; ask for confirmation first.
#   -I
#    Modify "filename" in place (as in `sed -i`) using specified extension.
#   Extension is mandatory.
#   -J
#    Same as -I, but extension is mandatory only if the string "gsed" cannot
#    be found in the output of `which sed`. Overridden by -I.
#   -t
#    Specify an interpreter, e.g. `shebang -t zsh` produces "#!/usr/bin/env zsh"
#   -v
#    Print (to stderr) the interpreter being used.

shebang () {
    local inplace inplace2 verbose interactive
    local interpreter input_shebang shebang continue
    local sed_command gsed_avail _nextopt _line _readbool
    local OPT OPTIND OPTARG
    # HACK: shift manually when encounters J
    while getopts 't:I:viJ' OPT; do case "$OPT" in
        i)  interactive=1;;
        I)  inplace="$OPTARG";;
        J)  eval "nextopt=\$$OPTIND";
            case "$_nextopt" in
                -*) inplace2='-J';;
                *)  inplace2="-J $_nextopt"; shift;;
            esac;;
        t)  interpreter="$OPTARG";;
        v)  verbose=1;;
    esac; done
    shift $((OPTIND-1))

    (( $? )) && return 1

    if [[ -n $1 ]]; then
        IFS='' read -r _line < "$1"
        if (( $? )); then
            echo "Unable to read $1." >&2
            return 1
        fi
        # if echo "$_line" | grep ^#!; then
        if [[ "$_line" =~ ^\#! ]]; then
            echo "$1 already has a shebang." >&2
            return 1
        fi
    fi

    if [[ (-z "$interpreter") && (-z "$1") ]]; then
          echo "The -t option is mandatory if no argument is supplied." >&2
          return 1
    fi

    if [[ (-z "$interpreter") && (-n "$1") ]]; then
          interpreter=$(filename=$(basename "$1"); [[ "$filename" = *.* ]] && echo "${filename##*.}")  # grab extension
          interpreter=${interpreter/#* *}  # "extensions" with whitespace probably aren't legit
          : ${interpreter:=sh}  # assume sh if no extension and no -t option
    fi

    if [[ "$ZSH_VERION" ]]; then
        # reads one character.
        _sb_read1(){ read -k 1 "$@"; }
    else
        # ksh/bash
        _sb_read1(){ read -n 1 "$@"; }
    fi

    shebang="#!/usr/bin/env $interpreter"

    if [[ -n $verbose ]]; then
        echo "Using interpreter '$interpreter'" >&2
    fi

    if [[ -n $interactive ]]; then
        while true; do
            printf "continue? Shebang will be '$shebang'. Ok? y/n: "
            # ah, zsh/bash have different ideas on read.
            _sb_read1 _readbool
            echo
            case "$_readbool" in
                [nN])   return 1;;
                [yY])   break;;
            esac
        done
    fi

    if [[ -z "$1" ]]; then
          echo $shebang
          return 0
    fi

    if type gsed; then
        sed_command="1 i\\$shebang\n"
        if [[ -n $inplace ]]; then
            gsed "${inplace/-I/-i}" "$sed_command" "$1"
        elif [[ -n $inplace2 ]]; then
            gsed "${inplace2/-J/-i}" "$sed_command" "$1"
        else
            gsed "$sed_command" "$1"
        fi
    else
        sed_command=$'1i\n'$shebang'\n'
        if [[ -n $inplace ]]; then
            sed "${inplace/-I/-i}" "$sed_command" "$1"
        elif [[ (-n $inplace2) && (-z ${inplace2#-J}) ]]; then
            echo "'-J' was given without an argument, but 'gsed' is unavailable. Specify an explicit extension or use -I."
        elif [[ -n ${inplace2#-J} ]]; then
            sed "${inplace2/-J/-i}" "$sed_command" "$1"
        else
            sed "$sed_command" "$1"
        fi
    fi
}

Using that grep for if gives extra ksh compatibility (untested).


Singly-linked queue in PHP 7 I am learning PHP 7 and decided to implement a simple FIFO singly-linked queue in it:

<?php

class QueueNode {
    var $item;
    var $next;

    function __construct($item) {
        $this->item = $item;
    }

    function get_item() {
        return $this->item;
    }
}

class Queue {
    var $head;
    var $tail;
    var $size;

    function push($item) {
        if ($this->size == 0) {
            $this->head = $this->tail = new QueueNode($item);
        } else {
            $new_node = new QueueNode($item);
            $this->tail->next = $new_node;
            $this->tail = $new_node;
        }

        $this->size++;
    }

    function pop() {
        if ($this->size == 0) {
            throw new Exception("Popping from an empty queue.");
        }

        $ret = $this->head->item;
        $this->head = $this->head->next;

        if (--$this->size == 0) {
            $this->head = $this->tail = null;
        }

        return $ret;
    }
}

$queue = new Queue();

for ($i = 1; $i <= 10; $i++) {
    $queue->push($i);
}

for ($i = 1; $i <= 10; $i++) {
    echo $queue->pop() . " ";
}

echo "<br>";
?>

As always, any critique is much appreciated.

Getters and setters
So there is a getter for item (i.e. get_item()) - why not a getter (and setter) for the next property? If getters and setters are added, then those properties could be set to private visibility if deemed appropriate.
Are you familiar with the PHP Standards Recommendations? While it is only a suggestion, you might find them helpful for writing code that is maintainable and readable, not only for others but also your future self.
According to PSR-1:

Method names MUST be declared in camelCase().1

A format of getItem() is more widely used amongst many PHP developers.
Types and conditions
Inside Queue::push() and Queue::pop() I see this common first line:

if ($this->size == 0) {

It is advisable to use strict equality comparison operators (i.e. === and !==) to avoid excess type-juggling. As a consequence, size should perhaps be declared with a initial value of 0.
The conditional could also be shortened to if (!$this->size) { though that would allow any type that is considered to FALSE to allow the conditional block to be executed.
keyword var
var is a feature from PHP 4 and it isn't needed anymore2 - while it works as a synonym for public it is deprecated. If you adhere to PSR-2 then note it specifies:

The var keyword MUST NOT be used to declare a property.3

for loops
There isn't anything wrong with a traditional loop, but you could use the range() function to iterate $i for you in a foreach loop:

for ($i = 1; $i <= 10; $i++) {

can be changed to:
foreach(range(1, 10) as $i) {


Extension method replacing elements from an IEnumerable collection Today I needed a method to replace all 'x' values in a said collection. Since there is no such method by default in .NET I wrote my own:

[Pure]
public static IEnumerable<T> Replace<T>(this IEnumerable<T> source, T oldValue, T newValue)
{
    if (source == null)
    {
        throw new ArgumentNullException(nameof(source));
    }

    List<T> newValues = new List<T>();
    using (var enumerator = source.GetEnumerator())
    {
        while (enumerator.MoveNext())
        {
            newValues.Add(enumerator.Current.Equals(oldValue) ? newValue : enumerator.Current);
        }
    }
    return newValues;
}

It's pretty short and does the job right in a reasonable amount of time.

I also tested few other solutions:

[Pure]
public static IEnumerable<T> Replace1<T>(this IEnumerable<T> source, T oldValue, T newValue)
{
    if (source == null)
    {
        throw new ArgumentNullException(nameof(source));
    }

    using (var enumerator = source.GetEnumerator())
    {
        while (enumerator.MoveNext())
        {
            yield return enumerator.Current.Equals(oldValue) ? newValue : enumerator.Current;
        }
    }
}

[Pure]
public static IEnumerable<T> Replace2<T>(this IEnumerable<T> source, T oldValue, T newValue)
{
    if (source == null)
    {
        throw new ArgumentNullException(nameof(source));
    }

    List<T> newValues = new List<T>(source);
    for (int i = 0; i < newValues.Count; i++)
    {
        if (newValues[i].Equals(oldValue))
        {
            newValues[i] = newValue;
        }
    }
    return newValues;
}

But they are all slower than the former. The only advantage is in the function which utilizes iterator because it's a bit shorter but it's actually the slowest out of the three.

Here are my benchmark results for each method running 1 million times:

Replace

Slowest: 207ms

Average: 177.8ms

Fastest: 161ms

Replace 1

Slowest: 353ms

Average: 293.9ms

Fastest: 253ms

Replace 2

Slowest: 344ms

Average: 276.4ms

Fastest: 252ms

Feel free to comment on anything you feel like can be improved.

Here are some of my questions:

Are there any flaws in my function?
Are there any improvements that can be made?
Why didn't Microsoft include this in the .NET framework?

Why didn't Microsoft include this in the .NET framework?

Probably because it can be realized in one line with Select:

source.Select(x => x.Equals(oldValue) ? newValue : x)

or with 2 lines as extension method if the function is needed frequently.

public static IEnumerable<T> Replace<T>(this IEnumerable<T> source, T oldValue, T newValue)
    => source.Select(x => x.Equals(oldValue) ? newValue : x)

That's the nice thing of enumerable methods. There are just some discrete methods available, but those can be parameterized / combined to realize the most use cases. I really like the compactness and elegance of the LINQ API :).


Is this a good way to use Try catch? I'm new to handling errors and am not sure how to do it, basically, in a speicific request err.code === 11000 is not actually an error, but expected behaviour. I want to output it but not like another error and I want the code to continue running. I don't think it looks nice.

(async () =>{
  let client;
  try {
    client = await MongoClient;
    let sales = await call(),
        collection = client.db("scraper").collection("sold");
        try {
          stored = await collection.insertMany(sales.sold, {ordered: false});
          console.log({completed: stored.result.n})
        }catch(err){
          if(err.code === 11000){log({completed: err.result.nInserted, duplicates: err.result.result.writeErrors.length})}
          else{log( {err} )}
        }
    //console.log(sales)
  } catch(err) {
    log(err)
  }
  client.close();
})()

In the case that the error code is not 11000 I would re-throw the error in the inner try. That way you do not repeat, possibly complex error logic or possibly execute code that you do not want to. i.e. instead of

try {
  try {
    // code
  } catch(err) {
    if (err.code === 11000) {
      log({completed: err.result.nInserted, duplicates: err.result.result.writeErrors.length})
    } else {
      log('an error occurred', {err} )
    }
  }
  //code that shouldn't execute when an error occurs
} catch(err) {
  log('an error occurred', {err} )
}

something like

try {
  try {
    // code
  } catch(err1) {
    if (err1.code !== 11000) {
      throw err1;
    }
    log({completed: err1.result.nInserted, duplicates: err1.result.result.writeErrors.length})
  }
  //code that shouldn't execute when an error occurs
} catch(err2) {
  log('an error occurred', {err2} )
}

I also suggest using different variable names in different exception handlers. Some spaces between parentheses and curly brackets would also make your code more readable.


Simple AJAX library in JavaScript I've created two simple methods: one to instantiate a new XMLHttpRequest object and open the request and another to handle the request.

Can you please point out improvements that can be made or any shortcomings in my code?

ajax: function(opts) {

  var xhr, method, body, constructor;

  xhr = new XMLHttpRequest();
  method = opts.body ? 'POST' : opts.method ? opts.method.toUpperCase() : 'GET';

  if(opts.body) {
    constructor = opts.body.constructor;
    if(constructor === Object || constructor === String) {
      body = opts.body;
    }
  }

  this.ajaxComplete.call(xhr, opts);

  xhr.open(method, opts.url, (opts.async === undefined ? true : false));

  // Set the default request headers
  xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
  xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');

  if(opts.headers) {
    for(var prop in opts.headers) {
      xhr.setRequestHeader(prop, opts.headers[prop]);
    }
  }

  xhr.send(body || null);
},

ajaxComplete: function(opts) {
  var that = this,
      data, complete;

  that.onreadystatechange = function() {
    if(that.readyState == 4) {
      if(that.status == 200) {
        data = (that.responseXML || that.responseText);
        opts.success.call(that, data);
      }
      else {
        data = (that.responseXML || that.responseText);
        opts.error.call(opts, data, that.statusText, that.status);
      }
    }
  }
}

As Dan Pantry pointed out, === Object and === String do not work; you'll have to compare with a string name of the object:

if(opts.body) {
  constructor = opts.body.constructor;
  if(typeof constructor === "object" || typeof constructor === "string") {
    body = opts.body;
  }
}

Not every browser supports the XMLHttpRequest object. You'll have to do a little checking to get the right object.

The two main objects used are XMLHttpRequest and ActiveXObject("Microsoft.XMLHTTP"). The second one is used by IE.

You can use a simple ternary to see which object to use:

xhr = (window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP"));

If you need to copy this into a variable, most people use self, not that.

I don't think you need to check whether to return that.responseXML or that.responseText; I think responseText will contain the response no matter what, so you should just use that.

The complete variable is un-used in the ajaxComplete function; you don't need it.

You should put parenthesis around some places when defining the method variable. It is quite difficult to understand being that there is more than one ternary.

For one-time-use variables like data, don't store them in a variable; just substitue the value of the variable where you are using the variable and destroy the variable.

It's a waste of memory to keep something in memory that you only use once.


Vowels in a String are in Alphabetical Order Task

Write an implementation that returns whether a String has vowels (English language) in alphabetical (A-Z) order or not.

Feedback

Is my vowels variable appropriate? Is there a better way to implement a vowel lookup?
If a candidate String has no vowels, the validator will return true - is that reasonable? From a logical perspective, the program isn't lying, but you could make the same argument if it returned false. Would it be better to return an exception - something like NoVowelsInCandidateException?

Implementation

public class VowelOrderValidator {
    private static final List<Character> vowels = new ArrayList<>(
            Arrays.asList('A', 'E', 'I', 'O', 'U', 'Y')
    );

    public static boolean areVowelsOrdered(final String candidate) {
        final char[] chars = candidate.toUpperCase().toCharArray();
        int lastVowelIndex = 0;
        for (final char c : chars) {
            final int lookupIndex = vowels.indexOf(c);
            if (-1 != lookupIndex) {
                if (lookupIndex < lastVowelIndex) {
                    return false;
                } else {
                    lastVowelIndex = lookupIndex;
                }
            }

        }

        return true;
    }
}

Since vowels is a constant for your program, the convention would be that its name is in all uppercase, like VOWELS.
Take great care when uppercasing Strings:

final char[] chars = candidate.toUpperCase().toCharArray();

Uppercasing a String depends on the locale. By not specifying a locale, you are relying on the default locale of the JVM, which may cause problems for Turkish users (for example). It would be better to specify the ROOT locale:

final char[] chars = candidate.toUpperCase(Locale.ROOT).toCharArray();

I'm not a big fan of inversing the conditions in an if:

if (-1 != lookupIndex) {

The following would be easier to read:

if (lookupIndex != -1) {

In fact, it would be even better to not check against -1 but test that the result is positive:

if (lookupIndex >= 0) {

It decouples the fact that indexOf returns -1 from what you really want to test, which is that the index was found.
I think returning true when there is no vowels is the least surprising result: when there are no vowels, then they all are in the right order. Throwing an exception would be a bad idea: no vowels in a String is not a real exceptional condition.


Non-recursively replace all uppercase letters in files within current directory with lowercase letters - without looping Let's say that I have a directory that looks like this:

dir
    | File1.txt
    | fILE2.md
    | file3.tex

When I execute my bash script from within the dir directory, I want to receive files with names "file1.txt", "file2.md" and "file3.tex".

I have written this script:

ls | xargs -n1 -I {} sh -c 'fst={}; snd=`echo $fst | tr [:upper:] [:lower:]`; mv $fst $snd'

It works but is complex (uses variables). Is there a nicer way to perform it by piping commands? I don't want to use loops.

The design constraint of "repeat (some action) without loops" is nonsensical.

Any solution that is not "type every rename command yourself" involves a loop.  The loop may be hidden inside xargs and awk or rename; it's still there.

Anyway, assuming the files are like you say (well-formed, no embedded whitespace, all printable characters), you can have awk generate a shell script and feed that to a shell:

\ls | awk '/[A-Z]/ {print "mv",$1,tolower($1)}' | sh

If you need to deal with spaces and special characters, add quotes and use $0 (whole line) instead of $1 (first field):

\ls | awk '/[A-Z]/ {printf "mv '\''%s'\'\ \''%s'\''\n",$0,tolower($0)}'

If the filenames contain ' then this will fail and you need to work that out.  Your code has the same problem.  I won't get into the solution here because it involves a zillion backslashes and is the wrong way to solve this problem.

The right way to solve this problem is to use a tool built for the task (rename) or a shell loop.  And adding -i is a good idea, in case the new filename already exists.  This will work with any filename:

for f in *[A-Z]* ; do mv -i -- "$f" "${f,,}"; done


Reading a web page with Python When I am scraping from a web page I need a way to open and read it. Previously, I used two functions, one for requests and one for Selenium

def read_page_w_requests(url):
    try:
        headers = {'User-agent': 'Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.0.1) \
                    Gecko/2008071615 Fedora/3.0.1-1.fc9 Firefox/3.0.1'}
        r = requests.get(url, headers=headers)
        text = r.text
    except Exception, e:
        print "Read page with requests error:", e
        text = None
    return text

def read_page_w_selenium(driver, url, element_be_located=""):
    try:
        driver.get(url)
        wait = WebDriverWait(driver, 10)
        if element_be_located:
            wait.until(EC.visibility_of_element_located((By.ID, element_be_located)))
            text = driver.page_source
        else:
            text = driver.page_source

    except Exception, e:
        print "Read page error:", e
        text = None

    return text

I am thinking of using just one, that combines both:

import requests
from selenium import webdriver
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC

def get_driver():
    try:
        dcap = dict(DesiredCapabilities.PHANTOMJS)
        dcap["phantomjs.page.settings.userAgent"] = (
            "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/53 "
            "(KHTML, like Gecko) Chrome/15.0.87"
        )
        driver = webdriver.PhantomJS(desired_capabilities=dcap)
        return driver
    except Exception, e:
        print "Driver error:", e
        return None

def get_page_source(url, driver="", element=""):
    if driver:
        try:
            driver.get(url)
            wait = WebDriverWait(driver, 10)
            if element:
                wait.until(EC.visibility_of_element_located((By.ID, element)))
            text = driver.page_source
        except Exception, e:
            print "Read page error:", e
            text = None

    else:
        try:
            headers = {'User-agent': 'Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.0.1) \
                        Gecko/2008071615 Fedora/3.0.1-1.fc9 Firefox/3.0.1'}
            r = requests.get(url, headers=headers)
            text = r.text
        except Exception, e:
            print "Read page error:", e
            text = None

    return text

Is it a good idea to combine two functions that do the same thing with a different way in a single function? One of my concerns is the name of each function.

I don't think it's worth having as one function. Why? Because you don't get to share any of the functionality. Your singular wrapped function just tests if there's a driver value and will execute one of two completely separate code blocks as a result. Instead, consider having the two functions separate, and then a single wrapper function that you can call which will determine which one to call.

In other words:

def get_page_source(url, driver="", element=""):
    if driver:
        return read_page_w_selenium(driver, url, element)
    else:
        return read_page_w_requests(url)

This way you only need to call get_page_source but you're not cramming two unrelated blocks into the same function.

Other notes, you shouldn't set driver as an empty string if you expect an object. Set the default value as None and then test for that.

def get_page_source(url, driver=None, element=""):
    if driver is None:
        return read_page_w_selenium(driver, url, element)

Also it's confusing to change the order of arguments. Make url first in both functions so that the order is consistent.

Instead of using text = None then return text. You could use a premature return and return None, though in Python that's equivalent to return. But I think even better would be the opposite, just use a premature return when you successfully get the text:

def read_page_w_requests(url):
    try:
        headers = {'User-agent': 'Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.0.1) \
                    Gecko/2008071615 Fedora/3.0.1-1.fc9 Firefox/3.0.1'}
        r = requests.get(url, headers=headers)
        return r.text
    except Exception, e:
        print "Read page with requests error:", e

Now your exception doesn't even need to return None, because by default a Python function without an explicit return will just return None anyway.