Most efficient implementation of Djisktra's shortest path using vectors and pairs in C++ stl

for(int i=0;i<v[ind].size();++i) {
    ...
    v[ind].erase(v[ind].begin()+i);
}

It looks like a bug. For instance, when you erase the 0-th element all other elements get shifted, so the new element at position 0 will never be deleted. You can just iterator over the vector and clear it after the loop.

I don't see the point in removing the graph edges after the vertex is processed. I'd suggest to create a separate vector (used or visited) to keep track of processed vertices and leave the input graph unchanged.

If the graph is sparse, you can improve the time complexity from O(|V|^2) to O(|E| log |V|) or even O(|E| + |V| log |V|) using an appropriate data structure (like a heap).

I'd also suggest to create a separate class for an edge instead of using std::pair<int, int>. It's hard to confuse edge.weight with edge.destination_vertex. It's easy to confuse the first and the second elements of the pair (it's not easy to keep the meaning of the first and the second elements of the pair in one's head).

You can make the code more readable by naming your variables in a more meaningful way (for instance, what is yo? It's something like min_distance, isn't it?).

When you need to iterate over a container and you don't need elements' indices, you can use a range-based for loop. For instance, this:

for(int i=0;i<v[ind].size();++i)
{
    if(ans[v[ind][i].first] > ans[ind]+v[ind][i].second)
        ans[v[ind][i].first] = ans[ind]+v[ind][i].second;
    v[ind].erase(v[ind].begin()+i);
}

could be

for (auto edge: v[ind]) { // or const auto& edge for heavier objects
// do something with the edge
}

You can also improve the readability of your code by creating smaller functions with a meaningful name that do one focused thing (like finding the closest vertex and so on) and call them from the function that implements Dijkstra's algorithm itself. Here's how I'd do it:

// Instances of this struct represent graph edges
struct Edge {
    int weight;
    int destination_vertex;

    Edge(int _weight, int _destination_vertex):
        weight(_weight), destination_vertex(_destination_vertex) {}
};

// Finds the closest unvisited vertex
int get_closest_unvisited_vertex(const vector<long long>& dist,
        const vector<bool>& visited) {
    int closest_vertex = -1;
    for (size_t v = 0; v < dist.size(); v++) {
        if (!visited[v]
                && (closest_vertex == -1 || dist[v] < dist[closest_vertex])) {
            closest_vertex = v;
        }
    }
    return closest_vertex;
}

// Updates the distances to all neighbors of the given vertex
// The dist vector is passed by reference to avoid copying the data
void relax_vertex(int vertex, const vector<vector<Edge>>& graph,
        vector<long long>& dist) {
    for (auto edge : graph[vertex]) {
        dist[edge.destination_vertex] = min(dist[edge.destination_vertex],
                dist[vertex] + edge.weight);
    }
}

// Finds the distance from the source vertex to all other vertices in
// the graph
vector<long long> get_distance_from(const vector<vector<Edge>>& graph,
        int source) {
    vector<long long> dist(graph.size(), numeric_limits<long long>::max());
    dist[source] = 0;
    vector<bool> visited(graph.size());
    while (true) {
        int closest_vertex = get_closest_unvisited_vertex(dist, visited);
        if (closest_vertex == -1
                || dist[closest_vertex] == numeric_limits<long long>::max()) {
            break;
        }
        visited[closest_vertex] = true;
        relax_vertex(closest_vertex, graph, dist);
    }
    return dist;
}


Serialize C# objects of unknown type to bytes using generics

Your methodology is solid on the generics front. Highly recommend using using statements rather than try..finallys. I also converted the methods to extension methods.

namespace Codingoutloud
{
   using System.IO;
   using System.Runtime.Serialization.Formatters.Binary;

   public static class ByteArraySerializer
   {
      public static byte[] Serialize<T>(this T m)
      {
         using (var ms = new MemoryStream())
         {
            new BinaryFormatter().Serialize(ms, m);
            return ms.ToArray();
         }
      }

      public static T Deserialize<T>(this byte[] byteArray)
      {
         using (var ms = new MemoryStream(byteArray))
         {
            return (T)new BinaryFormatter().Deserialize(ms);
         }
      }
   }
}


How can I modify my graph traversal algorithm to increase efficiency?

You can multiply the adjacency-matrix n times to get all paths of length n between any nodes. Therefore, if you multiply A^n * vector_with_only_your_startVertex, you can see in the resulting vector which nodes can be reached.
Make sure to also safe nodes that can be reached in less steps, because for example there may be cases where a node may be reached in 2, but not in 3 steps.
Also make sure your multyplying right-associatively, as matrix-vector multiplication is way faster than matrix-matrix multiplication.

I have no clue if this is faster though. Depends if you have a well-written matrix multiplication program that does not compute unnecessary zero-rows.

You can also always use Dijkstra's algorithm for that, in this case every edge has weight 1.
Also I don't understand why you are saving your result in a tree-structure. Unless you rely on an ordering of the elements of your result (which I guess you don't), you can use a hash-based set, which has access-time of O(1) and not O(log(N)) like trees do.


Reimplementation of call() method in JavaScript

Review

To be quick I will just add comments to the code with some alternatives

// if you add to a built in prototype use Object.defineProperty or Object.defineProperties
// using the default settings
// Function.prototype.myCall = function(...args){ // use 2 parameters
Function.prototype.myCall = function(name, ...args){

  // var param = args.slice(1),  // is now second parameter

  // Should be a constant
  //    paramLength = param.length,
  const  paramLength = args.length;

  // not really a param string. Rather its a eval function
  //  paramString = "JSONarg.myFun(";
  var evaledFunc = "JSONarg.myFun(";

  // The variable if defined in the loop should be let
  // Now starts at index 0
  //for(var i = 1; i <= paramLength; i++){
  for (let i = 0; i < paramLength; i++) {  // add space for ( and ) {

    evaledFunc += "args[" + i + "],";  // use spaces between operators
  }
  evaledFunc += ")";

  // This function is a prototype of Function. You would have to go hard
  // to have the next statement be true. Just let the native exception
  // generate the error
  /*if(typeof this != 'function'){
    throw new Error(this + " is not a Function");
  }*/

  // Does not change, thus should be a const
  // var JSONarg =  {
  const JSONarg =  {  // would be best defined at the top of the function

  // args[0] is now the param name
  //  ...args[0],
      ...name,
    myFun: this
  // }  // there should be a ; here
  };
  return eval(evaledFunc);
}

Removing the comments and some minor mods we get...

function myCaller(name, ...args) {
    const JSONarg =  {...name, myFun: this};
    var func = "JSONarg.myFun(";
    for (let i = 0; i < args.length; i++) {
        func += "args[" + i + "],";
    }
    func += ")";
    return eval(func);
}

Rather than eval you could also have use new Function

Object.defineProperty

To prevent problems (myCall showing up in strange places) and as it is in a very often used native type.( All functions get the new property). enumerable = true can slow every function call just a little depending on JS engine and version.

Add to prototype safely using Object.defineProperty. Default accessor configurable, enumerable, writable are false

if (! Function.prototype.myCall) {
    Object.defineProperty(Function.prototype, myCall, {value: myCaller});
}

Function.bind

With all that said there is a much easier way to do the same. Function.bind will bind a functions with an object (sets the functions this)

function printName(location, district){
    alert(this.name + ", " + this.version + ", " + location + ", " + district);
}
printName.bind({...name})( "Chrome", "browser");

// or just use original name obj

printName.bind(name)( "Chrome", "browser");

The bound function is a new reference, the original function remains unbound

const printNameBound = printName.bind(name);

printNameBound("Chrome", "browser");

printName("Chrome", "browser"); // will fail as not bound to name object

Function.call or Function.apply

You can also use Function.call or Function.apply to do the same. In this case there is no new reference to the function created. The binding is temporary.

printName.call(name, "Chrome", "browser");

// or

printName.apply(name, ["Chrome", "browser"]); // args as array


Separating items into ordered and unordered lists

How can I simplify the function and reduce multiple return statements?

You could reduce the number of return statements by building up the new object in a more imperative way, without using the map and reduce functions,
but I'm not sure that would be better.
I think it's fine using functions as it is.

This part doesn't look great:

  let listObject = acc.find((el, i) => i > lastHeadingIndex && i < index && el.type === 'list');

The problem with it is that you are using lastHeadingIndex to find the last heading added in acc,
but acc.find will search from the beginning.
With a large data, that would be a waste,
instead of searching from the end.

In fact, I'm wondering if lastHeadingIndex is important at all.
Isn't your real intention more like "consecutive items of list type should be combined into a list object"?
If that's the case, then you don't need to search from the end,
it's enough to look at the last item of acc:
if it's a list type, then append to it, if not, then create a new list type.

If this is indeed your real intention,
then you could get rid of lastHeadingIndex, and write a bit simpler:

function moveToNewObject(data) {
  const listItemTypes = ['unordered-list-item', 'ordered-list-item'];
  return data[0].areas.map(area => {
    var sec = area.sections;
    return sec.map(section => {
      return section.rjf.reduce((acc, current, index) => {
        if (!listItemTypes.includes(current.type)) {
          acc.push(current);
          return acc;
        }

        if (!acc.length || acc[acc.length - 1].type !== 'list') {
          acc.push({type: 'list', items: [current]});
          return acc;
        }

        acc[acc.length - 1].items.push(current);
        return acc;
      }, [])
    });
  });
}

I would also change the name of the function,
because moveToNewObject sounds overly generic,
it doesn't seem to describe its real purpose.
How about combineListItemTypes,
or transformCombiningListItemTypes?


Optimize and accelerate bash script to transform XML to SQLITE

Take-home message: pipelines in Bash are slow (compared to process substitution); loops in Bash are slow; Bash are slow.

Without a setup script and dummy data to test run it, I don't really understand exactly what your script is trying to achieve at each step, so I can only suggest the following improvements:

Avoid unnecessary pipelines

A lot of your code does cat $1 | grep Telegram | sed -e 's/"/ /g', which can be simplified to sed '/Telegram/!d; s/"/ /g' "$1", so you may want to save the result somewhere and extract from it when needed.
awk '{ print $9 }' | cut -c27-30 can be combined into awk '{print substr($9, 27, 4)}'.
In the command substitution that gets assigned to b, you have sed -e 's/;/ /g' | sed  -e 's/=/ /g' which should really just be sed -e 's/;/ /g' -e 's/=/ /g' or even better just sed 's/[;=]/ /g'. You don't need the -e option if you're not combining expressions.
kk=`wc -l trdata | awk '{ print $1 }'`: kk=`wc -l < trdata` can do the job just fine.
cat grhostfinal | cut -c1-4 > grhostfinal1 is not as efficient as cut -c1-4 < grhostfinal > grhostfinal1
sqlite3 test2.sqlite "select fecha from testxml4;" > data.csv

cat data.csv | sort | uniq > data2.csv

is probably best done entirely in SQL:

sqlite3 test2.sqlite "SELECT DISTINCT fecha FROM testxml4 ORDER BY fecha;" > data.csv

Avoid loops if possible, or optimize for each iteration of the loop

for i in `seq 1 $kk`
do
    echo $a >> rsctype
done

is much slower than

printf "$a\n%.0s" `seq 1 $kk` >> rsctype

for small $kk, and much slower than

yes "$a" | head -n "$kk" >> rsctype

for large $kk. See https://superuser.com/questions/86340/linux-command-to-repeat-a-string-n-times. (Not sure if you actually want to repeat the same strings, but that's what your code does.)
for k in `cat data2.csv`
do
    grep "$k" conjunto.csv >> quitar
done

diff quitar conjunto.csv | grep ">" | sed 's/^> //g' > diferencia.csv

looks like it could be done with just one diff? Maybe (haven't tested it):

diff --changed-group-format='%>' --unchanged-group-format='' data2.csv conjunto.csv\
 > diferencia.csv

Non-performance-related notes

You should wrap your cleanup command in a trap and put it at the beginning of the script so that it will always be executed unless the program is terminated by a SIGKILL:

trap 'rm -f \
rs{host,cname,ctype} \
ttstamp tservice tformat trdata{,2,3,4} \
grhost{,2,final{,{1..4}}} \
data{,2}.csv conjunto.csv \
{a..c} quitar' \
'EXIT'

Please don't rm -r if you're not deleting directories. This is a dangerous command if you're not careful. I used brace expansion to shorten the list of input files I need to type, but I'm not sure if you really need to create that many temporary files.
You don't need to touch the files. Redirection will create the files if they don't exist.

I can probably offer more suggestions if I could try out the script. I'll add to this answer if I think of anything, but this should be enough for now.


The implementation looks fine. Some small notes:

Consider using Guava's Uninterruptibles class if you don't want to handle InterruptedExceptions.
The default access waiting flag in Thread1 is makes the code hard to read/follow and results tight coupling.
Consider using Runnables instead of Threads. See: Java: “implements Runnable” vs. “extends Thread”
Consider synchronizing on a separate lock object: Avoid synchronized(this) in Java?

Anyway, it would be much easier, less error-prone and more readable with a fair Semaphore (from the concurrency utilities package):

App.java:

public class App {

    public static void main(final String[] args) throws InterruptedException {
        final Semaphore control = new Semaphore(1, true);

        final Thread1 thread1 = new Thread1(control);
        final Thread2 thread2 = new Thread2();

        thread1.start();
        Uninterruptibles.sleepUninterruptibly(500, TimeUnit.MILLISECONDS);
        control.acquireUninterruptibly();
        thread2.start();
        thread2.join();
        control.release();
    }
}

Thread1.java:

public class Thread1 extends Thread {
    private final Semaphore control;

    public Thread1(final Semaphore control) {
        this.control = control;
    }

    @Override
    public void run() {
        for (int i = 1; i < 10; i++) {
            control.acquireUninterruptibly();
            try {
                Uninterruptibles.sleepUninterruptibly(100, TimeUnit.MILLISECONDS);
                System.out.println("From testFun1() = " + i);
            } finally {
                control.release();
            }
        }
    }
}

Thread2.java:

public class Thread2 extends Thread {

    public void run() {
        for (int i = 20; i <= 25; i++) {
            Uninterruptibles.sleepUninterruptibly(100, TimeUnit.MILLISECONDS);
            System.out.println("From testFun2() = " + i);
        }

    }
}


jQuery nested ajax deffereds- looking for improvements

I'm not sure what do you exactly need?
http://jsfiddle.net/tomalec/GeRkG/1/

Use promise returned by $.post. we don't need var xml_A and $.when(xml_A)
Remove deffereds_b from global scope, and use it as resolved value.

And now improvements depends on what you are trying to achive:

Just get all responses together in right order, after all is done
Do above, but performe partial operations as soon as posible, if so do you really need countA while handling B response?

1:
http://jsfiddle.net/tomalec/GeRkG/3/
 - Move B response handling outside
 - Move content to local scopes
 or even: http://jsfiddle.net/tomalec/GeRkG/4/
  - one callback, and object creation less

2:
http://jsfiddle.net/tomalec/rwq2d/2/
 - Move AB response handling outside, we can move A separately if you want to perform it sooner, than later (before B response).
 - Move content to local scopes
 - Removed closure for $.when.apply( null, requests)

function parseContent(content) {
    console.log('content',content);
    $.each(content, function() {
        $('body').append('

' + this.a + '
' + this.b.join('
'));
    })
}
function handleABResponse(returnedXML, $el_A, countA) {
    var name_of_Attribute_of_Element_A = $el_A.attr("name"),
        $el_Bs = $(returnedXML).find("ElementB"),
        results_b = [];
    $el_Bs.each(function(index, el) {
        var name_of_Attribute_of_Element_B = $(el).attr("name");
        results_b.push (countA + ". " + name_of_Attribute_of_Element_B);
    });

    return {
        a: countA + ". " + name_of_Attribute_of_Element_A,
        b: results_b
    }
}
/* Request As */
$.post("/echo/xml/", {
    xml: a
}).pipe(function(returnedXML) {
    /* process As */
    /* array to store nested ajax promises */
    var requests = [];

    var $el_As = $(returnedXML).find("ElementA");
    $el_As.each(function(countA) {
        var $el_A = $(this);
        /* push B promise to array*/
        requests.push(
            $.post("/echo/xml/", {
                xml: b
            })
            .pipe(function bSuccess (response){
                /* process A and Bs  */
                return handleABResponse(response, $el_A, countA);
            })
        );
    });
    /* return promise for all requests */
    return $.when.apply( null, requests );
}).done(function() { //content[0], content[1],..
    /* collect processed responses */
    console.warn(this,arguments);
    parseContent(arguments);
    $("body").append("
All done!
");
});


Adding all IDs associated with a Fax to one Row

You could just use a dictionary to identify unique values, then use the dictionary to identify the matches and print them to the new sheet. This also eliminates the need for user input of "How many unique items max".
Doing it this way won't require as much coding, or calling any functions. In fact, it does it in one fell swoop, which should speed it up when there's a large amount of data. You could use the dictionary to pull the items into an array and then print the array, but I'm not certain it would speed up significantly more on this solution.
The trick to the dictionary is that it can't have duplicate keys - so it's doing your entire uniqueitems() in a simple loop.
In faxestouse you're copying and pasting - instead just define the worksheets and set the values without any need to use .activate - this is much cleaner.
Sub CombineOtherID()
Dim dict As Object
Set dict = CreateObject("Scripting.Dictionary")

Dim lastrow As Integer
lastrow = Cells(Rows.Count, "A").End(xlUp).Row

Dim strA As String

'Will use each fax number only once as a dictionary key
For i = 2 To lastrow
    strA = Cells(i, 2)
    dict(strA) = 1
Next

Dim countkey As Integer
countkey = 2
Dim countcol As Integer
Dim wsorigin As Worksheet
Set wsorigin = ActiveSheet
Dim wstarget As Worksheet
Set wstarget = Sheets("Use Me")

wstarget.Range("A1") = "Faxes"
wstarget.Range("B1") = "Other IDs"

'Use the keys to populate the target sheet
For Each Key In dict.keys
    wstarget.Cells(countkey, 1) = Key
    countkey = countkey + 1
    countcol = 2
        For j = 2 To lastrow
            If wsorigin.Cells(j, 2) Like Key Then
                wstarget.Cells(countkey - 1, countcol) = wsorigin.Cells(j, 1)
                countcol = countcol + 1
            End If
        Next
Next
End Sub

Otherwise
Now, if I were to go through your code there's a few things I'd note.
Your inputbox isn't handling any errors. I'd make sure it specifies the numeric type -
UniqueTotal = Application.InputBox("How Many Unique OtherIDs is Max?", Type:=1)

I'm a bit fuzzy how UniqueItems returns to subtotal. If it's a single integer, I guess it would work as a pretty inefficient loop, but as a variant - it should fail:
Next you call the UniqueItems() function which can return the number of uniques or an array of uniques. I'm not confident your matching algorithm is the most efficient - instead I'd use the dictionary object. It will give you the array or if you want the count you can use the .count method to get that.
If you return the count, then If SubTotal > UniqueTotal will execute no problem as subtotal is long. If the UniqueItems returns a variant (array), you will get type mismatch when you set SubTotal = UniqueItems - so I'm not sure what your goal here is - you pass an array to a long to check if your function returns a value greater than user input - is this to check to see if the list is already only uniques? There must be a better way to do that.
Then you're going to use .copy and .paste with .activate to fill in your sheet, but again you call UniqueItems as True so you'll get numunique - which doesn't have a type but would work as an integer. However, if you call it with False you'll get an array passed to a long which would return a type mismatch.
As far as the inefficient loop goes -
For CurRow = 2 To LastRow
        SubTotal = UniqueItems(Range("A2:A" & CurRow))
        If SubTotal > UniqueTotal Then
            SubTotal = UniqueItems(Range("A2:A" & CurRow - 1))
            Range("A1:B" & CurRow - 1).Copy
            Sheets("Use Me").Cells.Clear
            Sheets("Use Me").Range("A1").PasteSpecial xlPasteValues
            Sheets("Use Me").Activate
            MsgBox "Use Me Sheet rows contain " & SubTotal & " Unique OtherIDs"
            Exit Sub
        End If
        Cells(CurRow, 1).EntireRow.Interior.Color = RGB(255, 255, 0)
    Next CurRow

You will loop through everything until you count larger than the user input and then copy and paste the range - how does this work? Won't it just return the x number of rows, indiscriminately?  You might have an incomplete data set at this point on your new sheet.
I don't quite understand the RemoveDups() sub. I think it looks for duplicates in column B because you haven't reversed the array and column B is still Fax Numbers. But after that, I'm not sure how you're getting anywhere close to your output.


Shorter, simpler, and more Pythonic would be:

N, T = map(int, input().split())
widths = list(map(int, input().split()))
for _ in range(T):
    i, j = map(int, input().split())
    vehicle = min(widths[segment] for segment in range(i, j + 1))
    print(vehicle)

You would miss out on the shortcut when encountering a bike-only segment, though.

I've also renamed x to segment for clarity.


I think you should replace mixedBaseInc with a generator that returns the combinations of indexes. That would simplify XProd by taking out numElms and the construction of digits.

That gives you the option to parallelise XProd by instantiating more instances of the goroutine that outputs the product vectors (because the closure no longer binds digits). If that is the bottleneck then that improves throughput.

However it depends on the program where this is used; if most of the work is done by the consumer of the output vectors then the best speed-up is for the consumer to consume in a way that can be parallelised.

An alternative approach is to build the output vectors one element at a time — https://github.com/schwarmco/go-cartesian-product/blob/master/cartesian.go for example . That solution has pros and cons and it's a bit more complicated to increase its parallelism, but it might be much better on some inputs (perhaps if there are a large number of small input sets to the product).


Removing duplicate letters from list of words with Python and List Comprehensions

The reason you get \$O(n^2)\$ time complexity is due to you going through listLettersAlreadyFound, whilst checking if the new item is in that. To improve the performance, you could create another set, reducing time complexity to \$O(n)\$.

But before that, listLettersAlreadyFound is long, first list is unneeded, but lettersAlreadyFound is the same as previous_letters. And you should use snake_case rather than CamelCase.

I also find your comprehensions hard to read, you need to space the logic on different lines. Take:

listx = ['cat', 'dog','rabbit']
listLettersAlreadyFound = []
[
    [
        listLettersAlreadyFound.append(letter)
        for letter in list(word)
        if letter not in listLettersAlreadyFound
    ]
    for word in listx
]
print listLettersAlreadyFound

From this it's easy to notice that a comprehension is probably not the best choice here. You don't actually want the list, you only want the side affects from the list. This goes against the spirit of Functional Programming, which is what comprehensions are. And so you should instead just use a simple for loop.

Merging the above all together could get you some \$O(n^2)\$ time complexity code, that also has \$O(2n)\$ memory:

words = ['cat', 'dog','rabbit']
unique_letters = []
previous_letters = set()

for letter in (letter for word in words for letter in word):
    if letter in previous_letters:
        continue
    previous_letters.add(letter)
    unique_letters.append(letter)

print unique_letters

Finally if you don't care about the order of the letters, you can change the for loop to be set. And instead just use:

words = ['cat', 'dog','rabbit']

print set(letter for word in words for letter in word)

Also .pop(n) will keep the \$O(n^2)\$ time complexity, and so I'd suggest you don't use it, if you really want better memory performance, use a for loop, as it'd keep the code readable, not a list comprehension.


Fast hamming distance function in Julia that returns a distance matrix

I have three areas of suggestions below. Here's a modified version of your code that implements these suggestions:
# For memory safety, restrict type to Matrix due to the use of @inbounds below.
function ham(df::Matrix)
    nrows, ncols = size(df)
    A = fill(0, ncols, ncols)
    for j in 1:ncols, i in j+1:ncols
        v = 0
        for k in 1:nrows
            v += @inbounds (df[k, i] != df[k, j])
        end
        A[i, j] = A[j, i] = v
    end
    return A
end

ham(df::DataFrame) = ham(convert(Matrix, df))

1. Write code for column-major arrays.
Julia is column-major (and packages like DataFrames.jl conform with this by storing data in columns), so when performance is important, you should iterate through the rows of a column. For example, when iterating through an array A[x, y, z], the leftmost index x should be changing the most rapidly. Looking at the innermost loop in your code,
for j in 1:ncols
    if df[i,j] != df[k,j]
    v += 1
    end
end

notice that it is iterating through the columns of a row instead (i.e., j is changing most rapidly in df[i,j]). To get a free performance boost, rewrite the code to exchange the roles of columns and rows. The data will also need to be transposed. (Note that R is also column-major.)
Julia documentation: memory order.

2. In performance-critical loops, annotate @inbounds where possible.
In the modified code I gave, the array access in the innermost loop is annotated with @inbounds to disable bounds checking. This gives a speedup in large part because it allows compiler to automatically vectorize the loop.
Only use @inbounds if you are certain that out-of-bounds access is impossible; in our case, we cannot guarantee this for custom types, so we restrict the input type to a Matrix (an alias for Array{T,2} where T) to ensure that df[k, i] and df[k, j] are always in bounds. Like so:
function ham(df::Matrix)
    [...]
    for k in 1:nrows
        v += @inbounds (df[k, i] != df[k, j])
    end
    [...]
end

If @inbounds is not used, I would not restrict the input type and would instead leave it generic.
Julia documentation: performance annotations.

3. Beware of type instability.
For performant code, functions should be type stable, meaning that given an input type, the output type can be inferred during compilation. Similarly, variables used within a function should be type stable.
As noted in its documentation, DataFrame columns are not type stable! That is, the type of a DataFrame does not contain information about the types of its columns; in fact, the DataFrame type is not parametric, so the type contains no information other than that it is a DataFrame. This can drastically degrade performance.
The @code_warntype macro is very helpful for diagnosing this.
In our case, assuming that all columns are of the same type, a simple workaround is to copy the columns into a Matrix before calling the function. (The time this takes is negligible compared to the rest of the function.) To do so, we can specialize ham for the DataFrame type:
ham(df::DataFrame) = ham(convert(Matrix, df))

Note that the compiler specializes code for types at function boundaries, so it is important that this conversion takes place outside the original ham function. In particular, don't put the conversion into the original function like so:
# Don't do this!
function ham(x)
    df = convert(Matrix, x)
    [rest of ham...]
end

because the type of x here might not contain sufficient information to infer the type of df. Such is the case for DataFrames.
Julia documentation: function barriers.

Simple benchmark
After implementing these suggestions, the speedup on calculating the distance matrix for 128 vectors of 256 integers each is by about 1000x: (note that the times are in microseconds vs milliseconds)
using BenchmarkTools
using DataFrames
M = rand(0:1, 256, 128);
df = DataFrame(M);
tdf = DataFrame(permutedims(M)); # transpose rows and columns

julia> @benchmark ham($df)
BenchmarkTools.Trial:
  memory estimate:  387.33 KiB
  allocs estimate:  133
  --------------
  minimum time:     493.841 μs (0.00% GC)
  median time:      537.689 μs (0.00% GC)
  mean time:        610.732 μs (2.74% GC)
  maximum time:     6.215 ms (81.69% GC)
  --------------
  samples:          8176
  evals/sample:     1

julia> @benchmark hamjulia($tdf)
BenchmarkTools.Trial:
  memory estimate:  128.08 KiB
  allocs estimate:  2
  --------------
  minimum time:     538.585 ms (0.00% GC)
  median time:      546.390 ms (0.00% GC)
  mean time:        551.220 ms (0.00% GC)
  maximum time:     567.238 ms (0.00% GC)
  --------------
  samples:          10
  evals/sample:     1

The additional memory allocations in ham are due to the conversion of the DataFrame to a Matrix.


A couple of thoughts.

Always think about breaking your code into discrete units of work, this will make it more logical, more readable and importantly, more testable. In your case, separate out the reading of the data from the creation of the bitmap.
The ambiguous return will either be because you are modifying multiple local properties (count, len, buffer) or because you return a new Bitmap or null from different points in your code. By needing to use count in your Bitmap creation you make it harder to refactor.
If you are concerned about 0 length returns from inputStream.read() consider adding a handbrake to avoid infinite loops - I have never encountered this in real life  though.
Does your code perform better than using ByteArrayOutputStream, something like the below.

Code:

//add throws or try/catch as suits your code.

private byte[] readBitmapData() {
    ByteArrayOutputStream buffer = new ByteArrayOutputStream();
    byte[] inputBuffer = new byte[16384]; //16K default buffer size
    int nRead;

    while ((nRead = is.read(inputBuffer, 0, data.length)) != -1) {
        buffer.write(inputBuffer, 0, nRead);
    }

    return buffer.toByteArray();
}

You can check out the OpenJDK code for ByteArrayOutputStream on docjar. Note their code for grow and ensureCapacity.


Diamond in the rough! Finding Gems in the rocks

You have added

public GemCounter() {
    // default constructor. Does nothing.
}

which is not needed for the program to work because,

  The compiler automatically provides a no-argument, default constructor
  for any class without constructors. This default constructor will call
  the no-argument constructor of the superclass. In this situation, the
  compiler will complain if the superclass doesn't have a no-argument
  constructor so you must verify that it does. If your class has no
  explicit superclass, then it has an implicit superclass of Object,
  which does have a no-argument constructor [1].

therefore this also violates YAGNI

  "You aren't gonna need it" (acronym: YAGNI) is a principle of extreme
  programming (XP) that states a programmer should not add functionality
  until deemed necessary. XP co-founder Ron Jeffries has written:
  "Always implement things when you actually need them, never when you
  just foresee that you need them [2].

References

[1]“Providing Constructors for Your Classes.” [Online]. Available: http://docs.oracle.com/javase/tutorial/java/javaOO/constructors.html. [Accessed: 27-Aug-2014].
[2]“You aren’t gonna need it,” Wikipedia, the free encyclopedia. 24-Aug-2014.


I don't like using the object as a mutex and Condition variable. Doing that would let another programmer spin up a thread to lock and never release the Semaphore.

Instead you should either provide a private Object lock = new Object(); and sync on that or use the java.util.concurrent.locks.ReentrantLock and its condition:

private final Lock mutex = new ReentrantLock();
private final Condition condition = mutex.newCondition();

public void acquire() throws InterruptedException {
    mutex.lockInterruptibly();//let interrupt throw as soon as possible
    try{
        while (count <= 0) {
            condition.await();
        }
        --count;
    } finally {
        mutex.unlock();
    }
}

// Implementation
public void release() {
    mutex.lock();
    try{
        ++count;
        if (count > 0) {
            condition.signal();
        }
    } finally {
        mutex.unlock();
    }
}

This makes it easy to change the semaphore to a fair one by passing true to the constructor.

Though I expect you will want to implement the wait queue yourself as an example.

If you want to go a step lower and no use the pre-implemented locks can instead use LockSupport which lets to park the current thread and unpark it from another thread safely.


Showing all possible permutations from a set

As noted by 200_success in the comments, the m == len(nlist) check is a bug that can be fixed by simply removing the condition.

Also, if m > len(nlist): return is almost redundant because you would get an empty list as the result anyway in that case. (The deepest levels of recursion give empty results when the list runs out and the emptiness propagates all the way up)

Turning the function into a generator simplifies it and speeds it up at the same time: from 10.9 ms to 6.6 ms for the case perm(range(6), 6). (Of course I wrapped that in list() when timing the generator version)

def perm(nlist, m):
    if m == 0:
        yield []
        return

    for list_i in nlist:
        temp = list(nlist)
        temp.remove(list_i)
        for p in perm(temp, m-1):
            yield [list_i] + p


sb.insert(0, charArray[i]);
            if (sb.length() == 2)
                break;
        }
    }

    return sb.toString();

You could change this to

             sb.append(charArray[i]);
             if (sb.length() >= digitCount) {
                 break;
             }
         }
     }

     return sb.reverse().toString();

Then you're using your StringBuilder as intended.  Appending rather than constantly inserting.

Changing 2 to digitCount allows you to alter the number of digits to find easily.

I prefer to always use the block form of control structures, even when the statement form would work.


My PHP function that reads names and attempts to fix the suffixes

If it can be assumed that a suffix will always have a space before it this is easier.

Loop through suffixes and see if one is in the first name.  Strip out the suffix if is is there.  Any suffix that is found is added to a suffix variable, s.

Treating the suffix separately is nice because it can be added, separated, lower cased, modified etc.  For example, suffixes could be standardized; "SR." and "SR" could all be "SR." in the final name. This is easier to do if suffix is a separate variable.  It could be an array as well.

function extractFullName($name) {

    // $suffixes = ['II', 'III', 'IV', 'JR.', 'SR.'];
    // Suffixes would always have a space before them
    $suffixes = [' II', ' III', ' IV', ' JR.', ' SR.'];

    // lets first assemble a full name from the row
    $fullNameArray = explode(",", $name);
    $firstName = trim($fullNameArray[1]);
    $lastName = trim($fullNameArray[0]);
    $s = ''; // default zero length string.
    //
    //lets look at the FIRST NAME for II/III/IV/JR./SR.
    foreach ($suffixes as $suffix) {
        if (strpos($firstName, $suffix)) {
            // Suffix was found, remove it from first name
            $firstName = str_replace($suffix, "", $firstName);
            $s .= $suffix;  // keep ths suffixes stored separately.
        }
    }

    //Basically arranging it in a 'firstname lastname II/III/IV/JR./SR.' format
    $fullName = $firstName . " " . $lastName;
    $finalName = ucwords(strtolower($fullName)) . " " . $s;
    return $finalName;
}

$name1 = 'MILLERS, WALTER M IV';
$name2 = 'MIVERS, LIVEY M IV';  // test for IV in the middle of a name
$name3 = 'DUPONTE, THOMAS B. II';
$name4 = 'DUPONTE, THOMAS B. II SR.';  // test for multiple suffixes.
$name5 = 'HARDIWAY, GRANT U. SR.';
$name6 = 'GUIDRY, PAUL JOHN';
echo extractFullName($name1) . "
";
echo extractFullName($name2) . "
";
echo extractFullName($name3) . "
";
echo extractFullName($name4) . "
";
echo extractFullName($name5) . "
";
echo extractFullName($name6) . "
";


Yes.

You can see that your sort function operates by recursing directly on itself, using a shorter-by-one version of its list parameter. This is stopped when the list is of length 0 or 1. (That code should be cleaned up.) So your sort recurses n-1 times, given n >= 2.

Each time it recurses, sort calls push_up once. The push_up function linearly scans the list, which is of length 1, then 2, then ... n-1.

So in the worst case (input array is reverse-sorted) you have scans of total length \$ \sum 1 ... (n-1) \$, which makes your code \$ O(n^2) \$.


You have optimized this very well. However, using a different algorithm can reduce code size from 665 bytes to 411 bytes:

DelVar IDelVar VDelVar XDelVar LDelVar CDelVar DDelVar M"?->Str2
"IVXLCDM->Str3
ClrHome
Input Str1
expr(Str1->N
If N
Then
For(I,0,log(N
10fPart(.1N->A
While A
sum({4.1,4.1,9.2}(A={4,5,9->B
sub(Str3,2I+10fPart(B)+1,1)+Str2->Str2
abs(A-1-int(B->A
End
int(.1N->N
End
sub(Str2,1,length(Str2)-1
Else
Str2+Str1+"?->Str1
For(I,0,5
inString(Str1,sub("IVIXXLXCCDCM",2I+1,2
If Ans
Then
sub(Str1,1,Ans-1)+sub(Str1,Ans+2,length(Str1)-Ans-1->Str1
C+(4+10fPart(I/2))10^(iPart(I/2->C
End
End
For(I,1,length(Str1
inString(Str3,sub(Str1,I,1
If Ans
C+(5-8fPart(.5Ans))10^(iPart(.5Ans-.5->C
End
C
End
Ans


Simplify Oracle SQL: Treat null date as 'N' and non-null date as 'Y'

I'm not sure what's wrong with your code, but if you don't like all of those 'N''s would

  select  stricken_chicken_id,
          case when to_char(chicken_hatch_date) is null then
             'N'
          else
             'Y'
          end chicken_hatch_date
   from   stricken_chicken;

work for you?


I would consider returning with a more detailed JSON object:

{
    errorMessage: "things have gone wrong!",
    data: [
        {
            link: #,
            linkText: Test,
            size: 0MB
        },
        {
            link: #,
            linkText: Test2,
            size: 1MB
        }
}

It moves some processing from the server to the clients but it's more reusable. For example you need a second type of table later with the same data but with an extra column. With this JSON format you don't have to touch the server side code nor to parse and modify the returned HTML on the client side.

Finally, if there is an error maybe you want to omit the whole data part:

{
    errorMessage: "things have gone wrong!",
}


Get a notification when questions get posted

Why would you use stackexchange.com and only take ones with the title of stackoverflow.com? That's a huge waste.

You could change your url from https://stackexchange.com/questions?tab=realtime to https://stackoverflow.com/questions?tab=realtime.

However, actually visiting the website the way you are is hacky and overkill. Instead of web scraping, use the Stackexchange API.

There is no way to get a notification when a new question is posted. You will have to make a call every time you want the latest results.

Edit: there may be a way to get notifications, see vogel612's comment:

  there is websockets to receive notifications when a new question is
  posted. To my knowledge these are very much undocumented and easier to
  get access to with a userscript (which would imply changing to
  javascript), but it's not like there's no way to receive notifications
  from SE directly.


jQuery code for displaying server status from XML feed

Here is a proposition.
The idea is to define an object that maps the property (http, ftp...) with related images url indexed by possible property values (OK, WARNING,...).

With this approach :

get the img src for a service : object[service_name][service_status]
get the service status : $(xml).find(service_name).text()
get the img dom element $("." + service_name + " img")

Code :

    $(document).ready(function() {
       var config = {
            "http":{
                "OK":"http://placehold.it/40/00cc33/ffffff",
                "WARNING":"http://placehold.it/40/ff6600/000000",
                "CRITICAL":"http://placehold.it/40/ff0000/000000",
                "UNKNOWN":"/path/to/unknow"
            },
            "ftp":{
                "OK":"http://placehold.it/40/00cc33/ffffff",
                "WARNING":"http://placehold.it/40/ff6600/000000",
                "CRITICAL":"http://placehold.it/40/ff0000/000000",
                "UNKNOWN":"/path/to/unknow"
            },
            "mysql":{
                "OK":"http://placehold.it/40/00cc33/ffffff",
                "WARNING":"http://placehold.it/40/ff6600/000000",
                "CRITICAL":"http://placehold.it/40/ff0000/000000",
                "UNKNOWN":"/path/to/unknow"
            },
            "load":{
                "OK":"http://placehold.it/40/00cc33/ffffff",
                "WARNING":"http://placehold.it/40/ff6600/000000",
                "CRITICAL":"http://placehold.it/40/ff0000/000000",
                "UNKNOWN":"/path/to/unknow"
            }
        };

       function refreshView (xml) {
            for (var name in config) {
                $("." + name +" img").attr("src",config[name][$(xml).find(name).text()] );
            }
       }

        $.ajax({
            type:  'GET',
            url:   'https://status.clook.net/xml/status/harvey.xml',
            dataType: 'xml',
            success: refreshView
        });
    });

You can simplify if status images are the same for all services.

var img = {
  "OK":"http://placehold.it/40/00cc33/ffffff",
  "WARNING":"http://placehold.it/40/ff6600/000000",
  "CRITICAL":"http://placehold.it/40/ff0000/000000",
  "UNKNOWN":"/path/to/unknow"
}
var services = ['http','ftp','mysql']

function refreshView (xml) {
  for (var i=0; i<services.length; i++) {
    $("." + services[i] +" img").attr("src",img[ $(xml).find(services[i]).text()] );
  }
}


In a word, I would say that your program feels… discombobulated.  I see recognizable bits and pieces of "99 Bottles of Beer", but it's not obvious how it all fits together.

Overall, I'm not sure that it is much of an improvement over the question that inspired this one.  Naturally, I'm partial to my answer, which has the advantage of putting all of the conditionals right at the point of use by using the right tools for complex string substitutions.  You can streamify the for-loop in my answer, if you like.

That said, I think there are ways to improve a stream-based implementation.

enum Line isn't doing much, and makes your code incoherent.  "%s bottle%s of beer" is not really a line — it's just a phrase — and you're calling it a "line" just to reuse your wrapper for String.format().  The formatted BOTTLES, in turn, gets substituted into ON_WALL_PREFIX and ON_WALL_SUFFIX, so they are clearly not peers.  Furthermore, you still have PASS_AROUND and BUY_MORE as constants defined elsewhere.
Defining string constants instead of just using string literals isn't necessarily better.  It just makes your eyes jump around to figure out what's going on.
Your getVerse() is weird: it doesn't produce what I would think of as a verse, delimited by the paragraph breaks.  Rather, it produces the end of one verse and the beginning of the next, unified by the fact that they have the same number of bottles.
In getLyrics(), using a stream to generate the sequence 99, 98, …, 1, 0, 99 is awkward.  You have to start with an ascending count, reverse it, skip half of a weirdly delimited "verse", and concatenate a special case at the end that kind of looks like getVerse().
If you're using streams, why bother converting the lyrics to a List?
It's easier (though not necessarily more efficient) to lowercase an entire string than to uppercase just the first letter.
ALCOHOLISM_LEVEL was misspelled.

public final class Bottles {
    private static final long ALCOHOLISM_LEVEL = 99;

    private final long n, replenishment;

    private Bottles(long stock, long replenishment) {
        this.n = stock;
        this.replenishment = replenishment;
    }

    public String toString() {
        return String.format("%s bottle%s of beer",
                             n == 0 ? "No more" : n,
                             n == 1 ? "" : "s");
    }

    private String whatToDo() {
        return n == 0 ? "Go to the store and buy some more"
                      : "Take one down and pass it around";
    }

    private static Bottles next(Bottles b) {
        return new Bottles((b.n == 0) ? b.replenishment : b.n - 1,
                           b.replenishment);
    }

    private static String getVerse(Bottles b) {
        return String.format(
            "%1$s on the wall, %2$s.\n%3$s, %4$s on the wall.",
            b,
            b.toString().toLowerCase(),
            b.whatToDo(),
            next(b).toString().toLowerCase()
        );
    }

    public static Stream<String> getLyrics(long target) {
        return Stream.iterate(new Bottles(target, target), Bottles::next)
                     .limit(target + 1)
                     .map(Bottles::getVerse);
    }

    public static void main(String[] args) {
        System.out.println(getLyrics(ALCOHOLISM_LEVEL)
                           .collect(Collectors.joining("\n\n")));
    }

}


An iterator returning all possible permutations of a list in Java

Your solution looks good. It's a really challenging task. This is because you have to "flatten" an algorithm with recursive nature. Furthermore you have to break it apart into single steps and to be able to resume at the last step made.

So there are little things that I would change:

I like separated classes instead of inner classes they are more handy in testing
I would have separated the algorithm in "generateNextPermutation()" in an additional class.
I would follow the recursive nature of the problem and build a recursive structure. This is a slightly different approach.
I do not exactly know how the algorithm should behave if you provide an empty list. I assume that you will have one permutation as result. So I adapted your algorithm to work with an empty array of indices.

You see that our solutions do not differ in structure. Only the algorithm to generate a new permutation is extracted in a class and reformulated.

I unpacked this riddle (I somehow liked this riddle) and I want to provide a solution that can use either your algorithm or mine. But finally they converged against the same interface. I expected that as I know there is only one structure that fits the problem best. We may not have found it but both solutions have a "meeting" where the structure is mostly the same AND the things that may be different can work under the same abstraction. Sure, most structure was provided by the interfaces "Iterable" and "Iterator" but I found it interesting how the algorithms are interchangeable.

So first of all the interface for our algorithms:

public interface PermutationResolver<T> {

    List<T> resolvePermutation(List<T> base);

    boolean nextStep();

}

Your algorithm:

public class IndicesWalker<T> implements PermutationResolver<T> {

    private int[] indices;

    public IndicesWalker(int elements) {
        indices = new int[elements];
        for (int i = 0; i < indices.length; ++i) {
            indices[i] = i;
        }
    }

    @Override
    public boolean nextStep() {

        if (indices.length == 0) return false;

        int i = indices.length - 2;

        while (i >= 0 && indices[i] > indices[i + 1]) {
            --i;
        }

        if (i == -1) {
            // No more new permutations.
            return false;
        }

        int j = i + 1;
        int min = indices[j];
        int minIndex = j;

        while (j < indices.length) {
            if (indices[i] < indices[j] && indices[j] < min) {
                min = indices[j];
                minIndex = j;
            }

            ++j;
        }

        swap(indices, i, minIndex);

        ++i;
        j = indices.length - 1;

        while (i < j) {
            swap(indices, i++, j--);
        }
        return true;
    }

    @Override
    public List<T> resolvePermutation(List<T> base) {

        List<T> newPermutation = new ArrayList<>(indices.length);

        for (int i : indices) {
            newPermutation.add(base.get(i));
        }

        return newPermutation;
    }

    private void swap(int[] array, int a, int b) {
        int tmp = array[a];
        array[a] = array[b];
        array[b] = tmp;
    }

}

Mine:

public class RecursiveCounter<T> implements PermutationResolver<T> {

    private int i;
    private int max;
    private RecursiveCounter<T> nextState;

    public RecursiveCounter(int max) {
        this.max = max;
        this.i = 0;
        if (this.max > 1) {
            nextState = new RecursiveCounter<T>(max - 1);
        }
    }

    @Override
    public boolean nextStep() {

        boolean wasIncremented = true;

        if (nextState != null) {
            if (!nextState.nextStep()) {
                if (this.i == this.max - 1) {
                    this.i = 0;
                    wasIncremented = false;
                } else {
                    i++;
                }
            }
        } else {
            wasIncremented = false;
        }

        return wasIncremented;
    }

    private int getI(int level) {
        if (level == 0) {
            return this.i;
        } else {
            return nextState.getI(level - 1);
        }
    }

    @Override
    public List<T> resolvePermutation(List<T> base) {
        List<T> result = new ArrayList<>();
        List<T> work = new ArrayList<>(base);
        for(int i = 0; i < base.size(); i++) {
            result.add(work.remove(getI(i)));
        }
        return result;
    }

}

The iterator:

public class PermutationIterator<T> implements Iterator<List<T>>  {

    private List<T> base;

    private PermutationResolver<T> permutationResolver;
    private List<T> next;

    public PermutationIterator(List<T> base, PermutationResolver<T> resolver) {
        this.base = base;
        this.next = new ArrayList<>(base);
        this.permutationResolver = resolver;
    }

    private List<T> generateNextPermutation(boolean isLast) {

        List<T> result = null;

        if (!isLast) {
            result = getPermutationResolver().resolvePermutation(base);
        }

        return result;
    }

    @Override
    public boolean hasNext() {
        return next != null;
    }

    @Override
    public List<T> next() {

        if (!hasNext()) {
            throw new NoSuchElementException();
        }

        List<T> current = next;

        this.next = generateNextPermutation(!getPermutationResolver().nextStep());

        return current;
    }

    private PermutationResolver<T> getPermutationResolver() {
        return permutationResolver;
    }

}

The iterable:

public class PermutationIterable<T> implements Iterable<List<T>> {

    private List<T> base;
    private PermutationResolver<T> resolver;

    public PermutationIterable(List<T> base, PermutationResolver<T> resolver) {
        super();
        this.base = base;
        this.resolver = resolver;
    }

    @Override
    public Iterator<List<T>> iterator() {
        return new PermutationIterator<T>(base, resolver);
    }

}

Code in action with both algorithms:

public class Main {

    public static void main(String[] args) {

        List<String> base = Arrays.asList();

        PermutationIterable<String> permutationIterable1 = new PermutationIterable<String>(base, new IndicesWalker<String>(base.size()));

        for (List<String> permutation : permutationIterable1) {
            System.out.println(permutation);
        }

        PermutationIterable<String> permutationIterable2 = new PermutationIterable<String>(base, new RecursiveCounter<String>(base.size()));

        for (List<String> permutation : permutationIterable2) {
            System.out.println(permutation);
        }

    }

}


I think you're overcomplicating this and your code still doesn't work correctly. The LIKE pattern bcd shouldn't match abcde, but it does with your code.

What you should do is to always add ^ at the start and $ at the end.

This means the following conversions:

bcd → ^bcd$
%bcd → ^.*?bcd$
bcd% → ^bcd.*?$
%bcd% → ^.*?bcd.*?$

In the cases where the pattern starts with %, the ^ is not necessary (and similarly for $ and % at the end), but it also doesn't do any harm.


I would agree with @ardaozkal that an XP based system would be better (more flexible, etc).

But assuming that your approach is good enough for your situation, I also have some suggestions:

You have quite a bit of duplication, for example the completed mission queries or the completed campaign queries. You should extract those to their own function and reuse that.
Your code could generally benefit from more functions. Other candidates would be hasCompletexXMissions($db, $amount) or getCompletedMissionCount($db).
If this project is a bit more complex, you definitely want to add classes, such as Mission, which may then contain the functions mentioned above.
Your lines are too long, which seriously impacts readability. 226 characters don't even fit on many modern screens. I would aim for about 80 characters.
You have a bit too much vertical whitespace for my taste. Do the first three statements really all need their own paragraph?
You can get rid of $currentLevel, it's only used in one location, and the name doesn't really add any value. Just use $userObj->level directly.


Why don't you simply set the texture coordinates properly and have a "pass-thru" shader that just samples the texture and nothing else? For example, if you're using glVertexAttribPointer() with an array of vertices and texture coords, make sure that the texture coordinates you send have the proper tile offset. Something like this:

const int numXTiles = 8;
const int numYTiles = 8;
const int numXPixelsPerTile = 16;
const int numYPixelsPerTile = 16;
const int atlasWidth = numXTiles * numXPixelsPerTile;
const int atlasHeight = numYTiles * numYPixelsPerTile;
const double pixelXDelta = 1.0 / atlasWidth;
const double pixelYDelta = 1.0 / atlasHeight;
typedef struct vertex {
    Point3D position;
    Point2D texCoord;
} vertex;
// Assume you're drawing a square and want to texture it with tile 3,4
vertex square[] = {
    { {-1.0, -1.0, 0.0 }, { 3.0 * numXPixelsPerTile * pixelXDelta, 4.0 * numYPixelsPerTile * pixelYDelta } },
    { { 1.0, -1.0, 0.0 }, { 4.0 * numXPixelsPerTile * pixelXDelta, 4.0 * numYPixelPerTile * pixelYDelta } },
    { { 1.0, 1.0, 0.0 }, { 4.0 * numXPixelsPerTile * pixelXDelta, 5.0 * numYPixelPerTile * pixelYDelta } },
    { { -1.0, 1.0, 0.0 }, { 3.0 * numXPixelsPerTile * pixelXDelta, 5.0 * numYPixelPerTile * pixelYDelta } }
};
glBufferData(GL_ARRAY_BUFFER, 4, square, GL_STATIC_DRAW);
glVertexAttribPointer(0, 3, GL_FLOAT, sizeof(vertex), 0); // Position
glVertexAttribPointer(1, 2, GL_FLOAT, sizeof(vertex), (GLvoid*)sizeof(Point3D)); // Texture Coordinate

This assumes your vertex shader has attribute 0 as position and attribute 1 as texture coordinates. Then your fragment shader just becomes:

#version 330 core
in vec2 TexCoord;
out vec4 color;

uniform sampler2D image;

void main()
{
    color = texture(image, TexCoord);
}

NOTE: I may be off by 1 on the right and top side. You might need to subtract 1 pixelXDelta and 1 pixelYDelta from those coordinates - I can never remember.


This divides the class of game objects into material and immaterial

getGameObject - Never used. You should remove it. You can always use this, no need to have a function. If you meant for this to be protected, still remove it. Again use the object, no need to have a function.

ImMaterialGameObject - Unless "Im" stands for something, Immaterial is one word.

public Object filling; - You've obviously noticed all classes in Java extend from Object. Taking advantage of this is hackey. Instead you could use 2 separate fields and check if one or the other is null.

Onto the question "Is there a better approach?"

Without knowing what you're using this for, I'd say there's nothing wrong with your approach. To make things more clear, set GameObject to abstract.


Ahh, the origins of a simulator. I have always wanted to create one of those. Anyways...

I suggest you model this all in the JS. If you follow MVC, then all data (or most of it) live in the Model, the data storage. The View would be the HTML, and all event handlers like clicks, change, hovers, live in the controller. Controller updates the model data, like add/remove damage and the view updates values when the model data changes.

Using MVC, or a derivative, allows separation of concerns. For instance, you can easily swap HTML and avoid breaking the logic that controls actions and calculations.


Is it true that the complexity of the code is O(NlogN), where N is the total number of pixels (512x512 by example, not 512).

You main loop in bwlabelis:

for i in range(M - 1):
    for j in range(N - 1):
        if (im[i][j] == im[i][j+1]):
            qf.union(i * N + j, i * N + j + 1)
        if (im[i + 1][j] == im[i][j]):
            qf.union(i * N + j, (i + 1) * N + j)

So you are calling qf.union \$O(N*M) = O(n)\$ times. There you call self.root twice:

def root(self, i):
    while (i != self.id[i]):
        i = self.id[i]
    return i

What's the worst case running time of this? At most \$O(n)\$, since self.id has \$n\$ values and there are no cycles. However, since you are comparing ranks in union:

    if (self.sz[i] < self.sz[j]):
        self.id[i] = j
        self.sz[j] += self.sz[i]
    else:
        self.id[j] = i
        self.sz[j] += self.sz[i]

You will have \$O(log\ n)\$ paths to root, so the total running time is \$O(n\ log\ n)\$.

  Is there any way to improve the performance?

Yes, path compression. You descended down two paths from p and q to i and j and it took \$O(log\ n)\$. At each step you can point a node to its root, instead of just the next element. You can do this recursively like so:

def root(self, i):
    if i == self.id[i]:
        return i
    self.id[i] = self.root(self.id[i])
    return self.id[i]

Recursion adds its own cost, though, so whether it's faster in practice would require testing. An alternative would be to add a second iterative compression function:

def compress(self, i, r):
    while i != r:
        i, self.id[i] = self.id[i], r

Now you are walking the path twice, which again may or may not be faster than recursion. You should only need to call this for one of the paths, though.


C-style `switch` statement implementation using decorators

I wish I had enough practice with decorators to be able to comment on most of this. I've never really needed to play with them, so I've kind of neglected them beyond simple memoization toys. This looks pretty cool, but I think all I can comment on are a few things along with the low-hanging PEP fruit since no-ones jumped on that yet :)

len(closure)-1

This should have spaces in there:

  Always surround these binary operators with a single space on either side: assignment (=), augmented assignment (+=, -= etc.), comparisons (==, <, >, !=, <>, <=, >=, in, not in, is, is not), Booleans (and, or, not).

It doesn't explicitly mention -, but the "No:" examples after that bit above suggest that it should use spaces as well.

And on the other end,

test = op.eq

Shouldn't use spaces (from the link above again):

  Don't use spaces around the = sign when used to indicate a keyword argument, or when used to indicate a default value for an unannotated function parameter.

break_ doesn't need a return None in there. That's implicit.

Some of what you're documenting with doc-strings could be documented in other arguably cleaner ways.

For example, in switch_construct you have:

* The dictionary contains two keys: "control" and "halt".
          - "control": the value governing the current switch instance. `case` blocks are tested against this value.
          - `halt`: value is used to implement break functionality.
            > `True`: break after execution of current function.
            > Default: `False`.

You have a dictionary that should only take on certain keys. This sounds more like a job for a dataclass instead of a dictionary:

from dataclasses import dataclass

@dataclass
class SwitchMetadata:
    """- "control": the value governing the current switch instance. `case` blocks are tested against this value.
       - `halt`: value is used to implement break functionality.
    """

    control: str
    halt: bool = False  # Makes the constructor allow halt to default to False

. . .

closure.append(SwitchMetadata(input_))

. . .

if test(value, closure[index].control) and not closure[index].halt

. . .

closure[enclosing.switch_index].halt = True

This gets rid of the need for string dictionary lookups and gives some type safety. Both of these decrease the chance you'll make silly typos since both allow for static checking by the IDE. The class definition also clearly communicates to the reader what the structure holds and what types the data should be.


Iterate over large list of lists and replace its elements

You're looping in incorrect order, take the advantage of the fact that dictionary provides O(1) lookups. So, you should loop over the list and replace its items with the value present in the dictionary. This way you will loop over the list only once:

We can either use dict.get here and avoid an if condition:

def replace_matched_items(word_list, dictionary):
   for lst in word_list:
      for ind, item in enumerate(lst):
          lst[ind] = dictionary.get(item, item)

Or check for the key first and modify only matched item(LBYL):

def replace_matched_items(word_list, dictionary):
   for lst in word_list:
      for ind, item in enumerate(lst):
          if item in dictionary:
              lst[ind] = dictionary[item]

or if you prefer EAFP then try to catch the KeyError:

def replace_matched_items(word_list, dictionary):
   for lst in word_list:
      for ind, item in enumerate(lst):
          try:
              lst[ind] = dictionary[item]
          except KeyError:
              pass

I generally find functions that modify a mutable item in-place and don't return anything confusing, it's usually a better idea to return the list object from the function and re-assign to the variable from where it was called.

def replace_matched_items(word_list, dictionary):
   for lst in word_list:
      for ind, item in enumerate(lst):
          lst[ind] = dictionary.get(item, item)

list_ = replace_matched_items(list_, dictionary)

But the above approach is still flawed(at least when our object has multiple references), with this even though we re-assigned only a single variable all the other references to the list object will still be affected, which can be very confusing to users. For example:

def func(seq):
    for lst in seq:
        for i, x in enumerate(lst):
            if x == 1:
                lst[i] = 100
    return seq

foo = [[1, 1, 2], [1, 2, 3]]
dct = {'key': foo}

foo = func(foo)
print foo
print dct

Outputs:

[[100, 100, 2], [100, 2, 3]]
{'key': [[100, 100, 2], [100, 2, 3]]}

To fix such such cases we can either pass a deepcopy of the list to the function(or simple shallow copy for list containing only immutable items) or we can create a new list inside of the function. But as we are dealing with 1 million items creating another list will surely result in extra memory consumption. Here's an example of how to do this by creating a new list using dict.get:

def replace_matched_items(word_list, dictionary):
    new_list = [[dictionary.get(item, item) for item in lst] for lst in word_list]
    return new_list

list_ = replace_matched_items(list_, dictionary)

Few other questions on the same topic:

Is making in-place operations return the object a bad idea?
Why does django ORM's save method not return the saved object?


Python custom generator of object not efficient

Your ifs structure is needlessly complicated. They only set r1 and r2 based on simple rules (r1 [resp. r2] is 0.1 if SB1.fq [resp. SB2.fq] is lower than 100 and 0.2 otherwise) and compute upper1 and upper2 using the same formula. So you can use the simpler:

r1 = 0.1 if SB1.fq <= 100 else 0.2
r2 = 0.1 if SB2.fq <= 100 else 0.2
upper1 = (1 + r1) * SB1.fq + frequency_step
upper2 = (1 + r2) * SB2.fq + frequency_step

You can also use min to make these values not go over upper_frequency. But this is still some redundancies, especially given the fact that, later, you use r1 & SB1 and r2 & SB2 in the same kind of pattern in your ranges. So better extract out a function:

def frequency_range(SB, step, higher_frequency):
    r = 0.1 if SB.fq <= 100 else 0.2
    high = (1 + r) * SB.fq + step
    low = (1 - r) * SB.fq
    return range(int(low), int(min(high, higher_frequency)))

And the main function is now:

def duo_SBs_to_test(SB1, SB2, frequency_step=1, shift_step=50, max_shift=20000, permutations=True):
    max_phases = max(sum(SB1.phases), sum(SB2.phases))
    upper_frequency = frequency_step + 1/(2 * max_phases) * 1000000

    parameters = itertools.product(
            range(0, max_shift + shift_step, shift_step),
            frequency_range(SB1, frequency_step, upper_frequency),
            frequency_range(SB2, frequency_step, upper_frequency))

    for s, f1, f2 in parameters:
        yield Signal(f1, SB1.phase), Signal(f2, SB2.phase), s
        if permutations:
            yield Signal(f2, SB2.phase), Signal(f1, SB1.phase), s

Now the only little change that I can think of that could improve performances is to avoid testing permutations at each iteration. So you could perform two "radicaly" different iterations depending on the value of permutations:

def duo_SBs_to_test(SB1, SB2, frequency_step=1, shift_step=50, max_shift=20000, permutations=True):
    max_phases = max(sum(SB1.phases), sum(SB2.phases))
    upper_frequency = frequency_step + 1/(2 * max_phases) * 1000000

    parameters = itertools.product(
            range(0, max_shift + shift_step, shift_step),
            frequency_range(SB1, frequency_step, upper_frequency),
            frequency_range(SB2, frequency_step, upper_frequency))

    if permutations:
        for s, f1, f2 in parameters:
            yield Signal(f1, SB1.phase), Signal(f2, SB2.phase), s
            yield Signal(f2, SB2.phase), Signal(f1, SB1.phase), s
    else:
        for s, f1, f2 in parameters:
            yield Signal(f1, SB1.phase), Signal(f2, SB2.phase), s

Now, as regard to your next step, you’re basically just reinventing filter. Just use that instead:

def compute(SB1, SB2, frequency_step = 1, shift_step = 50, max_shift = 20000, permutations = True):
    return list(filter(condition, duo_SBs_to_test(SB1, SB2, frequency_step, shift_step, max_shift, permutations))

And if that compute function is called in a for loop, you can also remove the need to convert it to a list.


Your nested loop seems to serve the purpose of grouping the output by user.
Since Score has a link to User,
you can achieve the same effect by getting the scores ordered by the user field, like this:

def Home(request):
    scores = Score.objects.order_by('user')
    return render(request, "home.html", {'scores': scores})

And then in the template you can eliminate one for and one if:

{% for score in scores %}
{{ score.user }} -- {{ score.subject }} -- {{ score.score }} <br>
{% endfor %}


Find all substrings that contain k specific characters in a string

The trick of these things is to:

create a model, and then
create a mathematical formula that uses the model.

If you look at the example string .A.B.C.A. then you can may first notice that it doesn't matter a bit if you substitute any other character than ABC for the dot. So we don't care a single iota what characters are at those locations.

Now we see a substring xA.B.Cyyy where A.B.C is just the shortest string in which all the characters are present. Any amount of characters x and y can be present, going from the A.B.C part to the outside. In other words, from this you can construct (#x + 1) * (#y + 1) = (1 + 1) * (3 + 1) = 8 separate substrings that contain this A.B.C. This set of substrings of course also includes xA.B.C.Ay, i.e. all longer substrings that contain the ABC.

Now lets look for substrings that are not covered: -axB.C.Ay. Here - and a are not actually part of the substring, it's just to indicate that we have to skip these characters to find a new ones. If we include the first A then of course we've already counted that substring before. So now we calculate that we need to add (#x + 1) * #y = (1 + 1) * (1 + 1) = 4 separate substrings. After that we cannot find a shorter alphabet (-a-bxC.Ay doesn't contain it). So there we are, we have 8 + 4 = 12 substrings that contain the alphabet.

In words: we have to continue looking for the next offset in the string, try to find the shortest alphabet, and stop if there isn't one. We need to keep track where the start of the last substring was that we found, to avoid duplicates. So there is your model and set of calculations.

As you can see, there is just one starting offset of the substring that increases to the right, and then we need to find the end offset within the string. In other words, the complexity is somewhere at O(N * 1/2N) ~ O(N). Easy-peasy for any modern computer.

However, the algorithm doesn't perform any contains! Heck, it doesn't even create the substrings that it just needs to count.

Another longer example for more visually oriented persons (where we count the pipe and dot characters):

ABBCZBAC
|  |.... -> 1 * 5 = 5
 BBCZBAC
 |    |. -> 1 * 2 = 2
 BBCZBAC
  |   |. -> 1 * 2 = 2
  BCZBAC
   |  |. -> 1 * 2 = 2
    ZBAC
    .| | -> 2 * 1 = 2
                   ==+
                   13

I'll post my code (made and thought of from scratch) iff you show you can do the same; post code and the answer for the following string (it should take the computer no time at all to calculate it).

CBZBBZABBBBAABZZZAZZBACBZCACCZCZABBACCAZCABCBBZBAZAACBZCABZAZCZZ

Probably better to create a new question for it. I don't even want to touch the current example.

Happy programming.

No time at all means:

AACZCBZACBZCBZZBCZBBBAABBCAACBCZZCCZABCCCZBAAACCBCBAZAZZBCAAABBCZBCZZZZZCZAZBZZZBCZCBBBCABZZBCCBBBBBCCCBAAZACAZZBCZBAZCBBACACCCZBBZAZAZBCZCZZCCCACCBAZAZBACAAAZCAZACBABZCZZBZACAZZZZACAZBCCABZCCCBAZZBZBAZZCCZCBBBBBBBCAABZCBCAACACCZBCABAZZAZZCZBZCACACZBZCZZBZZCCZZZZBBCCCCZBCCBZABZBAABZZZACZAABBZCABCZCABZAZCZCAZBBBACBCZACZAAZZACBZCCBZBZACCCBACAZACZAACAZAZBCCZBBZCZCZBACACAZBAZZAACCZZBZZZCAZZAAAABBBAZABBBBZAZZBACBBZAACBAZCCBBZCAZZAZAACAAZAZZBCBZCCCZCZCCZZAZABCBZBBZBBBBZZAAZZCABAAABBBBCZCCCCCABBZCBCACBZAZCBZBBAZZZCBCZZZAAAAAZCBABZCCCAZZAAAZAABABZBBAAZZACZAACABZZCBZABZZCACAAACAABAZBABBZBBBCAZAACACZAACAZCBCCBZCCCACBAZBBBZBBCZAAZCZCZBCABCZCBZABAZBAZZBCCZBBABCCCABZZZCBCBAZCBBBCAZZCBBAZBCCZBCCCABZZBZAZBBABACCBABZZCCBCAZBZZACBAZBCCAZZBAACZACZBZZBBBCAAZBBBABBAZBBZABCCBBBZBZZZAZABBZBACBCZAZBCZACBZBBZZBZABAZZBZCAABZBZBBZCCCAZABZCAZBBBZCZBBBZZBCBCCZAZZZABCBZZZCAABBBZCZZCBZZCZZZZACZBZCBCBBBZCCBZZBBCCZZCCCBZAAZZCZBBCBBCBZCAZCZZBBCBBZCZBAZBAAZCZABBCCZAACBBCBZACAZCCCBABBCZZZBZACZCZACZABCCZCCBBBBBCBZACCZZCAABZBCACCAAZZZCZBCAAZBZAZBZCAZBZCCCCZAZBBCCBBCZZCCAAACCZAABCZZAABBZBZZZAAAZABAACBCCBBCZCCBZCABAAABBAAABCBACBZZABZZBAZABCBZZBABBCACABBAZCBZBAZZZZZBACBZCCBCZZBAAZBBAABZCCZCACZAZZBACAZBABCZBBBAAZZCAZBBCCAZBCBCAAAZBZCCCZZZCAZCBBBBACCAZBCBBCCCBBCABZCCAZACZBABZBBCCCAZAACAAACZZAAACABCAAABAAABACAACCCZABZZZZZCBAABCCAAACACAAZCZCBZBZZZCCCBAZBAZZZCZBCCBZCCACCABCAAAABZCZABCBABZCZACCCACCCZZCCBCZBZZAABBZABCZBCZZZZCACBCBAZZBCAZABACZZABABZBZZCBCACAZACAZZZBBBCCABABZBCAZZCBACACABCAZCCACZBBCCAACCBBCBABZZAZCAABAZAACZZBCCBAACCCCAACCBAZBAZCAABBZZBAZZZBBZZBZAABCCBCBZZCZZABCCZBZCACCZAABCAZBBCZACCZBZBBCZCZCAZZBAAZZZAABBAZZZBZCCZCABZBZCZCCAZAZCBAACCAZZCZBBCCACAABBBZZBZZZAACBZCAAZCBZZAZZBBCCZBBAAZAAZZZZBCBCBCBBACCCCZCACZAACZCCAAZAABCZCCZABCZBBCAAACCBCCABZACBACAAAZCBBACAACCCZACCABBACCBABZZBCACCZZACBBAZZCBABBZBAACCCAZAZAZZCCCCCCZCAACAABBZABCZAAZCCBZZZAZCBCAZACCAZBBCZZAZZCABCAZCBZAZABCBZACZCZAAZZZBZZZZZAZZCBZBBZZABABABAAAAZZZACZAZZZZZBBACZCZBZBAAZAAZCCCAZCZZCABCCABBZZBCACCCBBCCCAZCBABBZCBBBAZCBCZBCAZZCBZZAZBBCZABACCZACBABZCBCBZBAACCZBZAZACBBZZZZBBBBZZZAZBAABCCCZCCAZBCAABCAAZACCBZBCCZZABCABABBBBBBCZCBZACBCAABBBCCCZAABCBZBCAZAZZABZAZZCZZAZBAAAAACZZACZCACCZABACAZAACZCCAZABAACBZCABCCAZACCBBZBBZBZZCCZBAABZBBBBCAZAZZACZABABBZCZZZBZBBCBBAZZZBABAAZZBABZBCBAAZCACAACCZAABZZZBBBZACZCCCZABBBCCCBZACZCCZZAZCBABCCACZABCAZZCBZZCBBBCAZZABBABCZZBCABZBAAAABCCAAZABBZZZZZAABBBAZBCACABZACCCBBBZABZBAZAZBAAZAZCAZAZZBBZBCCCCZCZCBAZBCABZCZAACZAZACBABAAZBCBBACACBZCAZCCBZBZBZABCCZBCZCAZAAZCACCCBCBZZZCZBCBCAZBAAZCACAABZBCBBZZBBZBCABZABCCBCAZBAZCBAAZBZAZZZBCZCCBCCACAZBZZCCAZCACAZZCABCBCZCABBCZBBCZCBCBZACBZAACCBZACBZACCBCBZACACBCAZZZZCCZBCZACCACZACZCBCABCCABZAZCABCCCAACZCBZABZZCABBZBCCAABABAZBCZBBABCAZZCBABABZZACBZBBCBBCBZCBCZBCCZZCBABACABBAAABCCCACCABAABBBZZCCCZABZCZZBABCCCBCBZAZBABCZBZZZCABCZBZCBACCBAABABAZBAZACZBAACBAZZBABCZCBZCCAAZACACZCAAACBCBBABACACCCAZBZCCACBBZCCACAZBAZCACACZCZBCZBBBAAZBAZZZACCCCCCCAAZAZCAAAZBZZZCZCZBCBZZCZAACACCBAAABZZZBZZZACBZAABABCBAACAZCCZBZZCZACABCAZZABBCCAAAABAACABAZZACZZBZBAZZCACACBBCACAZCZZBZCACCZACCCABZCAZABCZZACAZACZAABBCZAZZABZCZCCZCZCZCAACACCCAZCCBZZCAZBACCZCBBZAABBAAAZACAAACBCCZAACBZBBBCACZZCZZCCCBZCBAAZCCCCACCZCZCZBZBZZCZCCBBZCAABBAABAACAZZBCACZZABBAZZBZZCBBAACBZAAABZAABBAZCZBZABBBBBCZBBCABABBBZZZABBAAABCCCZBCAAAZABZCBBACCAAZAABZCBCZBCABABCBCZCZCAACACCZZCCCBZZBCABAABABZBACAZBZBABBZCABZBBCACBBZCZABBZCZAZZZABZCZZBAACZZCZACBZBCZCCABCAAZBACCZCAACZBBACZCZCCBCBABBCZZBABZBBACACZZAACCCCCCZCBACCACZZZBACZZZBZCACBBCZCBBCAZBCACBCBBBCAACBZACAAZAACBCCZZZABCBCCAZBBBBCZBBACZCAZACZBBABABZCCZBCCACBAABBZAAACZAABZZCAZAABBBCABCCCACACCBABZCCZBBBAZCCAZZBBZZAZCABBZCCZAACZAZZCBBZABCACBZBCBCZZZBBACBBCAZABAACAZBBBAZBCBCBAACBAZBAAZZBZACBZBACZBZCCABZZCBAZZBCZBCCCZACAZAZCABAACAABBZZBAAACABZAAZBCACBACABACBCBZABCCACBBZBBZBAZCCBCCCABZZCBCZZAAZCCCCAZZACCZZCBZCZZZCAZZABZAZZACCABZABCCAAAAAABZBCCZCBBZCCZAZAACACBBBBCAZABZCBCZABZCBAAACCZBBBCBZCAAAZCZAACBAZZZZABCZCABAABZZAACCCAZZZCZAACZACCCZBACCBBBBZACZBBAZZABZACAZBAZCBCACACAAACBCBAZCCBZBBZAABAZZCCCCBACBZBCCBACZABZBZBZACABBBZBCAZZBCBBCZABCZBBBZZCCAAZBBAZCAZBAAZAAZZBBCCZABCZAAZBCACCCBABCZBCACZAABBBACCZBBABBCZACAZZAZCBZCCAACBZCBABZAZBCAZBCBCZBZBBABZZCBZAAZ

gives

8364211

instantly. Feel free to check that answer.

In under 2 minutes, I can have an answer for a 1 billion sized character string:

499999994166624150 substrings
116292 ms


Shortening JPA criteria query boilerplate

JPA Criteria API is horrific, even the creators admitted that it was designed for tooling support rather than for developers.
My personal favorite approach is to use a fluent query API like QueryDSL.

The query in QueryDSL would look more or less as follows:

new JPAQuery().from(transaction)
    .where(transaction.originalOperationId.eq(originalOperationId))
   .list();

The difference is staggering. And the query is fully typesafe.


Tkinter application with multiple windows

For me, it is a pretty piece of code. I learned much from it. Also, I'm not sure if it is a proper way. But, it works fine and is easy to read :)


The problem “Fun game” from a competition

The way your loops are organized results in an unpleasant phenomenon. Namely, you process the same subsequence many times. Let's say, a long good range starts at the index k and has a length n. The inner loop finds it. Then the next iteration of the outer loop starts processing it again, this time from index k + 1. Then from index k+2, etc. It will take \$O(n^2)\$ of unnecessary computations. In fact, each good range contributes a term quadratic to its length to the total complexity.
The fix is, once the inner loop terminated, adjust i to continue from the number which broke the good range.


The markup is definitely not easy to parse because of the nested table elements with no meaningful attributes. But, you are right that relying on relative index of a table and the desired cell being the 6th in the table is quite a fragile strategy.

Instead, let's use the row title as our "anchor". Then, we'll get the following cell via the .find_next_sibling():

DESIRED_MONEDAS = "DOLAR USA"

label = soup.find(lambda tag: tag.name == "td" and tag.get_text(strip=True) == DESIRED_MONEDAS)
value = label.find_next_sibling("td").get_text(strip=True)
print(value)


Here's my attempt. I assume, LINQ-method based approach is allowed by your problem statement.

I have not tested the code, so please cover it by unit test(s) which you may already have.
Also, please notice that this is not a pure function in the functional sense of this term. It means, the method changes the state of the arguments passed in (which may or may not be desirable in different scenarios).

private IEnumerable<SubProjectDto> GetProjectAndActivitiesForByOrg(IEnumerable<SubProjectDto> children, Guid? organiazaitonId)
{
    return children.Select(childSubProject =>
    {
        childSubProject.Activities.RemoveAll(activity =>
                activity.ActivityPersons.All(person => person.ResourceType.OrganizationId != organiazaitonId));

        // if (childSubProject.Children.Any()) // UPD: This check is not really required
        GetProjectAndActivitiesForByOrg(childSubProject.Children, organiazaitonId);

        return childSubProject;
    });
}


Isn't it something like this?

#include <limits.h> /* for CHAR_BIT */

unsigned
rotate_right(unsigned x, int n)
{
    int left_shift = ((sizeof x) * CHAR_BIT) - n;
    return x<<left_shift | x>>n;
}


K&R Exercise 2-6 : Inserting part of a bitset into another

Avoid UB

Shifting a 1 into the sign position is undefined behavior (UB). (C11 §6.5.7 4)  Instead, use unsigned types.  0 is an int constant.  0u is an unsigned constant.

// return ((~(~0 << n) & y) << p) | ((~(~(~0 << n) << p)) & x);
return ((~(~0u << n) & y) << p) | ((~(~(~0u << n) << p)) & x);

Clarity

Code for clarity and let the compiler form optimal code.

// return ((~(~0u << n) & y) << p) | ((~(~(~0u << n) << p)) & x);
unsigned new_mask = ~(~0u << n);
unsigned old_mask = ~(mask << p);
return ((new_mask & y) << p) | (old_mask & x);

Specifier matching

"%d" with unsigned should have raised a compiler warning/note.  Enable all compiler warnings to avoid such easy to identify problems.

// printf("%d\n", setbits(100, 4, 3, 5));
printf("%u\n", setbits(100, 4, 3, 5));

For this task, using "%4x" would be more informative than "%u".

Wider testing

"I've tested with a number of different scenarios, and this code has passed all of them.". --> Testing with UINT_MAX, UINT_MAX-1, 1, 0 would help check out the "corners" of the function.

Document restrictions

Code limited to 0 <= p < bit_width and 0 <= n < bit_width.  Since code cannot handle all possible input values, stating  restrictions lessens incorrect usage.

Defining behavior for all possible inputs has the advantage of not needing to list limitations, yet may not be functional needed (and code over-kill).

Still good to post limitations.

On this last point, perhaps a slight code re-write is in order as one could easily expect n == bit_width to be valid.

// This assumes no padding in `unsigned`
#define UINT_BIT_WIDTH (CHAR_BIT * sizeof(unsigned))

unsigned setbits(unsigned x, int p, int n, unsigned y) {
  unsigned new_mask = n >= UINT_BIT_WIDTH ? UINT_MAX : ~(~0u << n);
  ...
}


Slow SQL Server performance with multiple PreparedStatement loop

Here are some ideas to try:

You are not closing your PreparedStatements.  There might possibly be some slow down due to resource consumption or deadlock.  Use the try-with-resources feature so it will automatically close.

for (AgentUpdate update : updateList) {
    try (PreparedStatement ps = connection.prepareStatement(sql.toString())
    {
        // set parameters
        ps.executeUpdate();
    }
}

Alternatively, you are creating a custom query and creating a new PreparedStatement for each record.  Although you are optimizing individual queries by minimizing the number of fields you are updating, you are creating additional overhead by preparing a new statements for each record.  If you update every field for every row, you could re-use the same PreparedStatement, which may end up being more efficient (depending on the number of fields and length of data you are actually updating).  Just overwrite the values in the prepared statement and redo the executeUpdate() on it.

try (PreparedStatement ps = connection.prepareStatement(sql.toString())) {
    for (AgentUpdate update : updateList) {
        // set parameters
        ps.executeUpdate();
    }
}


Project Euler #2: sum of even Fibonacci numbers, using generators

It's weird that the fibonacci() generates a sequence that starts with 1, 2, 3, 5, 8, ….  Conventionally, the Fibonacci sequence starts with either 0, 1, 1, 2, 3, 5, 8, … or 1, 1, 2, 3, 5, 8, ….

A purer approach would be to use [itertools.takewhile()] in conjunction with an infinite generator.

You should also take advantage of parallel assignment.

The fibonacci() generator would look like this:

def fibonacci():
    a, b = 0, 1
    while True:
        yield a
        a, b = b, a + b

filter_even() is fine.  You could also just write a generator expression instead.

from itertools import takewhile

print(sum(n for n in takewhile(lambda n: n < 4000000, fibonacci()) if n % 2 == 0))


Class representing both cartesian and spherical coordinates

As far as I understand the code, a PositionVector object holds both cartesian and polar coordinates. This is surely redundant: multiple representations of the same position hold no more information than a single one (note that there are many more coordinate systems, and you cannot possibly account for all of them). I recommend to keep the position in a preferred coordinate system, and provide methods to convert it to and from other representations.

Edit: addressing concerns in the comment:

  What about if I want to set a new radius, r? What would be the most
  appropriate way to update [x, y, z]?

This is a very important question I didn't elaborate on in the answer. In the algebraic world we want to reason in terms of objects, as opposed to coordinates. Coordinates are secondary - they are just instrumental for calculations.

In other words, you do not want to set new radius. You want to apply a transformation (translate, rotate, scale, etc).

  I wrote the class with the
  ability to apply vector algebra in mind, if I follow your suggestion,
  would vector algebra be straight forward, regardless of which
  ordinates I am working with?

I seriously hope so.


Checking the presence of certain variables in a dataframe

I would do something like this:

tt <- function() {
  naI <- sapply(input_df[, c('var_in', 'var_out')], function(x) all(is.na(x)))
  if (sum(naI) == 2) {
    stop("both var_in and var_out are completely missing, so I cannot continue the EDA")
  } else {
    missing_variables <- names(naI[naI == TRUE])
  }
  missing_variables
}

I put the code into function for testing. Tests:

input_df <- data.frame(var_in = NA, var_out = 3)
tt()
#> [1] "var_in"
input_df <- data.frame(var_in = NA, var_out = NA)
tt()
#> Error in tt(): both var_in and var_out are completely missing, so I cannot continue the EDA
input_df <- data.frame(var_in = 3, var_out = NA)
tt()
#> [1] "var_out"
input_df <- data.frame(var_in = 3, var_out = 3)
tt()
#> character(0)

P.S. maybe you also want to add some kind of treatment if the one/both columns are missing in data.frame...


Convert Integer to String without using Java API library

Personally I think your algorithm has been made a lot more complex than needed.

Is the concatenation a requirement?  If not, you can simplify by directly converting each digit into a char and storing it in a char[].  This way instead of inefficiently concatenating each digit onto the string, you can use the string constructor overload that takes a char[].

With this simplification, the method can be reduced to just a few lines:

  public static String intToString(int num) {
    if(num == 0){
      return "0";
    }
    int count = 0;
    boolean isNeg = false;
    if (num < 0) {
      num *= -1;
      count = 1;
      isNeg = true;
    }
    count += (int) Math.log10(num) + 1;
    char[] digits = new char[count];
    if (isNeg) {
      digits[0] = '-';
    }
    --count;
    while(num > 0) {
      digits[count--] = (char) ((num % 10) + '0');
      num /= 10;
    }
    return new String(digits);
  }


A simple decorator written as a class, which counts how many times a function has been called

One thing you could try to improve the typing would be to type the method itself (although I'm not sure how well tools support it). Also, leading/trailing whitespace should be up to the logger, not the code using it.

F = TypeVar('F', bound=Callable[..., Any])

# This is mostly so that I practice using a class as a decorator.
class CountCalls:
    """Logs to DEBUG how many times a function gets called, saves the result in a newly created attribute `num_calls`."""
    def __init__(self, func: F) -> None:
        functools.update_wrapper(self, func)
        self.func = func
        self.num_calls: int = 0
        self._logger = logging.getLogger(__name__ + '.' + self.func.__name__)
        self.last_return_value = None

    __call__: F

    def __call__(self, *args: Any, **kwargs: Any) -> Any:
        self.num_calls += 1
        self._logger.debug(f'called %s times', self.num_calls)
        self.last_return_value = self.func(*args, **kwargs)
        return self.last_return_value

As for the code itself, you could make a callback-based API.

F = TypeVar('F', bound=Callable[..., Any])

# This is mostly so that I practice using a class as a decorator.
class CountCalls:
    """Logs to DEBUG how many times a function gets called, saves the result in a newly created attribute `num_calls`."""
    def __init__(self, func: F, callback: Optional[Callable[[int, Tuple[Any], Dict[str, Any]], Any]] = None) -> None:
        if callback is None:
            logger = logging.getLogger(__name__ + '.' + self.func.__name__)

            def callback(num_calls: int, args: Tuple[Any], kwargs: Dict[str, Any]):
                self._logger.debug(f'called %s times', self.num_calls)

        functools.update_wrapper(self, func)
        self.func = func
        self.callback = callback
        self.num_calls: int = 0
        self.last_return_value = None

    __call__: F

    def __call__(self, *args: Any, **kwargs: Any) -> Any:
        self.num_calls += 1
        self.callback(self.num_calls, args, kwargs)
        self.last_return_value = self.func(*args, **kwargs)
        return self.last_return_value

Or with the number of calls tracked in the callback (for increased flexibility):

F = TypeVar('F', bound=Callable[..., Any])

# This is mostly so that I practice using a class as a decorator.
class CountCalls:
    """Logs to DEBUG how many times a function gets called, saves the result in a newly created attribute `num_calls`."""
    def __init__(self, func: F, callback: Optional[Callable[[int, Tuple[Any], Dict[str, Any]], Any]] = None) -> None:
        if callback is None:
            logger = logging.getLogger(__name__ + '.' + self.func.__name__)
            num_calls: int = 0

            def callback(args: Tuple[Any], kwargs: Dict[str, Any]):
                nonlocal num_calls  # Not sure if this is necessary or not
                num_calls += 1
                self._logger.debug(f'called %s times', self.num_calls)

        functools.update_wrapper(self, func)
        self.func = func
        self.callback = callback
        self.last_return_value = None

    __call__: F

    def __call__(self, *args: Any, **kwargs: Any) -> Any:
        self.callback(self.num_calls, args, kwargs)
        self.last_return_value = self.func(*args, **kwargs)
        return self.last_return_value

Earlier, to pass a keyword argument while using it, @functools.partial(CountCalls, callback=callback) was needed. Now, @CountCalls(callback=callback) can be used instead.

F = TypeVar('F', bound=Callable[..., Any])

# This is mostly so that I practice using a class as a decorator.
class CountCalls:
    """Logs to DEBUG how many times a function gets called, saves the result in a newly created attribute `num_calls`."""
    def __init__(self, func: F = None, callback: Optional[Callable[[int, Tuple[Any], Dict[str, Any]], Any]] = None) -> None:
        if callback is None:
            logger = logging.getLogger(__name__ + '.' + self.func.__name__)
            num_calls: int = 0

            def callback(args: Tuple[Any], kwargs: Dict[str, Any]):
                nonlocal num_calls  # Not sure if this is necessary or not
                num_calls += 1
                self._logger.debug(f'called %s times', self.num_calls)

        if func is None:
            return functools.partial(CountCalls, callback=callback)

        functools.update_wrapper(self, func)
        self.func = func
        self.callback = callback
        self.last_return_value = None

    __call__: F

    def __call__(self, *args: Any, **kwargs: Any) -> Any:
        self.callback(self.num_calls, args, kwargs)
        self.last_return_value = self.func(*args, **kwargs)
        return self.last_return_value

(Note: none of this code has been tested.)


Functional composition of member function predicates

The verbosity of C++14 generic lambdas should be much lower than std::mem_fun

std::remove_if(v.begin(),
               v.end(),
               [](auto const & w) { return w.empty(); });

If you want to remove non-empty vectors, you can also do something like

std::function<bool(std::vector<int>)> is_empty = [](auto const & w) { return w.empty(); };
std::remove_if(v.begin(),
               v.end(),
               std::not1(is_empty));

Oh and the -> bool in your question is already superfluous in C++11 for single-line lambdas. Generic lambdas are currently supported by Clang >= 3.4, GCC 4.9 and MSVC 2013 November CTP.

I think Scott Meyers even has an Item "Prefer lambdas over bind" in his upcoming book Effective C++11/14.


First of all don't save your temporary file as tmp.jpg, think about what happends if there are 2 requests for an image at the same time, the first tmp.jpg will be overwritten by the second one (very unlikely, but still possible and very hard to debug / reproduce bug)..

Second saving to the disk is expensive and useless, avoid it whenever possible.

Third why do you need the blank image? I think you should have the frame image and overlay the profile image on top of it.

Given this, I think the code should look like this:

// Create a blank image with the underlying image correctly positioned
$base = imagecreatefrompng('frame.png');
$profile = imagecreatefromjpeg('img.jpg');
$w = imagesx($profile);
$h = imagesy($profile);
imagecopy($base, $profile, 0, 140, 0, 0, $w, $h);

imagejpeg($base, 'output.jpg', 100);

// Garbage collection
imagedestroy($base);
imagedestroy($profile);

Unless I miss something this code should do exactly the same thing, but faster and safer.


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.)